context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace Pacman.GameLogic
{
[Serializable()]
public abstract class Entity
{
public const int Width = 14;
public const int Height = 14;
protected double x, y;
public double Speed = 0.0f;
protected Direction direction;
protected Direction lastNoneDirection;
public Direction NextDirection;
public GameState GameState;
public Node Node;
Point lastPosition = new Point(-1000, 0);
public Direction Direction
{
get { return direction; }
}
//private Point lastPosition; // for use with setPosition
public void SetPosition(int x, int y) {
Node = GameState.Map.GetNode(x, y);
this.x = x;
this.y = y;
}
public void SetRoadPosition(int x, int y) {
Node = GameState.Map.GetNodeNonWall(x, y);
this.x = x;
this.y = y;
if (lastPosition.X != -1000) {
if (Math.Abs(x - lastPosition.X) > 4.0) {
if (x < lastPosition.X) {
this.direction = Direction.Left;
//Console.WriteLine("left");
} else {
this.direction = Direction.Right;
//Console.WriteLine("right");
}
//Console.WriteLine("X trigger: " + x + " : " + lastPosition.X + " ... " + y + " : " + lastPosition.Y);
}
if (Math.Abs(y - lastPosition.Y) > 4.0) {
if (y < lastPosition.Y) {
this.direction = Direction.Up;
//Console.WriteLine("up");
} else {
this.direction = Direction.Down;
//Console.WriteLine("down");
}
//Console.WriteLine("Y trigger: " + x + " : " + lastPosition.X + " ... " + y + " : " + lastPosition.Y);
}
}
lastPosition = new Point(x, y);
}
public int X { get { return (int)Math.Round(x); } }
public int Y { get { return (int)Math.Round(y); } }
public int ImgX { get { return X - 7; } }
public int ImgY { get { return Y - 7; } }
public double Xf { get { return x; } }
public double Yf { get { return y; } }
public Entity(int x, int y, GameState GameState) {
this.direction = Direction.Left;
this.NextDirection = Direction.Left;
this.x = x;
this.y = y;
this.GameState = GameState;
this.Node = GameState.Map.GetNode(x, y);
}
protected bool checkDirection(Direction checkDirection){
switch( checkDirection ) {
case Direction.Up:
if(Node.Up.Type != Node.NodeType.Wall ) {
return true;
}
break;
case Direction.Down:
if(Node.Down.Type != Node.NodeType.Wall ) {
return true;
}
break;
case Direction.Left:
if(Node.Left.Type != Node.NodeType.Wall ) {
return true;
}
break;
case Direction.Right:
if(Node.Right.Type != Node.NodeType.Wall ) {
return true;
}
break;
}
return false;
}
protected bool setNextDirection() {
if( NextDirection == direction )
return false;
switch( NextDirection ) {
case Direction.Up:
if(Node.Up.Type != Node.NodeType.Wall ) {
direction = NextDirection;
this.x = Node.CenterX;
this.y = Node.CenterY;
Node = Node.Up;
return true;
}
break;
case Direction.Down:
if(Node.Down.Type != Node.NodeType.Wall ) {
direction = NextDirection;
this.x = Node.CenterX;
this.y = Node.CenterY;
Node = Node.Down;
return true;
}
break;
case Direction.Left:
if( Node.Left.Type != Node.NodeType.Wall ) {
direction = NextDirection;
this.x = Node.CenterX;
this.y = Node.CenterY;
Node = Node.Left;
return true;
}
break;
case Direction.Right:
if( Node.Right.Type != Node.NodeType.Wall ) {
direction = NextDirection;
this.x = Node.CenterX;
this.y = Node.CenterY;
Node = Node.Right;
return true;
}
break;
}
return false;
}
protected virtual void ProcessNode() { }
protected virtual void ProcessNodeSimulated() { }
public virtual void MoveSimulated()
{
double curSpeed = Speed;
Ghosts.Ghost ghost = this as Ghosts.Ghost;
if (ghost != null)
{
if (!ghost.Entered)
{
// going back speed
}
else if (GameState.Map.Tunnels[Node.Y] && (Node.X <= 1 || Node.X >= Map.Width - 2))
{
curSpeed = ghost.TunnelSpeed; // Ghosts.Ghost.TunnelSpeed;
}
else if (!ghost.Chasing)
{
curSpeed = ghost.FleeSpeed; // Ghosts.Ghost.FleeSpeed;
}
}
//Console.WriteLine(direction + " << going " + Node.X + "," + Node.Y + ", " + Node.Type + " ::: " + X + "," + Y + " : " + Node.CenterX + "," + Node.CenterY);
switch (direction)
{
case Direction.Up:
if (this.y > Node.CenterY)
{ // move towards target Node if we haven't reached it yet
this.y -= curSpeed;
}
if (this.y <= Node.CenterY)
{
ProcessNodeSimulated();
if (!setNextDirection())
{ // try to change direction
if (Node.Up.Type == Node.NodeType.Wall)
{
this.y = Node.CenterY;
}
else
{
Node = Node.Up;
}
};
}
break;
case Direction.Down:
if (this.y < Node.CenterY)
{
this.y += curSpeed;
}
if (this.y >= Node.CenterY)
{
ProcessNodeSimulated();
if (!setNextDirection())
{
if (Node.Down.Type == Node.NodeType.Wall)
{
this.y = Node.CenterY;
}
else
{
Node = Node.Down;
}
};
}
break;
case Direction.Left:
if (Node.X == Map.Width - 1 && this.x < 10)
{ // check wrapping round // buggy on map 3
this.x -= curSpeed;
if (this.x < 0)
this.x = GameState.Map.PixelWidth + this.x;
}
else
{
if (this.x > Node.CenterX)
{
this.x -= curSpeed;
}
if (this.x <= Node.CenterX)
{
ProcessNodeSimulated();
if (!setNextDirection())
{
if (Node.Left.Type == Node.NodeType.Wall)
{
this.x = Node.CenterX;
}
else
{
Node = Node.Left;
}
};
}
}
break;
case Direction.Right:
if (Node.X == 0 && this.x > GameState.Map.PixelWidth - 10)
{ // check wrapping round // buggy on map 3
this.x += curSpeed;
if (this.x > GameState.Map.PixelWidth)
this.x = this.x - GameState.Map.PixelWidth;
}
else
{
if (this.x < Node.CenterX)
{
this.x += curSpeed;
}
if (this.x >= Node.CenterX)
{
ProcessNodeSimulated();
if (!setNextDirection())
{
if (Node.Right.Type == Node.NodeType.Wall)
{
this.x = Node.CenterX;
}
else
{
Node = Node.Right;
}
};
}
}
break;
case Direction.None:
setNextDirection();
break;
}
}
public virtual void Move() {
double curSpeed = Speed;
Ghosts.Ghost ghost = this as Ghosts.Ghost;
if( ghost != null ){
if( !ghost.Entered ) {
// going back speed
}
else if( GameState.Map.Tunnels[Node.Y] && (Node.X <= 1 || Node.X >= Map.Width - 2) ) {
curSpeed = ghost.TunnelSpeed; // Ghosts.Ghost.TunnelSpeed;
} else if( !ghost.Chasing ) {
curSpeed = ghost.FleeSpeed; // Ghosts.Ghost.FleeSpeed;
}
}
//Console.WriteLine(direction + " << going " + Node.X + "," + Node.Y + ", " + Node.Type + " ::: " + X + "," + Y + " : " + Node.CenterX + "," + Node.CenterY);
switch( direction ) {
case Direction.Up:
if( this.y > Node.CenterY ) { // move towards target Node if we haven't reached it yet
this.y -= curSpeed;
}
if( this.y <= Node.CenterY ) {
ProcessNode();
if( !setNextDirection() ) { // try to change direction
if( Node.Up.Type == Node.NodeType.Wall ) {
this.y = Node.CenterY;
} else {
Node = Node.Up;
}
};
}
break;
case Direction.Down:
if( this.y < Node.CenterY ) {
this.y += curSpeed;
}
if( this.y >= Node.CenterY ) {
ProcessNode();
if( !setNextDirection() ) {
if( Node.Down.Type == Node.NodeType.Wall ) {
this.y = Node.CenterY;
} else {
Node = Node.Down;
}
};
}
break;
case Direction.Left:
if( Node.X == Map.Width - 1 && this.x < 10 ) { // check wrapping round // buggy on map 3
this.x -= curSpeed;
if( this.x < 0 )
this.x = GameState.Map.PixelWidth + this.x;
} else {
if( this.x > Node.CenterX ) {
this.x -= curSpeed;
}
if( this.x <= Node.CenterX ) {
ProcessNode();
if( !setNextDirection() ){
if( Node.Left.Type == Node.NodeType.Wall ) {
this.x = Node.CenterX;
} else {
Node = Node.Left;
}
};
}
}
break;
case Direction.Right:
if( Node.X == 0 && this.x > GameState.Map.PixelWidth - 10 ) { // check wrapping round // buggy on map 3
this.x += curSpeed;
if( this.x > GameState.Map.PixelWidth )
this.x = this.x - GameState.Map.PixelWidth;
} else {
if( this.x < Node.CenterX ) {
this.x += curSpeed;
}
if( this.x >= Node.CenterX ) {
ProcessNode();
if( !setNextDirection() ) {
if( Node.Right.Type == Node.NodeType.Wall ) {
this.x = Node.CenterX;
} else {
Node = Node.Right;
}
};
}
}
break;
case Direction.None:
setNextDirection();
break;
}
}
public float Distance(Entity entity) {
return (float)Math.Sqrt(Math.Pow(X - entity.X, 2) + Math.Pow(Y - entity.Y, 2));
}
public bool IsBelow(Entity entity){
if( Y <= entity.Y )
return true;
return false;
}
public bool IsAbove(Entity entity) {
if( Y >= entity.Y )
return true;
return false;
}
public bool IsLeft(Entity entity) {
if( X >= entity.X )
return true;
return false;
}
public bool IsRight(Entity entity) {
if( X <= entity.X )
return true;
return false;
}
public List<Direction> PossibleDirections() {
List<Direction> possible = new List<Direction>();
/*if (this.GameState.Pacman.Lives < 0)
return possible;
*/
if( Node.Up.Type != Node.NodeType.Wall ) possible.Add(Direction.Up);
if( Node.Down.Type != Node.NodeType.Wall ) possible.Add(Direction.Down);
if( Node.Left.Type != Node.NodeType.Wall ) possible.Add(Direction.Left);
if( Node.Right.Type != Node.NodeType.Wall ) possible.Add(Direction.Right);
return possible;
}
public bool PossibleDirection(Direction d) {
switch(d){
case Direction.Up: return Node.Up.Type != Node.NodeType.Wall;
case Direction.Down: return Node.Down.Type != Node.NodeType.Wall;
case Direction.Left: return Node.Left.Type != Node.NodeType.Wall;
case Direction.Right: return Node.Right.Type != Node.NodeType.Wall;
}
return false;
}
public Direction InverseDirection(Direction d) {
switch( d ) {
case Direction.Up: return Direction.Down;
case Direction.Down: return Direction.Up;
case Direction.Left: return Direction.Right;
case Direction.Right: return Direction.Left;
}
return Direction.None;
}
public virtual void Draw(Graphics g, Image sprites) {
g.DrawRectangle(new Pen(Brushes.Red), new Rectangle(ImgX, ImgY, Width, Height));
}
}
public enum Direction { Up = 0, Down = 1, Left = 2, Right = 3, None = 5, Stall = 4 };
}
| |
using System;
using System.Collections.Generic;
using Esprima.Ast;
using Jint.Native;
using Jint.Native.Function;
using Jint.Runtime.Interpreter.Expressions;
namespace Jint.Runtime.Interpreter
{
/// <summary>
/// Works as memento for function execution. Optimization to cache things that don't change.
/// </summary>
internal sealed class JintFunctionDefinition
{
private readonly Engine _engine;
private JintExpression _bodyExpression;
private JintStatementList _bodyStatementList;
public readonly string Name;
public readonly bool Strict;
public readonly IFunction Function;
private State _state;
public JintFunctionDefinition(
Engine engine,
IFunction function)
{
_engine = engine;
Function = function;
Name = !string.IsNullOrEmpty(function.Id?.Name) ? function.Id.Name : null;
Strict = function.Strict;
}
public FunctionThisMode ThisMode => Strict || _engine._isStrict ? FunctionThisMode.Strict : FunctionThisMode.Global;
internal Completion Execute(EvaluationContext context)
{
if (Function.Expression)
{
_bodyExpression ??= JintExpression.Build(_engine, (Expression) Function.Body);
var jsValue = _bodyExpression?.GetValue(context).Value ?? Undefined.Instance;
return new Completion(CompletionType.Return, jsValue, Function.Body.Location);
}
var blockStatement = (BlockStatement) Function.Body;
_bodyStatementList ??= new JintStatementList(blockStatement, blockStatement.Body);
return _bodyStatementList.Execute(context);
}
internal State Initialize(FunctionInstance functionInstance)
{
return _state ??= DoInitialize(functionInstance);
}
internal sealed class State
{
public bool HasRestParameter;
public int Length;
public Key[] ParameterNames;
public bool HasDuplicates;
public bool IsSimpleParameterList;
public bool HasParameterExpressions;
public bool ArgumentsObjectNeeded;
public List<Key> VarNames;
public LinkedList<JintFunctionDefinition> FunctionsToInitialize;
public readonly HashSet<Key> FunctionNames = new HashSet<Key>();
public LexicalVariableDeclaration[] LexicalDeclarations = Array.Empty<LexicalVariableDeclaration>();
public HashSet<Key> ParameterBindings;
public List<VariableValuePair> VarsToInitialize;
internal struct VariableValuePair
{
public Key Name;
public JsValue InitialValue;
}
internal struct LexicalVariableDeclaration
{
public bool IsConstantDeclaration;
public List<string> BoundNames;
}
}
private State DoInitialize(FunctionInstance functionInstance)
{
var state = new State();
ProcessParameters(Function, state, out var hasArguments);
var hoistingScope = HoistingScope.GetFunctionLevelDeclarations(Function, collectVarNames: true, collectLexicalNames: true);
var functionDeclarations = hoistingScope._functionDeclarations;
var lexicalNames = hoistingScope._lexicalNames;
state.VarNames = hoistingScope._varNames;
LinkedList<JintFunctionDefinition> functionsToInitialize = null;
if (functionDeclarations != null)
{
functionsToInitialize = new LinkedList<JintFunctionDefinition>();
for (var i = functionDeclarations.Count - 1; i >= 0; i--)
{
var d = functionDeclarations[i];
var fn = d.Id.Name;
if (state.FunctionNames.Add(fn))
{
functionsToInitialize.AddFirst(new JintFunctionDefinition(_engine, d));
}
}
}
state.FunctionsToInitialize = functionsToInitialize;
const string ParameterNameArguments = "arguments";
state.ArgumentsObjectNeeded = true;
if (functionInstance._thisMode == FunctionThisMode.Lexical)
{
state.ArgumentsObjectNeeded = false;
}
else if (hasArguments)
{
state.ArgumentsObjectNeeded = false;
}
else if (!state.HasParameterExpressions)
{
if (state.FunctionNames.Contains(ParameterNameArguments)
|| lexicalNames?.Contains(ParameterNameArguments) == true)
{
state.ArgumentsObjectNeeded = false;
}
}
var parameterBindings = new HashSet<Key>(state.ParameterNames);
if (state.ArgumentsObjectNeeded)
{
parameterBindings.Add(KnownKeys.Arguments);
}
state.ParameterBindings = parameterBindings;
var varsToInitialize = new List<State.VariableValuePair>();
if (!state.HasParameterExpressions)
{
var instantiatedVarNames = state.VarNames != null
? new HashSet<Key>(state.ParameterBindings)
: new HashSet<Key>();
for (var i = 0; i < state.VarNames?.Count; i++)
{
var n = state.VarNames[i];
if (instantiatedVarNames.Add(n))
{
varsToInitialize.Add(new State.VariableValuePair
{
Name = n
});
}
}
}
else
{
var instantiatedVarNames = state.VarNames != null
? new HashSet<Key>(state.ParameterBindings)
: null;
for (var i = 0; i < state.VarNames?.Count; i++)
{
var n = state.VarNames[i];
if (instantiatedVarNames.Add(n))
{
JsValue initialValue = null;
if (!state.ParameterBindings.Contains(n) || state.FunctionNames.Contains(n))
{
initialValue = JsValue.Undefined;
}
varsToInitialize.Add(new State.VariableValuePair
{
Name = n,
InitialValue = initialValue
});
}
}
}
state.VarsToInitialize = varsToInitialize;
if (hoistingScope._lexicalDeclarations != null)
{
var _lexicalDeclarations = hoistingScope._lexicalDeclarations;
var lexicalDeclarationsCount = _lexicalDeclarations.Count;
var declarations = new State.LexicalVariableDeclaration[lexicalDeclarationsCount];
for (var i = 0; i < lexicalDeclarationsCount; i++)
{
var d = _lexicalDeclarations[i];
var boundNames = new List<string>();
d.GetBoundNames(boundNames);
declarations[i] = new State.LexicalVariableDeclaration
{
IsConstantDeclaration = d.IsConstantDeclaration(),
BoundNames = boundNames
};
}
state.LexicalDeclarations = declarations;
}
return state;
}
private static void GetBoundNames(
Expression parameter,
List<Key> target,
bool checkDuplicates,
ref bool _hasRestParameter,
ref bool _hasParameterExpressions,
ref bool _hasDuplicates,
ref bool hasArguments)
{
if (parameter is Identifier identifier)
{
_hasDuplicates |= checkDuplicates && target.Contains(identifier.Name);
target.Add(identifier.Name);
hasArguments |= identifier.Name == "arguments";
return;
}
while (true)
{
if (parameter is RestElement restElement)
{
_hasRestParameter = true;
_hasParameterExpressions = true;
parameter = restElement.Argument;
continue;
}
if (parameter is ArrayPattern arrayPattern)
{
_hasParameterExpressions = true;
ref readonly var arrayPatternElements = ref arrayPattern.Elements;
for (var i = 0; i < arrayPatternElements.Count; i++)
{
var expression = arrayPatternElements[i];
GetBoundNames(
expression,
target,
checkDuplicates,
ref _hasRestParameter,
ref _hasParameterExpressions,
ref _hasDuplicates,
ref hasArguments);
}
}
else if (parameter is ObjectPattern objectPattern)
{
_hasParameterExpressions = true;
ref readonly var objectPatternProperties = ref objectPattern.Properties;
for (var i = 0; i < objectPatternProperties.Count; i++)
{
var property = objectPatternProperties[i];
if (property is Property p)
{
GetBoundNames(
p.Value,
target,
checkDuplicates,
ref _hasRestParameter,
ref _hasParameterExpressions,
ref _hasDuplicates,
ref hasArguments);
}
else
{
_hasRestParameter = true;
_hasParameterExpressions = true;
parameter = ((RestElement) property).Argument;
continue;
}
}
}
else if (parameter is AssignmentPattern assignmentPattern)
{
_hasParameterExpressions = true;
parameter = assignmentPattern.Left;
continue;
}
break;
}
}
private static void ProcessParameters(
IFunction function,
State state,
out bool hasArguments)
{
hasArguments = false;
state.IsSimpleParameterList = true;
ref readonly var functionDeclarationParams = ref function.Params;
var count = functionDeclarationParams.Count;
var parameterNames = new List<Key>(count);
for (var i = 0; i < count; i++)
{
var parameter = functionDeclarationParams[i];
if (parameter is Identifier id)
{
state.HasDuplicates |= parameterNames.Contains(id.Name);
hasArguments = id.Name == "arguments";
parameterNames.Add(id.Name);
if (state.IsSimpleParameterList)
{
state.Length++;
}
}
else if (parameter.Type != Nodes.Literal)
{
state.IsSimpleParameterList = false;
GetBoundNames(
parameter,
parameterNames,
checkDuplicates: true,
ref state.HasRestParameter,
ref state.HasParameterExpressions,
ref state.HasDuplicates,
ref hasArguments);
}
}
state.ParameterNames = parameterNames.ToArray();
}
}
}
| |
#region Using Statements
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using JigLibX.Math;
#endregion
namespace JigLibX.Geometry
{
/// <summary>
/// Class Plane
/// </summary>
public class Plane : Primitive
{
internal Vector3 normal = Vector3.Zero;
private float d = 0.0f;
/// <summary>
/// Constructor
/// </summary>
public Plane()
: base((int)PrimitiveType.Plane)
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="n"></param>
/// <param name="d"></param>
public Plane(Vector3 n, float d)
: base((int)PrimitiveType.Plane)
{
JiggleMath.NormalizeSafe(ref n);
this.normal = n;
this.d = d;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="n"></param>
/// <param name="pos"></param>
public Plane(Vector3 n, Vector3 pos)
: base((int)PrimitiveType.Plane)
{
JiggleMath.NormalizeSafe(ref n);
this.normal = n;
this.d = -Vector3.Dot(n, pos);
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="pos0"></param>
/// <param name="pos1"></param>
/// <param name="pos2"></param>
public Plane(Vector3 pos0,Vector3 pos1,Vector3 pos2)
: base((int)PrimitiveType.Plane)
{
Vector3 dr1 = pos1 - pos0;
Vector3 dr2 = pos2 - pos0;
this.normal = Vector3.Cross(dr1, dr2);
float mNLen = normal.Length();
if (mNLen < JiggleMath.Epsilon)
{
this.normal = Vector3.Up;
this.d = 0.0f;
}
else
{
this.normal /= mNLen;
this.d = -Vector3.Dot(this.normal, pos0);
}
}
/// <summary>
/// Gets or Set normal
/// </summary>
public Vector3 Normal
{
get { return this.normal; }
set { this.normal = value; }
}
/// <summary>
/// Gets or Sets d
/// </summary>
public float D
{
get { return this.d; }
set { this.d = value; }
}
/// <summary>
/// Clone
/// </summary>
/// <returns>Primitive</returns>
public override Primitive Clone()
{
Plane newPlane = new Plane(this.Normal, this.D);
newPlane.Transform = Transform;
return newPlane;
}
private Matrix transformMatrix;
private Matrix invTransform;
/// <summary>
/// Gets Transform or Sets transformMatrix and invTransform
/// </summary>
public override Transform Transform
{
get
{
return base.Transform;
}
set
{
base.Transform = value;
transformMatrix = transform.Orientation;
transformMatrix.Translation = transform.Position;
invTransform = Matrix.Invert(transformMatrix);
}
}
/// <summary>
/// Use a cached version. Gets transformMatrix
/// </summary>
public override Matrix TransformMatrix
{
get
{
return transformMatrix;
}
}
/// <summary>
/// Use a cached version. Gets invTransform
/// </summary>
public override Matrix InverseTransformMatrix
{
get
{
return invTransform;
}
}
/// <summary>
/// SegmentIntersect
/// </summary>
/// <param name="frac"></param>
/// <param name="pos"></param>
/// <param name="normal"></param>
/// <param name="seg"></param>
/// <returns>bool</returns>
public override bool SegmentIntersect(out float frac, out Vector3 pos, out Vector3 normal, Segment seg)
{
bool result;
if (result = Intersection.SegmentPlaneIntersection(out frac, seg, this))
{
pos = seg.GetPoint(frac);
normal = this.Normal;
}
else
{
pos = Vector3.Zero;
normal = Vector3.Zero;
}
return result;
}
/// <summary>
/// GetVolume
/// </summary>
/// <returns>0.0f</returns>
public override float GetVolume()
{
return 0.0f;
}
/// <summary>
/// GetSurfaceArea
/// </summary>
/// <returns>0.0f</returns>
public override float GetSurfaceArea()
{
return 0.0f;
}
/// <summary>
/// GetMassProperties
/// </summary>
/// <param name="primitiveProperties"></param>
/// <param name="mass"></param>
/// <param name="centerOfMass"></param>
/// <param name="inertiaTensor"></param>
public override void GetMassProperties(PrimitiveProperties primitiveProperties, out float mass, out Vector3 centerOfMass, out Matrix inertiaTensor)
{
mass = 0.0f;
centerOfMass = Vector3.Zero;
inertiaTensor = Matrix.Identity;
}
/// <summary>
/// Invert
/// </summary>
public void Invert()
{
Vector3.Negate(ref normal, out normal);
}
/// <summary>
/// GetInverse
/// </summary>
/// <returns>Plane</returns>
public Plane GetInverse()
{
Plane plane = new Plane(this.normal, this.d);
plane.Invert();
return plane;
}
}
}
| |
//
// ServiceTests.cs
//
// Author:
// Scott Peterson <lunchtimemama@gmail.com>
//
// Copyright (c) 2009 Scott Peterson
//
// 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 NUnit.Framework;
using Mono.Upnp.Control;
namespace Mono.Upnp.Tests
{
[TestFixture]
public class ServiceTests
{
class ActionTestClass
{
[UpnpAction]
public void Foo ()
{
}
}
[Test]
public void ActionTest ()
{
var service = new DummyService<ActionTestClass> ();
var controller = new ServiceController (new[] { new DummyServiceAction ("Foo") }, null);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class ActionNameTestClass
{
[UpnpAction ("foo")]
public void Foo ()
{
}
}
[Test]
public void ActionNameTest ()
{
var service = new DummyService<ActionNameTestClass> ();
var controller = new ServiceController (new[] { new DummyServiceAction ("foo") }, null);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class ArgumentTestClass
{
[UpnpAction]
public void Foo (string bar)
{
}
}
[Test]
public void ArgumentTest ()
{
var service = new DummyService<ArgumentTestClass> ();
var controller = new ServiceController (
new[] {
new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) })
},
new[] {
new StateVariable ("A_ARG_bar", "string")
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class OutArgumentTestClass
{
[UpnpAction]
public void Foo (out string bar)
{
bar = string.Empty;
}
}
[Test]
public void OutArgumentTest ()
{
var service = new DummyService<OutArgumentTestClass> ();
var controller = new ServiceController (
new[] {
new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.Out) })
},
new[] {
new StateVariable ("A_ARG_bar", "string")
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class RefArgumentTestClass
{
[UpnpAction]
public void Foo (ref string bar)
{
}
}
[Test]
public void RefArgumentTest ()
{
var service = new DummyService<RefArgumentTestClass> ();
var controller = new ServiceController (
new[] {
new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.Out) })
},
new[] {
new StateVariable ("A_ARG_bar", "string")
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class ReturnArgumentTestClass
{
[UpnpAction]
public string Foo ()
{
return string.Empty;
}
}
[Test]
public void ReturnArgumentTest ()
{
var service = new DummyService<ReturnArgumentTestClass> ();
var controller = new ServiceController (
new[] {
new DummyServiceAction ("Foo", new[] { new Argument ("result", "A_ARG_result", ArgumentDirection.Out, true) })
},
new[] {
new StateVariable ("A_ARG_result", "string")
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class ArgumentNameTestClass
{
[UpnpAction]
public void Foo ([UpnpArgument ("Bar")]string bar)
{
}
}
[Test]
public void ArgumentNameTest ()
{
var service = new DummyService<ArgumentNameTestClass> ();
var controller = new ServiceController (
new[] {
new DummyServiceAction ("Foo", new[] { new Argument ("Bar", "A_ARG_Bar", ArgumentDirection.In) })
},
new[] {
new StateVariable ("A_ARG_Bar", "string")
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class ReturnArgumentNameTestClass
{
[UpnpAction]
[return: UpnpArgument ("foo")]
public string Foo ()
{
return null;
}
}
[Test]
public void ReturnArgumentNameTest ()
{
var service = new DummyService<ReturnArgumentNameTestClass> ();
var controller = new ServiceController (
new[] {
new DummyServiceAction ("Foo", new[] { new Argument ("foo", "A_ARG_foo", ArgumentDirection.Out, true) })
},
new[] {
new StateVariable ("A_ARG_foo", "string")
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class RelatedStateVariableNameTestClass
{
[UpnpAction]
public void Foo ([UpnpRelatedStateVariable ("X_ARG_bar")]string bar)
{
}
}
[Test]
public void RelatedStateVariableNameTest ()
{
var service = new DummyService<RelatedStateVariableNameTestClass> ();
var controller = new ServiceController (
new[] {
new DummyServiceAction ("Foo", new[] { new Argument ("bar", "X_ARG_bar", ArgumentDirection.In) })
},
new[] {
new StateVariable ("X_ARG_bar", "string")
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class ReturnArgumentRelatedStateVariableNameTestClass
{
[UpnpAction]
[return: UpnpRelatedStateVariable ("X_ARG_foo")]
public string Foo ()
{
return null;
}
}
[Test]
public void ReturnArgumentRelatedStateVariableNameTest ()
{
var service = new DummyService<ReturnArgumentRelatedStateVariableNameTestClass> ();
var controller = new ServiceController (
new[] {
new DummyServiceAction ("Foo", new[] { new Argument ("result", "X_ARG_foo", ArgumentDirection.Out, true) })
},
new[] {
new StateVariable ("X_ARG_foo", "string")
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class RelatedStateVariableDataTypeTestClass
{
[UpnpAction]
public void Foo ([UpnpRelatedStateVariable (DataType = "string.foo")]string bar)
{
}
}
[Test]
public void RelatedStateVariableDataTypeTest ()
{
var service = new DummyService<RelatedStateVariableDataTypeTestClass> ();
var controller = new ServiceController (
new[] {
new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) })
},
new[] {
new StateVariable ("A_ARG_bar", "string.foo")
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class RelatedStateVariableDefaultValueTestClass
{
[UpnpAction]
public void Foo ([UpnpRelatedStateVariable (DefaultValue = "hey")]string bar)
{
}
}
[Test]
public void RelatedStateVariableDefaultValueTest ()
{
var service = new DummyService<RelatedStateVariableDefaultValueTestClass> ();
var controller = new ServiceController (
new[] {
new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) })
},
new[] {
new StateVariable ("A_ARG_bar", "string", new StateVariableOptions { DefaultValue = "hey" })
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class RelatedStateVariableAllowedValueRangeTestClass
{
[UpnpAction]
public void Foo ([UpnpRelatedStateVariable ("0", "100", StepValue = "2")]int bar)
{
}
}
[Test]
public void RelatedStateVariableAllowedValueRangeTest ()
{
var service = new DummyService<RelatedStateVariableAllowedValueRangeTestClass> ();
var controller = new ServiceController (
new[] {
new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) })
},
new[] {
new StateVariable ("A_ARG_bar", "i4", new AllowedValueRange ("0", "100", "2"))
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
enum EnumArgumentTestEnum
{
Foo,
Bar
}
class EnumArgumentTestClass
{
[UpnpAction]
public void Foo (EnumArgumentTestEnum bar)
{
}
}
[Test]
public void EnumArgumentTest ()
{
var service = new DummyService<EnumArgumentTestClass> ();
var controller = new ServiceController (
new[] {
new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) })
},
new[] {
new StateVariable ("A_ARG_bar", new[] { "Foo", "Bar" })
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
enum EnumArgumentNameTestEnum
{
[UpnpEnum ("foo")] Foo,
[UpnpEnum ("bar")] Bar
}
class EnumArgumentNameTestClass
{
[UpnpAction]
public void Foo (EnumArgumentNameTestEnum bar)
{
}
}
[Test]
public void EnumArgumentNameTest ()
{
var service = new DummyService<EnumArgumentNameTestClass> ();
var controller = new ServiceController (
new[] {
new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) })
},
new[] {
new StateVariable ("A_ARG_bar", new[] { "foo", "bar" })
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class ArgumentNameAgreementTestClass
{
[UpnpAction]
public void Foo (string bar)
{
}
[UpnpAction]
public void Bar (string bar)
{
}
}
[Test]
public void ArgumentNameAgreementTest ()
{
var service = new DummyService<ArgumentNameAgreementTestClass> ();
var controller = new ServiceController (
new[] {
new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }),
new DummyServiceAction ("Bar", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) })
},
new[] {
new StateVariable ("A_ARG_bar", "string")
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class ArgumentTypeConflictTestClass
{
[UpnpAction]
public void Foo (string bar)
{
}
[UpnpAction]
public void Bar (int bar)
{
}
}
[Test]
public void ArgumentTypeConflictTest ()
{
var service = new DummyService<ArgumentTypeConflictTestClass> ();
var controller = new ServiceController (
new[] {
new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }),
new DummyServiceAction ("Bar", new[] { new Argument ("bar", "A_ARG_Bar_bar", ArgumentDirection.In) })
},
new[] {
new StateVariable ("A_ARG_bar", "string"),
new StateVariable ("A_ARG_Bar_bar", "i4")
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class RelatedStateVariableAllowedValueRangeConflictTest1Class
{
[UpnpAction]
public void Foo (int bar)
{
}
[UpnpAction]
public void Bar ([UpnpRelatedStateVariable("0", "100")] int bar)
{
}
}
[Test]
public void RelatedStateVariableAllowedValueRangeConflictTest1 ()
{
var service = new DummyService<RelatedStateVariableAllowedValueRangeConflictTest1Class> ();
var controller = new ServiceController (
new[] {
new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }),
new DummyServiceAction ("Bar", new[] { new Argument ("bar", "A_ARG_Bar_bar", ArgumentDirection.In) })
},
new[] {
new StateVariable ("A_ARG_bar", "i4"),
new StateVariable ("A_ARG_Bar_bar", "i4", new AllowedValueRange ("0", "100"))
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class RelatedStateVariableAllowedValueRangeConflictTest2Class
{
[UpnpAction]
public void Foo ([UpnpRelatedStateVariable("0", "100")] int bar)
{
}
[UpnpAction]
public void Bar (int bar)
{
}
}
[Test]
public void RelatedStateVariableAllowedValueRangeConflictTest2 ()
{
var service = new DummyService<RelatedStateVariableAllowedValueRangeConflictTest2Class> ();
var controller = new ServiceController (
new[] {
new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }),
new DummyServiceAction ("Bar", new[] { new Argument ("bar", "A_ARG_Bar_bar", ArgumentDirection.In) })
},
new[] {
new StateVariable ("A_ARG_bar", "i4", new AllowedValueRange ("0", "100")),
new StateVariable ("A_ARG_Bar_bar", "i4")
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class RelatedStateVariableAllowedValueRangeConflictTest3Class
{
[UpnpAction]
public void Foo ([UpnpRelatedStateVariable("0", "100")] int bar)
{
}
[UpnpAction]
public void Bar ([UpnpRelatedStateVariable("0", "101")] int bar)
{
}
}
[Test]
public void RelatedStateVariableAllowedValueRangeConflictTest3 ()
{
var service = new DummyService<RelatedStateVariableAllowedValueRangeConflictTest3Class> ();
var controller = new ServiceController (
new[] {
new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }),
new DummyServiceAction ("Bar", new[] { new Argument ("bar", "A_ARG_Bar_bar", ArgumentDirection.In) })
},
new[] {
new StateVariable ("A_ARG_bar", "i4", new AllowedValueRange ("0", "100")),
new StateVariable ("A_ARG_Bar_bar", "i4", new AllowedValueRange ("0", "101"))
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class RelatedStateVariableAllowedValuesConflictTest1Class
{
[UpnpAction]
public void Foo (string bar)
{
}
[UpnpAction]
public void Bar (EnumArgumentTestEnum bar)
{
}
}
[Test]
public void RelatedStateVariableAllowedValuesConflictTest1 ()
{
var service = new DummyService<RelatedStateVariableAllowedValuesConflictTest1Class> ();
var controller = new ServiceController (
new[] {
new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }),
new DummyServiceAction ("Bar", new[] { new Argument ("bar", "A_ARG_Bar_bar", ArgumentDirection.In) })
},
new[] {
new StateVariable ("A_ARG_bar", "string"),
new StateVariable ("A_ARG_Bar_bar", new[] { "Foo", "Bar" })
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class RelatedStateVariableAllowedValuesConflictTest2Class
{
[UpnpAction]
public void Foo (EnumArgumentTestEnum bar)
{
}
[UpnpAction]
public void Bar (string bar)
{
}
}
[Test]
public void RelatedStateVariableAllowedValuesConflictTest2 ()
{
var service = new DummyService<RelatedStateVariableAllowedValuesConflictTest2Class> ();
var controller = new ServiceController (
new[] {
new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }),
new DummyServiceAction ("Bar", new[] { new Argument ("bar", "A_ARG_Bar_bar", ArgumentDirection.In) })
},
new[] {
new StateVariable ("A_ARG_bar", new[] { "Foo", "Bar" }),
new StateVariable ("A_ARG_Bar_bar", "string")
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class RelatedStateVariableAllowedValuesConflictTest3Class
{
[UpnpAction]
public void Foo (EnumArgumentTestEnum bar)
{
}
[UpnpAction]
public void Bar (EnumArgumentNameTestEnum bar)
{
}
}
[Test]
public void RelatedStateVariableAllowedValuesConflictTest3 ()
{
var service = new DummyService<RelatedStateVariableAllowedValuesConflictTest3Class> ();
var controller = new ServiceController (
new[] {
new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }),
new DummyServiceAction ("Bar", new[] { new Argument ("bar", "A_ARG_Bar_bar", ArgumentDirection.In) })
},
new[] {
new StateVariable ("A_ARG_bar", new[] { "Foo", "Bar" }),
new StateVariable ("A_ARG_Bar_bar", new[] { "foo", "bar" })
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class ArgumentsTestClass
{
[UpnpAction]
public void Foo (string stringArg, int intArg, byte byteArg, ushort ushortArg, uint uintArg, sbyte sbyteArg,
short shortArg, long longArg, float floatArg, double doubleArg, char charArg,
DateTime dateTimeArg, bool boolArg, byte[] byteArrayArg, Uri uriArg)
{
}
}
[Test]
public void ArgumentsTest ()
{
var service = new DummyService<ArgumentsTestClass> ();
var controller = new ServiceController (
new[] {
new DummyServiceAction ("Foo", new[] {
new Argument ("stringArg", "A_ARG_stringArg", ArgumentDirection.In),
new Argument ("intArg", "A_ARG_intArg", ArgumentDirection.In),
new Argument ("byteArg", "A_ARG_byteArg", ArgumentDirection.In),
new Argument ("ushortArg", "A_ARG_ushortArg", ArgumentDirection.In),
new Argument ("uintArg", "A_ARG_uintArg", ArgumentDirection.In),
new Argument ("sbyteArg", "A_ARG_sbyteArg", ArgumentDirection.In),
new Argument ("shortArg", "A_ARG_shortArg", ArgumentDirection.In),
new Argument ("longArg", "A_ARG_longArg", ArgumentDirection.In),
new Argument ("floatArg", "A_ARG_floatArg", ArgumentDirection.In),
new Argument ("doubleArg", "A_ARG_doubleArg", ArgumentDirection.In),
new Argument ("charArg", "A_ARG_charArg", ArgumentDirection.In),
new Argument ("dateTimeArg", "A_ARG_dateTimeArg", ArgumentDirection.In),
new Argument ("boolArg", "A_ARG_boolArg", ArgumentDirection.In),
new Argument ("byteArrayArg", "A_ARG_byteArrayArg", ArgumentDirection.In),
new Argument ("uriArg", "A_ARG_uriArg", ArgumentDirection.In)
})
},
new[] {
new StateVariable ("A_ARG_stringArg", "string"),
new StateVariable ("A_ARG_intArg", "i4"),
new StateVariable ("A_ARG_byteArg", "ui1"),
new StateVariable ("A_ARG_ushortArg", "ui2"),
new StateVariable ("A_ARG_uintArg", "ui4"),
new StateVariable ("A_ARG_sbyteArg", "i1"),
new StateVariable ("A_ARG_shortArg", "i2"),
new StateVariable ("A_ARG_longArg", "int"),
new StateVariable ("A_ARG_floatArg", "r4"),
new StateVariable ("A_ARG_doubleArg", "r8"),
new StateVariable ("A_ARG_charArg", "char"),
new StateVariable ("A_ARG_dateTimeArg", "date"),
new StateVariable ("A_ARG_boolArg", "boolean"),
new StateVariable ("A_ARG_byteArrayArg", "bin"),
new StateVariable ("A_ARG_uriArg", "uri")
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class StateVariableTestClass
{
[UpnpStateVariable]
public event EventHandler<StateVariableChangedArgs<string>> FooChanged;
}
[Test]
public void StateVariableTest ()
{
var service = new DummyService<StateVariableTestClass> ();
var controller = new ServiceController (null,
new[] {
new DummyStateVariable ("FooChanged", "string")
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class StateVariableNameTestClass
{
[UpnpStateVariable ("fooChanged")]
public event EventHandler<StateVariableChangedArgs<string>> FooChanged;
}
[Test]
public void StateVariableNameTest ()
{
var service = new DummyService<StateVariableNameTestClass> ();
var controller = new ServiceController (null,
new[] {
new DummyStateVariable ("fooChanged", "string")
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class StateVariableDataTypeTestClass
{
[UpnpStateVariable (DataType = "string.foo")]
public event EventHandler<StateVariableChangedArgs<string>> FooChanged;
}
[Test]
public void StateVariableDataTypeTest ()
{
var service = new DummyService<StateVariableDataTypeTestClass> ();
var controller = new ServiceController (null,
new[] {
new DummyStateVariable ("FooChanged", "string.foo")
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class StateVariableIsMulticastTestClass
{
[UpnpStateVariable (IsMulticast = true)]
public event EventHandler<StateVariableChangedArgs<string>> FooChanged;
}
[Test]
public void StateVariableIsMulticastTest ()
{
var service = new DummyService<StateVariableIsMulticastTestClass> ();
var controller = new ServiceController (null,
new[] {
new DummyStateVariable ("FooChanged", "string", true)
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class StateVariablesTestClass
{
[UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<string>> StringChanged;
[UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<int>> IntChanged;
[UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<byte>> ByteChanged;
[UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<ushort>> UshortChanged;
[UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<uint>> UintChanged;
[UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<sbyte>> SbyteChanged;
[UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<short>> ShortChanged;
[UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<long>> LongChanged;
[UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<float>> FloatChanged;
[UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<double>> DoubleChanged;
[UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<char>> CharChanged;
[UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<bool>> BoolChanged;
[UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<byte[]>> ByteArrayChanged;
[UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<Uri>> UriChanged;
}
[Test]
public void StateVariablesTest ()
{
var service = new DummyService<StateVariablesTestClass> ();
var controller = new ServiceController (null,
new[] {
new DummyStateVariable ("StringChanged", "string"),
new DummyStateVariable ("IntChanged", "i4"),
new DummyStateVariable ("ByteChanged", "ui1"),
new DummyStateVariable ("UshortChanged", "ui2"),
new DummyStateVariable ("UintChanged", "ui4"),
new DummyStateVariable ("SbyteChanged", "i1"),
new DummyStateVariable ("ShortChanged", "i2"),
new DummyStateVariable ("LongChanged", "int"),
new DummyStateVariable ("FloatChanged", "r4"),
new DummyStateVariable ("DoubleChanged", "r8"),
new DummyStateVariable ("CharChanged", "char"),
new DummyStateVariable ("BoolChanged", "boolean"),
new DummyStateVariable ("ByteArrayChanged", "bin"),
new DummyStateVariable ("UriChanged", "uri")
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class EventedRelatedStateVariableTestClass
{
[UpnpAction]
public void GetFoo ([UpnpRelatedStateVariable ("Foo")] out string foo)
{
foo = null;
}
[UpnpStateVariable ("Foo")]
public event EventHandler<StateVariableChangedArgs<string>> FooChanged;
}
[Test]
public void EventedRelatedStateVariableTest ()
{
var service = new DummyService<EventedRelatedStateVariableTestClass> ();
var controller = new ServiceController (
new[] {
new DummyServiceAction ("GetFoo", new[] { new Argument ("foo", "Foo", ArgumentDirection.Out) })
},
new[] {
new DummyStateVariable ("Foo", "string")
}
);
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class OptionalActionClass
{
[UpnpAction (OmitUnless = "CanFoo")]
public void Foo (string foo)
{
}
[UpnpAction]
public void Bar (string bar)
{
}
public bool CanFoo { get; set; }
}
[Test]
public void UnimplementedOptionalAction ()
{
var service = new DummyService<OptionalActionClass> ();
var controller = new ServiceController (
new[] { new DummyServiceAction ("Bar", new [] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }) },
new[] { new StateVariable ("A_ARG_bar", "string") });
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
[Test]
public void ImplementedOptionalAction ()
{
var service = new DummyService<OptionalActionClass> (new OptionalActionClass { CanFoo = true });
var controller = new ServiceController (
new[] {
new DummyServiceAction ("Foo", new [] { new Argument ("foo", "A_ARG_foo", ArgumentDirection.In) }),
new DummyServiceAction ("Bar", new [] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) })
},
new[] {
new StateVariable ("A_ARG_foo", "string"),
new StateVariable ("A_ARG_bar", "string") });
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class ErroneousOptionalActionClass
{
[UpnpAction (OmitUnless = "CanFoo")]
public void Foo ()
{
}
}
[Test, ExpectedException (typeof (UpnpServiceDefinitionException))]
public void ErroneousOptionalAction ()
{
new DummyService<ErroneousOptionalActionClass> ();
}
class OptionalStateVariablesClass
{
[UpnpStateVariable (OmitUnless = "HasFoo")]
public event EventHandler<StateVariableChangedArgs<string>> FooChanged;
[UpnpStateVariable]
public event EventHandler<StateVariableChangedArgs<string>> BarChanged;
public bool HasFoo { get; set; }
}
[Test]
public void UnimplementedOptionalStateVariable ()
{
var service = new DummyService<OptionalStateVariablesClass> ();
var controller = new ServiceController (null,
new[] { new DummyStateVariable ("BarChanged", "string") });
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
[Test]
public void ImplementedOptionalStateVariable ()
{
var service = new DummyService<OptionalStateVariablesClass> (new OptionalStateVariablesClass { HasFoo = true });
var controller = new ServiceController (null,
new[] {
new DummyStateVariable ("FooChanged", "string"),
new DummyStateVariable ("BarChanged", "string") });
ServiceDescriptionTests.AssertEquality (controller, service.GetController ());
}
class ErroneousOptionalStateVariablesClass
{
[UpnpStateVariable (OmitUnless = "HasFoo")]
public event EventHandler<StateVariableChangedArgs<string>> FooChanged;
}
[Test, ExpectedException (typeof (UpnpServiceDefinitionException))]
public void ErroneousOptionalStateVariable ()
{
new DummyService<ErroneousOptionalStateVariablesClass> ();
}
class ErroneousArgumentTypeClass
{
[UpnpAction]
public void Foo (Exception e)
{
}
}
[Test, ExpectedException (typeof (UpnpServiceDefinitionException))]
public void ErroneousArgumentType ()
{
new DummyService<ErroneousArgumentTypeClass> ();
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="ReadOnlyMetadataCollection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
namespace System.Data.Metadata.Edm
{
/// <summary>
/// Class representing a read-only wrapper around MetadataCollection
/// </summary>
/// <typeparam name="T">The type of items in this collection</typeparam>
public class ReadOnlyMetadataCollection<T> : System.Collections.ObjectModel.ReadOnlyCollection<T> where T : MetadataItem
{
#region Constructors
/// <summary>
/// The constructor for constructing a read-only metadata collection to wrap another MetadataCollection.
/// </summary>
/// <param name="collection">The metadata collection to wrap</param>
/// <exception cref="System.ArgumentNullException">Thrown if collection argument is null</exception>
internal ReadOnlyMetadataCollection(IList<T> collection) : base(collection)
{
}
#endregion
#region InnerClasses
// On the surface, this Enumerator doesn't do anything but delegating to the underlying enumerator
/// <summary>
/// The enumerator for MetadataCollection
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")]
public struct Enumerator : IEnumerator<T>
{
/// <summary>
/// Constructor for the enumerator
/// </summary>
/// <param name="collection">The collection that this enumerator should enumerate on</param>
internal Enumerator(IList<T> collection)
{
_parent = collection;
_nextIndex = 0;
_current = null;
}
private int _nextIndex;
private IList<T> _parent;
private T _current;
/// <summary>
/// Gets the member at the current position
/// </summary>
public T Current
{
get
{
return _current;
}
}
/// <summary>
/// Gets the member at the current position
/// </summary>
object IEnumerator.Current
{
get
{
return this.Current;
}
}
/// <summary>
/// Dispose this enumerator
/// </summary>
public void Dispose()
{
}
/// <summary>
/// Move to the next member in the collection
/// </summary>
/// <returns>True if the enumerator is moved</returns>
public bool MoveNext()
{
if ((uint)_nextIndex < (uint)_parent.Count)
{
_current = _parent[_nextIndex];
_nextIndex++;
return true;
}
_current = null;
return false;
}
/// <summary>
/// Sets the enumerator to the initial position before the first member
/// </summary>
public void Reset()
{
_current = null;
_nextIndex = 0;
}
}
#endregion
#region Properties
/// <summary>
/// Gets whether the collection is a readonly collection
/// </summary>
public bool IsReadOnly
{
get
{
return true;
}
}
/// <summary>
/// Gets an item from the collection with the given identity
/// </summary>
/// <param name="identity">The identity of the item to search for</param>
/// <returns>An item from the collection</returns>
/// <exception cref="System.ArgumentNullException">Thrown if identity argument passed in is null</exception>
/// <exception cref="System.NotSupportedException">Thrown if setter is called</exception>
public virtual T this[string identity]
{
get
{
return (((MetadataCollection<T>)this.Items)[identity]);
}
}
/// <summary>
/// Returns the metadata collection over which this collection is the view
/// </summary>
internal MetadataCollection<T> Source
{
get
{
return (MetadataCollection<T>)this.Items;
}
}
#endregion
#region Methods
/// <summary>
/// Gets an item from the collection with the given identity
/// </summary>
/// <param name="identity">The identity of the item to search for</param>
/// <param name="ignoreCase">Whether case is ignore in the search</param>
/// <returns>An item from the collection</returns>
/// <exception cref="System.ArgumentNullException">Thrown if identity argument passed in is null</exception>
/// <exception cref="System.ArgumentException">Thrown if the Collection does not have an item with the given identity</exception>
public virtual T GetValue(string identity, bool ignoreCase)
{
return ((MetadataCollection<T>)this.Items).GetValue(identity, ignoreCase);
}
/// <summary>
/// Determines if this collection contains an item of the given identity
/// </summary>
/// <param name="identity">The identity of the item to check for</param>
/// <returns>True if the collection contains the item with the given identity</returns>
/// <exception cref="System.ArgumentNullException">Thrown if identity argument passed in is null</exception>
/// <exception cref="System.ArgumentException">Thrown if identity argument passed in is empty string</exception>
public virtual bool Contains(string identity)
{
return ((MetadataCollection<T>)this.Items).ContainsIdentity(identity);
}
/// <summary>
/// Gets an item from the collection with the given identity
/// </summary>
/// <param name="identity">The identity of the item to search for</param>
/// <param name="ignoreCase">Whether case is ignored in the search</param>
/// <param name="item">An item from the collection, null if the item is not found</param>
/// <returns>True an item is retrieved</returns>
/// <exception cref="System.ArgumentNullException">if identity argument is null</exception>
public virtual bool TryGetValue(string identity, bool ignoreCase, out T item)
{
return ((MetadataCollection<T>)this.Items).TryGetValue(identity, ignoreCase, out item);
}
/// <summary>
/// Gets the enumerator over this collection
/// </summary>
/// <returns></returns>
public new Enumerator GetEnumerator()
{
return new Enumerator(this.Items);
}
/// <summary>
/// Workaround for bug
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public new virtual int IndexOf(T value)
{
return base.IndexOf(value);
}
#endregion
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Contoso.Provisioning.Hybrid.Web
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* 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 BlendVariableByte()
{
var test = new SimpleTernaryOpTest__BlendVariableByte();
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();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (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();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleTernaryOpTest__BlendVariableByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] inArray3, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Byte, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Byte> _fld1;
public Vector128<Byte> _fld2;
public Vector128<Byte> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (byte)(((i % 2) == 0) ? 128 : 1); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld3), ref Unsafe.As<Byte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__BlendVariableByte testClass)
{
var result = Sse41.BlendVariable(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__BlendVariableByte testClass)
{
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
fixed (Vector128<Byte>* pFld3 = &_fld3)
{
var result = Sse41.BlendVariable(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(pFld2)),
Sse2.LoadVector128((Byte*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Byte[] _data3 = new Byte[Op3ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private static Vector128<Byte> _clsVar3;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private Vector128<Byte> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__BlendVariableByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (byte)(((i % 2) == 0) ? 128 : 1); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar3), ref Unsafe.As<Byte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public SimpleTernaryOpTest__BlendVariableByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (byte)(((i % 2) == 0) ? 128 : 1); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld3), ref Unsafe.As<Byte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (byte)(((i % 2) == 0) ? 128 : 1); }
_dataTable = new DataTable(_data1, _data2, _data3, new Byte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.BlendVariable(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse41.BlendVariable(
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse41.BlendVariable(
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.BlendVariable(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Byte>* pClsVar1 = &_clsVar1)
fixed (Vector128<Byte>* pClsVar2 = &_clsVar2)
fixed (Vector128<Byte>* pClsVar3 = &_clsVar3)
{
var result = Sse41.BlendVariable(
Sse2.LoadVector128((Byte*)(pClsVar1)),
Sse2.LoadVector128((Byte*)(pClsVar2)),
Sse2.LoadVector128((Byte*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray3Ptr);
var result = Sse41.BlendVariable(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var op3 = Sse2.LoadVector128((Byte*)(_dataTable.inArray3Ptr));
var result = Sse41.BlendVariable(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr));
var op3 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray3Ptr));
var result = Sse41.BlendVariable(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__BlendVariableByte();
var result = Sse41.BlendVariable(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__BlendVariableByte();
fixed (Vector128<Byte>* pFld1 = &test._fld1)
fixed (Vector128<Byte>* pFld2 = &test._fld2)
fixed (Vector128<Byte>* pFld3 = &test._fld3)
{
var result = Sse41.BlendVariable(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(pFld2)),
Sse2.LoadVector128((Byte*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.BlendVariable(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
fixed (Vector128<Byte>* pFld3 = &_fld3)
{
var result = Sse41.BlendVariable(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(pFld2)),
Sse2.LoadVector128((Byte*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.BlendVariable(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse41.BlendVariable(
Sse2.LoadVector128((Byte*)(&test._fld1)),
Sse2.LoadVector128((Byte*)(&test._fld2)),
Sse2.LoadVector128((Byte*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, Vector128<Byte> op3, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] inArray3 = new Byte[Op3ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] inArray3 = new Byte[Op3ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Byte[] firstOp, Byte[] secondOp, Byte[] thirdOp, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (((thirdOp[0] >> 7) & 1) == 1 ? secondOp[0] != result[0] : firstOp[0] != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (((thirdOp[i] >> 7) & 1) == 1 ? secondOp[i] != result[i] : firstOp[i] != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.BlendVariable)}<Byte>(Vector128<Byte>, Vector128<Byte>, Vector128<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.DirectoryServices.Interop;
namespace System.DirectoryServices
{
/// <devdoc>
/// Holds a collection of values for a multi-valued property.
/// </devdoc>
public class PropertyValueCollection : CollectionBase
{
internal enum UpdateType
{
Add = 0,
Delete = 1,
Update = 2,
None = 3
}
private readonly DirectoryEntry _entry;
private UpdateType _updateType = UpdateType.None;
private readonly ArrayList _changeList = null;
private readonly bool _allowMultipleChange = false;
private readonly bool _needNewBehavior = false;
internal PropertyValueCollection(DirectoryEntry entry, string propertyName)
{
_entry = entry;
PropertyName = propertyName;
PopulateList();
ArrayList tempList = new ArrayList();
_changeList = ArrayList.Synchronized(tempList);
_allowMultipleChange = entry.allowMultipleChange;
string tempPath = entry.Path;
if (tempPath == null || tempPath.Length == 0)
{
// user does not specify path, so we bind to default naming context using LDAP provider.
_needNewBehavior = true;
}
else
{
if (tempPath.StartsWith("LDAP:", StringComparison.Ordinal))
_needNewBehavior = true;
}
}
public object this[int index]
{
get => List[index];
set
{
if (_needNewBehavior && !_allowMultipleChange)
throw new NotSupportedException();
else
{
List[index] = value;
}
}
}
public string PropertyName { get; }
public object Value
{
get
{
if (this.Count == 0)
return null;
else if (this.Count == 1)
return List[0];
else
{
object[] objectArray = new object[this.Count];
List.CopyTo(objectArray, 0);
return objectArray;
}
}
set
{
try
{
this.Clear();
}
catch (System.Runtime.InteropServices.COMException e)
{
if (e.ErrorCode != unchecked((int)0x80004005) || (value == null))
// WinNT provider throws E_FAIL when null value is specified though actually ADS_PROPERTY_CLEAR option is used, need to catch exception
// here. But at the same time we don't want to catch the exception if user explicitly sets the value to null.
throw;
}
if (value == null)
return;
// we could not do Clear and Add, we have to bypass the existing collection cache
_changeList.Clear();
if (value is Array)
{
// byte[] is a special case, we will follow what ADSI is doing, it must be an octet string. So treat it as a single valued attribute
if (value is byte[])
_changeList.Add(value);
else if (value is object[])
_changeList.AddRange((object[])value);
else
{
//Need to box value type array elements.
object[] objArray = new object[((Array)value).Length];
((Array)value).CopyTo(objArray, 0);
_changeList.AddRange((object[])objArray);
}
}
else
_changeList.Add(value);
object[] allValues = new object[_changeList.Count];
_changeList.CopyTo(allValues, 0);
_entry.AdsObject.PutEx((int)AdsPropertyOperation.Update, PropertyName, allValues);
_entry.CommitIfNotCaching();
// populate the new context
PopulateList();
}
}
/// <devdoc>
/// Appends the value to the set of values for this property.
/// </devdoc>
public int Add(object value) => List.Add(value);
/// <devdoc>
/// Appends the values to the set of values for this property.
/// </devdoc>
public void AddRange(object[] value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
for (int i = 0; ((i) < (value.Length)); i = ((i) + (1)))
{
this.Add(value[i]);
}
}
/// <devdoc>
/// Appends the values to the set of values for this property.
/// </devdoc>
public void AddRange(PropertyValueCollection value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
int currentCount = value.Count;
for (int i = 0; i < currentCount; i = ((i) + (1)))
{
this.Add(value[i]);
}
}
public bool Contains(object value) => List.Contains(value);
/// <devdoc>
/// Copies the elements of this instance into an <see cref='System.Array'/>,
/// starting at a particular index into the given <paramref name="array"/>.
/// </devdoc>
public void CopyTo(object[] array, int index)
{
List.CopyTo(array, index);
}
public int IndexOf(object value) => List.IndexOf(value);
public void Insert(int index, object value) => List.Insert(index, value);
private void PopulateList()
{
//No need to fill the cache here, when GetEx is calles, an implicit
//call to GetInfo will be called against an uninitialized property
//cache. Which is exactly what FillCache does.
//entry.FillCache(propertyName);
object var;
int unmanagedResult = _entry.AdsObject.GetEx(PropertyName, out var);
if (unmanagedResult != 0)
{
// property not found (IIS provider returns 0x80005006, other provides return 0x8000500D).
if ((unmanagedResult == unchecked((int)0x8000500D)) || (unmanagedResult == unchecked((int)0x80005006)))
{
return;
}
else
{
throw COMExceptionHelper.CreateFormattedComException(unmanagedResult);
}
}
if (var is ICollection)
InnerList.AddRange((ICollection)var);
else
InnerList.Add(var);
}
/// <devdoc>
/// Removes the value from the collection.
/// </devdoc>
public void Remove(object value)
{
if (_needNewBehavior)
{
try
{
List.Remove(value);
}
catch (ArgumentException)
{
// exception is thrown because value does not exist in the current cache, but it actually might do exist just because it is a very
// large multivalued attribute, the value has not been downloaded yet.
OnRemoveComplete(0, value);
}
}
else
List.Remove(value);
}
protected override void OnClearComplete()
{
if (_needNewBehavior && !_allowMultipleChange && _updateType != UpdateType.None && _updateType != UpdateType.Update)
{
throw new InvalidOperationException(SR.DSPropertyValueSupportOneOperation);
}
_entry.AdsObject.PutEx((int)AdsPropertyOperation.Clear, PropertyName, null);
_updateType = UpdateType.Update;
try
{
_entry.CommitIfNotCaching();
}
catch (System.Runtime.InteropServices.COMException e)
{
// On ADSI 2.5 if property has not been assigned any value before,
// then IAds::SetInfo() in CommitIfNotCaching returns bad HREsult 0x8007200A, which we ignore.
if (e.ErrorCode != unchecked((int)0x8007200A)) // ERROR_DS_NO_ATTRIBUTE_OR_VALUE
throw;
}
}
protected override void OnInsertComplete(int index, object value)
{
if (_needNewBehavior)
{
if (!_allowMultipleChange)
{
if (_updateType != UpdateType.None && _updateType != UpdateType.Add)
{
throw new InvalidOperationException(SR.DSPropertyValueSupportOneOperation);
}
_changeList.Add(value);
object[] allValues = new object[_changeList.Count];
_changeList.CopyTo(allValues, 0);
_entry.AdsObject.PutEx((int)AdsPropertyOperation.Append, PropertyName, allValues);
_updateType = UpdateType.Add;
}
else
{
_entry.AdsObject.PutEx((int)AdsPropertyOperation.Append, PropertyName, new object[] { value });
}
}
else
{
object[] allValues = new object[InnerList.Count];
InnerList.CopyTo(allValues, 0);
_entry.AdsObject.PutEx((int)AdsPropertyOperation.Update, PropertyName, allValues);
}
_entry.CommitIfNotCaching();
}
protected override void OnRemoveComplete(int index, object value)
{
if (_needNewBehavior)
{
if (!_allowMultipleChange)
{
if (_updateType != UpdateType.None && _updateType != UpdateType.Delete)
{
throw new InvalidOperationException(SR.DSPropertyValueSupportOneOperation);
}
_changeList.Add(value);
object[] allValues = new object[_changeList.Count];
_changeList.CopyTo(allValues, 0);
_entry.AdsObject.PutEx((int)AdsPropertyOperation.Delete, PropertyName, allValues);
_updateType = UpdateType.Delete;
}
else
{
_entry.AdsObject.PutEx((int)AdsPropertyOperation.Delete, PropertyName, new object[] { value });
}
}
else
{
object[] allValues = new object[InnerList.Count];
InnerList.CopyTo(allValues, 0);
_entry.AdsObject.PutEx((int)AdsPropertyOperation.Update, PropertyName, allValues);
}
_entry.CommitIfNotCaching();
}
protected override void OnSetComplete(int index, object oldValue, object newValue)
{
// no need to consider the not allowing accumulative change case as it does not support Set
if (Count <= 1)
{
_entry.AdsObject.Put(PropertyName, newValue);
}
else
{
if (_needNewBehavior)
{
_entry.AdsObject.PutEx((int)AdsPropertyOperation.Delete, PropertyName, new object[] { oldValue });
_entry.AdsObject.PutEx((int)AdsPropertyOperation.Append, PropertyName, new object[] { newValue });
}
else
{
object[] allValues = new object[InnerList.Count];
InnerList.CopyTo(allValues, 0);
_entry.AdsObject.PutEx((int)AdsPropertyOperation.Update, PropertyName, allValues);
}
}
_entry.CommitIfNotCaching();
}
}
}
| |
/*
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.Collections.Generic;
using System.Configuration;
using System.Runtime.Caching;
using Microsoft.Xrm.Client.Configuration;
namespace Microsoft.Xrm.Client.Caching
{
/// <summary>
/// Provides methods for managing <see cref="ObjectCache"/> items.
/// </summary>
/// <remarks>
/// The <see cref="ObjectCache"/> can be retrieved from configuration by name prior to performing further cache management operations.
/// <example>
/// An example of the configuration element used by the class.
/// <code>
/// <![CDATA[
/// <configuration>
/// <configSections>
/// <section name="microsoft.xrm.client" type="Microsoft.Xrm.Client.Configuration.CrmSection, Microsoft.Xrm.Client"/>
/// </configSections>
/// <microsoft.xrm.client>
/// <objectCache default="Xrm">
/// <add name="Xrm" type=type="System.Runtime.Caching.MemoryCache, System.Runtime.Caching, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
/// </objectCache>
/// </microsoft.xrm.client>
/// </configuration>
/// ]]>
/// </code>
/// </example>
/// </remarks>
public static class ObjectCacheManager
{
private static Lazy<ObjectCacheProvider> _provider = new Lazy<ObjectCacheProvider>(CreateProvider);
private static ObjectCacheProvider CreateProvider()
{
var section = CrmConfigurationManager.GetCrmSection();
if (!string.IsNullOrWhiteSpace(section.ObjectCacheProviderType))
{
var typeName = section.ObjectCacheProviderType;
var type = TypeExtensions.GetType(typeName);
if (type == null || !type.IsA<ObjectCacheProvider>())
{
throw new ConfigurationErrorsException("The value '{0}' is not recognized as a valid type or is not of the type '{1}'.".FormatWith(typeName, typeof(ObjectCacheProvider)));
}
return Activator.CreateInstance(type) as ObjectCacheProvider;
}
return new ObjectCacheProvider();
}
/// <summary>
/// Resets the cached dependencies.
/// </summary>
public static void Reset()
{
_provider = new Lazy<ObjectCacheProvider>(CreateProvider);
}
/// <summary>
/// Retrieves a configured <see cref="ObjectCache"/>.
/// </summary>
/// <param name="objectCacheName"></param>
/// <returns></returns>
public static ObjectCache GetInstance(string objectCacheName = null)
{
return _provider.Value.GetInstance(objectCacheName);
}
/// <summary>
/// Builds a <see cref="CacheItemPolicy"/> from a configuration element.
/// </summary>
/// <param name="objectCacheName"></param>
/// <returns></returns>
public static CacheItemPolicy GetCacheItemPolicy(string objectCacheName = null)
{
return _provider.Value.GetCacheItemPolicy(objectCacheName);
}
/// <summary>
/// Builds a <see cref="CacheItemPolicy"/> from a configuration element and adds a single <see cref="ChangeMonitor"/> to the policy.
/// </summary>
/// <param name="monitor"></param>
/// <param name="objectCacheName"></param>
/// <returns></returns>
public static CacheItemPolicy GetCacheItemPolicy(this ChangeMonitor monitor, string objectCacheName = null)
{
return _provider.Value.GetCacheItemPolicy(monitor, objectCacheName);
}
/// <summary>
/// Builds a <see cref="CacheItemPolicy"/> from a configuration element and adds a set of <see cref="CacheEntryChangeMonitor"/> objects.
/// </summary>
/// <param name="dependencies"></param>
/// <param name="regionName"></param>
/// <param name="objectCacheName"></param>
/// <returns></returns>
public static CacheItemPolicy GetCacheItemPolicy(IEnumerable<string> dependencies, string regionName = null, string objectCacheName = null)
{
return _provider.Value.GetCacheItemPolicy(dependencies, regionName, objectCacheName);
}
/// <summary>
/// Builds a <see cref="CacheItemPolicy"/> and adds a set of <see cref="CacheEntryChangeMonitor"/> objects to the policy.
/// </summary>
/// <param name="cache"></param>
/// <param name="dependencies"></param>
/// <param name="regionName"></param>
/// <param name="objectCacheName"></param>
/// <returns></returns>
public static CacheItemPolicy GetCacheItemPolicy(this ObjectCache cache, IEnumerable<string> dependencies, string regionName = null, string objectCacheName = null)
{
return _provider.Value.GetCacheItemPolicy(cache, dependencies, regionName, objectCacheName);
}
/// <summary>
/// Builds a <see cref="CacheEntryChangeMonitor"/> from a set of cache keys.
/// </summary>
/// <param name="cache"></param>
/// <param name="monitorKeys"></param>
/// <param name="regionName"></param>
/// <returns></returns>
public static CacheEntryChangeMonitor GetChangeMonitor(this ObjectCache cache, IEnumerable<string> monitorKeys, string regionName)
{
return _provider.Value.GetChangeMonitor(cache, monitorKeys, regionName);
}
/// <summary>
/// Retrieves a cached object or loads the object if it does not exist in cache.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cacheKey"></param>
/// <param name="load"></param>
/// <param name="insert"></param>
/// <param name="regionName"></param>
/// <returns></returns>
public static T Get<T>(
string cacheKey,
Func<ObjectCache, T> load,
Action<ObjectCache, T> insert,
string regionName = null)
{
return Get((string)null, cacheKey, load, insert, regionName);
}
/// <summary>
/// Retrieves a cached object or loads the object if it does not exist in cache.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="objectCacheName"></param>
/// <param name="cacheKey"></param>
/// <param name="load"></param>
/// <param name="insert"></param>
/// <param name="regionName"></param>
/// <returns></returns>
public static T Get<T>(
string objectCacheName,
string cacheKey,
Func<ObjectCache, T> load,
Action<ObjectCache, T> insert,
string regionName = null)
{
var cache = GetInstance(objectCacheName);
return cache.Get(cacheKey, load, insert, regionName);
}
/// <summary>
/// Retrieves a cached object or loads the object if it does not exist in cache.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cacheKey"></param>
/// <param name="load"></param>
/// <param name="getPolicy"></param>
/// <param name="regionName"></param>
/// <returns></returns>
public static T Get<T>(
string cacheKey,
Func<ObjectCache, T> load,
Func<CacheItemPolicy> getPolicy = null,
string regionName = null)
{
return Get((string)null, cacheKey, load, getPolicy, regionName);
}
/// <summary>
/// Retrieves a cached object or loads the object if it does not exist in cache.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="objectCacheName"></param>
/// <param name="cacheKey"></param>
/// <param name="load"></param>
/// <param name="getPolicy"></param>
/// <param name="regionName"></param>
/// <returns></returns>
public static T Get<T>(
string objectCacheName,
string cacheKey,
Func<ObjectCache, T> load,
Func<CacheItemPolicy> getPolicy = null,
string regionName = null)
{
var cache = GetInstance(objectCacheName);
var getPol = getPolicy ?? (() => GetCacheItemPolicy(objectCacheName));
return cache.Get(cacheKey, load, getPol, regionName);
}
/// <summary>
/// Retrieves a cached object or loads the object if it does not exist in cache.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cache"></param>
/// <param name="cacheKey"></param>
/// <param name="load"></param>
/// <param name="insert"></param>
/// <param name="regionName"></param>
/// <returns></returns>
public static T Get<T>(
this ObjectCache cache,
string cacheKey,
Func<ObjectCache, T> load,
Action<ObjectCache, T> insert,
string regionName = null)
{
return _provider.Value.Get(cache, cacheKey, load, insert, regionName);
}
/// <summary>
/// Retrieves a cached object or loads the object if it does not exist in cache.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cache"></param>
/// <param name="cacheKey"></param>
/// <param name="load"></param>
/// <param name="getPolicy"></param>
/// <param name="regionName"></param>
/// <returns></returns>
public static T Get<T>(
this ObjectCache cache,
string cacheKey,
Func<ObjectCache, T> load,
Func<CacheItemPolicy> getPolicy = null,
string regionName = null)
{
Action<ObjectCache, T> insert = (c, obj) =>
{
var policy = getPolicy != null ? getPolicy() : GetCacheItemPolicy(cache.Name);
c.Insert(cacheKey, obj, policy, regionName);
};
return Get(cache, cacheKey, load, insert);
}
/// <summary>
/// Inserts an object into cache along with an associated <see cref="CacheItemDetail"/>.
/// </summary>
/// <param name="cache"></param>
/// <param name="cacheKey"></param>
/// <param name="value"></param>
/// <param name="policy"></param>
/// <param name="regionName"></param>
public static void Insert(
this ObjectCache cache,
string cacheKey,
object value,
CacheItemPolicy policy = null,
string regionName = null)
{
_provider.Value.Insert(cache, cacheKey, value, policy, regionName);
}
/// <summary>
/// Inserts an object into cache along with an associated <see cref="CacheItemDetail"/>.
/// </summary>
/// <remarks>
/// The corresponding <see cref="CacheItemPolicy"/> is updated to include a <see cref="CacheEntryChangeMonitor"/> for each dependency string provided.
/// </remarks>
/// <param name="cache"></param>
/// <param name="cacheKey"></param>
/// <param name="value"></param>
/// <param name="dependencies"></param>
/// <param name="regionName"></param>
public static void Insert(
this ObjectCache cache,
string cacheKey,
object value,
IEnumerable<string> dependencies,
string regionName = null)
{
var policy = GetCacheItemPolicy(cache, dependencies, regionName);
cache.Insert(cacheKey, value, policy, regionName);
}
/// <summary>
/// Returns the <see cref="CacheItemDetail"/> object for the given cache item.
/// </summary>
/// <param name="cache">Target cache.</param>
/// <param name="cacheKey">Cache item's key.</param>
/// <param name="policy">Cache item's policy.</param>
/// <param name="regionName">Region name.</param>
public static CacheItemDetail CreateCacheItemDetailObject(this ObjectCache cache, string cacheKey, CacheItemPolicy policy, string regionName)
{
return _provider.Value.CreateCacheItemDetailObject(cache, cacheKey, policy, regionName);
}
/// <summary>
/// Retrieves the associated <see cref="CacheItemDetail"/> for a cache item.
/// </summary>
/// <param name="cache"></param>
/// <param name="cacheKey"></param>
/// <param name="regionName"></param>
/// <returns></returns>
public static CacheItemDetail GetCacheItemDetail(this ObjectCache cache, string cacheKey, string regionName = null)
{
return _provider.Value.GetCacheItemDetail(cache, cacheKey, regionName);
}
/// <summary>
/// Removes all items from the cache.
/// </summary>
/// <param name="cache"></param>
public static void Clear(this ObjectCache cache)
{
_provider.Value.Clear(cache);
}
/// <summary>
/// Removes all items from the cache by invoking the <see cref="IExtendedObjectCache"/> if it is available.
/// </summary>
/// <param name="cache"></param>
/// <param name="regionName"></param>
public static void RemoveAll(this ObjectCache cache, string regionName = null)
{
_provider.Value.RemoveAll(cache, regionName);
}
}
}
| |
// 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 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Store
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// FileSystemOperations operations.
/// </summary>
internal partial class FileSystemOperations : IServiceOperations<DataLakeStoreFileSystemManagementClient>, IFileSystemOperations
{
/// <summary>
/// Test the existence of a file or directory object specified by the file path.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations on.
/// </param>
/// <param name='getFilePath'>
/// The Data Lake Store path (starting with '/') of the file or directory for
/// which to test.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<bool>> PathExistsWithHttpMessagesAsync(string accountName, string getFilePath, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (this.Client.AdlsFileSystemDnsSuffix == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.AdlsFileSystemDnsSuffix");
}
if (getFilePath == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "getFilePath");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
string op = "GETFILESTATUS";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("getFilePath", getFilePath);
tracingParameters.Add("op", op);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetFileStatus", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "webhdfs/v1/{getFilePath}";
_url = _url.Replace("{accountName}", accountName);
_url = _url.Replace("{adlsFileSystemDnsSuffix}", this.Client.AdlsFileSystemDnsSuffix);
_url = _url.Replace("{getFilePath}", Uri.EscapeDataString(getFilePath));
List<string> _queryParameters = new List<string>();
if (op != null)
{
_queryParameters.Add(string.Format("op={0}", Uri.EscapeDataString(op)));
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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 (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)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new AdlsErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
AdlsError _errorBody = SafeJsonConvert.DeserializeObject<AdlsError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
// there is only one exception in case in which we will return false and not throw,
// which is when the exception returned is a FileNotFoundException
if(ex.Body.RemoteException is AdlsFileNotFoundException)
{
var _toReturn = new AzureOperationResponse<bool>();
_toReturn.Request = _httpRequest;
_toReturn.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_toReturn.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// the file or folder does not exist
_toReturn.Body = false;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _toReturn);
}
return _toReturn;
}
}
}
catch (JsonException)
{
// Ignore the exception if the response can't be parsed,
// to ensure the original error is thrown with request/response information
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<bool>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_result.Body = true;
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections;
using System.Collections.Generic;
namespace Apache.NMS.Stomp.State
{
public class AtomicCollection<TValue>
where TValue : class
{
private readonly ArrayList _collection = new ArrayList();
public AtomicCollection()
{
}
public AtomicCollection(ICollection c)
{
lock(c.SyncRoot)
{
foreach(object obj in c)
{
_collection.Add(obj);
}
}
}
public int Count
{
get
{
lock(_collection.SyncRoot)
{
return _collection.Count;
}
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public int Add(TValue v)
{
lock(_collection.SyncRoot)
{
return _collection.Add(v);
}
}
public void Clear()
{
lock(_collection.SyncRoot)
{
_collection.Clear();
}
}
public bool Contains(TValue v)
{
lock(_collection.SyncRoot)
{
return _collection.Contains(v);
}
}
public void CopyTo(TValue[] a, int index)
{
lock(_collection.SyncRoot)
{
_collection.CopyTo(a, index);
}
}
public void Remove(TValue v)
{
lock(_collection.SyncRoot)
{
_collection.Remove(v);
}
}
public void RemoveAt(int index)
{
lock(_collection.SyncRoot)
{
_collection.RemoveAt(index);
}
}
public TValue this[int index]
{
get
{
TValue ret;
lock(_collection.SyncRoot)
{
ret = (TValue) _collection[index];
}
return (TValue) ret;
}
set
{
lock(_collection.SyncRoot)
{
_collection[index] = value;
}
}
}
public IEnumerator GetEnumerator()
{
lock(_collection.SyncRoot)
{
return _collection.GetEnumerator();
}
}
#if !NETCF
public IEnumerator GetEnumerator(int index, int count)
{
lock(_collection.SyncRoot)
{
return _collection.GetEnumerator(index, count);
}
}
#endif
}
public class AtomicDictionary<TKey, TValue>
where TKey : class
where TValue : class
{
private readonly Dictionary<TKey, TValue> _dictionary = new Dictionary<TKey, TValue>();
public void Clear()
{
_dictionary.Clear();
}
public TValue this[TKey key]
{
get
{
TValue ret;
lock(((ICollection) _dictionary).SyncRoot)
{
ret = _dictionary[key];
}
return ret;
}
set
{
lock(((ICollection) _dictionary).SyncRoot)
{
_dictionary[key] = value;
}
}
}
public bool TryGetValue(TKey key, out TValue val)
{
lock(((ICollection) _dictionary).SyncRoot)
{
return _dictionary.TryGetValue(key, out val);
}
}
public AtomicCollection<TKey> Keys
{
get
{
lock(((ICollection) _dictionary).SyncRoot)
{
return new AtomicCollection<TKey>(_dictionary.Keys);
}
}
}
public AtomicCollection<TValue> Values
{
get
{
lock(((ICollection) _dictionary).SyncRoot)
{
return new AtomicCollection<TValue>(_dictionary.Values);
}
}
}
public void Add(TKey k, TValue v)
{
lock(((ICollection) _dictionary).SyncRoot)
{
_dictionary.Add(k, v);
}
}
public bool Remove(TKey v)
{
lock(((ICollection) _dictionary).SyncRoot)
{
return _dictionary.Remove(v);
}
}
public bool ContainsKey(TKey k)
{
lock(((ICollection) _dictionary).SyncRoot)
{
return _dictionary.ContainsKey(k);
}
}
public bool ContainsValue(TValue v)
{
lock(((ICollection) _dictionary).SyncRoot)
{
return _dictionary.ContainsValue(v);
}
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// G07_RegionColl (editable child list).<br/>
/// This is a generated base class of <see cref="G07_RegionColl"/> business object.
/// </summary>
/// <remarks>
/// This class is child of <see cref="G06_Country"/> editable child object.<br/>
/// The items of the collection are <see cref="G08_Region"/> objects.
/// </remarks>
[Serializable]
public partial class G07_RegionColl : BusinessListBase<G07_RegionColl, G08_Region>
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="G08_Region"/> item from the collection.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to be removed.</param>
public void Remove(int region_ID)
{
foreach (var g08_Region in this)
{
if (g08_Region.Region_ID == region_ID)
{
Remove(g08_Region);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="G08_Region"/> item is in the collection.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to search for.</param>
/// <returns><c>true</c> if the G08_Region is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int region_ID)
{
foreach (var g08_Region in this)
{
if (g08_Region.Region_ID == region_ID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="G08_Region"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to search for.</param>
/// <returns><c>true</c> if the G08_Region is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int region_ID)
{
foreach (var g08_Region in DeletedList)
{
if (g08_Region.Region_ID == region_ID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="G08_Region"/> item of the <see cref="G07_RegionColl"/> collection, based on a given Region_ID.
/// </summary>
/// <param name="region_ID">The Region_ID.</param>
/// <returns>A <see cref="G08_Region"/> object.</returns>
public G08_Region FindG08_RegionByRegion_ID(int region_ID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].Region_ID.Equals(region_ID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="G07_RegionColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="G07_RegionColl"/> collection.</returns>
internal static G07_RegionColl NewG07_RegionColl()
{
return DataPortal.CreateChild<G07_RegionColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="G07_RegionColl"/> collection, based on given parameters.
/// </summary>
/// <param name="parent_Country_ID">The Parent_Country_ID parameter of the G07_RegionColl to fetch.</param>
/// <returns>A reference to the fetched <see cref="G07_RegionColl"/> collection.</returns>
internal static G07_RegionColl GetG07_RegionColl(int parent_Country_ID)
{
return DataPortal.FetchChild<G07_RegionColl>(parent_Country_ID);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="G07_RegionColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public G07_RegionColl()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="G07_RegionColl"/> collection from the database, based on given criteria.
/// </summary>
/// <param name="parent_Country_ID">The Parent Country ID.</param>
protected void Child_Fetch(int parent_Country_ID)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetG07_RegionColl", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Parent_Country_ID", parent_Country_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, parent_Country_ID);
OnFetchPre(args);
LoadCollection(cmd);
OnFetchPost(args);
}
}
foreach (var item in this)
{
item.FetchChildren();
}
}
private void LoadCollection(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
Fetch(dr);
}
}
/// <summary>
/// Loads all <see cref="G07_RegionColl"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
while (dr.Read())
{
Add(G08_Region.GetG08_Region(dr));
}
RaiseListChangedEvents = rlce;
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
using NUnit.Framework;
using SJP.Schematic.Core;
namespace SJP.Schematic.DataAccess.Tests
{
[TestFixture]
internal static class SnakeCaseNameTranslatorTests
{
[Test]
public static void SchemaToNamespace_GivenNullName_ThrowsArgumentNullException()
{
var nameTranslator = new SnakeCaseNameTranslator();
Assert.That(() => nameTranslator.SchemaToNamespace(null), Throws.ArgumentNullException);
}
[Test]
public static void SchemaToNamespace_GivenNullSchema_ReturnsNull()
{
var nameTranslator = new SnakeCaseNameTranslator();
var testName = new Identifier("test");
var result = nameTranslator.SchemaToNamespace(testName);
Assert.That(result, Is.Null);
}
[Test]
public static void SchemaToNamespace_GivenSpaceSeparatedSchemaName_ReturnsSpaceRemovedText()
{
var nameTranslator = new SnakeCaseNameTranslator();
var testName = new Identifier("first second", "test");
const string expected = "firstsecond";
var result = nameTranslator.SchemaToNamespace(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void SchemaToNamespace_GivenUnderscoreSeparatedSchemaName_ReturnsSnakeCasedText()
{
var nameTranslator = new SnakeCaseNameTranslator();
var testName = new Identifier("first_second", "test");
const string expected = "first_second";
var result = nameTranslator.SchemaToNamespace(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void SchemaToNamespace_GivenCamelCasedSchemaName_ReturnsSnakeCasedText()
{
var nameTranslator = new SnakeCaseNameTranslator();
var testName = new Identifier("FirstSecond", "test");
const string expected = "first_second";
var result = nameTranslator.SchemaToNamespace(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void TableToClassName_GivenNullName_ThrowsArgumentNullException()
{
var nameTranslator = new SnakeCaseNameTranslator();
Assert.That(() => nameTranslator.TableToClassName(null), Throws.ArgumentNullException);
}
[Test]
public static void TableToClassName_GivenSpaceSeparatedLocalName_ReturnsSpaceRemovedText()
{
var nameTranslator = new SnakeCaseNameTranslator();
var testName = new Identifier("first second");
const string expected = "firstsecond";
var result = nameTranslator.TableToClassName(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void TableToClassName_GivenCamelCasedSchemaName_ReturnsSnakeCasedText()
{
var nameTranslator = new SnakeCaseNameTranslator();
var testName = new Identifier("firstSecond");
const string expected = "first_second";
var result = nameTranslator.TableToClassName(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void TableToClassName_GivenPascalCasedSchemaName_ReturnsSnakeCasedText()
{
var nameTranslator = new SnakeCaseNameTranslator();
var testName = new Identifier("FirstSecond");
const string expected = "first_second";
var result = nameTranslator.TableToClassName(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void ViewToClassName_GivenNullName_ThrowsArgumentNullException()
{
var nameTranslator = new SnakeCaseNameTranslator();
Assert.That(() => nameTranslator.ViewToClassName(null), Throws.ArgumentNullException);
}
[Test]
public static void ViewToClassName_GivenSpaceSeparatedLocalName_ReturnsSpaceRemovedText()
{
var nameTranslator = new SnakeCaseNameTranslator();
var testName = new Identifier("first second");
const string expected = "firstsecond";
var result = nameTranslator.ViewToClassName(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void ViewToClassName_GivenCamelCaseSchemaName_ReturnsSnakeCasedText()
{
var nameTranslator = new SnakeCaseNameTranslator();
var testName = new Identifier("first_second");
const string expected = "first_second";
var result = nameTranslator.ViewToClassName(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void ViewToClassName_GivenCamelCasedSchemaName_ReturnsSnakeCasedText()
{
var nameTranslator = new SnakeCaseNameTranslator();
var testName = new Identifier("FirstSecond");
const string expected = "first_second";
var result = nameTranslator.ViewToClassName(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void ColumnToPropertyName_GivenNullClassName_ThrowsArgumentNullException()
{
const string columnName = "test";
var nameTranslator = new SnakeCaseNameTranslator();
Assert.That(() => nameTranslator.ColumnToPropertyName(null, columnName), Throws.ArgumentNullException);
}
[Test]
public static void ColumnToPropertyName_GivenEmptyClassName_ThrowsArgumentNullException()
{
const string columnName = "test";
var nameTranslator = new SnakeCaseNameTranslator();
Assert.That(() => nameTranslator.ColumnToPropertyName(string.Empty, columnName), Throws.ArgumentNullException);
}
[Test]
public static void ColumnToPropertyName_GivenWhiteSpaceClassName_ThrowsArgumentNullException()
{
const string columnName = "test";
var nameTranslator = new SnakeCaseNameTranslator();
Assert.That(() => nameTranslator.ColumnToPropertyName(" ", columnName), Throws.ArgumentNullException);
}
[Test]
public static void ColumnToPropertyName_GivenNullColumnName_ThrowsArgumentNullException()
{
const string className = "test";
var nameTranslator = new SnakeCaseNameTranslator();
Assert.That(() => nameTranslator.ColumnToPropertyName(className, null), Throws.ArgumentNullException);
}
[Test]
public static void ColumnToPropertyName_GivenEmptyColumnName_ThrowsArgumentNullException()
{
const string className = "test";
var nameTranslator = new SnakeCaseNameTranslator();
Assert.That(() => nameTranslator.ColumnToPropertyName(className, string.Empty), Throws.ArgumentNullException);
}
[Test]
public static void ColumnToPropertyName_GivenWhiteSpaceColumnName_ThrowsArgumentNullException()
{
const string className = "test";
var nameTranslator = new SnakeCaseNameTranslator();
Assert.That(() => nameTranslator.ColumnToPropertyName(className, " "), Throws.ArgumentNullException);
}
[Test]
public static void ColumnToPropertyName_GivenSpaceSeparatedSchemaName_ReturnsSpaceRemovedText()
{
var nameTranslator = new SnakeCaseNameTranslator();
const string className = "test";
const string testName = "first second";
const string expected = "firstsecond";
var result = nameTranslator.ColumnToPropertyName(className, testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void ColumnToPropertyName_GivenSnakeCasedClassName_ReturnsSnakeCasedText()
{
var nameTranslator = new SnakeCaseNameTranslator();
const string className = "test";
const string testName = "first_second";
const string expected = "first_second";
var result = nameTranslator.ColumnToPropertyName(className, testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void ColumnToPropertyName_GivenPascalCasedColumnName_ReturnsSnakeCasedText()
{
var nameTranslator = new SnakeCaseNameTranslator();
const string className = "test";
const string testName = "FirstSecond";
const string expected = "first_second";
var result = nameTranslator.ColumnToPropertyName(className, testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void ColumnToPropertyName_GivenTransformedNameMatchingClassName_ReturnsUnderscoreAppendedColumnName()
{
var nameTranslator = new SnakeCaseNameTranslator();
const string className = "first_second";
const string testName = "firstSecond";
const string expected = "first_second_";
var result = nameTranslator.ColumnToPropertyName(className, testName);
Assert.That(result, Is.EqualTo(expected));
}
}
}
| |
/* ====================================================================
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 TestCases.SS.UserModel;
using System;
using NUnit.Framework;
using NPOI.SS.UserModel;
using NPOI.OpenXml4Net.OPC;
namespace NPOI.XSSF.UserModel
{
[TestFixture]
public class TestXSSFHyperlink : BaseTestHyperlink
{
public TestXSSFHyperlink()
: base(XSSFITestDataProvider.instance)
{
}
[SetUp]
public void SetUp()
{
// Use system out logger
Environment.SetEnvironmentVariable(
"NPOI.util.POILogger",
"NPOI.util.SystemOutLogger"
);
}
[Test]
public void TestLoadExisting()
{
XSSFWorkbook workbook = XSSFTestDataSamples.OpenSampleWorkbook("WithMoreVariousData.xlsx");
Assert.AreEqual(3, workbook.NumberOfSheets);
XSSFSheet sheet = (XSSFSheet)workbook.GetSheetAt(0);
// Check the hyperlinks
Assert.AreEqual(4, sheet.NumHyperlinks);
doTestHyperlinkContents(sheet);
}
[Test]
public void TestCreate()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.CreateSheet() as XSSFSheet;
XSSFRow row = sheet.CreateRow(0) as XSSFRow;
XSSFCreationHelper CreateHelper = workbook.GetCreationHelper() as XSSFCreationHelper;
String[] urls = {
"http://apache.org/",
"www.apache.org",
"/temp",
"file:///c:/temp",
"http://apache.org/default.php?s=isTramsformed&submit=Search&la=*&li=*"};
for (int i = 0; i < urls.Length; i++)
{
String s = urls[i];
XSSFHyperlink link = CreateHelper.CreateHyperlink(HyperlinkType.Url) as XSSFHyperlink;
link.Address=(s);
XSSFCell cell = row.CreateCell(i) as XSSFCell;
cell.Hyperlink=(link);
}
workbook = XSSFTestDataSamples.WriteOutAndReadBack(workbook) as XSSFWorkbook;
sheet = workbook.GetSheetAt(0) as XSSFSheet;
PackageRelationshipCollection rels = sheet.GetPackagePart().Relationships;
Assert.AreEqual(urls.Length, rels.Size);
for (int i = 0; i < rels.Size; i++)
{
PackageRelationship rel = rels.GetRelationship(i);
if (rel.TargetUri.IsAbsoluteUri&&rel.TargetUri.IsFile)
Assert.AreEqual(urls[i].Replace("file:///","").Replace("/","\\"),rel.TargetUri.LocalPath);
else
// there should be a relationship for each URL
Assert.AreEqual(urls[i], rel.TargetUri.ToString());
}
// Bugzilla 53041: Hyperlink relations are duplicated when saving XSSF file
workbook = XSSFTestDataSamples.WriteOutAndReadBack(workbook) as XSSFWorkbook;
sheet = workbook.GetSheetAt(0) as XSSFSheet;
rels = sheet.GetPackagePart().Relationships;
Assert.AreEqual(urls.Length, rels.Size);
for (int i = 0; i < rels.Size; i++)
{
PackageRelationship rel = rels.GetRelationship(i);
if (rel.TargetUri.IsAbsoluteUri && rel.TargetUri.IsFile)
Assert.AreEqual(urls[i].Replace("file:///", "").Replace("/", "\\"), rel.TargetUri.LocalPath);
else
// there should be a relationship for each URL
Assert.AreEqual(urls[i], rel.TargetUri.ToString());
}
}
[Test]
public void TestInvalidURLs()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFCreationHelper CreateHelper = workbook.GetCreationHelper() as XSSFCreationHelper;
String[] invalidURLs = {
"http:\\apache.org",
"www.apache .org",
"c:\\temp",
"\\poi"};
foreach (String s in invalidURLs)
{
try
{
CreateHelper.CreateHyperlink(HyperlinkType.Url).Address = (s);
Assert.Fail("expected ArgumentException: " + s);
}
catch (ArgumentException)
{
}
}
}
[Test]
public void TestLoadSave()
{
XSSFWorkbook workbook = XSSFTestDataSamples.OpenSampleWorkbook("WithMoreVariousData.xlsx");
ICreationHelper CreateHelper = workbook.GetCreationHelper();
Assert.AreEqual(3, workbook.NumberOfSheets);
XSSFSheet sheet = (XSSFSheet)workbook.GetSheetAt(0);
// Check hyperlinks
Assert.AreEqual(4, sheet.NumHyperlinks);
doTestHyperlinkContents(sheet);
// Write out, and check
// Load up again, check all links still there
XSSFWorkbook wb2 = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(workbook);
Assert.AreEqual(3, wb2.NumberOfSheets);
Assert.IsNotNull(wb2.GetSheetAt(0));
Assert.IsNotNull(wb2.GetSheetAt(1));
Assert.IsNotNull(wb2.GetSheetAt(2));
sheet = (XSSFSheet)wb2.GetSheetAt(0);
// Check hyperlinks again
Assert.AreEqual(4, sheet.NumHyperlinks);
doTestHyperlinkContents(sheet);
// Add one more, and re-check
IRow r17 = sheet.CreateRow(17);
ICell r17c = r17.CreateCell(2);
IHyperlink hyperlink = CreateHelper.CreateHyperlink(HyperlinkType.Url);
hyperlink.Address = ("http://poi.apache.org/spreadsheet/");
hyperlink.Label = "POI SS Link";
r17c.Hyperlink=(hyperlink);
Assert.AreEqual(5, sheet.NumHyperlinks);
doTestHyperlinkContents(sheet);
Assert.AreEqual(HyperlinkType.Url,
sheet.GetRow(17).GetCell(2).Hyperlink.Type);
Assert.AreEqual("POI SS Link",
sheet.GetRow(17).GetCell(2).Hyperlink.Label);
Assert.AreEqual("http://poi.apache.org/spreadsheet/",
sheet.GetRow(17).GetCell(2).Hyperlink.Address);
// Save and re-load once more
XSSFWorkbook wb3 = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(wb2);
Assert.AreEqual(3, wb3.NumberOfSheets);
Assert.IsNotNull(wb3.GetSheetAt(0));
Assert.IsNotNull(wb3.GetSheetAt(1));
Assert.IsNotNull(wb3.GetSheetAt(2));
sheet = (XSSFSheet)wb3.GetSheetAt(0);
Assert.AreEqual(5, sheet.NumHyperlinks);
doTestHyperlinkContents(sheet);
Assert.AreEqual(HyperlinkType.Url,
sheet.GetRow(17).GetCell(2).Hyperlink.Type);
Assert.AreEqual("POI SS Link",
sheet.GetRow(17).GetCell(2).Hyperlink.Label);
Assert.AreEqual("http://poi.apache.org/spreadsheet/",
sheet.GetRow(17).GetCell(2).Hyperlink.Address);
}
/**
* Only for WithMoreVariousData.xlsx !
*/
private static void doTestHyperlinkContents(XSSFSheet sheet)
{
Assert.IsNotNull(sheet.GetRow(3).GetCell(2).Hyperlink);
Assert.IsNotNull(sheet.GetRow(14).GetCell(2).Hyperlink);
Assert.IsNotNull(sheet.GetRow(15).GetCell(2).Hyperlink);
Assert.IsNotNull(sheet.GetRow(16).GetCell(2).Hyperlink);
// First is a link to poi
Assert.AreEqual(HyperlinkType.Url,
sheet.GetRow(3).GetCell(2).Hyperlink.Type);
Assert.AreEqual(null,
sheet.GetRow(3).GetCell(2).Hyperlink.Label);
Assert.AreEqual("http://poi.apache.org/",
sheet.GetRow(3).GetCell(2).Hyperlink.Address);
// Next is an internal doc link
Assert.AreEqual(HyperlinkType.Document,
sheet.GetRow(14).GetCell(2).Hyperlink.Type);
Assert.AreEqual("Internal hyperlink to A2",
sheet.GetRow(14).GetCell(2).Hyperlink.Label);
Assert.AreEqual("Sheet1!A2",
sheet.GetRow(14).GetCell(2).Hyperlink.Address);
// Next is a file
Assert.AreEqual(HyperlinkType.File,
sheet.GetRow(15).GetCell(2).Hyperlink.Type);
Assert.AreEqual(null,
sheet.GetRow(15).GetCell(2).Hyperlink.Label);
Assert.AreEqual("WithVariousData.xlsx",
sheet.GetRow(15).GetCell(2).Hyperlink.Address);
// Last is a mailto
Assert.AreEqual(HyperlinkType.Email,
sheet.GetRow(16).GetCell(2).Hyperlink.Type);
Assert.AreEqual(null,
sheet.GetRow(16).GetCell(2).Hyperlink.Label);
Assert.AreEqual("mailto:dev@poi.apache.org?subject=XSSF Hyperlinks",
sheet.GetRow(16).GetCell(2).Hyperlink.Address);
}
[Test]
public void Test52716()
{
XSSFWorkbook wb1 = XSSFTestDataSamples.OpenSampleWorkbook("52716.xlsx");
XSSFSheet sh1 = wb1.GetSheetAt(0) as XSSFSheet;
XSSFWorkbook wb2 = XSSFTestDataSamples.WriteOutAndReadBack(wb1) as XSSFWorkbook;
XSSFSheet sh2 = wb2.GetSheetAt(0) as XSSFSheet;
Assert.AreEqual(sh1.NumberOfComments, sh2.NumberOfComments);
XSSFHyperlink l1 = sh1.GetHyperlink(0, 1);
Assert.AreEqual(HyperlinkType.Document, l1.Type);
Assert.AreEqual("B1", l1.GetCellRef());
Assert.AreEqual("Sort on Titel", l1.Tooltip);
XSSFHyperlink l2 = sh2.GetHyperlink(0, 1);
Assert.AreEqual(l1.Tooltip, l2.Tooltip);
Assert.AreEqual(HyperlinkType.Document, l2.Type);
Assert.AreEqual("B1", l2.GetCellRef());
}
[Test]
public void Test53734()
{
XSSFWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("53734.xlsx");
XSSFHyperlink link = wb.GetSheetAt(0).GetRow(0).GetCell(0).Hyperlink as XSSFHyperlink;
Assert.AreEqual("javascript:///", link.Address);
wb = XSSFTestDataSamples.WriteOutAndReadBack(wb) as XSSFWorkbook;
link = wb.GetSheetAt(0).GetRow(0).GetCell(0).Hyperlink as XSSFHyperlink;
Assert.AreEqual("javascript:///", link.Address);
}
[Test]
public void Test53282()
{
//since limitation in .NET Uri class, it's impossible to accept uri like mailto:nobody@nowhere.uk%C2%A0
XSSFWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("53282.xlsx");
XSSFHyperlink link = wb.GetSheetAt(0).GetRow(0).GetCell(14).Hyperlink as XSSFHyperlink;
Assert.AreEqual("mailto:nobody@nowhere.uk%C2%A0", link.Address);
wb = XSSFTestDataSamples.WriteOutAndReadBack(wb) as XSSFWorkbook;
link = wb.GetSheetAt(0).GetRow(0).GetCell(14).Hyperlink as XSSFHyperlink;
Assert.AreEqual("mailto:nobody@nowhere.uk%C2%A0", link.Address);
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Microsoft.DotNet.InternalAbstractions;
using Microsoft.DotNet.ProjectModel.Graph;
using Microsoft.DotNet.ProjectModel.Resolution;
using NuGet.Frameworks;
namespace Microsoft.DotNet.ProjectModel
{
public class ProjectContextBuilder
{
// Note: When adding a property, make sure to add it to Clone below. You'll also need to update the CloneTest in
// Microsoft.DotNet.ProjectModel.Tests.ProjectContextBuilderTests
private Project Project { get; set; }
private LockFile LockFile { get; set; }
private NuGetFramework TargetFramework { get; set; }
private IEnumerable<string> RuntimeIdentifiers { get; set; } = Enumerable.Empty<string>();
private string RootDirectory { get; set; }
private string ProjectDirectory { get; set; }
private string PackagesDirectory { get; set; }
private string ReferenceAssembliesPath { get; set; }
private bool IsDesignTime { get; set; }
private Func<string, Project> ProjectResolver { get; set; }
private Func<string, LockFile> LockFileResolver { get; set; }
private ProjectReaderSettings ProjectReaderSettings { get; set; } = ProjectReaderSettings.ReadFromEnvironment();
public ProjectContextBuilder()
{
ProjectResolver = ResolveProject;
LockFileResolver = ResolveLockFile;
}
public ProjectContextBuilder Clone()
{
var builder = new ProjectContextBuilder()
.WithLockFile(LockFile)
.WithProject(Project)
.WithProjectDirectory(ProjectDirectory)
.WithTargetFramework(TargetFramework)
.WithRuntimeIdentifiers(RuntimeIdentifiers)
.WithReferenceAssembliesPath(ReferenceAssembliesPath)
.WithPackagesDirectory(PackagesDirectory)
.WithRootDirectory(RootDirectory)
.WithProjectResolver(ProjectResolver)
.WithLockFileResolver(LockFileResolver)
.WithProjectReaderSettings(ProjectReaderSettings);
if (IsDesignTime)
{
builder.AsDesignTime();
}
return builder;
}
public ProjectContextBuilder WithLockFile(LockFile lockFile)
{
LockFile = lockFile;
return this;
}
public ProjectContextBuilder WithProject(Project project)
{
Project = project;
return this;
}
public ProjectContextBuilder WithProjectDirectory(string projectDirectory)
{
ProjectDirectory = projectDirectory;
return this;
}
public ProjectContextBuilder WithTargetFramework(NuGetFramework targetFramework)
{
TargetFramework = targetFramework;
return this;
}
public ProjectContextBuilder WithTargetFramework(string targetFramework)
{
TargetFramework = NuGetFramework.Parse(targetFramework);
return this;
}
public ProjectContextBuilder WithRuntimeIdentifiers(IEnumerable<string> runtimeIdentifiers)
{
RuntimeIdentifiers = runtimeIdentifiers;
return this;
}
public ProjectContextBuilder WithReferenceAssembliesPath(string referenceAssembliesPath)
{
ReferenceAssembliesPath = referenceAssembliesPath;
return this;
}
public ProjectContextBuilder WithPackagesDirectory(string packagesDirectory)
{
PackagesDirectory = packagesDirectory;
return this;
}
public ProjectContextBuilder WithRootDirectory(string rootDirectory)
{
RootDirectory = rootDirectory;
return this;
}
public ProjectContextBuilder WithProjectResolver(Func<string, Project> projectResolver)
{
ProjectResolver = projectResolver;
return this;
}
public ProjectContextBuilder WithLockFileResolver(Func<string, LockFile> lockFileResolver)
{
LockFileResolver = lockFileResolver;
return this;
}
public ProjectContextBuilder WithProjectReaderSettings(ProjectReaderSettings projectReaderSettings)
{
ProjectReaderSettings = projectReaderSettings;
return this;
}
public ProjectContextBuilder AsDesignTime()
{
IsDesignTime = true;
return this;
}
/// <summary>
/// Produce all targets found in the lock file associated with this builder.
/// Returns an empty enumerable if there is no lock file
/// (making this unsuitable for scenarios where the lock file may not be present,
/// such as at design-time)
/// </summary>
/// <returns></returns>
public IEnumerable<ProjectContext> BuildAllTargets()
{
ProjectDirectory = Project?.ProjectDirectory ?? ProjectDirectory;
EnsureProjectLoaded();
LockFile = LockFile ?? LockFileResolver(ProjectDirectory);
if (LockFile != null)
{
var deduper = new HashSet<string>();
foreach (var target in LockFile.Targets)
{
var context = Clone()
.WithTargetFramework(target.TargetFramework)
.WithRuntimeIdentifiers(new[] { target.RuntimeIdentifier }).Build();
var id = $"{context.TargetFramework}/{context.RuntimeIdentifier}";
if (deduper.Add(id))
{
yield return context;
}
}
}
else
{
// Build a context for each framework. It won't be fully valid, since it won't have resolved data or runtime data, but the diagnostics will show that.
foreach (var framework in Project.GetTargetFrameworks())
{
var builder = new ProjectContextBuilder()
.WithProject(Project)
.WithTargetFramework(framework.FrameworkName);
if (IsDesignTime)
{
builder.AsDesignTime();
}
yield return builder.Build();
}
}
}
public ProjectContext Build()
{
var diagnostics = new List<DiagnosticMessage>();
ProjectDirectory = Project?.ProjectDirectory ?? ProjectDirectory;
GlobalSettings globalSettings = null;
if (ProjectDirectory != null)
{
RootDirectory = ProjectRootResolver.ResolveRootDirectory(ProjectDirectory);
GlobalSettings.TryGetGlobalSettings(RootDirectory, out globalSettings);
}
RootDirectory = globalSettings?.DirectoryPath ?? RootDirectory;
PackagesDirectory = PackagesDirectory ?? PackageDependencyProvider.ResolvePackagesPath(RootDirectory, globalSettings);
FrameworkReferenceResolver frameworkReferenceResolver;
if (string.IsNullOrEmpty(ReferenceAssembliesPath))
{
// Use the default static resolver
frameworkReferenceResolver = FrameworkReferenceResolver.Default;
}
else
{
frameworkReferenceResolver = new FrameworkReferenceResolver(ReferenceAssembliesPath);
}
LockFileLookup lockFileLookup = null;
EnsureProjectLoaded();
ReadLockFile(diagnostics);
var validLockFile = true;
string lockFileValidationMessage = null;
if (LockFile != null)
{
if (Project != null)
{
validLockFile = LockFile.IsValidForProject(Project, out lockFileValidationMessage);
}
lockFileLookup = new LockFileLookup(LockFile);
}
var libraries = new Dictionary<LibraryKey, LibraryDescription>();
var projectResolver = new ProjectDependencyProvider(ProjectResolver);
ProjectDescription mainProject = null;
if (Project != null)
{
mainProject = projectResolver.GetDescription(TargetFramework, Project, targetLibrary: null);
// Add the main project
libraries.Add(new LibraryKey(mainProject.Identity.Name), mainProject);
}
LibraryRange? platformDependency = null;
if (mainProject != null)
{
platformDependency = mainProject.Dependencies
.Where(d => d.Type.Equals(LibraryDependencyType.Platform))
.Cast<LibraryRange?>()
.FirstOrDefault();
}
bool isPortable = platformDependency != null;
LockFileTarget target = null;
LibraryDescription platformLibrary = null;
if (lockFileLookup != null)
{
target = SelectTarget(LockFile, isPortable);
if (target != null)
{
var nugetPackageResolver = new PackageDependencyProvider(PackagesDirectory, frameworkReferenceResolver);
var msbuildProjectResolver = new MSBuildDependencyProvider(Project, ProjectResolver);
ScanLibraries(target, lockFileLookup, libraries, msbuildProjectResolver, nugetPackageResolver, projectResolver);
if (platformDependency != null)
{
libraries.TryGetValue(new LibraryKey(platformDependency.Value.Name), out platformLibrary);
}
}
}
string runtime = target?.RuntimeIdentifier;
if (string.IsNullOrEmpty(runtime) && TargetFramework.IsDesktop())
{
// we got a ridless target for desktop so turning portable mode on
isPortable = true;
var legacyRuntime = RuntimeEnvironmentRidExtensions.GetLegacyRestoreRuntimeIdentifier();
if (RuntimeIdentifiers.Contains(legacyRuntime))
{
runtime = legacyRuntime;
}
else
{
runtime = RuntimeIdentifiers.FirstOrDefault();
}
}
var referenceAssemblyDependencyResolver = new ReferenceAssemblyDependencyResolver(frameworkReferenceResolver);
bool requiresFrameworkAssemblies;
// Resolve the dependencies
ResolveDependencies(libraries, referenceAssemblyDependencyResolver, out requiresFrameworkAssemblies);
// REVIEW: Should this be in NuGet (possibly stored in the lock file?)
if (LockFile == null)
{
diagnostics.Add(new DiagnosticMessage(
ErrorCodes.NU1009,
$"The expected lock file doesn't exist. Please run \"dotnet restore\" to generate a new lock file.",
Path.Combine(Project.ProjectDirectory, LockFile.FileName),
DiagnosticMessageSeverity.Error));
}
if (!validLockFile)
{
diagnostics.Add(new DiagnosticMessage(
ErrorCodes.NU1006,
$"{lockFileValidationMessage}. Please run \"dotnet restore\" to generate a new lock file.",
Path.Combine(Project.ProjectDirectory, LockFile.FileName),
DiagnosticMessageSeverity.Warning));
}
if (requiresFrameworkAssemblies)
{
var frameworkInfo = Project.GetTargetFramework(TargetFramework);
if (frameworkReferenceResolver == null || string.IsNullOrEmpty(frameworkReferenceResolver.ReferenceAssembliesPath))
{
// If there was an attempt to use reference assemblies but they were not installed
// report an error
diagnostics.Add(new DiagnosticMessage(
ErrorCodes.DOTNET1012,
$"The reference assemblies directory was not specified. You can set the location using the DOTNET_REFERENCE_ASSEMBLIES_PATH environment variable.",
filePath: Project.ProjectFilePath,
severity: DiagnosticMessageSeverity.Error,
startLine: frameworkInfo.Line,
startColumn: frameworkInfo.Column
));
}
else if (!frameworkReferenceResolver.IsInstalled(TargetFramework))
{
// If there was an attempt to use reference assemblies but they were not installed
// report an error
diagnostics.Add(new DiagnosticMessage(
ErrorCodes.DOTNET1011,
$"Framework not installed: {TargetFramework.DotNetFrameworkName} in {ReferenceAssembliesPath}",
filePath: Project.ProjectFilePath,
severity: DiagnosticMessageSeverity.Error,
startLine: frameworkInfo.Line,
startColumn: frameworkInfo.Column
));
}
}
List<DiagnosticMessage> allDiagnostics = new List<DiagnosticMessage>(diagnostics);
if (Project != null)
{
allDiagnostics.AddRange(Project.Diagnostics);
}
// Create a library manager
var libraryManager = new LibraryManager(libraries.Values.ToList(), allDiagnostics, Project?.ProjectFilePath);
return new ProjectContext(
globalSettings,
mainProject,
platformLibrary,
TargetFramework,
isPortable,
runtime,
PackagesDirectory,
libraryManager,
LockFile,
diagnostics);
}
private void ReadLockFile(ICollection<DiagnosticMessage> diagnostics)
{
try
{
LockFile = LockFile ?? LockFileResolver(ProjectDirectory);
}
catch (FileFormatException e)
{
var lockFilePath = "";
if (LockFile != null)
{
lockFilePath = LockFile.LockFilePath;
}
else if (Project != null)
{
lockFilePath = Path.Combine(Project.ProjectDirectory, LockFile.FileName);
}
diagnostics.Add(new DiagnosticMessage(
ErrorCodes.DOTNET1014,
ComposeMessageFromInnerExceptions(e),
lockFilePath,
DiagnosticMessageSeverity.Error));
}
}
private static string ComposeMessageFromInnerExceptions(Exception exception)
{
var sb = new StringBuilder();
var messages = new HashSet<string>();
while (exception != null)
{
messages.Add(exception.Message);
exception = exception.InnerException;
}
foreach (var message in messages)
{
sb.AppendLine(message);
}
return sb.ToString();
}
private void ResolveDependencies(Dictionary<LibraryKey, LibraryDescription> libraries,
ReferenceAssemblyDependencyResolver referenceAssemblyDependencyResolver,
out bool requiresFrameworkAssemblies)
{
// Remark: the LibraryType in the key of the given dictionary are all "Unspecified" at the beginning.
requiresFrameworkAssemblies = false;
foreach (var pair in libraries.ToList())
{
var library = pair.Value;
// The System.* packages provide placeholders on any non netstandard platform
// To make them work seamlessly on those platforms, we fill the gap with a reference
// assembly (if available)
var package = library as PackageDescription;
if (package != null &&
package.Resolved &&
package.HasCompileTimePlaceholder &&
!TargetFramework.IsPackageBased)
{
// requiresFrameworkAssemblies is true whenever we find a CompileTimePlaceholder in a non-package based framework, even if
// the reference is unresolved. This ensures the best error experience when someone is building on a machine without
// the target framework installed.
requiresFrameworkAssemblies = true;
var newKey = new LibraryKey(library.Identity.Name, LibraryType.ReferenceAssembly);
var dependency = new LibraryRange(library.Identity.Name, LibraryType.ReferenceAssembly);
var replacement = referenceAssemblyDependencyResolver.GetDescription(dependency, TargetFramework);
// If the reference is unresolved, just skip it. Don't replace the package dependency
if (replacement == null)
{
continue;
}
// Remove the original package reference
libraries.Remove(pair.Key);
// Insert a reference assembly key if there isn't one
if (!libraries.ContainsKey(newKey))
{
libraries[newKey] = replacement;
}
}
}
foreach (var pair in libraries.ToList())
{
var library = pair.Value;
library.Framework = library.Framework ?? TargetFramework;
foreach (var dependency in library.Dependencies)
{
var keyType = dependency.Target == LibraryType.ReferenceAssembly ?
LibraryType.ReferenceAssembly :
LibraryType.Unspecified;
var key = new LibraryKey(dependency.Name, keyType);
LibraryDescription dependencyDescription;
if (!libraries.TryGetValue(key, out dependencyDescription))
{
if (keyType == LibraryType.ReferenceAssembly)
{
// a dependency is specified to be reference assembly but fail to match
// then add a unresolved dependency
dependencyDescription = referenceAssemblyDependencyResolver.GetDescription(dependency, TargetFramework) ??
UnresolvedDependencyProvider.GetDescription(dependency, TargetFramework);
libraries[key] = dependencyDescription;
}
else if (!libraries.TryGetValue(new LibraryKey(dependency.Name, LibraryType.ReferenceAssembly), out dependencyDescription))
{
// a dependency which type is unspecified fails to match, then try to find a
// reference assembly type dependency
dependencyDescription = UnresolvedDependencyProvider.GetDescription(dependency, TargetFramework);
libraries[key] = dependencyDescription;
}
}
dependencyDescription.RequestedRanges.Add(dependency);
dependencyDescription.Parents.Add(library);
}
}
// Deduplicate libraries with the same name
// Priority list is backwards so not found -1 would be last when sorting by descending
var priorities = new[] { LibraryType.Package, LibraryType.Project, LibraryType.ReferenceAssembly };
var nameGroups = libraries.Keys.ToLookup(libraryKey => libraryKey.Name);
foreach (var nameGroup in nameGroups)
{
var librariesToRemove = nameGroup
.OrderByDescending(libraryKey => Array.IndexOf(priorities, libraryKey.LibraryType))
.Skip(1);
foreach (var library in librariesToRemove)
{
libraries.Remove(library);
}
}
}
private void ScanLibraries(LockFileTarget target,
LockFileLookup lockFileLookup,
Dictionary<LibraryKey, LibraryDescription> libraries,
MSBuildDependencyProvider msbuildResolver,
PackageDependencyProvider packageResolver,
ProjectDependencyProvider projectResolver)
{
foreach (var library in target.Libraries)
{
LibraryDescription description = null;
var type = LibraryType.Unspecified;
if (string.Equals(library.Type, "project"))
{
var projectLibrary = lockFileLookup.GetProject(library.Name);
if (projectLibrary != null)
{
if (MSBuildDependencyProvider.IsMSBuildProjectLibrary(projectLibrary))
{
description = msbuildResolver.GetDescription(TargetFramework, projectLibrary, library, IsDesignTime);
type = LibraryType.MSBuildProject;
}
else
{
var path = Path.GetFullPath(Path.Combine(ProjectDirectory, projectLibrary.Path));
description = projectResolver.GetDescription(library.Name, path, library, ProjectResolver);
type = LibraryType.Project;
}
}
}
else
{
var packageEntry = lockFileLookup.GetPackage(library.Name, library.Version);
if (packageEntry != null)
{
description = packageResolver.GetDescription(TargetFramework, packageEntry, library);
}
type = LibraryType.Package;
}
description = description ?? UnresolvedDependencyProvider.GetDescription(new LibraryRange(library.Name, type), target.TargetFramework);
libraries.Add(new LibraryKey(library.Name), description);
}
}
private void EnsureProjectLoaded()
{
if (Project == null && ProjectDirectory != null)
{
Project = ProjectResolver(ProjectDirectory);
if (Project == null)
{
throw new InvalidOperationException($"Could not resolve project at: {ProjectDirectory}. " +
$"This could happen when project.lock.json was moved after restore.");
}
}
}
private LockFileTarget SelectTarget(LockFile lockFile, bool isPortable)
{
if (!isPortable)
{
foreach (var runtimeIdentifier in RuntimeIdentifiers)
{
foreach (var scanTarget in lockFile.Targets)
{
if (Equals(scanTarget.TargetFramework, TargetFramework) && string.Equals(scanTarget.RuntimeIdentifier, runtimeIdentifier, StringComparison.Ordinal))
{
return scanTarget;
}
}
}
}
foreach (var scanTarget in lockFile.Targets)
{
if (Equals(scanTarget.TargetFramework, TargetFramework) && string.IsNullOrEmpty(scanTarget.RuntimeIdentifier))
{
return scanTarget;
}
}
return null;
}
private Project ResolveProject(string projectDirectory)
{
Project project;
if (ProjectReader.TryGetProject(projectDirectory, out project, settings: ProjectReaderSettings))
{
return project;
}
else
{
return null;
}
}
private static LockFile ResolveLockFile(string projectDir)
{
var projectLockJsonPath = Path.Combine(projectDir, LockFile.FileName);
return File.Exists(projectLockJsonPath) ?
LockFileReader.Read(Path.Combine(projectDir, LockFile.FileName), designTime: false) :
null;
}
private struct LibraryKey
{
public LibraryKey(string name) : this(name, LibraryType.Unspecified)
{
}
public LibraryKey(string name, LibraryType libraryType)
{
Name = name;
LibraryType = libraryType;
}
public string Name { get; }
public LibraryType LibraryType { get; }
public override bool Equals(object obj)
{
var otherKey = (LibraryKey)obj;
return string.Equals(otherKey.Name, Name, StringComparison.Ordinal) &&
otherKey.LibraryType.Equals(LibraryType);
}
public override int GetHashCode()
{
var combiner = new HashCodeCombiner();
combiner.Add(Name);
combiner.Add(LibraryType);
return combiner.CombinedHash;
}
public override string ToString()
{
return Name + " " + LibraryType;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.Globalization;
namespace System.Management
{
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
/// <summary>
/// <para> Contains information about a WMI qualifier.</para>
/// </summary>
/// <example>
/// <code lang='C#'>using System;
/// using System.Management;
///
/// // This sample demonstrates how to enumerate qualifiers
/// // of a ManagementClass object.
/// class Sample_QualifierData
/// {
/// public static int Main(string[] args) {
/// ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
/// diskClass.Options.UseAmendedQualifiers = true;
/// QualifierData diskQualifier = diskClass.Qualifiers["Description"];
/// Console.WriteLine(diskQualifier.Name + " = " + diskQualifier.Value);
/// return 0;
/// }
/// }
/// </code>
/// <code lang='VB'>Imports System
/// Imports System.Management
///
/// ' This sample demonstrates how to enumerate qualifiers
/// ' of a ManagementClass object.
/// Class Sample_QualifierData
/// Overloads Public Shared Function Main(args() As String) As Integer
/// Dim diskClass As New ManagementClass("win32_logicaldisk")
/// diskClass.Options.UseAmendedQualifiers = True
/// Dim diskQualifier As QualifierData = diskClass.Qualifiers("Description")
/// Console.WriteLine(diskQualifier.Name + " = " + diskQualifier.Value)
/// Return 0
/// End Function
/// End Class
/// </code>
/// </example>
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
public class QualifierData
{
private readonly ManagementBaseObject parent; //need access to IWbemClassObject pointer to be able to refresh qualifiers
private readonly string propertyOrMethodName; //remains null for object qualifiers
private readonly string qualifierName;
private readonly QualifierType qualifierType;
private object qualifierValue;
private int qualifierFlavor;
private IWbemQualifierSetFreeThreaded qualifierSet;
internal QualifierData(ManagementBaseObject parent, string propName, string qualName, QualifierType type)
{
this.parent = parent;
this.propertyOrMethodName = propName;
this.qualifierName = qualName;
this.qualifierType = type;
RefreshQualifierInfo();
}
//This private function is used to refresh the information from the Wmi object before returning the requested data
private void RefreshQualifierInfo()
{
qualifierSet = null;
int status = qualifierType switch
{
QualifierType.ObjectQualifier => parent.wbemObject.GetQualifierSet_(out qualifierSet),
QualifierType.PropertyQualifier => parent.wbemObject.GetPropertyQualifierSet_(propertyOrMethodName, out qualifierSet),
QualifierType.MethodQualifier => parent.wbemObject.GetMethodQualifierSet_(propertyOrMethodName, out qualifierSet),
_ => throw new ManagementException(ManagementStatus.Unexpected, null, null), //is this the best fit error ??
};
if ((status & 0x80000000) == 0) //success
{
qualifierValue = null; //Make sure it's null so that we don't leak !
if (qualifierSet != null)
status = qualifierSet.Get_(qualifierName, 0, ref qualifierValue, ref qualifierFlavor);
}
if ((status & 0xfffff000) == 0x80041000) //WMI error
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else if ((status & 0x80000000) != 0) //any failure
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
private static object MapQualValueToWmiValue(object qualVal)
{
object wmiValue = System.DBNull.Value;
if (null != qualVal)
{
if (qualVal is Array)
{
if ((qualVal is int[]) || (qualVal is double[]) || (qualVal is string[]) || (qualVal is bool[]))
wmiValue = qualVal;
else
{
Array valArray = (Array)qualVal;
int length = valArray.Length;
Type elementType = (length > 0 ? valArray.GetValue(0).GetType() : null);
if (elementType == typeof(int))
{
wmiValue = new int[length];
for (int i = 0; i < length; i++)
((int[])(wmiValue))[i] = Convert.ToInt32(valArray.GetValue(i), (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(int)));
}
else if (elementType == typeof(double))
{
wmiValue = new double[length];
for (int i = 0; i < length; i++)
((double[])(wmiValue))[i] = Convert.ToDouble(valArray.GetValue(i), (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(double)));
}
else if (elementType == typeof(string))
{
wmiValue = new string[length];
for (int i = 0; i < length; i++)
((string[])(wmiValue))[i] = (valArray.GetValue(i)).ToString();
}
else if (elementType == typeof(bool))
{
wmiValue = new bool[length];
for (int i = 0; i < length; i++)
((bool[])(wmiValue))[i] = Convert.ToBoolean(valArray.GetValue(i), (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(bool)));
}
else
wmiValue = valArray; //should this throw ?
}
}
else
wmiValue = qualVal;
}
return wmiValue;
}
/// <summary>
/// <para>Represents the name of the qualifier.</para>
/// </summary>
/// <value>
/// <para>The name of the qualifier.</para>
/// </value>
public string Name
{
get { return qualifierName != null ? qualifierName : ""; }
}
/// <summary>
/// <para>Gets or sets the value of the qualifier.</para>
/// </summary>
/// <value>
/// <para>The value of the qualifier.</para>
/// </value>
/// <remarks>
/// <para> Qualifiers can only be of the following subset of CIM
/// types: <see langword='string'/>, <see langword='uint16'/>,
/// <see langword='uint32'/>, <see langword='sint32'/>, <see langword='uint64'/>,
/// <see langword='sint64'/>, <see langword='real32'/>, <see langword='real64'/>,
/// <see langword='bool'/>.
/// </para>
/// </remarks>
public object Value
{
get
{
RefreshQualifierInfo();
return ValueTypeSafety.GetSafeObject(qualifierValue);
}
set
{
int status = (int)ManagementStatus.NoError;
RefreshQualifierInfo();
object newValue = MapQualValueToWmiValue(value);
status = qualifierSet.Put_(qualifierName, ref newValue,
qualifierFlavor & ~(int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_MASK_ORIGIN);
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else if ((status & 0x80000000) != 0)
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
/// <summary>
/// <para> Gets or sets a value indicating whether the qualifier is amended.</para>
/// </summary>
/// <value>
/// <para><see langword='true'/> if this qualifier is amended;
/// otherwise, <see langword='false'/>.</para>
/// </value>
/// <remarks>
/// <para> Amended qualifiers are
/// qualifiers whose value can be localized through WMI. Localized qualifiers
/// reside in separate namespaces in WMI and can be merged into the basic class
/// definition when retrieved.</para>
/// </remarks>
public bool IsAmended
{
get
{
RefreshQualifierInfo();
return ((int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_MASK_AMENDED ==
(qualifierFlavor & (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_AMENDED));
}
set
{
int status = (int)ManagementStatus.NoError;
RefreshQualifierInfo();
// Mask out origin bits
int flavor = qualifierFlavor & ~(int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_MASK_ORIGIN;
if (value)
flavor |= (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_AMENDED;
else
flavor &= ~(int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_AMENDED;
status = qualifierSet.Put_(qualifierName, ref qualifierValue, flavor);
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else if ((status & 0x80000000) != 0)
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
/// <summary>
/// <para>Gets or sets a value indicating whether the qualifier has been defined locally on
/// this class or has been propagated from a base class.</para>
/// </summary>
/// <value>
/// <para><see langword='true'/> if the qualifier has been defined
/// locally on this class; otherwise, <see langword='false'/>. </para>
/// </value>
public bool IsLocal
{
get
{
RefreshQualifierInfo();
return ((int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_ORIGIN_LOCAL ==
(qualifierFlavor & (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_MASK_ORIGIN));
}
}
/// <summary>
/// <para>Gets or sets a value indicating whether the qualifier should be propagated to instances of the
/// class.</para>
/// </summary>
/// <value>
/// <para><see langword='true'/> if this qualifier should be
/// propagated to instances of the class; otherwise, <see langword='false'/>.</para>
/// </value>
public bool PropagatesToInstance
{
get
{
RefreshQualifierInfo();
return ((int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_FLAG_PROPAGATE_TO_INSTANCE ==
(qualifierFlavor & (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_FLAG_PROPAGATE_TO_INSTANCE));
}
set
{
int status = (int)ManagementStatus.NoError;
RefreshQualifierInfo();
// Mask out origin bits
int flavor = qualifierFlavor & ~(int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_MASK_ORIGIN;
if (value)
flavor |= (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_FLAG_PROPAGATE_TO_INSTANCE;
else
flavor &= ~(int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_FLAG_PROPAGATE_TO_INSTANCE;
status = qualifierSet.Put_(qualifierName, ref qualifierValue, flavor);
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else if ((status & 0x80000000) != 0)
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
/// <summary>
/// <para>Gets or sets a value indicating whether the qualifier should be propagated to
/// subclasses of the class.</para>
/// </summary>
/// <value>
/// <para><see langword='true'/> if the qualifier should be
/// propagated to subclasses of this class; otherwise, <see langword='false'/>.</para>
/// </value>
public bool PropagatesToSubclass
{
get
{
RefreshQualifierInfo();
return ((int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_FLAG_PROPAGATE_TO_DERIVED_CLASS ==
(qualifierFlavor & (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_FLAG_PROPAGATE_TO_DERIVED_CLASS));
}
set
{
int status = (int)ManagementStatus.NoError;
RefreshQualifierInfo();
// Mask out origin bits
int flavor = qualifierFlavor & ~(int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_MASK_ORIGIN;
if (value)
flavor |= (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_FLAG_PROPAGATE_TO_DERIVED_CLASS;
else
flavor &= ~(int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_FLAG_PROPAGATE_TO_DERIVED_CLASS;
status = qualifierSet.Put_(qualifierName, ref qualifierValue, flavor);
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else if ((status & 0x80000000) != 0)
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
/// <summary>
/// <para>Gets or sets a value indicating whether the value of the qualifier can be
/// overridden when propagated.</para>
/// </summary>
/// <value>
/// <para><see langword='true'/> if the value of the qualifier
/// can be overridden when propagated; otherwise, <see langword='false'/>.</para>
/// </value>
public bool IsOverridable
{
get
{
RefreshQualifierInfo();
return ((int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_OVERRIDABLE ==
(qualifierFlavor & (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_MASK_PERMISSIONS));
}
set
{
int status = (int)ManagementStatus.NoError;
RefreshQualifierInfo();
// Mask out origin bits
int flavor = qualifierFlavor & ~(int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_MASK_ORIGIN;
if (value)
flavor &= ~(int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_NOT_OVERRIDABLE;
else
flavor |= (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_NOT_OVERRIDABLE;
status = qualifierSet.Put_(qualifierName, ref qualifierValue, flavor);
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else if ((status & 0x80000000) != 0)
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
}//QualifierData
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using MongoDB.Connections;
using MongoDB.Protocol;
using MongoDB.Serialization;
using System.Linq;
using MongoDB.Util;
using MongoDB.Configuration.Mapping;
namespace MongoDB
{
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
public class Cursor<T> : ICursor<T> where T : class
{
private readonly Connection _connection;
private readonly string _databaseName;
private readonly Document _specOpts = new Document();
private object _spec;
private object _fields;
private int _limit;
private QueryOptions _options;
private ReplyMessage<T> _reply;
private int _skip;
private bool _keepCursor;
private readonly ISerializationFactory _serializationFactory;
private readonly IMappingStore _mappingStore;
/// <summary>
/// Initializes a new instance of the <see cref="Cursor<T>"/> class.
/// </summary>
/// <param name="serializationFactory">The serialization factory.</param>
/// <param name="mappingStore">The mapping store.</param>
/// <param name="connection">The conn.</param>
/// <param name="databaseName">Name of the database.</param>
/// <param name="collectionName">Name of the collection.</param>
internal Cursor(ISerializationFactory serializationFactory, IMappingStore mappingStore, Connection connection, string databaseName, string collectionName)
{
//Todo: add public constrcutor for users to call
IsModifiable = true;
_connection = connection;
_databaseName = databaseName;
FullCollectionName = databaseName + "." + collectionName;
_serializationFactory = serializationFactory;
_mappingStore = mappingStore;
}
/// <summary>
/// Initializes a new instance of the <see cref="Cursor<T>"/> class.
/// </summary>
/// <param name="serializationFactory">The serialization factory.</param>
/// <param name="mappingStore">The mapping store.</param>
/// <param name="connection">The conn.</param>
/// <param name="databaseName">Name of the database.</param>
/// <param name="collectionName">Name of the collection.</param>
/// <param name="spec">The spec.</param>
/// <param name="limit">The limit.</param>
/// <param name="skip">The skip.</param>
/// <param name="fields">The fields.</param>
internal Cursor(ISerializationFactory serializationFactory, IMappingStore mappingStore, Connection connection, string databaseName, string collectionName, object spec, int limit, int skip, object fields)
: this(serializationFactory, mappingStore, connection, databaseName, collectionName)
{
//Todo: add public constrcutor for users to call
if (spec == null)
spec = new Document();
_spec = spec;
_limit = limit;
_skip = skip;
_fields = fields;
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the
/// <see cref="Cursor<T>"/> is reclaimed by garbage collection.
/// </summary>
~Cursor(){
Dispose(false);
}
/// <summary>
/// Gets or sets the full name of the collection.
/// </summary>
/// <value>The full name of the collection.</value>
public string FullCollectionName { get; private set; }
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
public long Id { get; private set; }
/// <summary>
/// Specs the specified spec.
/// </summary>
/// <param name="spec">The spec.</param>
/// <returns></returns>
public ICursor<T> Spec(object spec){
TryModify();
_spec = spec;
return this;
}
/// <summary>
/// Limits the specified limit.
/// </summary>
/// <param name="limit">The limit.</param>
/// <returns></returns>
public ICursor<T> Limit(int limit){
TryModify();
_limit = limit;
return this;
}
/// <summary>
/// Skips the specified skip.
/// </summary>
/// <param name="skip">The skip.</param>
/// <returns></returns>
public ICursor<T> Skip(int skip){
TryModify();
_skip = skip;
return this;
}
/// <summary>
/// Fieldses the specified fields.
/// </summary>
/// <param name="fields">The fields.</param>
/// <returns></returns>
public ICursor<T> Fields(object fields){
TryModify();
_fields = fields;
return this;
}
/// <summary>
/// Sorts the specified field.
/// </summary>
/// <param name = "field">The field.</param>
/// <returns></returns>
public ICursor<T> Sort(string field){
return Sort(field, IndexOrder.Ascending);
}
/// <summary>
/// Sorts the specified field.
/// </summary>
/// <param name = "field">The field.</param>
/// <param name = "order">The order.</param>
/// <returns></returns>
public ICursor<T> Sort(string field, IndexOrder order){
return Sort(new Document().Add(field, order));
}
/// <summary>
/// Sorts the specified fields.
/// </summary>
/// <param name="fields">The fields.</param>
/// <returns></returns>
public ICursor<T> Sort(object fields){
TryModify();
AddOrRemoveSpecOpt("$orderby", fields);
return this;
}
/// <summary>
/// Hints the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <returns></returns>
public ICursor<T> Hint(object index){
TryModify();
AddOrRemoveSpecOpt("$hint", index);
return this;
}
/// <summary>
/// Keeps the cursor open.
/// </summary>
/// <param name="value">if set to <c>true</c> [value].</param>
/// <returns></returns>
/// <remarks>
/// By default cursors are closed automaticly after documents
/// are Enumerated.
/// </remarks>
public ICursor<T> KeepCursor(bool value)
{
_keepCursor = value;
return this;
}
/// <summary>
/// Snapshots the specified index.
/// </summary>
public ICursor<T> Snapshot(){
TryModify();
AddOrRemoveSpecOpt("$snapshot", true);
return this;
}
/// <summary>
/// Explains this instance.
/// </summary>
/// <returns></returns>
public Document Explain(){
TryModify();
_specOpts["$explain"] = true;
var explainResult = RetrieveData<Document>();
try
{
var explain = explainResult.Documents.FirstOrDefault();
if(explain==null)
throw new InvalidOperationException("Explain failed. No documents where returned.");
return explain;
}
finally
{
if(explainResult.CursorId > 0)
KillCursor(explainResult.CursorId);
}
}
/// <summary>
/// Gets a value indicating whether this <see cref = "Cursor<T>" /> is modifiable.
/// </summary>
/// <value><c>true</c> if modifiable; otherwise, <c>false</c>.</value>
public bool IsModifiable { get; private set; }
/// <summary>
/// Gets the documents.
/// </summary>
/// <value>The documents.</value>
public IEnumerable<T> Documents {
get {
do
{
_reply = RetrieveData<T>();
if(_reply == null)
throw new InvalidOperationException("Expecting reply but get null");
foreach(var document in _reply.Documents)
yield return document;
}
while(Id > 0 && _limit<CursorPosition);
if(!_keepCursor)
Dispose(true);
}
}
/// <summary>
/// Gets the cursor position.
/// </summary>
/// <value>The cursor position.</value>
public int CursorPosition
{
get
{
if(_reply == null)
return 0;
return _reply.StartingFrom + _reply.NumberReturned;
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if(Id == 0 || !_connection.IsConnected) //All server side resources disposed of.
return;
KillCursor(Id);
}
/// <summary>
/// Optionses the specified options.
/// </summary>
/// <param name = "options">The options.</param>
/// <returns></returns>
public ICursor<T> Options(QueryOptions options){
TryModify();
_options = options;
return this;
}
/// <summary>
/// Kills the cursor.
/// </summary>
private void KillCursor(long cursorId)
{
var killCursorsMessage = new KillCursorsMessage(cursorId);
try {
_connection.SendMessage(killCursorsMessage,_databaseName);
Id = 0;
} catch (IOException exception) {
throw new MongoConnectionException("Could not read data, communication failure", _connection, exception);
}
}
/// <summary>
/// Retrieves the data.
/// </summary>
/// <typeparam name="TReply">The type of the reply.</typeparam>
/// <returns></returns>
private ReplyMessage<TReply> RetrieveData<TReply>() where TReply : class
{
IsModifiable = false;
IRequestMessage message;
if(Id <= 0)
{
var writerSettings = _serializationFactory.GetBsonWriterSettings(typeof(T));
message = new QueryMessage(writerSettings)
{
FullCollectionName = FullCollectionName,
Query = BuildSpec(),
NumberToReturn = _limit,
NumberToSkip = _skip,
Options = _options,
ReturnFieldSelector = ConvertFieldSelectorToDocument(_fields)
};
}
else
{
message = new GetMoreMessage(FullCollectionName, Id, _limit);
}
var readerSettings = _serializationFactory.GetBsonReaderSettings(typeof(T));
try
{
var reply = _connection.SendTwoWayMessage<TReply>(message, readerSettings, _databaseName);
Id = reply.CursorId;
return reply;
}
catch(IOException exception)
{
throw new MongoConnectionException("Could not read data, communication failure", _connection, exception);
}
}
/// <summary>
/// Tries the modify.
/// </summary>
private void TryModify(){
if(!IsModifiable)
throw new InvalidOperationException("Cannot modify a cursor that has already returned documents.");
}
/// <summary>
/// Adds the or remove spec opt.
/// </summary>
/// <param name = "key">The key.</param>
/// <param name = "doc">The doc.</param>
private void AddOrRemoveSpecOpt(string key, object doc){
if (doc == null)
_specOpts.Remove(key);
else
_specOpts[key] = doc;
}
/// <summary>
/// Builds the spec.
/// </summary>
/// <returns></returns>
private object BuildSpec(){
if (_specOpts.Count == 0)
return _spec;
var document = new Document();
_specOpts.CopyTo(document);
document["$query"] = _spec;
return document;
}
private Document ConvertFieldSelectorToDocument(object document)
{
Document doc;
if (document == null)
doc = new Document();
else
doc = ConvertExampleToDocument(document) as Document;
if (doc == null)
throw new NotSupportedException("An entity type is not supported in field selection. Use either a document or an anonymous type.");
var classMap = _mappingStore.GetClassMap(typeof(T));
if (doc.Count > 0 && (classMap.IsPolymorphic || classMap.IsSubClass))
doc[classMap.DiscriminatorAlias] = true;
return doc.Count == 0 ? null : doc;
}
private object ConvertExampleToDocument(object document)
{
if (document == null)
return null;
Document doc = document as Document;
if (doc != null)
return doc;
doc = new Document();
if (!(document is T)) //some type that is being used as an example
{
foreach (var prop in document.GetType().GetProperties())
{
if (!prop.CanRead)
continue;
object value = prop.GetValue(document, null);
if (!TypeHelper.IsNativeToMongo(prop.PropertyType))
value = ConvertExampleToDocument(value);
doc[prop.Name] = value;
}
}
return doc;
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.SecurityTokenService;
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 JDP.Remediation.Console
{
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 (RequestFailedException)
{
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
SecondaryClientSecret,
authorizationCode,
redirectUri,
resource);
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
else
{
throw;
}
}
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 (RequestFailedException)
{
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, SecondaryClientSecret, refreshToken, resource);
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
else
{
throw;
}
}
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 (RequestFailedException)
{
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, SecondaryClientSecret, resource);
oauth2Request.Resource = resource;
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
else
{
throw;
}
}
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
}
}
| |
using System;
using System.Collections.Generic;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
namespace Avalonia.Media
{
public sealed class DrawingContext : IDisposable
{
private int _currentLevel;
static readonly Stack<Stack<PushedState>> StateStackPool = new Stack<Stack<PushedState>>();
static readonly Stack<Stack<TransformContainer>> TransformStackPool = new Stack<Stack<TransformContainer>>();
private Stack<PushedState> _states = StateStackPool.Count == 0 ? new Stack<PushedState>() : StateStackPool.Pop();
private Stack<TransformContainer> _transformContainers = TransformStackPool.Count == 0
? new Stack<TransformContainer>()
: TransformStackPool.Pop();
struct TransformContainer
{
public readonly Matrix LocalTransform;
public readonly Matrix ContainerTransform;
public TransformContainer(Matrix localTransform, Matrix containerTransform)
{
LocalTransform = localTransform;
ContainerTransform = containerTransform;
}
}
public DrawingContext(IDrawingContextImpl impl)
{
PlatformImpl = impl;
}
public IDrawingContextImpl PlatformImpl { get; }
private Matrix _currentTransform = Matrix.Identity;
private Matrix _currentContainerTransform = Matrix.Identity;
/// <summary>
/// Gets the current transform of the drawing context.
/// </summary>
public Matrix CurrentTransform
{
get { return _currentTransform; }
private set
{
_currentTransform = value;
var transform = _currentTransform * _currentContainerTransform;
PlatformImpl.Transform = transform;
}
}
//HACK: This is a temporary hack that is used in the render loop
//to update TransformedBounds property
[Obsolete("HACK for render loop, don't use")]
internal Matrix CurrentContainerTransform => _currentContainerTransform;
/// <summary>
/// Draws a bitmap image.
/// </summary>
/// <param name="source">The bitmap image.</param>
/// <param name="opacity">The opacity to draw with.</param>
/// <param name="sourceRect">The rect in the image to draw.</param>
/// <param name="destRect">The rect in the output to draw to.</param>
public void DrawImage(IBitmap source, double opacity, Rect sourceRect, Rect destRect)
{
Contract.Requires<ArgumentNullException>(source != null);
PlatformImpl.DrawImage(source.PlatformImpl, opacity, sourceRect, destRect);
}
/// <summary>
/// Draws a line.
/// </summary>
/// <param name="pen">The stroke pen.</param>
/// <param name="p1">The first point of the line.</param>
/// <param name="p2">The second point of the line.</param>
public void DrawLine(Pen pen, Point p1, Point p2)
{
if (PenIsVisible(pen))
{
PlatformImpl.DrawLine(pen, p1, p2);
}
}
/// <summary>
/// Draws a geometry.
/// </summary>
/// <param name="brush">The fill brush.</param>
/// <param name="pen">The stroke pen.</param>
/// <param name="geometry">The geometry.</param>
public void DrawGeometry(IBrush brush, Pen pen, Geometry geometry)
{
if (brush != null || PenIsVisible(pen))
{
PlatformImpl.DrawGeometry(brush, pen, geometry.PlatformImpl);
}
}
/// <summary>
/// Draws the outline of a rectangle.
/// </summary>
/// <param name="pen">The pen.</param>
/// <param name="rect">The rectangle bounds.</param>
/// <param name="cornerRadius">The corner radius.</param>
public void DrawRectangle(Pen pen, Rect rect, float cornerRadius = 0.0f)
{
if (PenIsVisible(pen))
{
PlatformImpl.DrawRectangle(pen, rect, cornerRadius);
}
}
/// <summary>
/// Draws text.
/// </summary>
/// <param name="foreground">The foreground brush.</param>
/// <param name="origin">The upper-left corner of the text.</param>
/// <param name="text">The text.</param>
public void DrawText(IBrush foreground, Point origin, FormattedText text)
{
Contract.Requires<ArgumentNullException>(text != null);
if (foreground != null)
{
PlatformImpl.DrawText(foreground, origin, text.PlatformImpl);
}
}
/// <summary>
/// Draws a filled rectangle.
/// </summary>
/// <param name="brush">The brush.</param>
/// <param name="rect">The rectangle bounds.</param>
/// <param name="cornerRadius">The corner radius.</param>
public void FillRectangle(IBrush brush, Rect rect, float cornerRadius = 0.0f)
{
if (brush != null && rect != Rect.Empty)
{
PlatformImpl.FillRectangle(brush, rect, cornerRadius);
}
}
public struct PushedState : IDisposable
{
private readonly int _level;
private readonly DrawingContext _context;
private readonly Matrix _matrix;
private readonly PushedStateType _type;
public enum PushedStateType
{
None,
Matrix,
Opacity,
Clip,
MatrixContainer,
GeometryClip,
OpacityMask
}
public PushedState(DrawingContext context, PushedStateType type, Matrix matrix = default(Matrix))
{
_context = context;
_type = type;
_matrix = matrix;
_level = context._currentLevel += 1;
context._states.Push(this);
}
public void Dispose()
{
if (_type == PushedStateType.None)
return;
if (_context._currentLevel != _level)
throw new InvalidOperationException("Wrong Push/Pop state order");
_context._currentLevel--;
_context._states.Pop();
if (_type == PushedStateType.Matrix)
_context.CurrentTransform = _matrix;
else if (_type == PushedStateType.Clip)
_context.PlatformImpl.PopClip();
else if (_type == PushedStateType.Opacity)
_context.PlatformImpl.PopOpacity();
else if (_type == PushedStateType.GeometryClip)
_context.PlatformImpl.PopGeometryClip();
else if (_type == PushedStateType.OpacityMask)
_context.PlatformImpl.PopOpacityMask();
else if (_type == PushedStateType.MatrixContainer)
{
var cont = _context._transformContainers.Pop();
_context._currentContainerTransform = cont.ContainerTransform;
_context.CurrentTransform = cont.LocalTransform;
}
}
}
/// <summary>
/// Pushes a clip rectange.
/// </summary>
/// <param name="clip">The clip rectangle.</param>
/// <returns>A disposable used to undo the clip rectangle.</returns>
public PushedState PushClip(Rect clip)
{
PlatformImpl.PushClip(clip);
return new PushedState(this, PushedState.PushedStateType.Clip);
}
/// <summary>
/// Pushes a clip geometry.
/// </summary>
/// <param name="clip">The clip geometry.</param>
/// <returns>A disposable used to undo the clip geometry.</returns>
public PushedState PushGeometryClip(Geometry clip)
{
Contract.Requires<ArgumentNullException>(clip != null);
PlatformImpl.PushGeometryClip(clip.PlatformImpl);
return new PushedState(this, PushedState.PushedStateType.GeometryClip);
}
/// <summary>
/// Pushes an opacity value.
/// </summary>
/// <param name="opacity">The opacity.</param>
/// <returns>A disposable used to undo the opacity.</returns>
public PushedState PushOpacity(double opacity)
//TODO: Eliminate platform-specific push opacity call
{
PlatformImpl.PushOpacity(opacity);
return new PushedState(this, PushedState.PushedStateType.Opacity);
}
/// <summary>
/// Pushes an opacity mask.
/// </summary>
/// <param name="mask">The opacity mask.</param>
/// <param name="bounds">
/// The size of the brush's target area. TODO: Are we sure this is needed?
/// </param>
/// <returns>A disposable to undo the opacity mask.</returns>
public PushedState PushOpacityMask(IBrush mask, Rect bounds)
{
PlatformImpl.PushOpacityMask(mask, bounds);
return new PushedState(this, PushedState.PushedStateType.OpacityMask);
}
/// <summary>
/// Pushes a matrix post-transformation.
/// </summary>
/// <param name="matrix">The matrix</param>
/// <returns>A disposable used to undo the transformation.</returns>
public PushedState PushPostTransform(Matrix matrix) => PushSetTransform(CurrentTransform * matrix);
/// <summary>
/// Pushes a matrix pre-transformation.
/// </summary>
/// <param name="matrix">The matrix</param>
/// <returns>A disposable used to undo the transformation.</returns>
public PushedState PushPreTransform(Matrix matrix) => PushSetTransform(matrix * CurrentTransform);
/// <summary>
/// Sets the current matrix transformation.
/// </summary>
/// <param name="matrix">The matrix</param>
/// <returns>A disposable used to undo the transformation.</returns>
PushedState PushSetTransform(Matrix matrix)
{
var oldMatrix = CurrentTransform;
CurrentTransform = matrix;
return new PushedState(this, PushedState.PushedStateType.Matrix, oldMatrix);
}
/// <summary>
/// Pushes a new transform context.
/// </summary>
/// <returns>A disposable used to undo the transformation.</returns>
public PushedState PushTransformContainer()
{
_transformContainers.Push(new TransformContainer(CurrentTransform, _currentContainerTransform));
_currentContainerTransform = CurrentTransform * _currentContainerTransform;
_currentTransform = Matrix.Identity;
return new PushedState(this, PushedState.PushedStateType.MatrixContainer);
}
/// <summary>
/// Disposes of any resources held by the <see cref="DrawingContext"/>.
/// </summary>
public void Dispose()
{
while (_states.Count != 0)
_states.Peek().Dispose();
StateStackPool.Push(_states);
_states = null;
TransformStackPool.Push(_transformContainers);
_transformContainers = null;
PlatformImpl.Dispose();
}
private static bool PenIsVisible(Pen pen)
{
return pen?.Brush != null && pen.Thickness > 0;
}
}
}
| |
/*
* 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.Collections.Specialized;
using System.IO;
using System.Net;
using System.Web;
using DotNetOpenId;
using DotNetOpenId.Provider;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Handlers.Base;
using OpenSim.Services.Interfaces;
using Nini.Config;
using OpenMetaverse;
namespace OpenSim.Server.Handlers.Authentication
{
/// <summary>
/// Temporary, in-memory store for OpenID associations
/// </summary>
public class ProviderMemoryStore : IAssociationStore<AssociationRelyingPartyType>
{
private class AssociationItem
{
public AssociationRelyingPartyType DistinguishingFactor;
public string Handle;
public DateTime Expires;
public byte[] PrivateData;
}
Dictionary<string, AssociationItem> m_store = new Dictionary<string, AssociationItem>();
SortedList<DateTime, AssociationItem> m_sortedStore = new SortedList<DateTime, AssociationItem>();
object m_syncRoot = new object();
#region IAssociationStore<AssociationRelyingPartyType> Members
public void StoreAssociation(AssociationRelyingPartyType distinguishingFactor, Association assoc)
{
AssociationItem item = new AssociationItem();
item.DistinguishingFactor = distinguishingFactor;
item.Handle = assoc.Handle;
item.Expires = assoc.Expires.ToLocalTime();
item.PrivateData = assoc.SerializePrivateData();
lock (m_syncRoot)
{
m_store[item.Handle] = item;
m_sortedStore[item.Expires] = item;
}
}
public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor)
{
lock (m_syncRoot)
{
if (m_sortedStore.Count > 0)
{
AssociationItem item = m_sortedStore.Values[m_sortedStore.Count - 1];
return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData);
}
else
{
return null;
}
}
}
public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor, string handle)
{
AssociationItem item;
bool success = false;
lock (m_syncRoot)
success = m_store.TryGetValue(handle, out item);
if (success)
return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData);
else
return null;
}
public bool RemoveAssociation(AssociationRelyingPartyType distinguishingFactor, string handle)
{
lock (m_syncRoot)
{
for (int i = 0; i < m_sortedStore.Values.Count; i++)
{
AssociationItem item = m_sortedStore.Values[i];
if (item.Handle == handle)
{
m_sortedStore.RemoveAt(i);
break;
}
}
return m_store.Remove(handle);
}
}
public void ClearExpiredAssociations()
{
lock (m_syncRoot)
{
List<AssociationItem> itemsCopy = new List<AssociationItem>(m_sortedStore.Values);
DateTime now = DateTime.Now;
for (int i = 0; i < itemsCopy.Count; i++)
{
AssociationItem item = itemsCopy[i];
if (item.Expires <= now)
{
m_sortedStore.RemoveAt(i);
m_store.Remove(item.Handle);
}
}
}
}
#endregion
}
public class OpenIdStreamHandler : BaseOutputStreamHandler
{
#region HTML
/// <summary>Login form used to authenticate OpenID requests</summary>
const string LOGIN_PAGE =
@"<html>
<head><title>OpenSim OpenID Login</title></head>
<body>
<h3>OpenSim Login</h3>
<form method=""post"">
<label for=""first"">First Name:</label> <input readonly type=""text"" name=""first"" id=""first"" value=""{0}""/>
<label for=""last"">Last Name:</label> <input readonly type=""text"" name=""last"" id=""last"" value=""{1}""/>
<label for=""pass"">Password:</label> <input type=""password"" name=""pass"" id=""pass""/>
<input type=""submit"" value=""Login"">
</form>
</body>
</html>";
/// <summary>Page shown for a valid OpenID identity</summary>
const string OPENID_PAGE =
@"<html>
<head>
<title>{2} {3}</title>
<link rel=""openid2.provider openid.server"" href=""{0}://{1}/openid/server/""/>
</head>
<body>OpenID identifier for {2} {3}</body>
</html>
";
/// <summary>Page shown for an invalid OpenID identity</summary>
const string INVALID_OPENID_PAGE =
@"<html><head><title>Identity not found</title></head>
<body>Invalid OpenID identity</body></html>";
/// <summary>Page shown if the OpenID endpoint is requested directly</summary>
const string ENDPOINT_PAGE =
@"<html><head><title>OpenID Endpoint</title></head><body>
This is an OpenID server endpoint, not a human-readable resource.
For more information, see <a href='http://openid.net/'>http://openid.net/</a>.
</body></html>";
#endregion HTML
IAuthenticationService m_authenticationService;
IUserAccountService m_userAccountService;
ProviderMemoryStore m_openidStore = new ProviderMemoryStore();
public override string ContentType { get { return "text/html"; } }
/// <summary>
/// Constructor
/// </summary>
public OpenIdStreamHandler(
string httpMethod, string path, IUserAccountService userService, IAuthenticationService authService)
: base(httpMethod, path, "OpenId", "OpenID stream handler")
{
m_authenticationService = authService;
m_userAccountService = userService;
}
/// <summary>
/// Handles all GET and POST requests for OpenID identifier pages and endpoint
/// server communication
/// </summary>
protected override void ProcessRequest(
string path, Stream request, Stream response, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
Uri providerEndpoint = new Uri(String.Format("{0}://{1}{2}", httpRequest.Url.Scheme, httpRequest.Url.Authority, httpRequest.Url.AbsolutePath));
// Defult to returning HTML content
httpResponse.ContentType = ContentType;
try
{
NameValueCollection postQuery = HttpUtility.ParseQueryString(new StreamReader(httpRequest.InputStream).ReadToEnd());
NameValueCollection getQuery = HttpUtility.ParseQueryString(httpRequest.Url.Query);
NameValueCollection openIdQuery = (postQuery.GetValues("openid.mode") != null ? postQuery : getQuery);
OpenIdProvider provider = new OpenIdProvider(m_openidStore, providerEndpoint, httpRequest.Url, openIdQuery);
if (provider.Request != null)
{
if (!provider.Request.IsResponseReady && provider.Request is IAuthenticationRequest)
{
IAuthenticationRequest authRequest = (IAuthenticationRequest)provider.Request;
string[] passwordValues = postQuery.GetValues("pass");
UserAccount account;
if (TryGetAccount(new Uri(authRequest.ClaimedIdentifier.ToString()), out account))
{
// Check for form POST data
if (passwordValues != null && passwordValues.Length == 1)
{
if (account != null &&
(m_authenticationService.Authenticate(account.PrincipalID,Util.Md5Hash(passwordValues[0]), 30) != string.Empty))
authRequest.IsAuthenticated = true;
else
authRequest.IsAuthenticated = false;
}
else
{
// Authentication was requested, send the client a login form
using (StreamWriter writer = new StreamWriter(response))
writer.Write(String.Format(LOGIN_PAGE, account.FirstName, account.LastName));
return;
}
}
else
{
// Cannot find an avatar matching the claimed identifier
authRequest.IsAuthenticated = false;
}
}
// Add OpenID headers to the response
foreach (string key in provider.Request.Response.Headers.Keys)
httpResponse.AddHeader(key, provider.Request.Response.Headers[key]);
string[] contentTypeValues = provider.Request.Response.Headers.GetValues("Content-Type");
if (contentTypeValues != null && contentTypeValues.Length == 1)
httpResponse.ContentType = contentTypeValues[0];
// Set the response code and document body based on the OpenID result
httpResponse.StatusCode = (int)provider.Request.Response.Code;
response.Write(provider.Request.Response.Body, 0, provider.Request.Response.Body.Length);
response.Close();
}
else if (httpRequest.Url.AbsolutePath.Contains("/openid/server"))
{
// Standard HTTP GET was made on the OpenID endpoint, send the client the default error page
using (StreamWriter writer = new StreamWriter(response))
writer.Write(ENDPOINT_PAGE);
}
else
{
// Try and lookup this avatar
UserAccount account;
if (TryGetAccount(httpRequest.Url, out account))
{
using (StreamWriter writer = new StreamWriter(response))
{
// TODO: Print out a full profile page for this avatar
writer.Write(String.Format(OPENID_PAGE, httpRequest.Url.Scheme,
httpRequest.Url.Authority, account.FirstName, account.LastName));
}
}
else
{
// Couldn't parse an avatar name, or couldn't find the avatar in the user server
using (StreamWriter writer = new StreamWriter(response))
writer.Write(INVALID_OPENID_PAGE);
}
}
}
catch (Exception ex)
{
httpResponse.StatusCode = (int)HttpStatusCode.InternalServerError;
using (StreamWriter writer = new StreamWriter(response))
writer.Write(ex.Message);
}
}
/// <summary>
/// Parse a URL with a relative path of the form /users/First_Last and try to
/// retrieve the profile matching that avatar name
/// </summary>
/// <param name="requestUrl">URL to parse for an avatar name</param>
/// <param name="profile">Profile data for the avatar</param>
/// <returns>True if the parse and lookup were successful, otherwise false</returns>
bool TryGetAccount(Uri requestUrl, out UserAccount account)
{
if (requestUrl.Segments.Length == 3 && requestUrl.Segments[1] == "users/")
{
// Parse the avatar name from the path
string username = requestUrl.Segments[requestUrl.Segments.Length - 1];
string[] name = username.Split('_');
if (name.Length == 2)
{
account = m_userAccountService.GetUserAccount(UUID.Zero, name[0], name[1]);
return (account != null);
}
}
account = null;
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace ALang
{
/// <summary>
/// Stores built-in or custom type
/// </summary>
public sealed class LanguageType
{
/// <summary>
/// Type name
/// </summary>
public string Name;
/// <summary>
/// Is built-in
/// </summary>
public bool IsReserved;
/// <summary>
/// Is integer
/// </summary>
public bool IsInteger;
/// <summary>
/// Is floating point
/// </summary>
public bool IsFloat;
/// <summary>
/// Is pointer to (type is stored in the Name field)
/// </summary>
public bool IsPointer;
}
/// <summary>
/// Stores defined function
/// </summary>
public sealed class LanguageFunction
{
/// <summary>
/// Stores function argument
/// </summary>
public sealed class FunctionArg
{
/// <summary>
/// Reference to argument type
/// </summary>
public LanguageType TypeInfo;
/// <summary>
/// Argument name
/// </summary>
public string ArgName;
/// <summary>
/// Argument default value. Can be null
/// </summary>
public ValueElement DefaultVal;
}
/// <summary>
/// Function name
/// </summary>
public string Name;
/// <summary>
/// Function name with arguments types
/// </summary>
public string BuildName;
/// <summary>
/// Function arguments
/// </summary>
public List<FunctionArg> Arguments;
/// <summary>
/// Function return types
/// </summary>
public List<LanguageType> ReturnTypes;
}
/// <summary>
/// Stores convertion between 2 types
/// </summary>
public sealed class PossibleConvertions
{
/// <summary>
/// Source type
/// </summary>
public string FromType;
/// <summary>
/// Target type
/// </summary>
public string ToType;
/// <summary>
/// Is cast exist
/// </summary>
public bool CanCast;
/// <summary>
/// Warning which compiler should display. Can be null or empty
/// </summary>
public string WarningMessage;
}
/// <summary>
/// Stores all type, function, etc information
/// </summary>
public sealed class LanguageSymbols
{
public const int PointerSize = 8;
public LanguageSymbols()
{
if (m_this != null)
{
Compilation.WriteCritical("Language symbols have been already created");
}
m_this = this;
}
/// <summary>
/// Returns symbols
/// </summary>
/// <returns></returns>
public static LanguageSymbols Instance
{
get { return m_this; }
}
/// <summary>
/// Returns built-in types
/// </summary>
/// <returns></returns>
public List<LanguageType> GetDefaultTypes()
{
return m_defaultTypes;
}
/// <summary>
/// Checks is type is a build-in type or custom
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public bool IsTypeExist(string name)
{
return m_defaultTypes.Exists(type => type.Name == name) ||
m_userTypes.Exists(type => type.Name == name);
}
/// <summary>
/// Returns type info by name
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public LanguageType GetTypeByName(string name)
{
var result = m_defaultTypes.Find(type => type.Name == name);
if (result == null)
{
result = m_userTypes.Find(type => type.Name == name);
}
Compilation.Assert(result != null, "Type '" + name + "' wasn't found", -1);
return result;
}
public string GetTypeNameByCSharpTypeName(string typeName)
{
try
{
return m_cSharpTypeToLang[typeName];
}
catch (KeyNotFoundException)
{
Compilation.WriteCritical(string.Format("BUG: CSharp type '{0}' wasn't found", typeName));
return null;
}
}
/// <summary>
/// Checks is type is built-in
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public bool IsTypeReserved(string name)
{
return m_defaultTypes.Exists(type => type.Name == name);
}
/// <summary>
/// Adds custom type
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public bool AddUserType(string name)
{
if (IsTypeExist(name))
return false;
m_userTypes.Add(new LanguageType {Name = name, IsReserved = false});
return true;
}
/// <summary>
/// Returns type size in bytes
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public int GetTypeSize(string name)
{
int size;
bool ok = m_typesSize.TryGetValue(name, out size);
Compilation.Assert(ok, "Type '" + name + "' isn't exist", -1);
return size;
}
/// <summary>
/// Returns type size in bytes
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public int GetTypeSize(LanguageType type)
{
if (type.IsPointer)
{
return PointerSize;
}
return GetTypeSize(type.Name);
}
/// <summary>
/// Returns default type id
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public sbyte GetDefaultTypeId(string name)
{
int index = m_defaultTypes.FindIndex(type => type.Name == name);
Compilation.Assert(index != -1, "Type '" + name + "' isn't exist", -1);
return (sbyte) index;
}
/// <summary>
/// Checks is function passed with name and arguments exist. Argument type can be null
/// </summary>
/// <param name="name"></param>
/// <param name="args"></param>
/// <returns></returns>
public bool IsFunctionExist(string name, IList<string> args)
{
return m_userFunctions.Exists(func => func.Name == name &&
func.Arguments.CompareTo(args,
(arg1, arg2) => arg1.TypeInfo.Name == arg2 ||
(String.IsNullOrEmpty(arg2) && arg1.DefaultVal !=
null)
));
}
/// <summary>
/// Checks is function passed with name and arguments exist. This function doesn't expect a default argument(null)
/// </summary>
/// <param name="name"></param>
/// <param name="args"></param>
/// <returns></returns>
public bool IsFunctionExist(string name, IList<LanguageFunction.FunctionArg> args)
{
return m_userFunctions.Exists(func => func.Name == name &&
func.Arguments.CompareTo(args,
(arg1, arg2) => arg1.TypeInfo.Name == arg2.TypeInfo.Name));
}
/// <summary>
/// Returns function by name and arguments types (can be null).l
/// </summary>
/// <param name="name"></param>
/// <param name="args"></param>
/// <returns></returns>
public LanguageFunction GetFunction(string name, IList<string> args)
{
var functions = m_userFunctions.Where(func =>
func.Name == name &&
func.Arguments.CompareTo(args, (arg1, arg2) =>
(String.IsNullOrEmpty(arg2) && arg1.DefaultVal != null) ||
arg1.TypeInfo.Name == arg2
)
)
.ToList();
Compilation.Assert(functions.Count != 0, "No function isn't founded with name '" + name +
"' and arguments' types["
+ args.MergeInString() + "]", -1);
Compilation.Assert(functions.Count == 1, "More than one functions are founded with name + '" + name + "'"
+ " and argumentss' types [" + args.MergeInString() + "] . It's a bug",
-1);
return functions.First();
}
/// <summary>
/// Check is function exist using it name and arguments types (can be null).
/// </summary>
/// <param name="name"></param>
/// <param name="args"></param>
/// <returns></returns>
public bool HasFunction(string name, IList<string> args)
{
return m_userFunctions.Any(func => func.Name == name &&
func.Arguments.CompareTo(args, (arg1, arg2) => arg1.TypeInfo.Name == arg2 ||
(String.IsNullOrEmpty(arg2) &&
arg1.DefaultVal != null)
));
}
/// <summary>
/// Check is function exist using it name. Ignores arguments
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public bool HasFunctionWithName(string name)
{
return m_userFunctions.Any(func => func.Name == name);
}
/// <summary>
/// Updates function information in symbols or add new function
/// </summary>
/// <param name="function"></param>
public void UpdateFunction(LanguageFunction function)
{
m_userFunctions.RemoveAll(func => func.Name == function.Name &&
func.Arguments.CompareTo(function.Arguments,
(arg1, arg2) => arg1.TypeInfo.Name == arg2.TypeInfo.Name));
UpdateFunctionBuildName(function);
m_userFunctions.Add(function);
}
/// <summary>
/// Returns function build name by name and arguments
/// </summary>
/// <param name="function"></param>
/// <returns></returns>
public string GetFunctionBuildName(LanguageFunction function)
{
string argsStr = "null";
if (function.Arguments.Count != 0)
{
argsStr = function.Arguments.Select(arg => arg.TypeInfo.Name)
.Aggregate((id1, id2) => id1 + "@" + id2);
}
return string.Format("{0}_@{1}", function.Name, argsStr);
}
/// <summary>
/// Updates function build name by name and arguments
/// </summary>
/// <param name="function"></param>
public void UpdateFunctionBuildName(LanguageFunction function)
{
function.BuildName = GetFunctionBuildName(function);
}
/// <summary>
/// Adds new function or returns false if it exists
/// </summary>
/// <param name="function"></param>
/// <returns>True if function is added, otherwise false</returns>
public bool AddUserFunction(LanguageFunction function)
{
if (IsFunctionExist(function.Name, function.Arguments))
{
return false;
}
UpdateFunctionBuildName(function);
m_userFunctions.Add(function);
return true;
}
/// <summary>
/// Adds new function or returns false if it exists
/// </summary>
/// <param name="name"></param>
/// <param name="args"></param>
/// <param name="returnTypes"></param>
/// <returns>True if function is added, otherwise false</returns>
public bool AddUserFunction(string name, IList<LanguageFunction.FunctionArg> args, IList<string> returnTypes)
{
var typesInfo = returnTypes.Select(typeName => GetTypeByName(typeName));
return AddUserFunction(new LanguageFunction
{
Name = name,
Arguments = args.ToList(),
ReturnTypes = typesInfo.ToList()
});
}
/// <summary>
/// Returns convertion information
/// </summary>
/// <param name="from"></param>
/// <param name="to"></param>
/// <returns></returns>
public PossibleConvertions GetCastInfo(string from, string to)
{
return m_defaultConvertions.Find(convertion => convertion.FromType == from && convertion.ToType == to);
}
/// <summary>
/// Returns most precise type from passed
/// </summary>
/// <param name="types"></param>
/// <returns></returns>
public string GetMostPrecise(params string[] types)
{
bool allSupported = types.All(type => m_preciseLevel.Contains(type));
if (!allSupported)
{
Compilation.WriteError("Type(s) [" + types.Where(type => !m_preciseLevel.Contains(type))
.Aggregate((type1, type2) => type1 + ", " + type2)
+ "] do(es) not support precission", -1);
}
return types.OrderBy(type => m_preciseLevel.IndexOf(type)).First();
}
/// <summary>
/// Returns most precise type from passed
/// </summary>
/// <param name="types"></param>
/// <returns></returns>
public LanguageType GetMostPrecise(params LanguageType[] types)
{
//TODO: Make it normal!
return types[0];
//return GetMostPrecise((from t in types select t.Name).ToArray());
}
/// <summary>
/// Returns type of built-in constant
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public string GetTypeOfConstVal(string val)
{
if (val.Contains('.'))
{
return DefTypesName.Get(DefTypesName.Index.Single);
}
else
{
return DefTypesName.Get(DefTypesName.Index.Int32);
}
}
/// <summary>
/// Get default value of type(null for custom)
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public ConstValElement GetDefaultVal(string type)
{
if (m_defaultValOfDefaultTypes.ContainsKey(type))
{
return GetDefaultValOfDefaultType(type);
}
else
{
return new ConstValElement {Type = type, Value = "null"};
}
}
/// <summary>
/// Get default value of built-in type
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public ConstValElement GetDefaultValOfDefaultType(string type)
{
return m_defaultValOfDefaultTypes[type];
}
public static class DefTypesName
{
public enum Index : byte
{
Int64,
Int32,
Int16,
Int8,
Double,
Single,
String,
Bool
}
public static string Get(Index index)
{
return m_defaultTypesName[(int) index];
}
private static string[] m_defaultTypesName =
{"Int64", "Int32", "Int16", "Int8", "Double", "Single", "String", "Bool"};
}
private Dictionary<string, ConstValElement> m_defaultValOfDefaultTypes = new Dictionary<string, ConstValElement>
{
{
DefTypesName.Get(DefTypesName.Index.Int32),
new ConstValElement {Type = DefTypesName.Get(DefTypesName.Index.Int32), Value = "0"}
}
};
private Dictionary<string, int> m_typesSize = new Dictionary<string, int>
{
{DefTypesName.Get(DefTypesName.Index.Int32), 4},
{DefTypesName.Get(DefTypesName.Index.Int8), 1}
};
private List<string> m_preciseLevel = new List<string>
{
DefTypesName.Get(DefTypesName.Index.String),
DefTypesName.Get(DefTypesName.Index.Double),
DefTypesName.Get(DefTypesName.Index.Single),
DefTypesName.Get(DefTypesName.Index.Int64),
DefTypesName.Get(DefTypesName.Index.Int32),
DefTypesName.Get(DefTypesName.Index.Int16),
DefTypesName.Get(DefTypesName.Index.Int8),
DefTypesName.Get(DefTypesName.Index.Bool)
};
private List<PossibleConvertions> m_defaultConvertions = new List<PossibleConvertions>
{
new PossibleConvertions
{
FromType = DefTypesName.Get(DefTypesName.Index.Int8),
ToType = DefTypesName.Get(DefTypesName.Index.Int16),
CanCast = true
}
};
//The order of this list !MUST! be same as order in DefTypesName
private List<LanguageType> m_defaultTypes = new List<LanguageType>
{
new LanguageType {Name = DefTypesName.Get(DefTypesName.Index.Int64), IsReserved = true, IsInteger = true},
new LanguageType {Name = DefTypesName.Get(DefTypesName.Index.Int32), IsReserved = true, IsInteger = true},
new LanguageType {Name = DefTypesName.Get(DefTypesName.Index.Int16), IsReserved = true, IsInteger = true},
new LanguageType {Name = DefTypesName.Get(DefTypesName.Index.Int8), IsReserved = true, IsInteger = true},
new LanguageType {Name = DefTypesName.Get(DefTypesName.Index.Double), IsReserved = true, IsFloat = true},
new LanguageType {Name = DefTypesName.Get(DefTypesName.Index.Single), IsReserved = true, IsFloat = true},
new LanguageType {Name = DefTypesName.Get(DefTypesName.Index.String), IsReserved = true},
new LanguageType {Name = DefTypesName.Get(DefTypesName.Index.Bool), IsReserved = true}
};
private List<LanguageType> m_userTypes = new List<LanguageType>();
private List<LanguageFunction> m_userFunctions = new List<LanguageFunction>();
private Dictionary<string, string> m_cSharpTypeToLang = new Dictionary<string, string>()
{
{typeof(SByte).Name, DefTypesName.Get(DefTypesName.Index.Int8)},
{typeof(Int16).Name, DefTypesName.Get(DefTypesName.Index.Int16)},
{typeof(Int32).Name, DefTypesName.Get(DefTypesName.Index.Int32)},
{typeof(Int64).Name, DefTypesName.Get(DefTypesName.Index.Int64)},
{typeof(Single).Name, DefTypesName.Get(DefTypesName.Index.Single)},
{typeof(Double).Name, DefTypesName.Get(DefTypesName.Index.Double)},
{typeof(String).Name, DefTypesName.Get(DefTypesName.Index.String)},
{typeof(Boolean).Name, DefTypesName.Get(DefTypesName.Index.Bool)}
};
private static LanguageSymbols m_this;
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using Aurora.Simulation.Base;
using OpenSim.Services.Interfaces;
using Aurora.Framework;
using Aurora.Framework.Servers.HttpServer;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenMetaverse.Imaging;
namespace OpenSim.Services.CapsService
{
public class AssetCAPS : ICapsServiceConnector
{
#region Stream Handler
public delegate byte[] StreamHandlerCallback(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse);
public class StreamHandler : BaseStreamHandler
{
readonly StreamHandlerCallback m_callback;
public StreamHandler(string httpMethod, string path, StreamHandlerCallback callback)
: base(httpMethod, path)
{
m_callback = callback;
}
public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
return m_callback(path, request, httpRequest, httpResponse);
}
}
#endregion Stream Handler
private const string m_uploadBakedTexturePath = "0010";
protected IAssetService m_assetService;
protected IRegionClientCapsService m_service;
public const string DefaultFormat = "x-j2c";
// TODO: Change this to a config option
protected string REDIRECT_URL = null;
public void RegisterCaps(IRegionClientCapsService service)
{
m_service = service;
m_assetService = service.Registry.RequestModuleInterface<IAssetService>();
service.AddStreamHandler("GetTexture",
new StreamHandler("GET", service.CreateCAPS("GetTexture", ""),
ProcessGetTexture));
service.AddStreamHandler("UploadBakedTexture",
new RestStreamHandler("POST", service.CreateCAPS("UploadBakedTexture", m_uploadBakedTexturePath),
UploadBakedTexture));
service.AddStreamHandler("GetMesh",
new RestHTTPHandler("GET", service.CreateCAPS("GetMesh", ""),
ProcessGetMesh));
}
public void EnteringRegion()
{
}
public void DeregisterCaps()
{
m_service.RemoveStreamHandler("GetTexture", "GET");
m_service.RemoveStreamHandler("UploadBakedTexture", "POST");
m_service.RemoveStreamHandler("GetMesh", "GET");
}
#region Get Texture
private byte[] ProcessGetTexture(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
//MainConsole.Instance.DebugFormat("[GETTEXTURE]: called in {0}", m_scene.RegionInfo.RegionName);
// Try to parse the texture ID from the request URL
NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query);
string textureStr = query.GetOne("texture_id");
string format = query.GetOne("format");
if (m_assetService == null)
{
httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
return null;
}
UUID textureID;
if (!String.IsNullOrEmpty(textureStr) && UUID.TryParse(textureStr, out textureID))
{
string[] formats;
if (!string.IsNullOrEmpty(format))
{
formats = new[] { format.ToLower() };
}
else
{
formats = WebUtils.GetPreferredImageTypes(httpRequest.Headers.Get("Accept"));
if (formats.Length == 0)
formats = new[] { DefaultFormat }; // default
}
// OK, we have an array with preferred formats, possibly with only one entry
httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
foreach (string f in formats)
{
if (FetchTexture(httpRequest, httpResponse, textureID, f))
break;
}
}
else
{
MainConsole.Instance.Warn("[GETTEXTURE]: Failed to parse a texture_id from GetTexture request: " + httpRequest.Url);
}
httpResponse.Send();
httpRequest.InputStream.Close();
httpRequest = null;
return null;
}
/// <summary>
///
/// </summary>
/// <param name="httpRequest"></param>
/// <param name="httpResponse"></param>
/// <param name="textureID"></param>
/// <param name="format"></param>
/// <returns>False for "caller try another codec"; true otherwise</returns>
private bool FetchTexture(OSHttpRequest httpRequest, OSHttpResponse httpResponse, UUID textureID, string format)
{
MainConsole.Instance.DebugFormat("[GETTEXTURE]: {0} with requested format {1}", textureID, format);
AssetBase texture;
string fullID = textureID.ToString();
if (format != DefaultFormat)
fullID = fullID + "-" + format;
if (!String.IsNullOrEmpty(REDIRECT_URL))
{
// Only try to fetch locally cached textures. Misses are redirected
texture = m_assetService.GetCached(fullID);
if (texture != null)
{
if (texture.Type != (sbyte)AssetType.Texture && texture.Type != (sbyte)AssetType.Unknown && texture.Type != (sbyte)AssetType.Simstate)
{
httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
return true;
}
WriteTextureData(httpRequest, httpResponse, texture, format);
}
else
{
string textureUrl = REDIRECT_URL + textureID.ToString();
MainConsole.Instance.Debug("[GETTEXTURE]: Redirecting texture request to " + textureUrl);
httpResponse.RedirectLocation = textureUrl;
return true;
}
}
else // no redirect
{
// try the cache
texture = m_assetService.GetCached(fullID);
if (texture == null)
{
//MainConsole.Instance.DebugFormat("[GETTEXTURE]: texture was not in the cache");
// Fetch locally or remotely. Misses return a 404
texture = m_assetService.Get(textureID.ToString());
if (texture != null)
{
if (texture.Type != (sbyte)AssetType.Texture && texture.Type != (sbyte)AssetType.Unknown && texture.Type != (sbyte)AssetType.Simstate)
{
httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
return true;
}
if (format == DefaultFormat)
{
WriteTextureData(httpRequest, httpResponse, texture, format);
texture = null;
return true;
}
AssetBase newTexture = new AssetBase(texture.ID + "-" + format, texture.Name, AssetType.Texture,
texture.CreatorID)
{Data = ConvertTextureData(texture, format)};
if (newTexture.Data.Length == 0)
return false; // !!! Caller try another codec, please!
newTexture.Flags = AssetFlags.Collectable | AssetFlags.Temporary;
newTexture.ID = m_assetService.Store(newTexture);
WriteTextureData(httpRequest, httpResponse, newTexture, format);
newTexture = null;
return true;
}
}
else // it was on the cache
{
if (texture.Type != (sbyte)AssetType.Texture && texture.Type != (sbyte)AssetType.Unknown && texture.Type != (sbyte)AssetType.Simstate)
{
httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
return true;
}
//MainConsole.Instance.DebugFormat("[GETTEXTURE]: texture was in the cache");
WriteTextureData(httpRequest, httpResponse, texture, format);
texture = null;
return true;
}
}
// not found
MainConsole.Instance.Warn("[GETTEXTURE]: Texture " + textureID + " not found");
httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
return true;
}
private void WriteTextureData(OSHttpRequest request, OSHttpResponse response, AssetBase texture, string format)
{
m_service.Registry.RequestModuleInterface<ISimulationBase>().EventManager.FireGenericEventHandler(
"AssetRequested", new object[] {m_service.Registry, texture, m_service.AgentID});
string range = request.Headers.GetOne("Range");
//MainConsole.Instance.DebugFormat("[GETTEXTURE]: Range {0}", range);
if (!String.IsNullOrEmpty(range)) // JP2's only
{
// Range request
int start, end;
if (TryParseRange(range, out start, out end))
{
// Before clamping start make sure we can satisfy it in order to avoid
// sending back the last byte instead of an error status
if (start >= texture.Data.Length)
{
response.StatusCode = (int)System.Net.HttpStatusCode.RequestedRangeNotSatisfiable;
}
else
{
end = Utils.Clamp(end, 0, texture.Data.Length - 1);
start = Utils.Clamp(start, 0, end);
int len = end - start + 1;
//MainConsole.Instance.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID);
if (len < texture.Data.Length)
response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent;
else
response.StatusCode = (int)System.Net.HttpStatusCode.OK;
response.ContentLength = len;
response.ContentType = texture.TypeString;
response.AddHeader("Content-Range", String.Format("bytes {0}-{1}/{2}", start, end, texture.Data.Length));
response.Body.Write(texture.Data, start, len);
}
}
else
{
MainConsole.Instance.Warn("[GETTEXTURE]: Malformed Range header: " + range);
response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
}
}
else // JP2's or other formats
{
// Full content request
response.StatusCode = (int)System.Net.HttpStatusCode.OK;
response.ContentLength = texture.Data.Length;
response.ContentType = texture.TypeString;
if (format == DefaultFormat)
response.ContentType = texture.TypeString;
else
response.ContentType = "image/" + format;
response.Body.Write(texture.Data, 0, texture.Data.Length);
}
}
private bool TryParseRange(string header, out int start, out int end)
{
if (header.StartsWith("bytes="))
{
string[] rangeValues = header.Substring(6).Split('-');
if (rangeValues.Length == 2)
{
if (Int32.TryParse(rangeValues[0], out start) && Int32.TryParse(rangeValues[1], out end))
return true;
}
}
start = end = 0;
return false;
}
private byte[] ConvertTextureData(AssetBase texture, string format)
{
MainConsole.Instance.DebugFormat("[GETTEXTURE]: Converting texture {0} to {1}", texture.ID, format);
byte[] data = new byte[0];
MemoryStream imgstream = new MemoryStream();
Bitmap mTexture = new Bitmap(1, 1);
ManagedImage managedImage;
Image image = mTexture;
try
{
// Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular data
imgstream = new MemoryStream();
// Decode image to System.Drawing.Image
if (OpenJPEG.DecodeToImage(texture.Data, out managedImage, out image))
{
// Save to bitmap
mTexture = new Bitmap(image);
EncoderParameters myEncoderParameters = new EncoderParameters();
myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
// Save bitmap to stream
ImageCodecInfo codec = GetEncoderInfo("image/" + format);
if (codec != null)
{
mTexture.Save(imgstream, codec, myEncoderParameters);
// Write the stream to a byte array for output
data = imgstream.ToArray();
}
else
MainConsole.Instance.WarnFormat("[GETTEXTURE]: No such codec {0}", format);
}
}
catch (Exception e)
{
MainConsole.Instance.WarnFormat("[GETTEXTURE]: Unable to convert texture {0} to {1}: {2}", texture.ID, format, e.Message);
}
finally
{
// Reclaim memory, these are unmanaged resources
// If we encountered an exception, one or more of these will be null
mTexture.Dispose();
mTexture = null;
managedImage = null;
if (image != null)
image.Dispose();
image = null;
imgstream.Close();
imgstream = null;
}
return data;
}
// From msdn
private static ImageCodecInfo GetEncoderInfo(String mimeType)
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
#if (!ISWIN)
foreach (ImageCodecInfo t in encoders)
{
if (t.MimeType == mimeType) return t;
}
return null;
#else
return encoders.FirstOrDefault(t => t.MimeType == mimeType);
#endif
}
#endregion
#region Baked Textures
public string UploadBakedTexture(string request, string path,
string param, OSHttpRequest httpRequest,
OSHttpResponse httpResponse)
{
try
{
//MainConsole.Instance.Debug("[CAPS]: UploadBakedTexture Request in region: " +
// m_regionName);
string uploaderPath = UUID.Random().ToString();
string uploadpath = m_service.CreateCAPS("Upload" + uploaderPath, uploaderPath);
BakedTextureUploader uploader =
new BakedTextureUploader(uploadpath, "Upload" + uploaderPath,
m_service);
uploader.OnUpLoad += BakedTextureUploaded;
m_service.AddStreamHandler(uploadpath,
new BinaryStreamHandler("POST", uploadpath,
uploader.uploaderCaps));
string uploaderURL = m_service.HostUri + uploadpath;
OSDMap map = new OSDMap();
map["uploader"] = uploaderURL;
map["state"] = "upload";
return OSDParser.SerializeLLSDXmlString(map);
}
catch (Exception e)
{
MainConsole.Instance.Error("[CAPS]: " + e);
}
return null;
}
public delegate void UploadedBakedTexture(byte[] data, out UUID newAssetID);
public class BakedTextureUploader
{
public event UploadedBakedTexture OnUpLoad;
private UploadedBakedTexture handlerUpLoad = null;
private readonly string uploaderPath = String.Empty;
private readonly string uploadMethod = "";
private readonly IRegionClientCapsService clientCaps;
public BakedTextureUploader(string path, string method, IRegionClientCapsService caps)
{
uploaderPath = path;
uploadMethod = method;
clientCaps = caps;
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <returns></returns>
public string uploaderCaps(byte[] data, string path, string param)
{
handlerUpLoad = OnUpLoad;
UUID newAssetID;
handlerUpLoad(data, out newAssetID);
string res = String.Empty;
OSDMap map = new OSDMap();
map["new_asset"] = newAssetID.ToString();
map["item_id"] = UUID.Zero;
map["state"] = "complete";
res = OSDParser.SerializeLLSDXmlString(map);
clientCaps.RemoveStreamHandler(uploadMethod, "POST", uploaderPath);
return res;
}
}
public void BakedTextureUploaded(byte[] data, out UUID newAssetID)
{
//MainConsole.Instance.InfoFormat("[AssetCAPS]: Received baked texture {0}", assetID.ToString());
AssetBase asset = new AssetBase(UUID.Random(), "Baked Texture", AssetType.Texture, m_service.AgentID)
{Data = data, Flags = AssetFlags.Deletable | AssetFlags.Temporary};
newAssetID = m_assetService.Store(asset);
MainConsole.Instance.DebugFormat("[AssetCAPS]: Baked texture new id {0}", asset.ID.ToString());
asset.ID = newAssetID;
}
public Hashtable ProcessGetMesh(Hashtable request)
{
Hashtable responsedata = new Hashtable();
responsedata["int_response_code"] = 400; //501; //410; //404;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = "Request wasn't what was expected";
string meshStr = string.Empty;
if (request.ContainsKey("mesh_id"))
meshStr = request["mesh_id"].ToString();
UUID meshID = UUID.Zero;
if (!String.IsNullOrEmpty(meshStr) && UUID.TryParse(meshStr, out meshID))
{
if (m_assetService == null)
{
responsedata["int_response_code"] = 404; //501; //410; //404;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = "The asset service is unavailable. So is your mesh.";
return responsedata;
}
// Only try to fetch locally cached textures. Misses are redirected
AssetBase mesh = m_assetService.GetCached(meshID.ToString());
if (mesh != null)
{
if (mesh.Type == (SByte)AssetType.Mesh)
{
responsedata["str_response_string"] = Convert.ToBase64String(mesh.Data);
responsedata["content_type"] = "application/vnd.ll.mesh";
responsedata["int_response_code"] = 200;
}
// Optionally add additional mesh types here
else
{
responsedata["int_response_code"] = 404; //501; //410; //404;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = "Unfortunately, this asset isn't a mesh.";
return responsedata;
}
}
else
{
mesh = m_assetService.Get(meshID.ToString());
if (mesh != null)
{
if (mesh.Type == (SByte)AssetType.Mesh)
{
responsedata["str_response_string"] = Convert.ToBase64String(mesh.Data);
responsedata["content_type"] = "application/vnd.ll.mesh";
responsedata["int_response_code"] = 200;
}
// Optionally add additional mesh types here
else
{
responsedata["int_response_code"] = 404; //501; //410; //404;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = "Unfortunately, this asset isn't a mesh.";
return responsedata;
}
}
else
{
responsedata["int_response_code"] = 404; //501; //410; //404;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = "Your Mesh wasn't found. Sorry!";
return responsedata;
}
}
}
return responsedata;
}
#endregion
}
}
| |
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 OD4B.NavLinksInjectionWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
namespace CefSharp.WinForms.Example.Minimal
{
partial class SimpleBrowserForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SimpleBrowserForm));
this.toolStripContainer = new System.Windows.Forms.ToolStripContainer();
this.statusLabel = new System.Windows.Forms.Label();
this.outputLabel = new System.Windows.Forms.Label();
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.backButton = new System.Windows.Forms.ToolStripButton();
this.forwardButton = new System.Windows.Forms.ToolStripButton();
this.urlTextBox = new System.Windows.Forms.ToolStripTextBox();
this.goButton = new System.Windows.Forms.ToolStripButton();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripContainer.ContentPanel.SuspendLayout();
this.toolStripContainer.TopToolStripPanel.SuspendLayout();
this.toolStripContainer.SuspendLayout();
this.toolStrip1.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// toolStripContainer
//
//
// toolStripContainer.ContentPanel
//
this.toolStripContainer.ContentPanel.Controls.Add(this.statusLabel);
this.toolStripContainer.ContentPanel.Controls.Add(this.outputLabel);
this.toolStripContainer.ContentPanel.Size = new System.Drawing.Size(730, 441);
this.toolStripContainer.Dock = System.Windows.Forms.DockStyle.Fill;
this.toolStripContainer.LeftToolStripPanelVisible = false;
this.toolStripContainer.Location = new System.Drawing.Point(0, 24);
this.toolStripContainer.Name = "toolStripContainer";
this.toolStripContainer.RightToolStripPanelVisible = false;
this.toolStripContainer.Size = new System.Drawing.Size(730, 466);
this.toolStripContainer.TabIndex = 0;
this.toolStripContainer.Text = "toolStripContainer1";
//
// toolStripContainer.TopToolStripPanel
//
this.toolStripContainer.TopToolStripPanel.Controls.Add(this.toolStrip1);
//
// statusLabel
//
this.statusLabel.AutoSize = true;
this.statusLabel.Dock = System.Windows.Forms.DockStyle.Bottom;
this.statusLabel.Location = new System.Drawing.Point(0, 415);
this.statusLabel.Name = "statusLabel";
this.statusLabel.Size = new System.Drawing.Size(0, 13);
this.statusLabel.TabIndex = 1;
//
// outputLabel
//
this.outputLabel.AutoSize = true;
this.outputLabel.Dock = System.Windows.Forms.DockStyle.Bottom;
this.outputLabel.Location = new System.Drawing.Point(0, 428);
this.outputLabel.Name = "outputLabel";
this.outputLabel.Size = new System.Drawing.Size(0, 13);
this.outputLabel.TabIndex = 0;
//
// toolStrip1
//
this.toolStrip1.Dock = System.Windows.Forms.DockStyle.None;
this.toolStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.backButton,
this.forwardButton,
this.urlTextBox,
this.goButton});
this.toolStrip1.Location = new System.Drawing.Point(0, 0);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Padding = new System.Windows.Forms.Padding(0);
this.toolStrip1.Size = new System.Drawing.Size(730, 25);
this.toolStrip1.Stretch = true;
this.toolStrip1.TabIndex = 0;
this.toolStrip1.Layout += new System.Windows.Forms.LayoutEventHandler(this.HandleToolStripLayout);
//
// backButton
//
this.backButton.Enabled = false;
this.backButton.Image = global::CefSharp.WinForms.Example.Properties.Resources.nav_left_green;
this.backButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.backButton.Name = "backButton";
this.backButton.Size = new System.Drawing.Size(52, 22);
this.backButton.Text = "Back";
this.backButton.Click += new System.EventHandler(this.BackButtonClick);
//
// forwardButton
//
this.forwardButton.Enabled = false;
this.forwardButton.Image = global::CefSharp.WinForms.Example.Properties.Resources.nav_right_green;
this.forwardButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.forwardButton.Name = "forwardButton";
this.forwardButton.Size = new System.Drawing.Size(70, 22);
this.forwardButton.Text = "Forward";
this.forwardButton.Click += new System.EventHandler(this.ForwardButtonClick);
//
// urlTextBox
//
this.urlTextBox.AutoSize = false;
this.urlTextBox.Name = "urlTextBox";
this.urlTextBox.Size = new System.Drawing.Size(500, 25);
this.urlTextBox.KeyUp += new System.Windows.Forms.KeyEventHandler(this.UrlTextBoxKeyUp);
//
// goButton
//
this.goButton.Image = global::CefSharp.WinForms.Example.Properties.Resources.nav_plain_green;
this.goButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.goButton.Name = "goButton";
this.goButton.Size = new System.Drawing.Size(42, 22);
this.goButton.Text = "Go";
this.goButton.Click += new System.EventHandler(this.GoButtonClick);
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(730, 24);
this.menuStrip1.TabIndex = 1;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "File";
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.exitToolStripMenuItem.Text = "Exit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.ExitMenuItemClick);
//
// SimpleBrowserForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(730, 490);
this.Controls.Add(this.toolStripContainer);
this.Controls.Add(this.menuStrip1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.menuStrip1;
this.Name = "SimpleBrowserForm";
this.Text = "SimpleBrowserForm";
this.toolStripContainer.ContentPanel.ResumeLayout(false);
this.toolStripContainer.ContentPanel.PerformLayout();
this.toolStripContainer.TopToolStripPanel.ResumeLayout(false);
this.toolStripContainer.TopToolStripPanel.PerformLayout();
this.toolStripContainer.ResumeLayout(false);
this.toolStripContainer.PerformLayout();
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ToolStripContainer toolStripContainer;
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.ToolStripButton backButton;
private System.Windows.Forms.ToolStripButton forwardButton;
private System.Windows.Forms.ToolStripTextBox urlTextBox;
private System.Windows.Forms.ToolStripButton goButton;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.Label outputLabel;
private System.Windows.Forms.Label statusLabel;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Network Client
/// </summary>
public partial interface INetworkManagementClient : System.IDisposable
{
/// <summary>
/// The base URI of the service.
/// </summary>
System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
JsonSerializerSettings SerializationSettings { get; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
JsonSerializerSettings DeserializationSettings { get; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
ServiceClientCredentials Credentials { get; }
/// <summary>
/// The subscription credentials which uniquely identify the Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
string SubscriptionId { get; set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running
/// Operations. Default value is 30.
/// </summary>
int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated
/// and included in each request. Default is true.
/// </summary>
bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IApplicationGatewaysOperations.
/// </summary>
IApplicationGatewaysOperations ApplicationGateways { get; }
/// <summary>
/// Gets the IApplicationSecurityGroupsOperations.
/// </summary>
IApplicationSecurityGroupsOperations ApplicationSecurityGroups { get; }
/// <summary>
/// Gets the IAvailableEndpointServicesOperations.
/// </summary>
IAvailableEndpointServicesOperations AvailableEndpointServices { get; }
/// <summary>
/// Gets the IExpressRouteCircuitAuthorizationsOperations.
/// </summary>
IExpressRouteCircuitAuthorizationsOperations ExpressRouteCircuitAuthorizations { get; }
/// <summary>
/// Gets the IExpressRouteCircuitPeeringsOperations.
/// </summary>
IExpressRouteCircuitPeeringsOperations ExpressRouteCircuitPeerings { get; }
/// <summary>
/// Gets the IExpressRouteCircuitsOperations.
/// </summary>
IExpressRouteCircuitsOperations ExpressRouteCircuits { get; }
/// <summary>
/// Gets the IExpressRouteServiceProvidersOperations.
/// </summary>
IExpressRouteServiceProvidersOperations ExpressRouteServiceProviders { get; }
/// <summary>
/// Gets the ILoadBalancersOperations.
/// </summary>
ILoadBalancersOperations LoadBalancers { get; }
/// <summary>
/// Gets the ILoadBalancerBackendAddressPoolsOperations.
/// </summary>
ILoadBalancerBackendAddressPoolsOperations LoadBalancerBackendAddressPools { get; }
/// <summary>
/// Gets the ILoadBalancerFrontendIPConfigurationsOperations.
/// </summary>
ILoadBalancerFrontendIPConfigurationsOperations LoadBalancerFrontendIPConfigurations { get; }
/// <summary>
/// Gets the IInboundNatRulesOperations.
/// </summary>
IInboundNatRulesOperations InboundNatRules { get; }
/// <summary>
/// Gets the ILoadBalancerLoadBalancingRulesOperations.
/// </summary>
ILoadBalancerLoadBalancingRulesOperations LoadBalancerLoadBalancingRules { get; }
/// <summary>
/// Gets the ILoadBalancerNetworkInterfacesOperations.
/// </summary>
ILoadBalancerNetworkInterfacesOperations LoadBalancerNetworkInterfaces { get; }
/// <summary>
/// Gets the ILoadBalancerProbesOperations.
/// </summary>
ILoadBalancerProbesOperations LoadBalancerProbes { get; }
/// <summary>
/// Gets the INetworkInterfacesOperations.
/// </summary>
INetworkInterfacesOperations NetworkInterfaces { get; }
/// <summary>
/// Gets the INetworkInterfaceIPConfigurationsOperations.
/// </summary>
INetworkInterfaceIPConfigurationsOperations NetworkInterfaceIPConfigurations { get; }
/// <summary>
/// Gets the INetworkInterfaceLoadBalancersOperations.
/// </summary>
INetworkInterfaceLoadBalancersOperations NetworkInterfaceLoadBalancers { get; }
/// <summary>
/// Gets the INetworkSecurityGroupsOperations.
/// </summary>
INetworkSecurityGroupsOperations NetworkSecurityGroups { get; }
/// <summary>
/// Gets the ISecurityRulesOperations.
/// </summary>
ISecurityRulesOperations SecurityRules { get; }
/// <summary>
/// Gets the IDefaultSecurityRulesOperations.
/// </summary>
IDefaultSecurityRulesOperations DefaultSecurityRules { get; }
/// <summary>
/// Gets the INetworkWatchersOperations.
/// </summary>
INetworkWatchersOperations NetworkWatchers { get; }
/// <summary>
/// Gets the IPacketCapturesOperations.
/// </summary>
IPacketCapturesOperations PacketCaptures { get; }
/// <summary>
/// Gets the IPublicIPAddressesOperations.
/// </summary>
IPublicIPAddressesOperations PublicIPAddresses { get; }
/// <summary>
/// Gets the IRouteFiltersOperations.
/// </summary>
IRouteFiltersOperations RouteFilters { get; }
/// <summary>
/// Gets the IRouteFilterRulesOperations.
/// </summary>
IRouteFilterRulesOperations RouteFilterRules { get; }
/// <summary>
/// Gets the IRouteTablesOperations.
/// </summary>
IRouteTablesOperations RouteTables { get; }
/// <summary>
/// Gets the IRoutesOperations.
/// </summary>
IRoutesOperations Routes { get; }
/// <summary>
/// Gets the IBgpServiceCommunitiesOperations.
/// </summary>
IBgpServiceCommunitiesOperations BgpServiceCommunities { get; }
/// <summary>
/// Gets the IUsagesOperations.
/// </summary>
IUsagesOperations Usages { get; }
/// <summary>
/// Gets the IVirtualNetworksOperations.
/// </summary>
IVirtualNetworksOperations VirtualNetworks { get; }
/// <summary>
/// Gets the ISubnetsOperations.
/// </summary>
ISubnetsOperations Subnets { get; }
/// <summary>
/// Gets the IVirtualNetworkPeeringsOperations.
/// </summary>
IVirtualNetworkPeeringsOperations VirtualNetworkPeerings { get; }
/// <summary>
/// Gets the IVirtualNetworkGatewaysOperations.
/// </summary>
IVirtualNetworkGatewaysOperations VirtualNetworkGateways { get; }
/// <summary>
/// Gets the IVirtualNetworkGatewayConnectionsOperations.
/// </summary>
IVirtualNetworkGatewayConnectionsOperations VirtualNetworkGatewayConnections { get; }
/// <summary>
/// Gets the ILocalNetworkGatewaysOperations.
/// </summary>
ILocalNetworkGatewaysOperations LocalNetworkGateways { get; }
/// <summary>
/// Checks whether a domain name in the cloudapp.azure.com zone is
/// available for use.
/// </summary>
/// <param name='location'>
/// The location of the domain name.
/// </param>
/// <param name='domainNameLabel'>
/// The domain name to be verified. It must conform to the following
/// regular expression: ^[a-z][a-z0-9-]{1,61}[a-z0-9]$.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<DnsNameAvailabilityResult>> CheckDnsNameAvailabilityWithHttpMessagesAsync(string location, string domainNameLabel, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, 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.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.IO;
using System.Text;
using Encog.App.Analyst.CSV.Basic;
using Encog.App.Analyst.Script.Normalize;
using Encog.App.Quant;
using Encog.ML;
using Encog.ML.Data;
using Encog.ML.Data.Basic;
using Encog.Util.CSV;
namespace Encog.App.Analyst.CSV
{
/// <summary>
/// Used by the analyst to evaluate a CSV file.
/// </summary>
public class AnalystEvaluateRawCSV : BasicFile
{
/// <summary>
/// The analyst file to use.
/// </summary>
private EncogAnalyst _analyst;
/// <summary>
/// The ideal count.
/// </summary>
private int _idealCount;
/// <summary>
/// The input count.
/// </summary>
private int _inputCount;
/// <summary>
/// The output count.
/// </summary>
private int _outputCount;
/// <summary>
/// Analyze the data. This counts the records and prepares the data to be
/// processed.
/// </summary>
/// <param name="theAnalyst">The analyst to use.</param>
/// <param name="inputFile">The input file.</param>
/// <param name="headers">True if headers are present.</param>
/// <param name="format">The format the file is in.</param>
public void Analyze(EncogAnalyst theAnalyst,
FileInfo inputFile, bool headers, CSVFormat format)
{
InputFilename = inputFile;
ExpectInputHeaders = headers;
Format = format;
_analyst = theAnalyst;
Analyzed = true;
PerformBasicCounts();
_inputCount = _analyst.DetermineInputCount();
_outputCount = _analyst.DetermineOutputCount();
_idealCount = InputHeadings.Length - _inputCount;
if ((InputHeadings.Length != _inputCount)
&& (InputHeadings.Length != (_inputCount + _outputCount)))
{
throw new AnalystError("Invalid number of columns("
+ InputHeadings.Length + "), must match input("
+ _inputCount + ") count or input+output("
+ (_inputCount + _outputCount) + ") count.");
}
}
/// <summary>
/// Prepare the output file, write headers if needed.
/// </summary>
/// <param name="outputFile">The name of the output file.</param>
/// <returns>The output stream for the text file.</returns>
private StreamWriter AnalystPrepareOutputFile(FileInfo outputFile)
{
try
{
var tw = new StreamWriter(outputFile.OpenWrite());
// write headers, if needed
if (ProduceOutputHeaders)
{
var line = new StringBuilder();
// first handle the input fields
foreach (AnalystField field in _analyst.Script.Normalize.NormalizedFields)
{
if (field.Input)
{
field.AddRawHeadings(line, null, Format);
}
}
// now, handle any ideal fields
if (_idealCount > 0)
{
foreach (AnalystField field in _analyst.Script.Normalize.NormalizedFields)
{
if (field.Output)
{
field.AddRawHeadings(line, "ideal:",
Format);
}
}
}
// now, handle the output fields
foreach (AnalystField field in _analyst.Script.Normalize.NormalizedFields)
{
if (field.Output)
{
field.AddRawHeadings(line, "output:", Format);
}
}
tw.WriteLine(line.ToString());
}
return tw;
}
catch (IOException e)
{
throw new QuantError(e);
}
}
/// <summary>
/// Process the file.
/// </summary>
/// <param name="outputFile">The output file.</param>
/// <param name="method">The method to use.</param>
public void Process(FileInfo outputFile, IMLRegression method)
{
var csv = new ReadCSV(InputFilename.ToString(),
ExpectInputHeaders, Format);
if (method.InputCount != _inputCount)
{
throw new AnalystError("This machine learning method has "
+ method.InputCount
+ " inputs, however, the data has " + _inputCount
+ " inputs.");
}
var input = new BasicMLData(method.InputCount);
StreamWriter tw = AnalystPrepareOutputFile(outputFile);
ResetStatus();
while (csv.Next())
{
UpdateStatus(false);
var row = new LoadedRow(csv, _idealCount);
int dataIndex = 0;
// load the input data
for (int i = 0; i < _inputCount; i++)
{
String str = row.Data[i];
double d = Format.Parse(str);
input[i] = d;
dataIndex++;
}
// do we need to skip the ideal values?
dataIndex += _idealCount;
// compute the result
IMLData output = method.Compute(input);
// display the computed result
for (int i = 0; i < _outputCount; i++)
{
double d = output[i];
row.Data[dataIndex++] = Format.Format(d, Precision);
}
WriteRow(tw, row);
}
ReportDone(false);
tw.Close();
csv.Close();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
public class Outside
{
public class Inside
{
public void GenericMethod<T>() { }
public void TwoGenericMethod<T, U>() { }
}
public void GenericMethod<T>() { }
public void TwoGenericMethod<T, U>() { }
}
public class Outside<T>
{
public class Inside<U>
{
public void GenericMethod<V>() { }
public void TwoGenericMethod<V, W>() { }
}
public void GenericMethod<U>() { }
public void TwoGenericMethod<U, V>() { }
}
namespace System.Tests
{
public partial class TypeTests
{
[Fact]
public void FilterName_Get_ReturnsExpected()
{
Assert.NotNull(Type.FilterName);
Assert.Same(Type.FilterName, Type.FilterName);
Assert.NotSame(Type.FilterName, Type.FilterNameIgnoreCase);
}
[Theory]
[InlineData("FilterName_Invoke_DelegateFiltersExpectedMembers", true)]
[InlineData(" FilterName_Invoke_DelegateFiltersExpectedMembers ", true)]
[InlineData("*", true)]
[InlineData(" * ", true)]
[InlineData(" Filter* ", true)]
[InlineData("FilterName_Invoke_DelegateFiltersExpectedMembe*", true)]
[InlineData("FilterName_Invoke_DelegateFiltersExpectedMember*", true)]
[InlineData("filterName_Invoke_DelegateFiltersExpectedMembers", false)]
[InlineData("FilterName_Invoke_DelegateFiltersExpectedMemberss*", false)]
[InlineData("FilterName", false)]
[InlineData("*FilterName", false)]
[InlineData("", false)]
[InlineData(" ", false)]
public void FilterName_Invoke_DelegateFiltersExpectedMembers(string filterCriteria, bool expected)
{
MethodInfo mi = typeof(TypeTests).GetMethod(nameof(FilterName_Invoke_DelegateFiltersExpectedMembers));
Assert.Equal(expected, Type.FilterName(mi, filterCriteria));
}
[Fact]
public void FilterName_InvalidFilterCriteria_ThrowsInvalidFilterCriteriaException()
{
MethodInfo mi = typeof(TypeTests).GetMethod(nameof(FilterName_Invoke_DelegateFiltersExpectedMembers));
Assert.Throws<InvalidFilterCriteriaException>(() => Type.FilterName(mi, null));
Assert.Throws<InvalidFilterCriteriaException>(() => Type.FilterName(mi, new object()));
}
[Fact]
public void FilterNameIgnoreCase_Get_ReturnsExpected()
{
Assert.NotNull(Type.FilterNameIgnoreCase);
Assert.Same(Type.FilterNameIgnoreCase, Type.FilterNameIgnoreCase);
Assert.NotSame(Type.FilterNameIgnoreCase, Type.FilterName);
}
[Theory]
[InlineData("FilterNameIgnoreCase_Invoke_DelegateFiltersExpectedMembers", true)]
[InlineData("filternameignorecase_invoke_delegatefiltersexpectedmembers", true)]
[InlineData(" filterNameIgnoreCase_Invoke_DelegateFiltersexpectedMembers ", true)]
[InlineData("*", true)]
[InlineData(" * ", true)]
[InlineData(" fIlTeR* ", true)]
[InlineData("FilterNameIgnoreCase_invoke_delegateFiltersExpectedMembe*", true)]
[InlineData("FilterNameIgnoreCase_invoke_delegateFiltersExpectedMember*", true)]
[InlineData("filterName_Invoke_DelegateFiltersExpectedMembers", false)]
[InlineData("filterNameIgnoreCase_Invoke_DelegateFiltersExpectedMemberss", false)]
[InlineData("FilterNameIgnoreCase_Invoke_DelegateFiltersExpectedMemberss*", false)]
[InlineData("filterNameIgnoreCase", false)]
[InlineData("*FilterNameIgnoreCase", false)]
[InlineData("", false)]
[InlineData(" ", false)]
public void FilterNameIgnoreCase_Invoke_DelegateFiltersExpectedMembers(string filterCriteria, bool expected)
{
MethodInfo mi = typeof(TypeTests).GetMethod(nameof(FilterNameIgnoreCase_Invoke_DelegateFiltersExpectedMembers));
Assert.Equal(expected, Type.FilterNameIgnoreCase(mi, filterCriteria));
}
[Fact]
public void FilterNameIgnoreCase_InvalidFilterCriteria_ThrowsInvalidFilterCriteriaException()
{
MethodInfo mi = typeof(TypeTests).GetMethod(nameof(FilterName_Invoke_DelegateFiltersExpectedMembers));
Assert.Throws<InvalidFilterCriteriaException>(() => Type.FilterNameIgnoreCase(mi, null));
Assert.Throws<InvalidFilterCriteriaException>(() => Type.FilterNameIgnoreCase(mi, new object()));
}
public static IEnumerable<object[]> FindMembers_TestData()
{
yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterName, "HelloWorld", 0 };
yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterName, "FilterName_Invoke_DelegateFiltersExpectedMembers", 1 };
yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterName, "FilterName_Invoke_Delegate*", 1 };
yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterName, "filterName_Invoke_Delegate*", 0 };
yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterNameIgnoreCase, "HelloWorld", 0 };
yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterNameIgnoreCase, "FilterName_Invoke_DelegateFiltersExpectedMembers", 1 };
yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterNameIgnoreCase, "FilterName_Invoke_Delegate*", 1 };
yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterNameIgnoreCase, "filterName_Invoke_Delegate*", 1 };
}
[Theory]
[MemberData(nameof(FindMembers_TestData))]
public void FindMembers_Invoke_ReturnsExpected(MemberTypes memberType, BindingFlags bindingAttr, MemberFilter filter, object filterCriteria, int expectedLength)
{
Assert.Equal(expectedLength, typeof(TypeTests).FindMembers(memberType, bindingAttr, filter, filterCriteria).Length);
}
[Theory]
[InlineData(typeof(int), typeof(int))]
[InlineData(typeof(int[]), typeof(int[]))]
[InlineData(typeof(Outside<int>), typeof(Outside<int>))]
public void TypeHandle(Type t1, Type t2)
{
RuntimeTypeHandle r1 = t1.TypeHandle;
RuntimeTypeHandle r2 = t2.TypeHandle;
Assert.Equal(r1, r2);
Assert.Equal(t1, Type.GetTypeFromHandle(r1));
Assert.Equal(t1, Type.GetTypeFromHandle(r2));
}
[Fact]
public void GetTypeFromDefaultHandle()
{
Assert.Null(Type.GetTypeFromHandle(default(RuntimeTypeHandle)));
}
[Theory]
[InlineData(typeof(int[]), 1)]
[InlineData(typeof(int[,,]), 3)]
public void GetArrayRank_Get_ReturnsExpected(Type t, int expected)
{
Assert.Equal(expected, t.GetArrayRank());
}
[Theory]
[InlineData(typeof(int))]
[InlineData(typeof(IList<int>))]
[InlineData(typeof(IList<>))]
public void GetArrayRank_NonArrayType_ThrowsArgumentException(Type t)
{
AssertExtensions.Throws<ArgumentException>(null, () => t.GetArrayRank());
}
[Theory]
[InlineData(typeof(int), typeof(int[]))]
public void MakeArrayType_Invoke_ReturnsExpected(Type t, Type tArrayExpected)
{
Type tArray = t.MakeArrayType();
Assert.Equal(tArrayExpected, tArray);
Assert.Equal(t, tArray.GetElementType());
Assert.True(tArray.IsArray);
Assert.True(tArray.HasElementType);
string s1 = t.ToString();
string s2 = tArray.ToString();
Assert.Equal(s2, s1 + "[]");
}
[Theory]
[InlineData(typeof(int))]
public void MakeByRefType_Invoke_ReturnsExpected(Type t)
{
Type tRef1 = t.MakeByRefType();
Type tRef2 = t.MakeByRefType();
Assert.Equal(tRef1, tRef2);
Assert.True(tRef1.IsByRef);
Assert.True(tRef1.HasElementType);
Assert.Equal(t, tRef1.GetElementType());
string s1 = t.ToString();
string s2 = tRef1.ToString();
Assert.Equal(s2, s1 + "&");
}
[Theory]
[InlineData("System.Nullable`1[System.Int32]", typeof(int?))]
[InlineData("System.Int32*", typeof(int*))]
[InlineData("System.Int32**", typeof(int**))]
[InlineData("Outside`1", typeof(Outside<>))]
[InlineData("Outside`1+Inside`1", typeof(Outside<>.Inside<>))]
[InlineData("Outside[]", typeof(Outside[]))]
[InlineData("Outside[,,]", typeof(Outside[,,]))]
[InlineData("Outside[][]", typeof(Outside[][]))]
[InlineData("Outside`1[System.Nullable`1[System.Boolean]]", typeof(Outside<bool?>))]
public void GetTypeByName_ValidType_ReturnsExpected(string typeName, Type expectedType)
{
Assert.Equal(expectedType, Type.GetType(typeName, throwOnError: false, ignoreCase: false));
Assert.Equal(expectedType, Type.GetType(typeName.ToLower(), throwOnError: false, ignoreCase: true));
}
[Theory]
[InlineData("system.nullable`1[system.int32]", typeof(TypeLoadException), false)]
[InlineData("System.NonExistingType", typeof(TypeLoadException), false)]
[InlineData("", typeof(TypeLoadException), false)]
[InlineData("System.Int32[,*,]", typeof(ArgumentException), false)]
[InlineData("Outside`2", typeof(TypeLoadException), false)]
[InlineData("Outside`1[System.Boolean, System.Int32]", typeof(ArgumentException), true)]
public void GetTypeByName_Invalid(string typeName, Type expectedException, bool alwaysThrowsException)
{
if (!alwaysThrowsException)
{
Assert.Null(Type.GetType(typeName, throwOnError: false, ignoreCase: false));
}
Assert.Throws(expectedException, () => Type.GetType(typeName, throwOnError: true, ignoreCase: false));
}
[Fact]
public void GetTypeByName_InvokeViaReflection_Success()
{
MethodInfo method = typeof(Type).GetMethod("GetType", new[] { typeof(string) });
object result = method.Invoke(null, new object[] { "System.Tests.TypeTests" });
Assert.Equal(typeof(TypeTests), result);
}
[Fact]
public void Delimiter()
{
Assert.Equal('.', Type.Delimiter);
}
[Theory]
[InlineData(typeof(bool), TypeCode.Boolean)]
[InlineData(typeof(byte), TypeCode.Byte)]
[InlineData(typeof(char), TypeCode.Char)]
[InlineData(typeof(DateTime), TypeCode.DateTime)]
[InlineData(typeof(decimal), TypeCode.Decimal)]
[InlineData(typeof(double), TypeCode.Double)]
[InlineData(null, TypeCode.Empty)]
[InlineData(typeof(short), TypeCode.Int16)]
[InlineData(typeof(int), TypeCode.Int32)]
[InlineData(typeof(long), TypeCode.Int64)]
[InlineData(typeof(object), TypeCode.Object)]
[InlineData(typeof(System.Nullable), TypeCode.Object)]
[InlineData(typeof(Nullable<int>), TypeCode.Object)]
[InlineData(typeof(Dictionary<,>), TypeCode.Object)]
[InlineData(typeof(Exception), TypeCode.Object)]
[InlineData(typeof(sbyte), TypeCode.SByte)]
[InlineData(typeof(float), TypeCode.Single)]
[InlineData(typeof(string), TypeCode.String)]
[InlineData(typeof(ushort), TypeCode.UInt16)]
[InlineData(typeof(uint), TypeCode.UInt32)]
[InlineData(typeof(ulong), TypeCode.UInt64)]
public void GetTypeCode_ValidType_ReturnsExpected(Type t, TypeCode typeCode)
{
Assert.Equal(typeCode, Type.GetTypeCode(t));
}
[Fact]
public void ReflectionOnlyGetType()
{
Assert.Throws<PlatformNotSupportedException>(() => Type.ReflectionOnlyGetType(null, true, false));
Assert.Throws<PlatformNotSupportedException>(() => Type.ReflectionOnlyGetType("", true, true));
Assert.Throws<PlatformNotSupportedException>(() => Type.ReflectionOnlyGetType("System.Tests.TypeTests", false, true));
}
}
public class TypeTestsExtended {
public class ContextBoundClass : ContextBoundObject
{
public string Value = "The Value property.";
}
static string s_testAssemblyPath = Path.Combine(Environment.CurrentDirectory, "TestLoadAssembly.dll");
static string testtype = "System.Collections.Generic.Dictionary`2[[Program, Foo], [Program, Foo]]";
private static Func<AssemblyName, Assembly> assemblyloader = (aName) => aName.Name == "TestLoadAssembly" ?
Assembly.LoadFrom(@".\TestLoadAssembly.dll") :
null;
private static Func<Assembly, string, bool, Type> typeloader = (assem, name, ignore) => assem == null ?
Type.GetType(name, false, ignore) :
assem.GetType(name, false, ignore);
[Fact]
public void GetTypeByName()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
RemoteExecutor.Invoke(() =>
{
string test1 = testtype;
Type t1 = Type.GetType(test1,
(aName) => aName.Name == "Foo" ?
Assembly.LoadFrom(s_testAssemblyPath) : null,
typeloader,
true
);
Assert.NotNull(t1);
string test2 = "System.Collections.Generic.Dictionary`2[[Program, TestLoadAssembly], [Program, TestLoadAssembly]]";
Type t2 = Type.GetType(test2, assemblyloader, typeloader, true);
Assert.NotNull(t2);
Assert.Equal(t1, t2);
}, options).Dispose();
}
[Theory]
[InlineData("System.Collections.Generic.Dictionary`2[[Program, TestLoadAssembly], [Program2, TestLoadAssembly]]")]
[InlineData("")]
public void GetTypeByName_NoSuchType_ThrowsTypeLoadException(string typeName)
{
RemoteExecutor.Invoke(marshalledTypeName =>
{
Assert.Throws<TypeLoadException>(() => Type.GetType(marshalledTypeName, assemblyloader, typeloader, true));
Assert.Null(Type.GetType(marshalledTypeName, assemblyloader, typeloader, false));
}, typeName).Dispose();
}
[Fact]
public void GetTypeByNameCaseSensitiveTypeloadFailure()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
RemoteExecutor.Invoke(() =>
{
//Type load failure due to case sensitive search of type Ptogram
string test3 = "System.Collections.Generic.Dictionary`2[[Program, TestLoadAssembly], [program, TestLoadAssembly]]";
Assert.Throws<TypeLoadException>(() =>
Type.GetType(test3,
assemblyloader,
typeloader,
true,
false //case sensitive
));
//non throwing version
Type t2 = Type.GetType(test3,
assemblyloader,
typeloader,
false, //no throw
false
);
Assert.Null(t2);
}, options).Dispose();
}
[Fact]
public void IsContextful()
{
Assert.True(!typeof(TypeTestsExtended).IsContextful);
Assert.True(!typeof(ContextBoundClass).IsContextful);
}
#region GetInterfaceMap tests
public static IEnumerable<object[]> GetInterfaceMap_TestData()
{
yield return new object[]
{
typeof(ISimpleInterface),
typeof(SimpleType),
new Tuple<MethodInfo, MethodInfo>[]
{
new Tuple<MethodInfo, MethodInfo>(typeof(ISimpleInterface).GetMethod("Method"), typeof(SimpleType).GetMethod("Method")),
new Tuple<MethodInfo, MethodInfo>(typeof(ISimpleInterface).GetMethod("GenericMethod"), typeof(SimpleType).GetMethod("GenericMethod"))
}
};
yield return new object[]
{
typeof(IGenericInterface<object>),
typeof(DerivedType),
new Tuple<MethodInfo, MethodInfo>[]
{
new Tuple<MethodInfo, MethodInfo>(typeof(IGenericInterface<object>).GetMethod("Method"), typeof(DerivedType).GetMethod("Method", new Type[] { typeof(object) })),
}
};
yield return new object[]
{
typeof(IGenericInterface<string>),
typeof(DerivedType),
new Tuple<MethodInfo, MethodInfo>[]
{
new Tuple<MethodInfo, MethodInfo>(typeof(IGenericInterface<string>).GetMethod("Method"), typeof(DerivedType).GetMethod("Method", new Type[] { typeof(string) })),
}
};
}
[Theory]
[MemberData(nameof(GetInterfaceMap_TestData))]
public void GetInterfaceMap(Type interfaceType, Type classType, Tuple<MethodInfo, MethodInfo>[] expectedMap)
{
InterfaceMapping actualMapping = classType.GetInterfaceMap(interfaceType);
Assert.Equal(interfaceType, actualMapping.InterfaceType);
Assert.Equal(classType, actualMapping.TargetType);
Assert.Equal(expectedMap.Length, actualMapping.InterfaceMethods.Length);
Assert.Equal(expectedMap.Length, actualMapping.TargetMethods.Length);
for (int i = 0; i < expectedMap.Length; i++)
{
Assert.Contains(expectedMap[i].Item1, actualMapping.InterfaceMethods);
int index = Array.IndexOf(actualMapping.InterfaceMethods, expectedMap[i].Item1);
Assert.Equal(expectedMap[i].Item2, actualMapping.TargetMethods[index]);
}
}
interface ISimpleInterface
{
void Method();
void GenericMethod<T>();
}
class SimpleType : ISimpleInterface
{
public void Method() { }
public void GenericMethod<T>() { }
}
interface IGenericInterface<T>
{
void Method(T arg);
}
class GenericBaseType<T> : IGenericInterface<T>
{
public void Method(T arg) { }
}
class DerivedType : GenericBaseType<object>, IGenericInterface<string>
{
public void Method(string arg) { }
}
#endregion
}
public class NonGenericClass { }
public class NonGenericSubClassOfNonGeneric : NonGenericClass { }
public class GenericClass<T> { }
public class NonGenericSubClassOfGeneric : GenericClass<string> { }
public class GenericClass<T, U> { }
public abstract class AbstractClass { }
public struct NonGenericStruct { }
public ref struct RefStruct { }
public struct GenericStruct<T> { }
public struct GenericStruct<T, U> { }
public interface NonGenericInterface { }
public interface GenericInterface<T> { }
public interface GenericInterface<T, U> { }
}
| |
#define USE_LIST_VIEW
#region Namespaces
using System;
using System.Diagnostics;
using System.Linq;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB.Electrical;
#endregion // Namespaces
namespace BipChecker
{
/// <summary>
/// List all accessible built-in parameters on
/// a selected element in a DataGridView.
/// Todo: add support for shared parameters also.
/// </summary>
[Transaction( TransactionMode.ReadOnly )]
public class BuiltInParamsChecker : IExternalCommand
{
const string _type_prompt =
"This element {0}, so it has both type and"
+ " instance parameters. By default, the instance"
+ " parameters are displayed."
//+ " If you select 'No',"
//+ " the type parameters will be displayed instead."
+ " Would you like to see the instance parameters or the type parameters?";
#region Contained in ParameterSet Collection
#region Unnecessarily complicated first approach
/// <summary>
/// Return BuiltInParameter id for a given parameter,
/// assuming it is a built-in parameter.
/// </summary>
static BuiltInParameter BipOf( Parameter p )
{
return ( p.Definition as InternalDefinition )
.BuiltInParameter;
}
/// <summary>
/// Check whether two given parameters represent
/// the same parameter, i.e. shared parameters
/// have the same GUID, others the same built-in
/// parameter id.
/// </summary>
static bool IsSameParameter( Parameter p, Parameter q )
{
return ( p.IsShared == q.IsShared )
&& ( p.IsShared
? p.GUID.Equals( q.GUID )
: BipOf( p ) == BipOf( q ) );
}
/// <summary>
/// Return true if the given element parameter
/// retrieved by get_parameter( BuiltInParameter )
/// is contained in the element Parameters collection.
/// Workaround to replace ParameterSet.Contains.
/// Why does this not work?
/// return _parameter.Element.Parameters.Contains(_parameter);
/// </summary>
bool ContainedInCollectionUnnecessarilyComplicated(
Parameter p,
ParameterSet set )
{
bool rc = false;
foreach( Parameter q in set )
{
rc = IsSameParameter( p, q );
if( rc )
{
break;
}
}
return rc;
}
#endregion // Unnecessarily complicated first approach
/// <summary>
/// Return true if the given element parameter
/// retrieved by get_Parameter( BuiltInParameter )
/// is contained in the element Parameters collection.
/// Workaround to replace ParameterSet.Contains.
/// Why does the following statement not work?
/// return _parameter.Element.Parameters.Contains(_parameter);
/// </summary>
bool ContainedInCollection(
Parameter p,
ParameterSet set )
{
return set
.OfType<Parameter>()
.Any( x => x.Id == p.Id );
}
#endregion // Contained in ParameterSet Collection
/// <summary>
/// Revit external command to list all valid
/// built-in parameters for a given selected
/// element.
/// </summary>
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements )
{
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Document doc = uidoc.Document;
// Select element
Element e
= Util.GetSingleSelectedElementOrPrompt(
uidoc );
if( null == e )
{
return Result.Cancelled;
}
bool isSymbol = false;
// For a family instance, ask user whether to
// display instance or type parameters; in a
// similar manner, we could add dedicated
// switches for Wall --> WallType,
// Floor --> FloorType etc. ...
if( e is FamilyInstance )
{
FamilyInstance inst = e as FamilyInstance;
if( null != inst.Symbol )
{
string symbol_name = Util.ElementDescription(
inst.Symbol, true );
string family_name = Util.ElementDescription(
inst.Symbol.Family, true );
string msg = string.Format( _type_prompt,
"is a family instance" );
if( !Util.QuestionMsg( msg ) )
{
e = inst.Symbol;
isSymbol = true;
}
}
}
else if( e.CanHaveTypeAssigned() )
{
ElementId typeId = e.GetTypeId();
if( null == typeId )
{
Util.InfoMsg( "Element can have a type,"
+ " but the current type is null." );
}
else if( ElementId.InvalidElementId == typeId )
{
Util.InfoMsg( "Element can have a type,"
+ " but the current type id is the"
+ " invalid element id." );
}
else
{
Element type = doc.GetElement( typeId );
if( null == type )
{
Util.InfoMsg( "Element has a type,"
+ " but it cannot be accessed." );
}
else
{
string msg = string.Format( _type_prompt,
"has an element type" );
if( !Util.QuestionMsg( msg ) )
{
e = type;
isSymbol = true;
}
}
}
}
// Retrieve parameter data
SortableBindingList<ParameterData> data
= new SortableBindingList<ParameterData>();
{
WaitCursor waitCursor = new WaitCursor();
ParameterSet set = e.Parameters;
bool containedInCollection;
/*
* Edited by Chekalin Victor 13.12.2012
* !!! This implemention does not work properly
* if enum has the same integer value
* For example, BuiltInParameter.All_MODEL_COST and
* BuiltInParameter.DOOR_COST have -1001205 integer value
*
Array bips = Enum.GetValues(
typeof( BuiltInParameter ) );
int n = bips.Length;
*
*/
/*
* Edited by Chekalin Victor 13.12.2012
*/
var bipNames =
Enum.GetNames( typeof( BuiltInParameter ) );
Parameter p;
/*
* Edited by Chekalin Victor 13.12.2012
*/
//foreach( BuiltInParameter a in bips )
foreach( var bipName in bipNames )
{
BuiltInParameter a;
if( !Enum.TryParse( bipName, out a ) )
continue;
try
{
p = e.get_Parameter( a );
#region Check for external definition
#if CHECK_FOR_EXTERNAL_DEFINITION
Definition d = p.Definition;
ExternalDefinition e = d as ExternalDefinition; // this is never possible
string guid = ( null == e ) ? null : e.GUID.ToString();
#endif // CHECK_FOR_EXTERNAL_DEFINITION
#endregion // Check for external definition
if( null != p )
{
string valueString =
( StorageType.ElementId == p.StorageType )
? Util.GetParameterValue2( p, doc )
: p.AsValueString();
//containedInCollection = set.Contains( p ); // this does not work
containedInCollection = ContainedInCollection( p, set );
data.Add( new ParameterData( a, p,
valueString,
containedInCollection,
bipName ) );
}
}
catch( Exception ex )
{
Debug.Print(
"Exception retrieving built-in parameter {0}: {1}",
a, ex );
}
}
}
// Retrieve parameters from Element.Parameters collection
foreach( Parameter p in e.Parameters )
{
string valueString =
( StorageType.ElementId == p.StorageType )
? Util.GetParameterValue2( p, doc )
: p.AsValueString();
ParameterData parameterData = new ParameterData(
( p.Definition as InternalDefinition ).BuiltInParameter,
p,
valueString,
true,
null );
if( !data.Contains( parameterData ) )
data.Add( parameterData );
}
// Display form
string description
= Util.ElementDescription( e, true )
+ ( isSymbol
? " Type"
: " Instance" );
#if USE_LIST_VIEW
using( BuiltInParamsCheckerFormListView form
= new BuiltInParamsCheckerFormListView( e,
description, data ) )
#else
using (BuiltInParamsCheckerForm form
= new BuiltInParamsCheckerForm(
description, data))
#endif // USE_LIST_VIEW
{
form.ShowDialog();
}
return Result.Succeeded;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Threading;
using System.Threading.Tasks;
using SteamKit2;
using SteamTrade.Exceptions;
using SteamTrade.TradeWebAPI;
namespace SteamTrade
{
/// <summary>
/// Class which represents a trade.
/// Note that the logic that Steam uses can be seen from their web-client source-code: http://steamcommunity-a.akamaihd.net/public/javascript/economy_trade.js
/// </summary>
public partial class Trade
{
#region Static Public data
public static Schema CurrentSchema = null;
public enum TradeStatusType
{
OnGoing = 0,
CompletedSuccessfully = 1,
Empty = 2,
TradeCancelled = 3,
SessionExpired = 4,
TradeFailed = 5,
PendingConfirmation = 6
}
public string GetTradeStatusErrorString(TradeStatusType tradeStatusType)
{
switch(tradeStatusType)
{
case TradeStatusType.OnGoing:
return "is still going on";
case TradeStatusType.CompletedSuccessfully:
return "completed successfully";
case TradeStatusType.Empty:
return "completed empty - no items were exchanged";
case TradeStatusType.TradeCancelled:
return "was cancelled " + (tradeCancelledByBot ? "by bot" : "by other user");
case TradeStatusType.SessionExpired:
return String.Format("expired because {0} timed out", (otherUserTimingOut ? "other user" : "bot"));
case TradeStatusType.TradeFailed:
return "failed unexpectedly";
case TradeStatusType.PendingConfirmation:
return "completed - pending confirmation";
default:
return "STATUS IS UNKNOWN - THIS SHOULD NEVER HAPPEN!";
}
}
#endregion
private const int WEB_REQUEST_MAX_RETRIES = 3;
private const int WEB_REQUEST_TIME_BETWEEN_RETRIES_MS = 600;
// list to store all trade events already processed
private readonly List<TradeEvent> eventList;
// current bot's sid
private readonly SteamID mySteamId;
private readonly Dictionary<int, TradeUserAssets> myOfferedItemsLocalCopy;
private readonly TradeSession session;
private readonly Task<Inventory> myInventoryTask;
private readonly Task<Inventory> otherInventoryTask;
private List<TradeUserAssets> myOfferedItems;
private List<TradeUserAssets> otherOfferedItems;
private bool otherUserTimingOut;
private bool tradeCancelledByBot;
private int numUnknownStatusUpdates;
private long tradeOfferID; //Used for email confirmation
internal Trade(SteamID me, SteamID other, SteamWeb steamWeb, Task<Inventory> myInventoryTask, Task<Inventory> otherInventoryTask)
{
TradeStarted = false;
OtherIsReady = false;
MeIsReady = false;
mySteamId = me;
OtherSID = other;
session = new TradeSession(other, steamWeb);
this.eventList = new List<TradeEvent>();
myOfferedItemsLocalCopy = new Dictionary<int, TradeUserAssets>();
otherOfferedItems = new List<TradeUserAssets>();
myOfferedItems = new List<TradeUserAssets>();
this.otherInventoryTask = otherInventoryTask;
this.myInventoryTask = myInventoryTask;
}
#region Public Properties
/// <summary>Gets the other user's steam ID.</summary>
public SteamID OtherSID { get; private set; }
/// <summary>
/// Gets the bot's Steam ID.
/// </summary>
public SteamID MySteamId
{
get { return mySteamId; }
}
/// <summary>
/// Gets the inventory of the other user.
/// </summary>
public Inventory OtherInventory
{
get
{
if(otherInventoryTask == null)
return null;
otherInventoryTask.Wait();
return otherInventoryTask.Result;
}
}
/// <summary>
/// Gets the private inventory of the other user.
/// </summary>
public ForeignInventory OtherPrivateInventory { get; private set; }
/// <summary>
/// Gets the inventory of the bot.
/// </summary>
public Inventory MyInventory
{
get
{
if(myInventoryTask == null)
return null;
myInventoryTask.Wait();
return myInventoryTask.Result;
}
}
/// <summary>
/// Gets the items the user has offered, by itemid.
/// </summary>
/// <value>
/// The other offered items.
/// </value>
public IEnumerable<TradeUserAssets> OtherOfferedItems
{
get { return otherOfferedItems; }
}
/// <summary>
/// Gets the items the bot has offered, by itemid.
/// </summary>
/// <value>
/// The bot offered items.
/// </value>
public IEnumerable<TradeUserAssets> MyOfferedItems
{
get { return myOfferedItems; }
}
/// <summary>
/// Gets a value indicating if the other user is ready to trade.
/// </summary>
public bool OtherIsReady { get; private set; }
/// <summary>
/// Gets a value indicating if the bot is ready to trade.
/// </summary>
public bool MeIsReady { get; private set; }
/// <summary>
/// Gets a value indicating if a trade has started.
/// </summary>
public bool TradeStarted { get; private set; }
/// <summary>
/// Gets a value indicating if the remote trading partner cancelled the trade.
/// </summary>
public bool OtherUserCancelled { get; private set; }
/// <summary>
/// Gets a value indicating whether the trade completed normally. This
/// is independent of other flags.
/// </summary>
public bool HasTradeCompletedOk { get; private set; }
/// <summary>
/// Gets a value indicating whether the trade completed awaiting email confirmation. This
/// is independent of other flags.
/// </summary>
public bool IsTradeAwaitingConfirmation { get; private set; }
/// <summary>
/// Gets a value indicating whether the trade has finished (regardless of the cause, eg. success, cancellation, error, etc)
/// </summary>
public bool HasTradeEnded
{
get { return OtherUserCancelled || HasTradeCompletedOk || IsTradeAwaitingConfirmation || tradeCancelledByBot; }
}
/// <summary>
/// Gets a value indicating if the remote trading partner accepted the trade.
/// </summary>
public bool OtherUserAccepted { get; private set; }
#endregion
#region Public Events
public delegate void CloseHandler();
public delegate void CompleteHandler();
public delegate void WaitingForEmailHandler(long tradeOfferID);
public delegate void ErrorHandler(string errorMessage);
public delegate void StatusErrorHandler(TradeStatusType statusType);
public delegate void TimeoutHandler();
public delegate void SuccessfulInit();
public delegate void UserAddItemHandler(Schema.Item schemaItem, Inventory.Item inventoryItem);
public delegate void UserRemoveItemHandler(Schema.Item schemaItem, Inventory.Item inventoryItem);
public delegate void MessageHandler(string msg);
public delegate void UserSetReadyStateHandler(bool ready);
public delegate void UserAcceptHandler();
/// <summary>
/// When the trade closes, this is called. It doesn't matter
/// whether or not it was a timeout or an error, this is called
/// to close the trade.
/// </summary>
public event CloseHandler OnClose;
/// <summary>
/// Called when the trade ends awaiting email confirmation
/// </summary>
public event WaitingForEmailHandler OnAwaitingConfirmation;
/// <summary>
/// This is for handling errors that may occur, like inventories
/// not loading.
/// </summary>
public event ErrorHandler OnError;
/// <summary>
/// Specifically for trade_status errors.
/// </summary>
public event StatusErrorHandler OnStatusError;
/// <summary>
/// This occurs after Inventories have been loaded.
/// </summary>
public event SuccessfulInit OnAfterInit;
/// <summary>
/// This occurs when the other user adds an item to the trade.
/// </summary>
public event UserAddItemHandler OnUserAddItem;
/// <summary>
/// This occurs when the other user removes an item from the
/// trade.
/// </summary>
public event UserAddItemHandler OnUserRemoveItem;
/// <summary>
/// This occurs when the user sends a message to the bot over
/// trade.
/// </summary>
public event MessageHandler OnMessage;
/// <summary>
/// This occurs when the user sets their ready state to either
/// true or false.
/// </summary>
public event UserSetReadyStateHandler OnUserSetReady;
/// <summary>
/// This occurs when the user accepts the trade.
/// </summary>
public event UserAcceptHandler OnUserAccept;
#endregion
/// <summary>
/// Cancel the trade. This calls the OnClose handler, as well.
/// </summary>
public bool CancelTrade()
{
tradeCancelledByBot = true;
return RetryWebRequest(session.CancelTradeWebCmd);
}
/// <summary>
/// Adds a specified TF2 item by its itemid.
/// If the item is not a TF2 item, use the AddItem(ulong itemid, int appid, long contextid) overload
/// </summary>
/// <returns><c>false</c> if the tf2 item was not found in the inventory.</returns>
public bool AddItem(ulong itemid)
{
if(MyInventory.GetItem(itemid) == null)
{
return false;
}
else
{
return AddItem(new TradeUserAssets(440, 2, itemid));
}
}
public bool AddItem(ulong itemid, int appid, long contextid)
{
return AddItem(new TradeUserAssets(appid, contextid, itemid));
}
public bool AddItem(TradeUserAssets item)
{
var slot = NextTradeSlot();
bool success = RetryWebRequest(() => session.AddItemWebCmd(item.assetid, slot, item.appid, item.contextid));
if(success)
myOfferedItemsLocalCopy[slot] = item;
return success;
}
/// <summary>
/// Adds a single item by its Defindex.
/// </summary>
/// <returns>
/// <c>true</c> if an item was found with the corresponding
/// defindex, <c>false</c> otherwise.
/// </returns>
public bool AddItemByDefindex(int defindex)
{
List<Inventory.Item> items = MyInventory.GetItemsByDefindex(defindex);
foreach(Inventory.Item item in items)
{
if(item != null && myOfferedItemsLocalCopy.Values.All(o => o.assetid != item.Id) && !item.IsNotTradeable)
{
return AddItem(item.Id);
}
}
return false;
}
/// <summary>
/// Adds an entire set of items by Defindex to each successive
/// slot in the trade.
/// </summary>
/// <param name="defindex">The defindex. (ex. 5022 = crates)</param>
/// <param name="numToAdd">The upper limit on amount of items to add. <c>0</c> to add all items.</param>
/// <returns>Number of items added.</returns>
public uint AddAllItemsByDefindex(int defindex, uint numToAdd = 0)
{
List<Inventory.Item> items = MyInventory.GetItemsByDefindex(defindex);
uint added = 0;
foreach(Inventory.Item item in items)
{
if(item != null && myOfferedItemsLocalCopy.Values.All(o => o.assetid != item.Id) && !item.IsNotTradeable)
{
bool success = AddItem(item.Id);
if(success)
added++;
if(numToAdd > 0 && added >= numToAdd)
return added;
}
}
return added;
}
public bool RemoveItem(TradeUserAssets item)
{
return RemoveItem(item.assetid, item.appid, item.contextid);
}
/// <summary>
/// Removes an item by its itemid.
/// </summary>
/// <returns><c>false</c> the item was not found in the trade.</returns>
public bool RemoveItem(ulong itemid, int appid = 440, long contextid = 2)
{
int? slot = GetItemSlot(itemid);
if(!slot.HasValue)
return false;
bool success = RetryWebRequest(() => session.RemoveItemWebCmd(itemid, slot.Value, appid, contextid));
if(success)
myOfferedItemsLocalCopy.Remove(slot.Value);
return success;
}
/// <summary>
/// Removes an item with the given Defindex from the trade.
/// </summary>
/// <returns>
/// Returns <c>true</c> if it found a corresponding item; <c>false</c> otherwise.
/// </returns>
public bool RemoveItemByDefindex(int defindex)
{
foreach(TradeUserAssets asset in myOfferedItemsLocalCopy.Values)
{
Inventory.Item item = MyInventory.GetItem(asset.assetid);
if(item != null && item.Defindex == defindex)
{
return RemoveItem(item.Id);
}
}
return false;
}
/// <summary>
/// Removes an entire set of items by Defindex.
/// </summary>
/// <param name="defindex">The defindex. (ex. 5022 = crates)</param>
/// <param name="numToRemove">The upper limit on amount of items to remove. <c>0</c> to remove all items.</param>
/// <returns>Number of items removed.</returns>
public uint RemoveAllItemsByDefindex(int defindex, uint numToRemove = 0)
{
List<Inventory.Item> items = MyInventory.GetItemsByDefindex(defindex);
uint removed = 0;
foreach(Inventory.Item item in items)
{
if(item != null && myOfferedItemsLocalCopy.Values.Any(o => o.assetid == item.Id))
{
bool success = RemoveItem(item.Id);
if(success)
removed++;
if(numToRemove > 0 && removed >= numToRemove)
return removed;
}
}
return removed;
}
/// <summary>
/// Removes all offered items from the trade.
/// </summary>
/// <returns>Number of items removed.</returns>
public uint RemoveAllItems()
{
uint numRemoved = 0;
foreach(TradeUserAssets asset in myOfferedItemsLocalCopy.Values.ToList())
{
Inventory.Item item = MyInventory.GetItem(asset.assetid);
if(item != null)
{
bool wasRemoved = RemoveItem(item.Id);
if(wasRemoved)
numRemoved++;
}
}
return numRemoved;
}
/// <summary>
/// Sends a message to the user over the trade chat.
/// </summary>
public bool SendMessage(string msg)
{
return RetryWebRequest(() => session.SendMessageWebCmd(msg));
}
/// <summary>
/// Sets the bot to a ready status.
/// </summary>
public bool SetReady(bool ready)
{
//If the bot calls SetReady(false) and the call fails, we still want meIsReady to be
//set to false. Otherwise, if the call to SetReady() was a result of a callback
//from Trade.Poll() inside of the OnTradeAccept() handler, the OnTradeAccept()
//handler might think the bot is ready, when really it's not!
if(!ready)
MeIsReady = false;
ValidateLocalTradeItems();
return RetryWebRequest(() => session.SetReadyWebCmd(ready));
}
/// <summary>
/// Accepts the trade from the user. Returns whether the acceptance went through or not
/// </summary>
public bool AcceptTrade()
{
if(!MeIsReady)
return false;
ValidateLocalTradeItems();
return RetryWebRequest(session.AcceptTradeWebCmd);
}
/// <summary>
/// Calls the given function multiple times, until we get a non-null/non-false/non-zero result, or we've made at least
/// WEB_REQUEST_MAX_RETRIES attempts (with WEB_REQUEST_TIME_BETWEEN_RETRIES_MS between attempts)
/// </summary>
/// <returns>The result of the function if it succeeded, or default(T) (null/false/0) otherwise</returns>
private T RetryWebRequest<T>(Func<T> webEvent)
{
for(int i = 0; i < WEB_REQUEST_MAX_RETRIES; i++)
{
//Don't make any more requests if the trade has ended!
if (HasTradeEnded)
return default(T);
try
{
T result = webEvent();
// if the web request returned some error.
if(!EqualityComparer<T>.Default.Equals(result, default(T)))
return result;
}
catch(Exception ex)
{
// TODO: log to SteamBot.Log but... see issue #394
// realistically we should not throw anymore
Console.WriteLine(ex);
}
if(i != WEB_REQUEST_MAX_RETRIES)
{
//This will cause the bot to stop responding while we wait between web requests. ...Is this really what we want?
Thread.Sleep(WEB_REQUEST_TIME_BETWEEN_RETRIES_MS);
}
}
return default(T);
}
/// <summary>
/// This updates the trade. This is called at an interval of a
/// default of 800ms, not including the execution time of the
/// method itself.
/// </summary>
/// <returns><c>true</c> if the other trade partner performed an action; otherwise <c>false</c>.</returns>
public bool Poll()
{
if(!TradeStarted)
{
TradeStarted = true;
// since there is no feedback to let us know that the trade
// is fully initialized we assume that it is when we start polling.
if(OnAfterInit != null)
OnAfterInit();
}
TradeStatus status = RetryWebRequest(session.GetStatus);
if(status == null)
return false;
TradeStatusType tradeStatusType = (TradeStatusType) status.trade_status;
switch (tradeStatusType)
{
// Nothing happened. i.e. trade hasn't closed yet.
case TradeStatusType.OnGoing:
return HandleTradeOngoing(status);
// Successful trade
case TradeStatusType.CompletedSuccessfully:
HasTradeCompletedOk = true;
return false;
// Email/mobile confirmation
case TradeStatusType.PendingConfirmation:
IsTradeAwaitingConfirmation = true;
tradeOfferID = long.Parse(status.tradeid);
return false;
//On a status of 2, the Steam web code attempts the request two more times
case TradeStatusType.Empty:
numUnknownStatusUpdates++;
if(numUnknownStatusUpdates < 3)
{
return false;
}
break;
}
FireOnStatusErrorEvent(tradeStatusType);
OtherUserCancelled = true;
return false;
}
private bool HandleTradeOngoing(TradeStatus status)
{
bool otherUserDidSomething = false;
if (status.newversion)
{
HandleTradeVersionChange(status);
otherUserDidSomething = true;
}
else if(status.version > session.Version)
{
// oh crap! we missed a version update abort so we don't get
// scammed. if we could get what steam thinks what's in the
// trade then this wouldn't be an issue. but we can only get
// that when we see newversion == true
throw new TradeException("The trade version does not match. Aborting.");
}
// Update Local Variables
if(status.them != null)
{
OtherIsReady = status.them.ready == 1;
MeIsReady = status.me.ready == 1;
OtherUserAccepted = status.them.confirmed == 1;
//Similar to the logic Steam uses to determine whether or not to show the "waiting" spinner in the trade window
otherUserTimingOut = (status.them.connection_pending || status.them.sec_since_touch >= 5);
}
var events = status.GetAllEvents();
foreach(var tradeEvent in events.OrderBy(o => o.timestamp))
{
if(eventList.Contains(tradeEvent))
continue;
//add event to processed list, as we are taking care of this event now
eventList.Add(tradeEvent);
bool isBot = tradeEvent.steamid == MySteamId.ConvertToUInt64().ToString();
// dont process if this is something the bot did
if(isBot)
continue;
otherUserDidSomething = true;
switch((TradeEventType) tradeEvent.action)
{
case TradeEventType.ItemAdded:
TradeUserAssets newAsset = new TradeUserAssets(tradeEvent.appid, tradeEvent.contextid, tradeEvent.assetid);
if(!otherOfferedItems.Contains(newAsset))
{
otherOfferedItems.Add(newAsset);
FireOnUserAddItem(newAsset);
}
break;
case TradeEventType.ItemRemoved:
TradeUserAssets oldAsset = new TradeUserAssets(tradeEvent.appid, tradeEvent.contextid, tradeEvent.assetid);
if(otherOfferedItems.Contains(oldAsset))
{
otherOfferedItems.Remove(oldAsset);
FireOnUserRemoveItem(oldAsset);
}
break;
case TradeEventType.UserSetReady:
OnUserSetReady(true);
break;
case TradeEventType.UserSetUnReady:
OnUserSetReady(false);
break;
case TradeEventType.UserAccept:
OnUserAccept();
break;
case TradeEventType.UserChat:
OnMessage(tradeEvent.text);
break;
default:
throw new TradeException("Unknown event type: " + tradeEvent.action);
}
}
if(status.logpos != 0)
{
session.LogPos = status.logpos;
}
return otherUserDidSomething;
}
private void HandleTradeVersionChange(TradeStatus status)
{
//Figure out which items have been added/removed
IEnumerable<TradeUserAssets> otherOfferedItemsUpdated = status.them.GetAssets();
IEnumerable<TradeUserAssets> addedItems = otherOfferedItemsUpdated.Except(otherOfferedItems).ToList();
IEnumerable<TradeUserAssets> removedItems = otherOfferedItems.Except(otherOfferedItemsUpdated).ToList();
//Copy over the new items and update the version number
otherOfferedItems = status.them.GetAssets().ToList();
myOfferedItems = status.me.GetAssets().ToList();
session.Version = status.version;
//Fire the OnUserRemoveItem events
foreach (TradeUserAssets asset in removedItems)
{
FireOnUserRemoveItem(asset);
}
//Fire the OnUserAddItem events
foreach (TradeUserAssets asset in addedItems)
{
FireOnUserAddItem(asset);
}
}
/// <summary>
/// Gets an item from a TradeEvent, and passes it into the UserHandler's implemented OnUserAddItem([...]) routine.
/// Passes in null items if something went wrong.
/// </summary>
private void FireOnUserAddItem(TradeUserAssets asset)
{
if(MeIsReady)
{
SetReady(false);
}
if(OtherInventory != null && !OtherInventory.IsPrivate)
{
Inventory.Item item = OtherInventory.GetItem(asset.assetid);
if(item != null)
{
Schema.Item schemaItem = CurrentSchema.GetItem(item.Defindex);
if(schemaItem == null)
{
Console.WriteLine("User added an unknown item to the trade.");
}
OnUserAddItem(schemaItem, item);
}
else
{
item = new Inventory.Item
{
Id = asset.assetid,
AppId = asset.appid,
ContextId = asset.contextid
};
//Console.WriteLine("User added a non TF2 item to the trade.");
OnUserAddItem(null, item);
}
}
else
{
var schemaItem = GetItemFromPrivateBp(asset);
if(schemaItem == null)
{
Console.WriteLine("User added an unknown item to the trade.");
}
OnUserAddItem(schemaItem, null);
// todo: figure out what to send in with Inventory item.....
}
}
private Schema.Item GetItemFromPrivateBp(TradeUserAssets asset)
{
if (OtherPrivateInventory == null)
{
dynamic foreignInventory = session.GetForeignInventory(OtherSID, asset.contextid, asset.appid);
if (foreignInventory == null || foreignInventory.success == null || !foreignInventory.success.Value)
{
return null;
}
OtherPrivateInventory = new ForeignInventory(foreignInventory);
}
int defindex = OtherPrivateInventory.GetDefIndex(asset.assetid);
Schema.Item schemaItem = CurrentSchema.GetItem(defindex);
return schemaItem;
}
/// <summary>
/// Gets an item from a TradeEvent, and passes it into the UserHandler's implemented OnUserRemoveItem([...]) routine.
/// Passes in null items if something went wrong.
/// </summary>
/// <returns></returns>
private void FireOnUserRemoveItem(TradeUserAssets asset)
{
if(MeIsReady)
{
SetReady(false);
}
if(OtherInventory != null)
{
Inventory.Item item = OtherInventory.GetItem(asset.assetid);
if(item != null)
{
Schema.Item schemaItem = CurrentSchema.GetItem(item.Defindex);
if(schemaItem == null)
{
// TODO: Add log (counldn't find item in CurrentSchema)
}
OnUserRemoveItem(schemaItem, item);
}
else
{
// TODO: Log this (Couldn't find item in user's inventory can't find item in CurrentSchema
item = new Inventory.Item
{
Id = asset.assetid,
AppId = asset.appid,
ContextId = asset.contextid
};
OnUserRemoveItem(null, item);
}
}
else
{
var schemaItem = GetItemFromPrivateBp(asset);
if(schemaItem == null)
{
// TODO: Add log (counldn't find item in CurrentSchema)
}
OnUserRemoveItem(schemaItem, null);
}
}
internal void FireOnAwaitingConfirmation()
{
var onAwaitingConfirmation = OnAwaitingConfirmation;
if (onAwaitingConfirmation != null)
onAwaitingConfirmation(tradeOfferID);
}
internal void FireOnCloseEvent()
{
var onCloseEvent = OnClose;
if(onCloseEvent != null)
onCloseEvent();
}
internal void FireOnErrorEvent(string message)
{
var onErrorEvent = OnError;
if(onErrorEvent != null)
onErrorEvent(message);
}
internal void FireOnStatusErrorEvent(TradeStatusType statusType)
{
var onStatusErrorEvent = OnStatusError;
if (onStatusErrorEvent != null)
onStatusErrorEvent(statusType);
}
private int NextTradeSlot()
{
int slot = 0;
while(myOfferedItemsLocalCopy.ContainsKey(slot))
{
slot++;
}
return slot;
}
private int? GetItemSlot(ulong itemid)
{
foreach(int slot in myOfferedItemsLocalCopy.Keys)
{
if(myOfferedItemsLocalCopy[slot].assetid == itemid)
{
return slot;
}
}
return null;
}
private void ValidateLocalTradeItems()
{
if (!myOfferedItemsLocalCopy.Values.OrderBy(o => o).SequenceEqual(MyOfferedItems.OrderBy(o => o)))
{
throw new TradeException("Error validating local copy of offered items in the trade");
}
}
}
}
| |
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 OpenLeczna.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;
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Internal.Network.Version2017_03_01
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.Internal;
using Microsoft.Azure.Management.Internal.Network;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// NetworkInterfacesOperations operations.
/// </summary>
public partial interface INetworkInterfacesOperations
{
/// <summary>
/// Deletes the specified network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets information about the specified network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkInterface>> GetWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network interface
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkInterface>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, NetworkInterface parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network interfaces in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network interfaces in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all route tables applied to a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<EffectiveRouteListResult>> GetEffectiveRouteTableWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network security groups applied to a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<EffectiveNetworkSecurityGroupListResult>> ListEffectiveNetworkSecurityGroupsWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network interface
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkInterface>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, NetworkInterface parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all route tables applied to a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<EffectiveRouteListResult>> BeginGetEffectiveRouteTableWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network security groups applied to a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<EffectiveNetworkSecurityGroupListResult>> BeginListEffectiveNetworkSecurityGroupsWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network interfaces in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network interfaces in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. 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.
*******************************************************************************/
//
// Novell.Directory.Ldap.Utilclass.RDN.cs
//
// Author:
// Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
using System.Collections;
namespace Novell.Directory.LDAP.VQ.Utilclass
{
/// <summary> A RDN encapsulates a single object's name of a Distinguished Name(DN).
/// The object name represented by this class contains no context. Thus a
/// Relative Distinguished Name (RDN) could be relative to anywhere in the
/// Directories tree.
///
/// For example, of following DN, 'cn=admin, ou=marketing, o=corporation', all
/// possible RDNs are 'cn=admin', 'ou=marketing', and 'o=corporation'.
///
/// Multivalued attributes are encapsulated in this class. For example the
/// following could be represented by an RDN: 'cn=john + l=US', or
/// 'cn=juan + l=ES'
///
/// </summary>
/// <seealso cref="DN">
/// </seealso>
public class RDN : object
{
/// <summary> Returns the actually Raw string before Normalization
///
/// </summary>
/// <returns> The raw string
/// </returns>
virtual protected internal string RawValue
{
get
{
return rawValue;
}
}
/// <summary> Returns the type of this RDN. This method assumes that only one value
/// is used, If multivalues attributes are used only the first Type is
/// returned. Use GetTypes.
/// </summary>
/// <returns> Type of attribute
/// </returns>
virtual public string Type
{
get
{
return (string)types[0];
}
}
/// <summary> Returns all the types for this RDN.</summary>
/// <returns> list of types
/// </returns>
virtual public string[] Types
{
get
{
string[] toReturn = new string[types.Count];
for (int i = 0; i < types.Count; i++)
toReturn[i] = ((string)types[i]);
return toReturn;
}
}
/// <summary> Returns the values of this RDN. If multivalues attributes are used only
/// the first Type is returned. Use GetTypes.
///
/// </summary>
/// <returns> Type of attribute
/// </returns>
virtual public string Value
{
get
{
return (string)values[0];
}
}
/// <summary> Returns all the types for this RDN.</summary>
/// <returns> list of types
/// </returns>
virtual public string[] Values
{
get
{
string[] toReturn = new string[values.Count];
for (int i = 0; i < values.Count; i++)
toReturn[i] = ((string)values[i]);
return toReturn;
}
}
/// <summary> Determines if this RDN is multivalued or not</summary>
/// <returns> true if this RDN is multivalued
/// </returns>
virtual public bool Multivalued
{
get
{
return (values.Count > 1) ? true : false;
}
}
private ArrayList types; //list of Type strings
private ArrayList values; //list of Value strings
private string rawValue; //the unnormalized value
/// <summary> Creates an RDN object from the DN component specified in the string RDN
///
/// </summary>
/// <param name="rdn">the DN component
/// </param>
public RDN(string rdn)
{
rawValue = rdn;
DN dn = new DN(rdn);
ArrayList rdns = dn.RDNs;
//there should only be one rdn
if (rdns.Count != 1)
throw new ArgumentException("Invalid RDN: see API " + "documentation");
RDN thisRDN = (RDN)(rdns[0]);
types = thisRDN.types;
values = thisRDN.values;
rawValue = thisRDN.rawValue;
return;
}
public RDN()
{
types = new ArrayList();
values = new ArrayList();
rawValue = "";
}
/// <summary> Compares the RDN to the rdn passed. Note: If an there exist any
/// mulivalues in one RDN they must all be present in the other.
///
/// </summary>
/// <param name="rdn">the RDN to compare to
///
/// @throws IllegalArgumentException if the application compares a name
/// with an OID.
/// </param>
[CLSCompliant(false)]
public virtual bool equals(RDN rdn)
{
if (values.Count != rdn.values.Count)
{
return false;
}
int j, i;
for (i = 0; i < values.Count; i++)
{
//verify that the current value and type exists in the other list
j = 0;
//May need a more intellegent compare
while (j < values.Count && (!((string)values[i]).ToUpper().Equals(((string)rdn.values[j]).ToUpper()) || !equalAttrType((string)types[i], (string)rdn.types[j])))
{
j++;
}
if (j >= rdn.values.Count)
//couldn't find first value
return false;
}
return true;
}
/// <summary> Internal function used by equal to compare Attribute types. Because
/// attribute types could either be an OID or a name. There needs to be a
/// Translation mechanism. This function will absract this functionality.
///
/// Currently if types differ (Oid and number) then UnsupportedOperation is
/// thrown, either one or the other must used. In the future an OID to name
/// translation can be used.
///
///
/// </summary>
private bool equalAttrType(string attr1, string attr2)
{
if (Char.IsDigit(attr1[0]) ^ Char.IsDigit(attr2[0]))
//isDigit tests if it is an OID
throw new ArgumentException("OID numbers are not " + "currently compared to attribute names");
return attr1.ToUpper().Equals(attr2.ToUpper());
}
/// <summary> Adds another value to the RDN. Only one attribute type is allowed for
/// the RDN.
/// </summary>
/// <param name="attrType">Attribute type, could be an OID or string
/// </param>
/// <param name="attrValue">Attribute Value, must be normalized and escaped
/// </param>
/// <param name="rawValue">or text before normalization, can be Null
/// </param>
public virtual void add(string attrType, string attrValue, string rawValue)
{
types.Add(attrType);
values.Add(attrValue);
this.rawValue += rawValue;
}
/// <summary> Creates a string that represents this RDN, according to RFC 2253
///
/// </summary>
/// <returns> An RDN string
/// </returns>
public override string ToString()
{
return ToString(false);
}
/// <summary> Creates a string that represents this RDN.
///
/// If noTypes is true then Atribute types will be ommited.
///
/// </summary>
/// <param name="noTypes">true if attribute types will be omitted.
///
/// </param>
/// <returns> An RDN string
/// </returns>
[CLSCompliant(false)]
public virtual string ToString(bool noTypes)
{
int length = types.Count;
string toReturn = "";
if (length < 1)
return null;
if (!noTypes)
{
toReturn = types[0] + "=";
}
toReturn += values[0];
for (int i = 1; i < length; i++)
{
toReturn += "+";
if (!noTypes)
{
toReturn += (types[i] + "=");
}
toReturn += values[i];
}
return toReturn;
}
/// <summary> Returns each multivalued name in the current RDN as an array of strings.
///
/// </summary>
/// <param name="noTypes">Specifies whether Attribute types are included. The attribute
/// type names will be ommitted if the parameter noTypes is true.
///
/// </param>
/// <returns> List of multivalued Attributes
/// </returns>
public virtual string[] explodeRDN(bool noTypes)
{
int length = types.Count;
if (length < 1)
return null;
string[] toReturn = new string[types.Count];
if (!noTypes)
{
toReturn[0] = types[0] + "=";
}
toReturn[0] += values[0];
for (int i = 1; i < length; i++)
{
if (!noTypes)
{
toReturn[i] += (types[i] + "=");
}
toReturn[i] += values[i];
}
return toReturn;
}
} //end class RDN
}
| |
// 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.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Text;
using System.Threading.Tasks;
namespace System.Xml
{
public abstract class XmlDictionaryWriter : XmlWriter
{
public static XmlDictionaryWriter CreateBinaryWriter(Stream stream)
{
return CreateBinaryWriter(stream, null);
}
public static XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary dictionary)
{
return CreateBinaryWriter(stream, dictionary, null);
}
public static XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session)
{
return CreateBinaryWriter(stream, dictionary, session, true);
}
public static XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session, bool ownsStream)
{
XmlBinaryWriter writer = new XmlBinaryWriter();
writer.SetOutput(stream, dictionary, session, ownsStream);
return writer;
}
private static readonly Encoding s_UTF8Encoding = new UTF8Encoding(false);
public static XmlDictionaryWriter CreateTextWriter(Stream stream)
{
return CreateTextWriter(stream, s_UTF8Encoding, true);
}
public static XmlDictionaryWriter CreateTextWriter(Stream stream, Encoding encoding)
{
return CreateTextWriter(stream, encoding, true);
}
public static XmlDictionaryWriter CreateTextWriter(Stream stream, Encoding encoding, bool ownsStream)
{
XmlUTF8TextWriter writer = new XmlUTF8TextWriter();
writer.SetOutput(stream, encoding, ownsStream);
var asyncWriter = new XmlDictionaryAsyncCheckWriter(writer);
return asyncWriter;
}
public static XmlDictionaryWriter CreateMtomWriter(Stream stream, Encoding encoding, int maxSizeInBytes, string startInfo)
{
return CreateMtomWriter(stream, encoding, maxSizeInBytes, startInfo, null, null, true, true);
}
public static XmlDictionaryWriter CreateMtomWriter(Stream stream, Encoding encoding, int maxSizeInBytes, string startInfo, string boundary, string startUri, bool writeMessageHeaders, bool ownsStream)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_MtomEncoding);
}
public static XmlDictionaryWriter CreateDictionaryWriter(XmlWriter writer)
{
if (writer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(writer));
XmlDictionaryWriter dictionaryWriter = writer as XmlDictionaryWriter;
if (dictionaryWriter == null)
{
dictionaryWriter = new XmlWrappedWriter(writer);
}
return dictionaryWriter;
}
public override Task WriteBase64Async(byte[] buffer, int index, int count)
{
WriteBase64(buffer, index, count);
return Task.CompletedTask;
}
public void WriteStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
WriteStartElement((string)null, localName, namespaceUri);
}
public virtual void WriteStartElement(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
WriteStartElement(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri));
}
public void WriteStartAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
WriteStartAttribute((string)null, localName, namespaceUri);
}
public virtual void WriteStartAttribute(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
WriteStartAttribute(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri));
}
public void WriteAttributeString(XmlDictionaryString localName, XmlDictionaryString namespaceUri, string value)
{
WriteAttributeString((string)null, localName, namespaceUri, value);
}
public virtual void WriteXmlnsAttribute(string prefix, string namespaceUri)
{
if (namespaceUri == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri));
if (prefix == null)
{
if (LookupPrefix(namespaceUri) != null)
return;
#pragma warning suppress 56506 // Microsoft, namespaceUri is already checked
prefix = namespaceUri.Length == 0 ? string.Empty : string.Concat("d", namespaceUri.Length.ToString(System.Globalization.NumberFormatInfo.InvariantInfo));
}
WriteAttributeString("xmlns", prefix, null, namespaceUri);
}
public virtual void WriteXmlnsAttribute(string prefix, XmlDictionaryString namespaceUri)
{
WriteXmlnsAttribute(prefix, XmlDictionaryString.GetString(namespaceUri));
}
public virtual void WriteXmlAttribute(string localName, string value)
{
WriteAttributeString("xml", localName, null, value);
}
public virtual void WriteXmlAttribute(XmlDictionaryString localName, XmlDictionaryString value)
{
WriteXmlAttribute(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(value));
}
public void WriteAttributeString(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, string value)
{
WriteStartAttribute(prefix, localName, namespaceUri);
WriteString(value);
WriteEndAttribute();
}
public void WriteElementString(XmlDictionaryString localName, XmlDictionaryString namespaceUri, string value)
{
WriteElementString((string)null, localName, namespaceUri, value);
}
public void WriteElementString(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, string value)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteString(value);
WriteEndElement();
}
public virtual void WriteString(XmlDictionaryString value)
{
WriteString(XmlDictionaryString.GetString(value));
}
public virtual void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
if (localName == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localName)));
if (namespaceUri == null)
namespaceUri = XmlDictionaryString.Empty;
#pragma warning suppress 56506 // Microsoft, XmlDictionaryString.Empty is never null
WriteQualifiedName(localName.Value, namespaceUri.Value);
}
public virtual void WriteValue(XmlDictionaryString value)
{
WriteValue(XmlDictionaryString.GetString(value));
}
public virtual void WriteValue(UniqueId value)
{
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value));
WriteString(value.ToString());
}
public virtual void WriteValue(Guid value)
{
WriteString(value.ToString());
}
public virtual void WriteValue(TimeSpan value)
{
WriteString(XmlConvert.ToString(value));
}
public virtual void WriteValue(IStreamProvider value)
{
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(value)));
Stream stream = value.GetStream();
if (stream == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.XmlInvalidStream));
int blockSize = 256;
int bytesRead = 0;
byte[] block = new byte[blockSize];
while (true)
{
bytesRead = stream.Read(block, 0, blockSize);
if (bytesRead > 0)
WriteBase64(block, 0, bytesRead);
else
break;
if (blockSize < 65536 && bytesRead == blockSize)
{
blockSize = blockSize * 16;
block = new byte[blockSize];
}
}
value.ReleaseStream(stream);
}
public virtual Task WriteValueAsync(IStreamProvider value)
{
WriteValue(value);
return Task.CompletedTask;
}
public virtual bool CanCanonicalize
{
get
{
return false;
}
}
public virtual void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
public virtual void EndCanonicalization()
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
private void WriteElementNode(XmlDictionaryReader reader, bool defattr)
{
XmlDictionaryString localName;
XmlDictionaryString namespaceUri;
if (reader.TryGetLocalNameAsDictionaryString(out localName) && reader.TryGetNamespaceUriAsDictionaryString(out namespaceUri))
{
WriteStartElement(reader.Prefix, localName, namespaceUri);
}
else
{
WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
}
if (defattr || !reader.IsDefault)
{
if (reader.MoveToFirstAttribute())
{
do
{
if (reader.TryGetLocalNameAsDictionaryString(out localName) && reader.TryGetNamespaceUriAsDictionaryString(out namespaceUri))
{
WriteStartAttribute(reader.Prefix, localName, namespaceUri);
}
else
{
WriteStartAttribute(reader.Prefix, reader.LocalName, reader.NamespaceURI);
}
while (reader.ReadAttributeValue())
{
if (reader.NodeType == XmlNodeType.EntityReference)
{
WriteEntityRef(reader.Name);
}
else
{
WriteTextNode(reader, true);
}
}
WriteEndAttribute();
}
while (reader.MoveToNextAttribute());
reader.MoveToElement();
}
}
if (reader.IsEmptyElement)
{
WriteEndElement();
}
}
private void WriteArrayNode(XmlDictionaryReader reader, string prefix, string localName, string namespaceUri, Type type)
{
if (type == typeof(bool))
BooleanArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(short))
Int16ArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(int))
Int32ArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(long))
Int64ArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(float))
SingleArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(double))
DoubleArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(decimal))
DecimalArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(DateTime))
DateTimeArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(Guid))
GuidArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(TimeSpan))
TimeSpanArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else
{
WriteElementNode(reader, false);
reader.Read();
}
}
private void WriteArrayNode(XmlDictionaryReader reader, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Type type)
{
if (type == typeof(bool))
BooleanArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(short))
Int16ArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(int))
Int32ArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(long))
Int64ArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(float))
SingleArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(double))
DoubleArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(decimal))
DecimalArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(DateTime))
DateTimeArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(Guid))
GuidArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(TimeSpan))
TimeSpanArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else
{
WriteElementNode(reader, false);
reader.Read();
}
}
private void WriteArrayNode(XmlDictionaryReader reader, Type type)
{
XmlDictionaryString localName;
XmlDictionaryString namespaceUri;
if (reader.TryGetLocalNameAsDictionaryString(out localName) && reader.TryGetNamespaceUriAsDictionaryString(out namespaceUri))
WriteArrayNode(reader, reader.Prefix, localName, namespaceUri, type);
else
WriteArrayNode(reader, reader.Prefix, reader.LocalName, reader.NamespaceURI, type);
}
protected virtual void WriteTextNode(XmlDictionaryReader reader, bool isAttribute)
{
XmlDictionaryString value;
if (reader.TryGetValueAsDictionaryString(out value))
{
WriteString(value);
}
else
{
WriteString(reader.Value);
}
if (!isAttribute)
{
reader.Read();
}
}
public override void WriteNode(XmlReader reader, bool defattr)
{
XmlDictionaryReader dictionaryReader = reader as XmlDictionaryReader;
if (dictionaryReader != null)
WriteNode(dictionaryReader, defattr);
else
base.WriteNode(reader, defattr);
}
public virtual void WriteNode(XmlDictionaryReader reader, bool defattr)
{
if (reader == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(reader)));
int d = (reader.NodeType == XmlNodeType.None ? -1 : reader.Depth);
do
{
XmlNodeType nodeType = reader.NodeType;
Type type;
if (nodeType == XmlNodeType.Text || nodeType == XmlNodeType.Whitespace || nodeType == XmlNodeType.SignificantWhitespace)
{
// This will advance if necessary, so we don't need to call Read() explicitly
WriteTextNode(reader, false);
}
else if (reader.Depth > d && reader.IsStartArray(out type))
{
WriteArrayNode(reader, type);
}
else
{
// These will not advance, so we must call Read() explicitly
switch (nodeType)
{
case XmlNodeType.Element:
WriteElementNode(reader, defattr);
break;
case XmlNodeType.CDATA:
WriteCData(reader.Value);
break;
case XmlNodeType.EntityReference:
WriteEntityRef(reader.Name);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
WriteProcessingInstruction(reader.Name, reader.Value);
break;
case XmlNodeType.DocumentType:
WriteDocType(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value);
break;
case XmlNodeType.Comment:
WriteComment(reader.Value);
break;
case XmlNodeType.EndElement:
WriteFullEndElement();
break;
}
if (!reader.Read())
break;
}
}
while (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement));
}
private void CheckArray(Array array, int offset, int count)
{
if (array == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(array)));
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > array.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, array.Length)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > array.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, array.Length - offset)));
}
// bool
public virtual void WriteArray(string prefix, string localName, string namespaceUri, bool[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Int16
public virtual void WriteArray(string prefix, string localName, string namespaceUri, short[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Int32
public virtual void WriteArray(string prefix, string localName, string namespaceUri, int[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Int64
public virtual void WriteArray(string prefix, string localName, string namespaceUri, long[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// float
public virtual void WriteArray(string prefix, string localName, string namespaceUri, float[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// double
public virtual void WriteArray(string prefix, string localName, string namespaceUri, double[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// decimal
public virtual void WriteArray(string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// DateTime
public virtual void WriteArray(string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Guid
public virtual void WriteArray(string prefix, string localName, string namespaceUri, Guid[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// TimeSpan
public virtual void WriteArray(string prefix, string localName, string namespaceUri, TimeSpan[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
protected override void Dispose(bool disposing)
{
if (disposing && WriteState != WriteState.Closed)
{
Close();
}
}
public override void Close() { }
private class XmlWrappedWriter : XmlDictionaryWriter
{
private XmlWriter _writer;
private int _depth;
private int _prefix;
public XmlWrappedWriter(XmlWriter writer)
{
_writer = writer;
_depth = 0;
}
public override void Close()
{
_writer.Dispose();
}
public override void Flush()
{
_writer.Flush();
}
public override string LookupPrefix(string namespaceUri)
{
return _writer.LookupPrefix(namespaceUri);
}
public override void WriteAttributes(XmlReader reader, bool defattr)
{
_writer.WriteAttributes(reader, defattr);
}
public override void WriteBase64(byte[] buffer, int index, int count)
{
_writer.WriteBase64(buffer, index, count);
}
public override void WriteBinHex(byte[] buffer, int index, int count)
{
_writer.WriteBinHex(buffer, index, count);
}
public override void WriteCData(string text)
{
_writer.WriteCData(text);
}
public override void WriteCharEntity(char ch)
{
_writer.WriteCharEntity(ch);
}
public override void WriteChars(char[] buffer, int index, int count)
{
_writer.WriteChars(buffer, index, count);
}
public override void WriteComment(string text)
{
_writer.WriteComment(text);
}
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
_writer.WriteDocType(name, pubid, sysid, subset);
}
public override void WriteEndAttribute()
{
_writer.WriteEndAttribute();
}
public override void WriteEndDocument()
{
_writer.WriteEndDocument();
}
public override void WriteEndElement()
{
_writer.WriteEndElement();
_depth--;
}
public override void WriteEntityRef(string name)
{
_writer.WriteEntityRef(name);
}
public override void WriteFullEndElement()
{
_writer.WriteFullEndElement();
}
public override void WriteName(string name)
{
_writer.WriteName(name);
}
public override void WriteNmToken(string name)
{
_writer.WriteNmToken(name);
}
public override void WriteNode(XmlReader reader, bool defattr)
{
_writer.WriteNode(reader, defattr);
}
public override void WriteProcessingInstruction(string name, string text)
{
_writer.WriteProcessingInstruction(name, text);
}
public override void WriteQualifiedName(string localName, string namespaceUri)
{
_writer.WriteQualifiedName(localName, namespaceUri);
}
public override void WriteRaw(char[] buffer, int index, int count)
{
_writer.WriteRaw(buffer, index, count);
}
public override void WriteRaw(string data)
{
_writer.WriteRaw(data);
}
public override void WriteStartAttribute(string prefix, string localName, string namespaceUri)
{
_writer.WriteStartAttribute(prefix, localName, namespaceUri);
_prefix++;
}
public override void WriteStartDocument()
{
_writer.WriteStartDocument();
}
public override void WriteStartDocument(bool standalone)
{
_writer.WriteStartDocument(standalone);
}
public override void WriteStartElement(string prefix, string localName, string namespaceUri)
{
_writer.WriteStartElement(prefix, localName, namespaceUri);
_depth++;
_prefix = 1;
}
public override WriteState WriteState
{
get
{
return _writer.WriteState;
}
}
public override void WriteString(string text)
{
_writer.WriteString(text);
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
_writer.WriteSurrogateCharEntity(lowChar, highChar);
}
public override void WriteWhitespace(string whitespace)
{
_writer.WriteWhitespace(whitespace);
}
public override void WriteValue(object value)
{
_writer.WriteValue(value);
}
public override void WriteValue(string value)
{
_writer.WriteValue(value);
}
public override void WriteValue(bool value)
{
_writer.WriteValue(value);
}
public override void WriteValue(DateTimeOffset value)
{
_writer.WriteValue(value);
}
public override void WriteValue(double value)
{
_writer.WriteValue(value);
}
public override void WriteValue(int value)
{
_writer.WriteValue(value);
}
public override void WriteValue(long value)
{
_writer.WriteValue(value);
}
public override void WriteXmlnsAttribute(string prefix, string namespaceUri)
{
if (namespaceUri == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri));
if (prefix == null)
{
if (LookupPrefix(namespaceUri) != null)
return;
if (namespaceUri.Length == 0)
{
prefix = string.Empty;
}
else
{
string depthStr = _depth.ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
string prefixStr = _prefix.ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
prefix = string.Concat("d", depthStr, "p", prefixStr);
}
}
WriteAttributeString("xmlns", prefix, null, namespaceUri);
}
public override string XmlLang
{
get
{
return _writer.XmlLang;
}
}
public override XmlSpace XmlSpace
{
get
{
return _writer.XmlSpace;
}
}
}
}
}
| |
#region Copyright (c) 2020 Filip Fodemski
//
// Copyright (c) 2020 Filip Fodemski
//
// 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.Timers;
using System.Xml;
using System.Xml.Serialization;
using SmartGraph.Common;
using SmartGraph.Core.Interfaces;
using SmartGraph.Xml;
namespace SmartGraph.Nodes.Core
{
[Serializable]
[InvariantNode]
[XmlRoot(Namespace="urn:smartgraph:nodes", IsNullable = false)]
public sealed class ConstValue : NodeBase
{
private const string output = "Value";
private XmlElement elementValue;
private object innerValue;
[XmlAttribute("type")]
public string Type = string.Empty;
[XmlAttribute("value")]
public string AttributeValue
{
get { return innerValue.ToString(); }
set
{
Guard.AssertNotNull(value, "value");
Type t = System.Type.GetType(Type, true, true);
innerValue = Convert.ChangeType(value, t);
}
}
[XmlElement("XmlValue")]
public XmlElement ElementValue
{
get { return elementValue; }
set
{
Guard.AssertNotNull(value, "value");
elementValue = value;
Type t = System.Type.GetType(Type, true, true);
innerValue = XmlHelpers.Deserialize(t, elementValue.OuterXml);
}
}
public override void Update()
{
Value = innerValue;
}
}
[Serializable]
[XmlRoot(Namespace = "urn:smartgraph:nodes", IsNullable = false)]
public sealed class SumOfInputs : NodeBase
{
private const string output = "Value";
public override void Update()
{
double sum = 0.0;
foreach (var input in InputValues.Keys)
{
sum += GetInputNode<double>(input);
}
Value = sum;
}
}
[Serializable]
[XmlRoot(Namespace = "urn:smartgraph:nodes", IsNullable = false)]
public sealed class RandomValue : NodeBase
{
private const string output = "Value";
private readonly Random random = new Random();
[XmlAttribute("minValue")]
public string MinValue { get; set; }
[XmlAttribute("maxValue")]
public string MaxValue { get; set; }
public override void Update()
{
var min = double.Parse(MinValue);
var max = double.Parse(MaxValue);
Value = random.NextBetween(min, max);
}
}
[Serializable]
[XmlRoot(Namespace = "urn:smartgraph:nodes", IsNullable = false)]
public sealed class Ticker : ActiveNodeBase
{
private const string output = "Ticker";
private Random random;
private Timer timer;
private long sequenceNumber = 0;
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
if (IsRandom)
{
var min = double.Parse(MinValue);
var max = double.Parse(MaxValue);
Value = random.NextBetween(min, max);
}
else
{
if (IsCounter)
{
Value = ++sequenceNumber;
}
else
{
Value = DateTime.Now;
}
}
Diagnostics.WriteLine(this, string.Format("[{0}] ticked new value '{1}'", Name, Value));
MarkNodeAsDirty();
}
[XmlAttribute("minValue")]
public string MinValue;
[XmlAttribute("maxValue")]
public string MaxValue;
[XmlAttribute("freq")]
public double Frequency = 1000; // in miliseconds
[XmlAttribute("repeat")]
public bool IsRepeat = true;
[XmlAttribute("count")]
public bool IsCounter = false;
[XmlAttribute("random")]
public bool IsRandom = false;
public override void Activate()
{
timer = new Timer(Frequency);
timer.Elapsed += new ElapsedEventHandler( OnTimedEvent );
timer.AutoReset = IsRepeat;
if (IsRandom)
{
random = new Random();
}
timer.Start();
}
}
[Serializable]
[XmlRoot(Namespace = "urn:smartgraph:nodes", IsNullable = false)]
public sealed class RandomSleeper : NodeBase
{
private const string output = "Value";
private readonly Random random = new Random();
[XmlAttribute("duration")]
public double Duration = 100; // in miliseconds
public override void Update()
{
var duration = Duration;
if (duration < 1)
{
duration = 1.0;
}
System.Threading.Thread.Sleep((int)duration);
Value = duration;
}
}
[Serializable]
[XmlRoot(Namespace = "urn:smartgraph:nodes", IsNullable = false)]
public sealed class SleepJob : NodeBase
{
private const string output = "Value";
public override void Update()
{
double sum = 0.0;
foreach (var input in InputValues.Keys)
{
sum += GetInputNode<double>(input);
}
System.Threading.Thread.Sleep((int)sum);
Value = sum;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Data;
using OpenMetaverse;
using OpenSim.Framework;
using MySql.Data.MySqlClient;
namespace OpenSim.Data.MySQL
{
public class MySqlAuthenticationData : MySqlFramework, IAuthenticationData
{
private string m_Realm;
private List<string> m_ColumnNames;
private int m_LastExpire;
// private string m_connectionString;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
public MySqlAuthenticationData(string connectionString, string realm)
: base(connectionString)
{
m_Realm = realm;
m_connectionString = connectionString;
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
Migration m = new Migration(dbcon, Assembly, "AuthStore");
m.Update();
}
}
public AuthenticationData Get(UUID principalID)
{
AuthenticationData ret = new AuthenticationData();
ret.Data = new Dictionary<string, object>();
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd
= new MySqlCommand("select * from `" + m_Realm + "` where UUID = ?principalID", dbcon))
{
cmd.Parameters.AddWithValue("?principalID", principalID.ToString());
IDataReader result = cmd.ExecuteReader();
if (result.Read())
{
ret.PrincipalID = principalID;
CheckColumnNames(result);
foreach (string s in m_ColumnNames)
{
if (s == "UUID")
continue;
ret.Data[s] = result[s].ToString();
}
return ret;
}
else
{
return null;
}
}
}
}
private void CheckColumnNames(IDataReader result)
{
if (m_ColumnNames != null)
return;
List<string> columnNames = new List<string>();
DataTable schemaTable = result.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
columnNames.Add(row["ColumnName"].ToString());
m_ColumnNames = columnNames;
}
public bool Store(AuthenticationData data)
{
if (data.Data.ContainsKey("UUID"))
data.Data.Remove("UUID");
string[] fields = new List<string>(data.Data.Keys).ToArray();
using (MySqlCommand cmd = new MySqlCommand())
{
string update = "update `"+m_Realm+"` set ";
bool first = true;
foreach (string field in fields)
{
if (!first)
update += ", ";
update += "`" + field + "` = ?"+field;
first = false;
cmd.Parameters.AddWithValue("?"+field, data.Data[field]);
}
update += " where UUID = ?principalID";
cmd.CommandText = update;
cmd.Parameters.AddWithValue("?principalID", data.PrincipalID.ToString());
if (ExecuteNonQuery(cmd) < 1)
{
string insert = "insert into `" + m_Realm + "` (`UUID`, `" +
String.Join("`, `", fields) +
"`) values (?principalID, ?" + String.Join(", ?", fields) + ")";
cmd.CommandText = insert;
if (ExecuteNonQuery(cmd) < 1)
return false;
}
}
return true;
}
public bool SetDataItem(UUID principalID, string item, string value)
{
using (MySqlCommand cmd
= new MySqlCommand("update `" + m_Realm + "` set `" + item + "` = ?" + item + " where UUID = ?UUID"))
{
cmd.Parameters.AddWithValue("?"+item, value);
cmd.Parameters.AddWithValue("?UUID", principalID.ToString());
if (ExecuteNonQuery(cmd) > 0)
return true;
}
return false;
}
public bool SetToken(UUID principalID, string token, int lifetime)
{
if (System.Environment.TickCount - m_LastExpire > 30000)
DoExpire();
using (MySqlCommand cmd
= new MySqlCommand(
"insert into tokens (UUID, token, validity) values (?principalID, ?token, date_add(now(), interval ?lifetime minute))"))
{
cmd.Parameters.AddWithValue("?principalID", principalID.ToString());
cmd.Parameters.AddWithValue("?token", token);
cmd.Parameters.AddWithValue("?lifetime", lifetime.ToString());
if (ExecuteNonQuery(cmd) > 0)
return true;
}
return false;
}
public bool CheckToken(UUID principalID, string token, int lifetime)
{
if (System.Environment.TickCount - m_LastExpire > 30000)
DoExpire();
using (MySqlCommand cmd
= new MySqlCommand(
"update tokens set validity = date_add(now(), interval ?lifetime minute) where UUID = ?principalID and token = ?token and validity > now()"))
{
cmd.Parameters.AddWithValue("?principalID", principalID.ToString());
cmd.Parameters.AddWithValue("?token", token);
cmd.Parameters.AddWithValue("?lifetime", lifetime.ToString());
if (ExecuteNonQuery(cmd) > 0)
return true;
}
return false;
}
private void DoExpire()
{
using (MySqlCommand cmd = new MySqlCommand("delete from tokens where validity < now()"))
{
ExecuteNonQuery(cmd);
}
m_LastExpire = System.Environment.TickCount;
}
}
}
| |
#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.Anywhere.AnywherePublic
File: MainWindow.xaml.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Anywhere
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security;
using Ecng.Common;
using Ecng.Xaml;
using Algo;
using BusinessEntities;
using Fix;
using Messages;
using Quik;
using Quik.Lua;
public class UserSubscription
{
public Security Security { set; get; }
public string SecurityId => Security.Id;
public bool Trades { set; get; }
public bool MarketDepth { set; get; }
public bool Level1 { set; get; }
public bool Orders { set; get; }
public bool MyTrades { set; get; }
}
public partial class MainWindow : INotifyPropertyChanged
{
private readonly FixMessageAdapter _messAdapter;
private readonly List<Security> _securities;
private readonly LuaFixTransactionMessageAdapter _transAdapter;
private bool _isConnectClick; // flag - click on connect button
private bool _isConnected;
private bool _isUnloading; // flag - data loading ...
private bool _marketDataStarted;
private InputTranParser _parser;
private ObservableCollectionEx<UserSubscription> _subscriptions;
private bool _transactionsStarted;
public MainWindow()
{
InitializeComponent();
ConnectCommand = new DelegateCommand(OnConnect, CanOnConnect);
UnloadingCommand = new DelegateCommand(Unloading, CanUnloading);
DeleteSubscriptionCommand = new DelegateCommand(DeleteSubscription, CanDeleteSubscription);
ParsingCommand = new DelegateCommand(Parsing, CanParsing);
_securities = new List<Security>();
_transAdapter = new LuaFixTransactionMessageAdapter(new MillisecondIncrementalIdGenerator())
{
Login = "quik",
Password = "quik".To<SecureString>(),
Address = QuikTrader.DefaultLuaAddress,
TargetCompId = "StockSharpTS",
SenderCompId = "quik",
};
_messAdapter = new LuaFixMarketDataMessageAdapter(new MillisecondIncrementalIdGenerator())
{
Login = "quik",
Password = "quik".To<SecureString>(),
Address = QuikTrader.DefaultLuaAddress,
TargetCompId = "StockSharpMD",
SenderCompId = "quik",
};
_messAdapter.AddSupportedMessage(MessageTypes.Connect);
((IMessageAdapter)_messAdapter).NewOutMessage += OnNewOutMessage;
}
/// <summary>
/// Information about a market data subscribing
/// </summary>
public ObservableCollectionEx<UserSubscription> Subscriptions
{
get
{
if (_subscriptions == null)
Subscriptions = new ObservableCollectionEx<UserSubscription>();
return _subscriptions;
}
set { _subscriptions = value; }
}
/// <summary>
/// Connection status
/// </summary>
public bool IsConnected
{
get { return _isConnected; }
private set
{
if (_isConnected != value)
{
_isConnected = value;
NotifyPropertyChanged();
}
}
}
private void OnNewOutMessage(Message message)
{
try
{
switch (message.Type)
{
case MessageTypes.QuoteChange:
//Debug.WriteLine("QuoteChange");
((QuoteChangeMessage)message).WriteMarketDepth();
break;
case MessageTypes.Board:
//Debug.WriteLine("Board");
break;
case MessageTypes.Security:
//Debug.WriteLine("Security");
_securities.Add(((SecurityMessage)message).ToSecurity());
break;
case MessageTypes.SecurityLookupResult:
//Debug.WriteLine("SecurityLookupResult");
break;
case MessageTypes.PortfolioLookupResult:
//Debug.WriteLine("PortfolioLookupResult");
break;
case MessageTypes.Level1Change:
//Debug.WriteLine("Level1Change");
((Level1ChangeMessage)message).WriteLevel1();
break;
case MessageTypes.News:
break;
case MessageTypes.Execution:
//Debug.WriteLine("Execution");
var execMsg = (ExecutionMessage)message;
if (execMsg.ExecutionType == ExecutionTypes.Tick)
execMsg.WriteTrade();
else
{
if (execMsg.HasOrderInfo())
execMsg.WriteOrder();
if (execMsg.HasTradeInfo())
execMsg.WriteMyTrade();
}
break;
case MessageTypes.Portfolio:
//Debug.WriteLine("Portfolio");
break;
case MessageTypes.PortfolioLookup:
// Debug.WriteLine("PortfolioLookup");
break;
case MessageTypes.PortfolioChange:
//Debug.WriteLine("PortfolioChange");
break;
case MessageTypes.Position:
//Debug.WriteLine("Position");
//position.WritePosition();
break;
case MessageTypes.PositionChange:
//Debug.WriteLine("PositionChange");
((PositionChangeMessage)message).WritePosition();
break;
case MessageTypes.MarketData:
{
//Debug.WriteLine("MarketData");
//var mdMsg = (MarketDataMessage)message;
break;
}
case MessageTypes.Error:
Debug.WriteLine(((ErrorMessage)message).Error.Message);
break;
case MessageTypes.Connect:
{
if (((ConnectMessage)message).Error == null)
{
if (_messAdapter.PortfolioLookupRequired)
_messAdapter.SendInMessage(new PortfolioLookupMessage { IsBack = true, IsSubscribe = true, TransactionId = _messAdapter.TransactionIdGenerator.GetNextId() });
if (_messAdapter.OrderStatusRequired)
{
var transactionId = _messAdapter.TransactionIdGenerator.GetNextId();
_messAdapter.SendInMessage(new OrderStatusMessage { TransactionId = transactionId });
}
if (_messAdapter.SecurityLookupRequired)
_messAdapter.SendInMessage(new SecurityLookupMessage { TransactionId = _messAdapter.TransactionIdGenerator.GetNextId() });
IsConnected = true;
}
else
Debug.WriteLine(((ConnectMessage)message).Error.Message);
_isConnectClick = false;
break;
}
case MessageTypes.Disconnect:
//Debug.WriteLine("Disconnect");
IsConnected = false;
_isConnectClick = false;
break;
case MessageTypes.SecurityLookup:
{
// Debug.WriteLine("SecurityLookup");
break;
}
case MessageTypes.Session:
//Debug.WriteLine("Session");
break;
default:
throw new ArgumentOutOfRangeException("Message type {0} not suppoted.".Put(message.Type));
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message + " " + ex.StackTrace);
}
}
private void SecurityEditor_SecuritySelected()
{
if (Subscriptions.Any(s => s.Security == SecurityEditor.SelectedSecurity))
return;
Subscriptions.Add(new UserSubscription { Security = SecurityEditor.SelectedSecurity });
}
private void SubscribeMarketData(SecurityId securityId, MarketDataTypes type)
{
var message = new MarketDataMessage
{
DataType = type,
IsSubscribe = true,
SecurityId = securityId,
From = DateTimeOffset.MinValue,
To = DateTimeOffset.MaxValue,
TransactionId = _messAdapter.TransactionIdGenerator.GetNextId()
};
switch (type)
{
case MarketDataTypes.MarketDepth:
message.MaxDepth = MarketDataMessage.DefaultMaxDepth;
break;
case MarketDataTypes.Trades:
message.Arg = ExecutionTypes.Tick;
break;
case MarketDataTypes.OrderLog:
message.Arg = ExecutionTypes.OrderLog;
break;
}
_messAdapter.SendInMessage(message);
}
private void UnSubscribeMarketData(SecurityId securityId, MarketDataTypes type)
{
var message = new MarketDataMessage
{
DataType = type,
SecurityId = securityId,
IsSubscribe = false,
TransactionId = _messAdapter.TransactionIdGenerator.GetNextId()
};
switch (type)
{
case MarketDataTypes.Trades:
message.Arg = ExecutionTypes.Tick;
break;
case MarketDataTypes.OrderLog:
message.Arg = ExecutionTypes.OrderLog;
break;
}
_messAdapter.SendInMessage(message);
}
private void Window_Closing(object sender, CancelEventArgs e)
{
if (IsConnected)
_messAdapter.SendInMessage(new DisconnectMessage());
}
#region Commands
public DelegateCommand ConnectCommand { set; get; }
private void OnConnect(object obj)
{
if (!IsConnected)
_messAdapter.SendInMessage(new ConnectMessage());
else
_messAdapter.SendInMessage(new DisconnectMessage());
_isConnectClick = true;
}
private bool CanOnConnect(object obj)
{
return !_isConnectClick;
}
public DelegateCommand UnloadingCommand { set; get; }
private void Unloading(object e)
{
if (!_marketDataStarted)
{
_isUnloading = true;
//SecurityPicker.SecurityProvider = new FilterableSecurityProvider(_connector);
//SecurityPicker.MarketDataProvider = _connector;
//var securities = SecurityPicker.FilteredSecurities.ToArray();
foreach (var subscr in Subscriptions)
{
var secId = subscr.Security.ToSecurityId();
if (subscr.MarketDepth)
SubscribeMarketData(secId, MarketDataTypes.MarketDepth);
;
if (subscr.Trades)
SubscribeMarketData(secId, MarketDataTypes.Trades);
;
if (subscr.Level1)
SubscribeMarketData(secId, MarketDataTypes.Level1);
;
}
_marketDataStarted = true;
}
else
{
foreach (var subscr in Subscriptions)
{
var secId = subscr.Security.ToSecurityId();
if (subscr.MarketDepth)
UnSubscribeMarketData(secId, MarketDataTypes.MarketDepth);
;
if (subscr.Trades)
UnSubscribeMarketData(secId, MarketDataTypes.Trades);
;
if (subscr.Level1)
UnSubscribeMarketData(secId, MarketDataTypes.Level1);
;
}
//SecurityPicker.SecurityProvider = null;
//SecurityPicker.MarketDataProvider = null;
//SecurityPicker.ExcludeSecurities.Clear();
_isUnloading = false;
_marketDataStarted = false;
}
}
private bool CanUnloading(object obj)
{
return IsConnected && Subscriptions.Any(s => s.MarketDepth || s.Level1 || s.Trades);
}
public DelegateCommand ParsingCommand { set; get; }
private void Parsing(object e)
{
if (!_transactionsStarted)
{
_parser = new InputTranParser(_transAdapter, _messAdapter, _securities);
_parser.Start();
_transactionsStarted = true;
}
else
{
_parser.Stop();
_transactionsStarted = false;
}
}
private static bool CanParsing(object obj)
{
return true;
}
/// <summary>
/// Remove usersubscription
/// </summary>
public DelegateCommand DeleteSubscriptionCommand { set; get; }
private void DeleteSubscription(object obj)
{
if (Subscriptions.Contains((UserSubscription)obj))
{
Subscriptions.Remove((UserSubscription)obj);
SecurityPicker.ExcludeSecurities.Add(((UserSubscription)obj).Security);
}
}
private bool CanDeleteSubscription(object obj)
{
return (obj != null && !_isUnloading);
}
#endregion
#region INotifyPropertyChanged releases
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
| |
using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Presentation.Media;
namespace Skewworks.NETMF.Controls
{
/// <summary>
/// Nested container
/// </summary>
/// <remarks>
/// Use panels inside of other <see cref="Container"/>s to group controls together.
/// </remarks>
[Serializable]
public class Panel : Container
{
#region Variables
// Background
private Color _bkg;
private Bitmap _img;
private ScaleMode _scale;
private bool _trans;
private bool _border;
// Auto Scroll
private bool _autoScroll;
private int _maxX, _maxY;
private int _minX, _minY;
private bool _moving;
private bool _touch;
#endregion
#region Constructors
/// <summary>
/// Creates a new Panel
/// </summary>
/// <param name="name">Name of the panel</param>
/// <param name="x">X position relative to it's parent</param>
/// <param name="y">Y position relative to it's parent</param>
/// <param name="width">Width in pixel</param>
/// <param name="height">Height in pixel</param>
public Panel(string name, int x, int y, int width, int height)
{
Name = name;
_bkg = Core.SystemColors.ContainerBackground;
// ReSharper disable DoNotCallOverridableMethodsInConstructor
X = x;
Y = y;
Width = width;
Height = height;
// ReSharper restore DoNotCallOverridableMethodsInConstructor
}
/// <summary>
/// Creates a new Panel
/// </summary>
/// <param name="name">Name of the panel</param>
/// <param name="x">X position relative to it's parent</param>
/// <param name="y">Y position relative to it's parent</param>
/// <param name="width">Width in pixel</param>
/// <param name="height">Height in pixel</param>
/// <param name="backColor">Background color</param>
public Panel(string name, int x, int y, int width, int height, Color backColor)
{
Name = name;
_bkg = backColor;
// ReSharper disable DoNotCallOverridableMethodsInConstructor
X = x;
Y = y;
Width = width;
Height = height;
// ReSharper restore DoNotCallOverridableMethodsInConstructor
}
#endregion
#region Properties
/// <summary>
/// Gets/Sets AutoScroll feature for Panel
/// </summary>
/// <remarks>
/// Panel will automatically display scrollbars as needed when true
/// </remarks>
public bool AutoScroll
{
get { return _autoScroll; }
set
{
if (_autoScroll == value)
{
return;
}
_autoScroll = value;
Invalidate();
}
}
/// <summary>
/// Gets/Sets Panel's background color
/// </summary>
public Color BackColor
{
get { return _bkg; }
set
{
if (value == _bkg)
{
return;
}
_bkg = value;
Invalidate();
}
}
/// <summary>
/// Gets/Sets the background image to display on the Panel
/// </summary>
/// <seealso cref="BackgroundImageScaleMode"/>
public Bitmap BackgroundImage
{
get { return _img; }
set
{
if (_img == value)
{
return;
}
_img = value;
Invalidate();
}
}
/// <summary>
/// Gets/Sets the Scale Mode to use when rendering background image
/// </summary>
/// <seealso cref="BackgroundImage"/>
public ScaleMode BackgroundImageScaleMode
{
get { return _scale; }
set
{
if (_scale == value)
{
return;
}
_scale = value;
if (_img != null)
{
Invalidate();
}
}
}
/// <summary>
/// Gets/Sets if the Panel should have a border
/// </summary>
public bool DrawBorder
{
get { return _border; }
set
{
if (_border == value)
{
return;
}
_border = value;
Invalidate();
}
}
/// <summary>
/// Gets/Sets if the background is transparent
/// </summary>
public bool TransparentBackground
{
get { return _trans; }
set
{
if (_trans == value)
{
return;
}
_trans = value;
Invalidate();
}
}
/// <summary>
/// Gets the current touch state of the control
/// </summary>
/// <remarks>
/// Returns true if the control is currently being touched.
/// If the Touching property of the parent or of any child is true, then Panel.Touching returns true as well.
/// </remarks>
public override bool Touching
{
get
{
if (base.Touching)
{
return true;
}
if (Children != null)
{
for (int i = 0; i < Children.Length; i++)
{
if (Children[i].Touching)
{
return true;
}
}
}
return false;
}
}
/// <summary>
/// Gets/Sets the X position in pixels
/// </summary>
/// <remarks>
/// X is a relative location inside the parent, Left is the exact location on the screen.
/// Updates the offsets of all childes as well.
/// </remarks>
public override int X
{
get { return base.X; }
set
{
if (base.X == value)
{
return;
}
base.X = value;
if (Children != null)
{
for (int i = 0; i < Children.Length; i++)
{
Children[i].UpdateOffsets();
}
}
}
}
/// <summary>
/// Gets/Sets the Y position in pixels
/// </summary>
/// <remarks>
/// Y is a relative location inside the parent, Top is the exact location on the screen.
/// Updates the offsets of all childes as well.
/// </remarks>
public override int Y
{
get { return base.Y; }
set
{
if (base.Y == value)
return;
base.Y = value;
if (Children != null)
{
for (int i = 0; i < Children.Length; i++)
Children[i].UpdateOffsets();
}
}
}
#endregion
#region Button Methods
/// <summary>
/// Override this message to handle button pressed events internally.
/// </summary>
/// <param name="buttonId">Integer ID corresponding to the affected button</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
/// <remarks>
/// Forwards the message to <see cref="Container.ActiveChild"/> or if null, to the child under <see cref="Core.MousePosition"/>
/// </remarks>
protected override void ButtonPressedMessage(int buttonId, ref bool handled)
{
//TODO: check if this code shouldn't go to Container
if (Children != null)
{
if (ActiveChild != null)
{
ActiveChild.SendButtonEvent(buttonId, true);
//TODO: check if handled should be set true
}
else
{
for (int i = 0; i < Children.Length; i++)
{
if (Children[i].ScreenBounds.Contains(Core.MousePosition))
{
handled = true;
Children[i].SendButtonEvent(buttonId, true);
break;
}
}
}
}
}
/// <summary>
/// Override this message to handle button released events internally.
/// </summary>
/// <param name="buttonId">Integer ID corresponding to the affected button</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
/// <remarks>
/// Forwards the message to <see cref="Container.ActiveChild"/> or if null, to the child under <see cref="Core.MousePosition"/>
/// </remarks>
protected override void ButtonReleasedMessage(int buttonId, ref bool handled)
{
//TODO: check if this code shouldn't go to Container
if (Children != null)
{
if (ActiveChild != null)
{
ActiveChild.SendButtonEvent(buttonId, false);
//TODO: check if handled should be set true
}
else
{
for (int i = 0; i < Children.Length; i++)
{
if (Children[i].ScreenBounds.Contains(Core.MousePosition))
{
handled = true;
Children[i].SendButtonEvent(buttonId, false);
break;
}
}
}
}
}
#endregion
#region Keyboard Methods
/// <summary>
/// Override this message to handle alt key events internally.
/// </summary>
/// <param name="key">Integer value of the Alt key affected</param>
/// <param name="pressed">True if the key is currently being pressed; false if released</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
/// <remarks>
/// Forwards the message to <see cref="Container.ActiveChild"/>
/// </remarks>
protected override void KeyboardAltKeyMessage(int key, bool pressed, ref bool handled)
{
//TODO: check if this code shouldn't go to Container
if (ActiveChild != null)
{
handled = true;
ActiveChild.SendKeyboardAltKeyEvent(key, pressed);
}
base.KeyboardAltKeyMessage(key, pressed, ref handled);
}
/// <summary>
/// Override this message to handle key events internally.
/// </summary>
/// <param name="key">Integer value of the key affected</param>
/// <param name="pressed">True if the key is currently being pressed; false if released</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
/// <remarks>
/// Forwards the message to <see cref="Container.ActiveChild"/>
/// </remarks>
protected override void KeyboardKeyMessage(char key, bool pressed, ref bool handled)
{
//TODO: check if this code shouldn't go to Container
if (ActiveChild != null)
{
handled = true;
ActiveChild.SendKeyboardKeyEvent(key, pressed);
}
base.KeyboardKeyMessage(key, pressed, ref handled);
}
#endregion
#region Touch Methods
/// <summary>
/// Override this message to handle touch events internally.
/// </summary>
/// <param name="sender">Object sending the event</param>
/// <param name="point">Point on screen touch event is occurring</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
/// <remarks>
/// Forwards the message to the top most child under the point.
/// The hit child is made the active child.
/// </remarks>
protected override void TouchDownMessage(object sender, point point, ref bool handled)
{
//TODO: check if this code shouldn't go to Container
// Check Controls
if (Children != null)
{
lock (Children)
{
for (int i = Children.Length - 1; i >= 0; i--)
{
if (Children[i].Visible && Children[i].HitTest(point))
{
ActiveChild = Children[i];
Children[i].SendTouchDown(this, point);
handled = true;
return;
}
}
}
}
if (ActiveChild != null)
{
ActiveChild.Blur();
Render(ActiveChild.ScreenBounds, true);
ActiveChild = null;
}
_touch = true;
}
/// <summary>
/// Override this message to handle touch events internally.
/// </summary>
/// <param name="sender">Object sending the event</param>
/// <param name="type">Type of touch gesture</param>
/// <param name="force">Force associated with gesture (0.0 to 1.0)</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
/// <remarks>
/// Forwards the message to <see cref="Container.ActiveChild"/>
/// </remarks>
protected override void TouchGestureMessage(object sender, TouchType type, float force, ref bool handled)
{
//TODO: check if this code shouldn't go to Container
if (ActiveChild != null)
{
handled = true;
ActiveChild.SendTouchGesture(sender, type, force);
}
}
/// <summary>
/// Override this message to handle touch events internally.
/// </summary>
/// <param name="sender">Object sending the event</param>
/// <param name="point">Point on screen touch event is occurring</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
/// <remarks>
/// Moves the form if touch down was on the form.
/// If no then forwards the message to <see cref="Container.ActiveChild"/> or if null, to the child under point
/// </remarks>
protected override void TouchMoveMessage(object sender, point point, ref bool handled)
{
try
{
if (_touch)
{
bool bUpdated = false;
int diffY = 0;
int diffX = 0;
// Scroll Y
if (_maxY > Height)
{
diffY = point.Y - LastTouch.Y;
if (diffY > 0 && _minY < Top)
{
diffY = System.Math.Min(diffY, _minY + Top);
bUpdated = true;
}
else if (diffY < 0 && _maxY > Height)
{
diffY = System.Math.Min(-diffY, _maxY - _minY - Height);
bUpdated = true;
}
else
{
diffY = 0;
}
_moving = true;
}
// Scroll X
if (_maxX > Width)
{
diffX = point.X - LastTouch.X;
if (diffX > 0 && _minX < Left)
{
diffX = System.Math.Min(diffX, _minX + Left);
bUpdated = true;
}
else if (diffX < 0 && _maxX > Width)
{
diffX = System.Math.Min(-diffX, _maxX - _minX - Width);
bUpdated = true;
}
else
{
diffX = 0;
}
_moving = true;
handled = true;
}
LastTouch = point;
if (bUpdated)
{
var ptOff = new point(diffX, diffY);
for (int i = 0; i < Children.Length; i++)
{
Children[i].UpdateOffsets(ptOff);
}
Render(true);
handled = true;
}
else if (_moving)
{
Render(true);
}
}
else
{
//TODO: check if this code shouldn't go to Container (or may be even the whole method?)
// Check Controls
if (ActiveChild != null && ActiveChild.Touching)
{
ActiveChild.SendTouchMove(this, point);
handled = true;
return;
}
if (Children != null)
{
for (int i = Children.Length - 1; i >= 0; i--)
{
if (Children[i].Touching || Children[i].HitTest(point))
{
Children[i].SendTouchMove(this, point);
}
}
}
}
}
finally
{
base.TouchMoveMessage(sender, point, ref handled);
}
}
/// <summary>
/// Override this message to handle touch events internally.
/// </summary>
/// <param name="sender">Object sending the event</param>
/// <param name="point">Point on screen touch event is occurring</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
/// <remarks>
/// Finishes the from moving if touch down was on the form.
/// If not then it forwards the message to <see cref="Container.ActiveChild"/> or if null, to the child under point
/// </remarks>
protected override void TouchUpMessage(object sender, point point, ref bool handled)
{
_touch = false;
if (_moving)
{
_moving = false;
Render(true);
}
else
{
//TODO: check if this code shouldn't go to Container
// Check Controls
if (Children != null)
{
for (int i = Children.Length - 1; i >= 0; i--)
{
try
{
if (Children[i].HitTest(point) && !handled)
{
handled = true;
Children[i].SendTouchUp(this, point);
}
else if (Children[i].Touching)
{
Children[i].SendTouchUp(this, point);
}
}
// ReSharper disable once EmptyGeneralCatchClause
catch // This can happen if the user clears the Form during a tap
{}
}
}
}
base.TouchUpMessage(sender, point, ref handled);
}
#endregion
#region GUI
/// <summary>
/// Renders the control contents
/// </summary>
/// <param name="x">X position in screen coordinates</param>
/// <param name="y">Y position in screen coordinates</param>
/// <param name="width">Width in pixel</param>
/// <param name="height">Height in pixel</param>
/// <remarks>
/// Renders the form and all its childes.
/// </remarks>
protected override void OnRender(int x, int y, int width, int height)
{
var area = new rect(x, y, width, height);
if (!_trans)
{
DrawBackground();
}
_maxX = Width;
_maxY = Height;
//TODO: check if this code shouldn't go to Container
// Render controls
if (Children != null)
{
for (int i = 0; i < Children.Length; i++)
{
if (Children[i] != null)
{
if (Children[i].ScreenBounds.Intersects(area))
{
Children[i].Render();
}
if (Children[i].Y < _minY)
{
_minY = Children[i].Y;
}
else if (Children[i].Y + Children[i].Height > _maxY)
{
_maxY = Children[i].Y + Children[i].Height;
}
if (Children[i].X < _minX)
{
_minX = Children[i].X;
}
else if (Children[i].X + Children[i].Width > _maxX)
{
_maxX = Children[i].X + Children[i].Width;
}
}
}
}
if (_border)
{
Core.Screen.DrawRectangle(Core.SystemColors.BorderColor, 1, Left, Top, Width, Height, 0, 0, 0, 0, 0, 0, 0, 0, 256);
}
base.OnRender(x, y, width, height);
}
#endregion
#region Private Methods
private void DrawBackground()
{
Core.Screen.DrawRectangle(_bkg, 0, Left, Top, Width, Height, 0, 0, _bkg, 0, 0, _bkg, 0, 0, 256);
if (_img != null)
{
switch (_scale)
{
case ScaleMode.Center:
Core.Screen.DrawImage(Left + (Core.ScreenWidth / 2 - _img.Width / 2), Top + (Core.ScreenHeight / 2 - _img.Height / 2), _img, 0, 0, _img.Width, _img.Height);
break;
case ScaleMode.Normal:
Core.Screen.DrawImage(Left, Top, _img, 0, 0, _img.Width, _img.Height);
break;
case ScaleMode.Scale:
float multiplier;
if (_img.Height > _img.Width)
{
// Portrait
if (Height > Width)
{
multiplier = Width/(float) _img.Width;
}
else
{
multiplier = Height / (float)_img.Height;
}
}
else
{
// Landscape
if (Height > Width)
{
multiplier = Width/(float) _img.Width;
}
else
{
multiplier = Height / (float)_img.Height;
}
}
int dsW = (int)(_img.Width * multiplier);
int dsH = (int)(_img.Height * multiplier);
int dX = (int)(Width / 2.0f - dsW / 2.0f);
int dY = (int)(Height / 2.0f - dsH / 2.0f);
Core.Screen.StretchImage(Left + dX, Top + dY, _img, dsW, dsH, 256);
break;
case ScaleMode.Stretch:
Core.Screen.StretchImage(Left, Top, _img, Core.ScreenWidth, Core.ScreenHeight, 256);
break;
case ScaleMode.Tile:
Core.Screen.TileImage(Left, Top, _img, Core.ScreenWidth, Core.ScreenHeight, 256);
break;
}
}
}
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JustSending.Data;
using JustSending.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SignalR;
namespace JustSending.Services
{
public class ConversationHub : Hub
{
public const string FILE_EXT = ".file";
private readonly AppDbContext _db;
private readonly IWebHostEnvironment _env;
private readonly BackgroundJobScheduler _jobScheduler;
private readonly string _uploadFolder;
public ConversationHub(AppDbContext db, IWebHostEnvironment env, BackgroundJobScheduler jobScheduler)
{
_db = db;
_env = env;
_jobScheduler = jobScheduler;
_uploadFolder = Helper.GetUploadFolder(string.Empty, _env.WebRootPath);
if (!Directory.Exists(_uploadFolder)) Directory.CreateDirectory(_uploadFolder);
}
internal async Task RequestReloadMessage(string sessionId)
{
await SignalREvent(sessionId, "requestReloadMessage");
}
internal async Task ShowSharePanel(string sessionId, int token)
{
await SignalREvent(sessionId, "showSharePanel", token.ToString(Constants.TOKEN_FORMAT_STRING));
}
internal async Task HideSharePanel(string sessionId)
{
await SignalREvent(sessionId, "hideSharePanel");
}
internal async Task NotifySessionDeleted(string[] connectionIds)
{
await SignalREventToClients(connectionIds, "sessionDeleted");
}
internal async Task SendNumberOfDevices(string sessionId, int count)
{
await SignalREvent(sessionId, "setNumberOfDevices", count);
}
internal async Task RedirectTo(string sessionId, string relativeUrl)
{
await SignalREvent(sessionId, "redirect", relativeUrl);
}
internal async Task<int> SendNumberOfDevices(string sessionId)
{
var numConnectedDevices = _db.Connections.Count(x => x.SessionId == sessionId);
await SendNumberOfDevices(sessionId, numConnectedDevices);
return numConnectedDevices;
}
private async Task SignalREvent(string sessionId, string message, object data = null)
{
try
{
if (data != null)
await GetClientsBySessionId(sessionId).SendAsync(message, data);
else
await GetClientsBySessionId(sessionId).SendAsync(message);
}
catch (Exception ex)
{
Trace.TraceError($"[SignalR/SignalREvent:{message}] {ex.GetBaseException().Message}");
}
}
private async Task SignalREventToClients(string[] connectionIds, string message, object data = null)
{
try
{
if (data != null)
await Clients.Clients(connectionIds).SendAsync(message, data);
else
await Clients.Clients(connectionIds).SendAsync(message);
}
catch (Exception ex)
{
Trace.TraceError($"[SignalR/SignalREventToClients:{message}] {ex.GetBaseException().Message}");
}
}
private IClientProxy GetClientsBySessionId(string sessionId, string except = null)
{
var connectionIds = _db.FindClient(sessionId);
if (!string.IsNullOrEmpty(except))
{
connectionIds = connectionIds.Where(x => x != except);
}
return Clients.Clients(connectionIds.ToList());
}
private IClientProxy GetClientByConnectionId(string connectionId) => Clients.Client(connectionId);
public override Task OnConnectedAsync()
{
_db.RecordStats(s => s.Devices++);
return Task.CompletedTask;
}
public override async Task OnDisconnectedAsync(Exception exception)
{
var sessionId = _db.UntrackClientReturnSessionId(Context.ConnectionId);
if (string.IsNullOrEmpty(sessionId)) return;
// Don't Erase session if this session had been converted
// to a Lite Session in the mean time
//
var session = _db.Sessions.FindById(sessionId);
if (session.IsLiteSession) return;
if (!string.IsNullOrEmpty(sessionId))
{
var numDevices = await SendNumberOfDevices(sessionId);
if (numDevices == 0)
{
var cIds = _jobScheduler.EraseSessionReturnConnectionIds(sessionId);
await NotifySessionDeleted(cIds);
}
else
{
await AddSessionNotification(sessionId, "A device was disconnected.");
}
}
}
public async Task AddSessionNotification(string sessionId, string message, bool isLiteSession = false)
{
var msg = new Message
{
Id = _db.NewGuid(),
SessionId = sessionId,
DateSent = DateTime.UtcNow,
Text = message,
SocketConnectionId = Context?.ConnectionId,
IsNotification = true
};
_db.MessagesInsert(msg);
if (!isLiteSession)
await RequestReloadMessage(sessionId);
}
public async Task<string> Connect(string sessionId)
{
_db.TrackClient(sessionId, Context.ConnectionId);
// Check if any active share token is open
//
await CheckIfShareTokenExists(sessionId);
var numDevices = _db.Connections.Count(x => x.SessionId == sessionId);
await SendNumberOfDevices(sessionId, numDevices);
if (numDevices > 1)
{
await InitKeyExchange(sessionId);
await CancelShare();
}
return Context.ConnectionId;
}
public async Task StreamFile(string sessionId, string content)
{
var uploadPath = Path.Combine(_uploadFolder, Context.ConnectionId + FILE_EXT);
await File.AppendAllLinesAsync(uploadPath, new[] { content });
}
#region KeyExchange
private async Task InitKeyExchange(string sessionId)
{
// enable end to end encryption
//
var newDevice = Context.ConnectionId;
var firstDeviceId =
_db
.Connections
.FindOne(x => x.SessionId == sessionId && x.ConnectionId != newDevice)
.ConnectionId;
//
// Send shared p & g to both parties then
// request the original device to initite key-exchange
//
var p = Helper.GetPrime(1024, _env);
var g = Helper.GetPrime(2, _env);
var pka = Guid.NewGuid().ToString("N");
var initFirstDevice = Clients
.Client(firstDeviceId)
.SendAsync("startKeyExchange", newDevice, p, g, pka, false);
await initFirstDevice.ContinueWith(async x =>
{
await Clients
.Client(newDevice)
.SendAsync("startKeyExchange", firstDeviceId, p, g, pka, true);
});
}
public async Task CallPeer(string peerId, string method, string param)
{
ValidateIntent(peerId);
IClientProxy endpoint;
if (peerId == "ALL")
{
var sessionId = GetSessionId();
endpoint = GetClientsBySessionId(sessionId, except: Context.ConnectionId);
var msg = new StringBuilder("A new device connected.<br/><i class=\"fa fa-lock\"></i> Message is end to end encrypted.");
var numDevices = _db.Connections.Count(x => x.SessionId == sessionId);
if (numDevices == 2)
{
msg.Append("<hr/><div class='text-info'>Frequently share data between these devices?<br/><span class='small'>Bookmark this page on each devices to quickly connect your devices.</span></div>");
}
await AddSessionNotification(sessionId, msg.ToString());
}
else
{
endpoint = GetClientByConnectionId(peerId);
}
await endpoint.SendAsync("callback", method, param);
}
private void ValidateIntent(string peerId)
{
if (peerId == "ALL")
return;
// check if the peer is actually a device within the current session
// this is to prevent cross session communication
//
// Get session from connection
var connection = _db.Connections.FindById(Context.ConnectionId);
if (connection != null)
{
var devices = _db.FindClient(connection.SessionId);
if (devices.Contains(peerId))
{
// OK
return;
}
}
throw new InvalidOperationException("Attempt of cross session communication.");
}
#endregion
private async Task<bool> CheckIfShareTokenExists(string sessionId, bool notifyIfExist = true)
{
var shareToken = _db.ShareTokens.FindOne(x => x.SessionId == sessionId);
if (shareToken != null)
{
if (notifyIfExist)
await ShowSharePanel(sessionId, shareToken.Id);
return true;
}
return false;
}
public async Task Share()
{
var connection = _db.Connections.FindById(Context.ConnectionId);
if (connection == null) return;
// Check if any share exist
if (!await CheckIfShareTokenExists(connection.SessionId))
{
var token = _db.CreateNewShareToken(connection.SessionId);
await ShowSharePanel(connection.SessionId, token);
}
}
public async Task CancelShare()
{
var connection = _db.Connections.FindById(Context.ConnectionId);
if (connection == null) return;
if (CancelShareSessionBySessionId(connection.SessionId))
{
await HideSharePanel(connection.SessionId);
}
}
public bool CancelShareSessionBySessionId(string sessionId)
{
var shareToken = _db.ShareTokens.FindOne(x => x.SessionId == sessionId);
if (shareToken != null)
{
_db.ShareTokens.Delete(shareToken.Id);
return true;
}
return false;
}
public async Task EraseSession()
{
var connection = _db.Connections.FindById(Context.ConnectionId);
if (connection == null) return;
await EraseSessionInternal(connection.SessionId);
}
private async Task EraseSessionInternal(string sessionId)
{
var cIds = _jobScheduler.EraseSessionReturnConnectionIds(sessionId);
await NotifySessionDeleted(cIds);
}
private string GetSessionId() =>
_db
.Connections
.FindOne(x => x.ConnectionId == Context.ConnectionId)
.SessionId;
}
}
| |
using System;
using System.Linq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Serialization;
using Umbraco.Tests.TestHelpers;
using Umbraco.Tests.TestHelpers.Entities;
namespace Umbraco.Tests.Models
{
[TestFixture]
public class ContentTypeTests : BaseUmbracoConfigurationTest
{
[Test]
public void Can_Deep_Clone_Content_Type_Sort()
{
var contentType = new ContentTypeSort(new Lazy<int>(() => 3), 4, "test");
var clone = (ContentTypeSort) contentType.DeepClone();
Assert.AreNotSame(clone, contentType);
Assert.AreEqual(clone, contentType);
Assert.AreEqual(clone.Id.Value, contentType.Id.Value);
Assert.AreEqual(clone.SortOrder, contentType.SortOrder);
Assert.AreEqual(clone.Alias, contentType.Alias);
}
[Test]
public void Can_Deep_Clone_Content_Type_With_Reset_Identities()
{
var contentType = MockedContentTypes.CreateTextpageContentType();
contentType.Id = 99;
var i = 200;
foreach (var propertyType in contentType.PropertyTypes)
{
propertyType.Id = ++i;
}
foreach (var group in contentType.PropertyGroups)
{
group.Id = ++i;
}
//add a property type without a property group
contentType.PropertyTypeCollection.Add(
new PropertyType("test", DataTypeDatabaseType.Ntext, "title2") { Name = "Title2", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 });
contentType.AllowedTemplates = new[] { new Template("-1,2", "Name", "name") { Id = 200 }, new Template("-1,3", "Name2", "name2") { Id = 201 } };
contentType.AllowedContentTypes = new[] { new ContentTypeSort(new Lazy<int>(() => 888), 8, "sub"), new ContentTypeSort(new Lazy<int>(() => 889), 9, "sub2") };
contentType.Id = 10;
contentType.CreateDate = DateTime.Now;
contentType.CreatorId = 22;
contentType.SetDefaultTemplate(new Template("-1,2,3,4", "Test Template", "testTemplate")
{
Id = 88
});
contentType.Description = "test";
contentType.Icon = "icon";
contentType.IsContainer = true;
contentType.Thumbnail = "thumb";
contentType.Key = Guid.NewGuid();
contentType.Level = 3;
contentType.Path = "-1,4,10";
contentType.SortOrder = 5;
contentType.Trashed = false;
contentType.UpdateDate = DateTime.Now;
//ensure that nothing is marked as dirty
contentType.ResetDirtyProperties(false);
var clone = (ContentType)contentType.Clone("newAlias");
Assert.AreEqual("newAlias", clone.Alias);
Assert.AreNotEqual("newAlias", contentType.Alias);
Assert.IsFalse(clone.HasIdentity);
foreach (var propertyGroup in clone.PropertyGroups)
{
Assert.IsFalse(propertyGroup.HasIdentity);
foreach (var propertyType in propertyGroup.PropertyTypes)
{
Assert.IsFalse(propertyType.HasIdentity);
}
}
foreach (var propertyType in clone.PropertyTypes.Where(x => x.HasIdentity))
{
Assert.IsFalse(propertyType.HasIdentity);
}
}
[Ignore]
[Test]
public void Can_Deep_Clone_Content_Type_Perf_Test()
{
// Arrange
var contentType = MockedContentTypes.CreateTextpageContentType();
contentType.Id = 99;
var i = 200;
foreach (var propertyType in contentType.PropertyTypes)
{
propertyType.Id = ++i;
}
foreach (var group in contentType.PropertyGroups)
{
group.Id = ++i;
}
contentType.AllowedTemplates = new[] { new Template("-1,2", "Name", "name") { Id = 200 }, new Template("-1,3", "Name2", "name2") { Id = 201 } };
contentType.AllowedContentTypes = new[] { new ContentTypeSort(new Lazy<int>(() => 888), 8, "sub"), new ContentTypeSort(new Lazy<int>(() => 889), 9, "sub2") };
contentType.Id = 10;
contentType.CreateDate = DateTime.Now;
contentType.CreatorId = 22;
contentType.SetDefaultTemplate(new Template("-1,2,3,4", "Test Template", "testTemplate")
{
Id = 88
});
contentType.Description = "test";
contentType.Icon = "icon";
contentType.IsContainer = true;
contentType.Thumbnail = "thumb";
contentType.Key = Guid.NewGuid();
contentType.Level = 3;
contentType.Path = "-1,4,10";
contentType.SortOrder = 5;
contentType.Trashed = false;
contentType.UpdateDate = DateTime.Now;
((IUmbracoEntity)contentType).AdditionalData.Add("test1", 123);
((IUmbracoEntity)contentType).AdditionalData.Add("test2", "hello");
using (DisposableTimer.DebugDuration<ContentTypeTests>("STARTING PERF TEST"))
{
for (int j = 0; j < 1000; j++)
{
using (DisposableTimer.DebugDuration<ContentTypeTests>("Cloning content type"))
{
var clone = (ContentType)contentType.DeepClone();
}
}
}
}
[Test]
public void Can_Deep_Clone_Content_Type()
{
// Arrange
var contentType = MockedContentTypes.CreateTextpageContentType();
contentType.Id = 99;
var i = 200;
foreach (var propertyType in contentType.PropertyTypes)
{
propertyType.Id = ++i;
}
foreach (var group in contentType.PropertyGroups)
{
group.Id = ++i;
}
contentType.AllowedTemplates = new[] { new Template("-1,2", "Name", "name") { Id = 200 }, new Template("-1,3", "Name2", "name2") { Id = 201 } };
contentType.AllowedContentTypes = new[] {new ContentTypeSort(new Lazy<int>(() => 888), 8, "sub"), new ContentTypeSort(new Lazy<int>(() => 889), 9, "sub2")};
contentType.Id = 10;
contentType.CreateDate = DateTime.Now;
contentType.CreatorId = 22;
contentType.SetDefaultTemplate(new Template("-1,2,3,4", "Test Template", "testTemplate")
{
Id = 88
});
contentType.Description = "test";
contentType.Icon = "icon";
contentType.IsContainer = true;
contentType.Thumbnail = "thumb";
contentType.Key = Guid.NewGuid();
contentType.Level = 3;
contentType.Path = "-1,4,10";
contentType.SortOrder = 5;
contentType.Trashed = false;
contentType.UpdateDate = DateTime.Now;
((IUmbracoEntity)contentType).AdditionalData.Add("test1", 123);
((IUmbracoEntity)contentType).AdditionalData.Add("test2", "hello");
// Act
var clone = (ContentType)contentType.DeepClone();
// Assert
Assert.AreNotSame(clone, contentType);
Assert.AreEqual(clone, contentType);
Assert.AreEqual(clone.Id, contentType.Id);
Assert.AreEqual(((IUmbracoEntity)clone).AdditionalData, ((IUmbracoEntity)contentType).AdditionalData);
Assert.AreEqual(clone.AllowedTemplates.Count(), contentType.AllowedTemplates.Count());
for (var index = 0; index < contentType.AllowedTemplates.Count(); index++)
{
Assert.AreNotSame(clone.AllowedTemplates.ElementAt(index), contentType.AllowedTemplates.ElementAt(index));
Assert.AreEqual(clone.AllowedTemplates.ElementAt(index), contentType.AllowedTemplates.ElementAt(index));
}
Assert.AreNotSame(clone.PropertyGroups, contentType.PropertyGroups);
Assert.AreEqual(clone.PropertyGroups.Count, contentType.PropertyGroups.Count);
for (var index = 0; index < contentType.PropertyGroups.Count; index++)
{
Assert.AreNotSame(clone.PropertyGroups[index], contentType.PropertyGroups[index]);
Assert.AreEqual(clone.PropertyGroups[index], contentType.PropertyGroups[index]);
}
Assert.AreNotSame(clone.PropertyTypes, contentType.PropertyTypes);
Assert.AreEqual(clone.PropertyTypes.Count(), contentType.PropertyTypes.Count());
Assert.AreEqual(0, clone.NoGroupPropertyTypes.Count());
for (var index = 0; index < contentType.PropertyTypes.Count(); index++)
{
Assert.AreNotSame(clone.PropertyTypes.ElementAt(index), contentType.PropertyTypes.ElementAt(index));
Assert.AreEqual(clone.PropertyTypes.ElementAt(index), contentType.PropertyTypes.ElementAt(index));
}
Assert.AreEqual(clone.CreateDate, contentType.CreateDate);
Assert.AreEqual(clone.CreatorId, contentType.CreatorId);
Assert.AreEqual(clone.Key, contentType.Key);
Assert.AreEqual(clone.Level, contentType.Level);
Assert.AreEqual(clone.Path, contentType.Path);
Assert.AreEqual(clone.SortOrder, contentType.SortOrder);
Assert.AreNotSame(clone.DefaultTemplate, contentType.DefaultTemplate);
Assert.AreEqual(clone.DefaultTemplate, contentType.DefaultTemplate);
Assert.AreEqual(clone.DefaultTemplateId, contentType.DefaultTemplateId);
Assert.AreEqual(clone.Trashed, contentType.Trashed);
Assert.AreEqual(clone.UpdateDate, contentType.UpdateDate);
Assert.AreEqual(clone.Thumbnail, contentType.Thumbnail);
Assert.AreEqual(clone.Icon, contentType.Icon);
Assert.AreEqual(clone.IsContainer, contentType.IsContainer);
//This double verifies by reflection
var allProps = clone.GetType().GetProperties();
foreach (var propertyInfo in allProps)
{
Assert.AreEqual(propertyInfo.GetValue(clone, null), propertyInfo.GetValue(contentType, null));
}
//need to ensure the event handlers are wired
var asDirty = (ICanBeDirty)clone;
Assert.IsFalse(asDirty.IsPropertyDirty("PropertyTypes"));
clone.AddPropertyType(new PropertyType("test", DataTypeDatabaseType.Nvarchar, "blah"));
Assert.IsTrue(asDirty.IsPropertyDirty("PropertyTypes"));
Assert.IsFalse(asDirty.IsPropertyDirty("PropertyGroups"));
clone.AddPropertyGroup("hello");
Assert.IsTrue(asDirty.IsPropertyDirty("PropertyGroups"));
}
[Test]
public void Can_Serialize_Content_Type_Without_Error()
{
var ss = new SerializationService(new JsonNetSerializer());
// Arrange
var contentType = MockedContentTypes.CreateTextpageContentType();
contentType.Id = 99;
var i = 200;
foreach (var propertyType in contentType.PropertyTypes)
{
propertyType.Id = ++i;
}
contentType.AllowedTemplates = new[] { new Template("-1,2", "Name", "name") { Id = 200 }, new Template("-1,3", "Name2", "name2") { Id = 201 } };
contentType.AllowedContentTypes = new[] { new ContentTypeSort(new Lazy<int>(() => 888), 8, "sub"), new ContentTypeSort(new Lazy<int>(() => 889), 9, "sub2") };
contentType.Id = 10;
contentType.CreateDate = DateTime.Now;
contentType.CreatorId = 22;
contentType.SetDefaultTemplate(new Template("-1,2,3,4", "Test Template", "testTemplate")
{
Id = 88
});
contentType.Description = "test";
contentType.Icon = "icon";
contentType.IsContainer = true;
contentType.Thumbnail = "thumb";
contentType.Key = Guid.NewGuid();
contentType.Level = 3;
contentType.Path = "-1,4,10";
contentType.SortOrder = 5;
contentType.Trashed = false;
contentType.UpdateDate = DateTime.Now;
((IUmbracoEntity)contentType).AdditionalData.Add("test1", 123);
((IUmbracoEntity)contentType).AdditionalData.Add("test2", "hello");
var result = ss.ToStream(contentType);
var json = result.ResultStream.ToJsonString();
Console.WriteLine(json);
}
[Test]
public void Can_Deep_Clone_Media_Type()
{
// Arrange
var contentType = MockedContentTypes.CreateImageMediaType();
contentType.Id = 99;
var i = 200;
foreach (var propertyType in contentType.PropertyTypes)
{
propertyType.Id = ++i;
}
contentType.Id = 10;
contentType.CreateDate = DateTime.Now;
contentType.CreatorId = 22;
contentType.Description = "test";
contentType.Icon = "icon";
contentType.IsContainer = true;
contentType.Thumbnail = "thumb";
contentType.Key = Guid.NewGuid();
contentType.Level = 3;
contentType.Path = "-1,4,10";
contentType.SortOrder = 5;
contentType.Trashed = false;
contentType.UpdateDate = DateTime.Now;
((IUmbracoEntity)contentType).AdditionalData.Add("test1", 123);
((IUmbracoEntity)contentType).AdditionalData.Add("test2", "hello");
// Act
var clone = (MediaType)contentType.DeepClone();
// Assert
Assert.AreNotSame(clone, contentType);
Assert.AreEqual(clone, contentType);
Assert.AreEqual(clone.Id, contentType.Id);
Assert.AreEqual(((IUmbracoEntity)clone).AdditionalData, ((IUmbracoEntity)contentType).AdditionalData);
Assert.AreEqual(clone.PropertyGroups.Count, contentType.PropertyGroups.Count);
for (var index = 0; index < contentType.PropertyGroups.Count; index++)
{
Assert.AreNotSame(clone.PropertyGroups[index], contentType.PropertyGroups[index]);
Assert.AreEqual(clone.PropertyGroups[index], contentType.PropertyGroups[index]);
}
Assert.AreEqual(clone.PropertyTypes.Count(), contentType.PropertyTypes.Count());
for (var index = 0; index < contentType.PropertyTypes.Count(); index++)
{
Assert.AreNotSame(clone.PropertyTypes.ElementAt(index), contentType.PropertyTypes.ElementAt(index));
Assert.AreEqual(clone.PropertyTypes.ElementAt(index), contentType.PropertyTypes.ElementAt(index));
}
Assert.AreEqual(clone.CreateDate, contentType.CreateDate);
Assert.AreEqual(clone.CreatorId, contentType.CreatorId);
Assert.AreEqual(clone.Key, contentType.Key);
Assert.AreEqual(clone.Level, contentType.Level);
Assert.AreEqual(clone.Path, contentType.Path);
Assert.AreEqual(clone.SortOrder, contentType.SortOrder);
Assert.AreEqual(clone.Trashed, contentType.Trashed);
Assert.AreEqual(clone.UpdateDate, contentType.UpdateDate);
Assert.AreEqual(clone.Thumbnail, contentType.Thumbnail);
Assert.AreEqual(clone.Icon, contentType.Icon);
Assert.AreEqual(clone.IsContainer, contentType.IsContainer);
//This double verifies by reflection
var allProps = clone.GetType().GetProperties();
foreach (var propertyInfo in allProps)
{
Assert.AreEqual(propertyInfo.GetValue(clone, null), propertyInfo.GetValue(contentType, null));
}
}
[Test]
public void Can_Serialize_Media_Type_Without_Error()
{
var ss = new SerializationService(new JsonNetSerializer());
// Arrange
var contentType = MockedContentTypes.CreateImageMediaType();
contentType.Id = 99;
var i = 200;
foreach (var propertyType in contentType.PropertyTypes)
{
propertyType.Id = ++i;
}
contentType.Id = 10;
contentType.CreateDate = DateTime.Now;
contentType.CreatorId = 22;
contentType.Description = "test";
contentType.Icon = "icon";
contentType.IsContainer = true;
contentType.Thumbnail = "thumb";
contentType.Key = Guid.NewGuid();
contentType.Level = 3;
contentType.Path = "-1,4,10";
contentType.SortOrder = 5;
contentType.Trashed = false;
contentType.UpdateDate = DateTime.Now;
((IUmbracoEntity)contentType).AdditionalData.Add("test1", 123);
((IUmbracoEntity)contentType).AdditionalData.Add("test2", "hello");
var result = ss.ToStream(contentType);
var json = result.ResultStream.ToJsonString();
Console.WriteLine(json);
}
[Test]
public void Can_Deep_Clone_Member_Type()
{
// Arrange
var contentType = MockedContentTypes.CreateSimpleMemberType();
contentType.Id = 99;
var i = 200;
foreach (var propertyType in contentType.PropertyTypes)
{
propertyType.Id = ++i;
}
contentType.Id = 10;
contentType.CreateDate = DateTime.Now;
contentType.CreatorId = 22;
contentType.Description = "test";
contentType.Icon = "icon";
contentType.IsContainer = true;
contentType.Thumbnail = "thumb";
contentType.Key = Guid.NewGuid();
contentType.Level = 3;
contentType.Path = "-1,4,10";
contentType.SortOrder = 5;
contentType.Trashed = false;
contentType.UpdateDate = DateTime.Now;
contentType.SetMemberCanEditProperty("title", true);
contentType.SetMemberCanViewProperty("bodyText", true);
((IUmbracoEntity)contentType).AdditionalData.Add("test1", 123);
((IUmbracoEntity)contentType).AdditionalData.Add("test2", "hello");
// Act
var clone = (MemberType)contentType.DeepClone();
// Assert
Assert.AreNotSame(clone, contentType);
Assert.AreEqual(clone, contentType);
Assert.AreEqual(clone.Id, contentType.Id);
Assert.AreEqual(((IUmbracoEntity)clone).AdditionalData, ((IUmbracoEntity)contentType).AdditionalData);
Assert.AreEqual(clone.PropertyGroups.Count, contentType.PropertyGroups.Count);
for (var index = 0; index < contentType.PropertyGroups.Count; index++)
{
Assert.AreNotSame(clone.PropertyGroups[index], contentType.PropertyGroups[index]);
Assert.AreEqual(clone.PropertyGroups[index], contentType.PropertyGroups[index]);
}
Assert.AreEqual(clone.PropertyTypes.Count(), contentType.PropertyTypes.Count());
for (var index = 0; index < contentType.PropertyTypes.Count(); index++)
{
Assert.AreNotSame(clone.PropertyTypes.ElementAt(index), contentType.PropertyTypes.ElementAt(index));
Assert.AreEqual(clone.PropertyTypes.ElementAt(index), contentType.PropertyTypes.ElementAt(index));
}
Assert.AreEqual(clone.CreateDate, contentType.CreateDate);
Assert.AreEqual(clone.CreatorId, contentType.CreatorId);
Assert.AreEqual(clone.Key, contentType.Key);
Assert.AreEqual(clone.Level, contentType.Level);
Assert.AreEqual(clone.Path, contentType.Path);
Assert.AreEqual(clone.SortOrder, contentType.SortOrder);
Assert.AreEqual(clone.Trashed, contentType.Trashed);
Assert.AreEqual(clone.UpdateDate, contentType.UpdateDate);
Assert.AreEqual(clone.Thumbnail, contentType.Thumbnail);
Assert.AreEqual(clone.Icon, contentType.Icon);
Assert.AreEqual(clone.IsContainer, contentType.IsContainer);
Assert.AreEqual(clone.MemberTypePropertyTypes, contentType.MemberTypePropertyTypes);
//This double verifies by reflection
var allProps = clone.GetType().GetProperties();
foreach (var propertyInfo in allProps)
{
Assert.AreEqual(propertyInfo.GetValue(clone, null), propertyInfo.GetValue(contentType, null));
}
}
[Test]
public void Can_Serialize_Member_Type_Without_Error()
{
var ss = new SerializationService(new JsonNetSerializer());
// Arrange
var contentType = MockedContentTypes.CreateSimpleMemberType();
contentType.Id = 99;
var i = 200;
foreach (var propertyType in contentType.PropertyTypes)
{
propertyType.Id = ++i;
}
contentType.Id = 10;
contentType.CreateDate = DateTime.Now;
contentType.CreatorId = 22;
contentType.Description = "test";
contentType.Icon = "icon";
contentType.IsContainer = true;
contentType.Thumbnail = "thumb";
contentType.Key = Guid.NewGuid();
contentType.Level = 3;
contentType.Path = "-1,4,10";
contentType.SortOrder = 5;
contentType.Trashed = false;
contentType.UpdateDate = DateTime.Now;
contentType.SetMemberCanEditProperty("title", true);
contentType.SetMemberCanViewProperty("bodyText", true);
((IUmbracoEntity)contentType).AdditionalData.Add("test1", 123);
((IUmbracoEntity)contentType).AdditionalData.Add("test2", "hello");
var result = ss.ToStream(contentType);
var json = result.ResultStream.ToJsonString();
Console.WriteLine(json);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers
{
internal class NamedParameterCompletionProvider : AbstractCompletionProvider, IEqualityComparer<IParameterSymbol>
{
private const string ColonString = ":";
public override bool IsCommitCharacter(CompletionItem completionItem, char ch, string textTypedSoFar)
{
return CompletionUtilities.IsCommitCharacter(completionItem, ch, textTypedSoFar);
}
public override bool SendEnterThroughToEditor(CompletionItem completionItem, string textTypedSoFar)
{
return CompletionUtilities.SendEnterThroughToEditor(completionItem, textTypedSoFar);
}
public override bool IsTriggerCharacter(SourceText text, int characterPosition, OptionSet options)
{
return CompletionUtilities.IsTriggerCharacter(text, characterPosition, options);
}
public override TextChange GetTextChange(CompletionItem selectedItem, char? ch = null, string textTypedSoFar = null)
{
return new TextChange(
selectedItem.FilterSpan,
selectedItem.DisplayText.Substring(0, selectedItem.DisplayText.Length - ColonString.Length));
}
protected override async Task<bool> IsExclusiveAsync(Document document, int caretPosition, CompletionTriggerInfo triggerInfo, CancellationToken cancellationToken)
{
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var token = syntaxTree.FindTokenOnLeftOfPosition(caretPosition, cancellationToken)
.GetPreviousTokenIfTouchingWord(caretPosition);
return token.IsMandatoryNamedParameterPosition();
}
protected override async Task<IEnumerable<CompletionItem>> GetItemsWorkerAsync(
Document document, int position, CompletionTriggerInfo triggerInfo, CancellationToken cancellationToken)
{
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
if (syntaxTree.IsInNonUserCode(position, cancellationToken))
{
return null;
}
var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
token = token.GetPreviousTokenIfTouchingWord(position);
if (token.Kind() != SyntaxKind.OpenParenToken &&
token.Kind() != SyntaxKind.OpenBracketToken &&
token.Kind() != SyntaxKind.CommaToken)
{
return null;
}
var argumentList = token.Parent as BaseArgumentListSyntax;
if (argumentList == null)
{
return null;
}
var semanticModel = await document.GetSemanticModelForNodeAsync(argumentList, cancellationToken).ConfigureAwait(false);
var parameterLists = GetParameterLists(semanticModel, position, argumentList.Parent, cancellationToken);
if (parameterLists == null)
{
return null;
}
var existingNamedParameters = GetExistingNamedParameters(argumentList, position);
parameterLists = parameterLists.Where(pl => IsValid(pl, existingNamedParameters));
var unspecifiedParameters = parameterLists.SelectMany(pl => pl)
.Where(p => !existingNamedParameters.Contains(p.Name))
.Distinct(this);
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
return unspecifiedParameters.Select(
p =>
{
// Note: the filter text does not include the ':'. We want to ensure that if
// the user types the name exactly (up to the colon) that it is selected as an
// exact match.
var workspace = document.Project.Solution.Workspace;
var escaped = p.Name.ToIdentifierToken().ToString();
return new CSharpCompletionItem(
workspace,
this,
escaped + ColonString,
CompletionUtilities.GetTextChangeSpan(text, position),
CommonCompletionUtilities.CreateDescriptionFactory(workspace, semanticModel, token.SpanStart, p),
p.GetGlyph(),
sortText: p.Name,
filterText: escaped);
});
}
private bool IsValid(ImmutableArray<IParameterSymbol> parameterList, ISet<string> existingNamedParameters)
{
// A parameter list is valid if it has parameters that match in name all the existing
// named parameters that have been provided.
return existingNamedParameters.Except(parameterList.Select(p => p.Name)).IsEmpty();
}
private ISet<string> GetExistingNamedParameters(BaseArgumentListSyntax argumentList, int position)
{
var existingArguments = argumentList.Arguments.Where(a => a.Span.End <= position && a.NameColon != null)
.Select(a => a.NameColon.Name.Identifier.ValueText);
return existingArguments.ToSet();
}
private IEnumerable<ImmutableArray<IParameterSymbol>> GetParameterLists(
SemanticModel semanticModel,
int position,
SyntaxNode invocableNode,
CancellationToken cancellationToken)
{
return invocableNode.TypeSwitch(
(InvocationExpressionSyntax invocationExpression) => GetInvocationExpressionParameterLists(semanticModel, position, invocationExpression, cancellationToken),
(ConstructorInitializerSyntax constructorInitializer) => GetConstructorInitializerParameterLists(semanticModel, position, constructorInitializer, cancellationToken),
(ElementAccessExpressionSyntax elementAccessExpression) => GetElementAccessExpressionParameterLists(semanticModel, position, elementAccessExpression, cancellationToken),
(ObjectCreationExpressionSyntax objectCreationExpression) => GetObjectCreationExpressionParameterLists(semanticModel, position, objectCreationExpression, cancellationToken));
}
private IEnumerable<ImmutableArray<IParameterSymbol>> GetObjectCreationExpressionParameterLists(
SemanticModel semanticModel,
int position,
ObjectCreationExpressionSyntax objectCreationExpression,
CancellationToken cancellationToken)
{
var type = semanticModel.GetTypeInfo(objectCreationExpression, cancellationToken).Type as INamedTypeSymbol;
var within = semanticModel.GetEnclosingNamedType(position, cancellationToken);
if (type != null && within != null && type.TypeKind != TypeKind.Delegate)
{
return type.InstanceConstructors.Where(c => c.IsAccessibleWithin(within))
.Select(c => c.Parameters);
}
return null;
}
private IEnumerable<ImmutableArray<IParameterSymbol>> GetElementAccessExpressionParameterLists(
SemanticModel semanticModel,
int position,
ElementAccessExpressionSyntax elementAccessExpression,
CancellationToken cancellationToken)
{
var expressionSymbol = semanticModel.GetSymbolInfo(elementAccessExpression.Expression, cancellationToken).GetAnySymbol();
var expressionType = semanticModel.GetTypeInfo(elementAccessExpression.Expression, cancellationToken).Type;
if (expressionSymbol != null && expressionType != null)
{
var indexers = semanticModel.LookupSymbols(position, expressionType, WellKnownMemberNames.Indexer).OfType<IPropertySymbol>();
var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken);
if (within != null)
{
return indexers.Where(i => i.IsAccessibleWithin(within, throughTypeOpt: expressionType))
.Select(i => i.Parameters);
}
}
return null;
}
private IEnumerable<ImmutableArray<IParameterSymbol>> GetConstructorInitializerParameterLists(
SemanticModel semanticModel,
int position,
ConstructorInitializerSyntax constructorInitializer,
CancellationToken cancellationToken)
{
var within = semanticModel.GetEnclosingNamedType(position, cancellationToken);
if (within != null &&
(within.TypeKind == TypeKind.Struct || within.TypeKind == TypeKind.Class))
{
var type = constructorInitializer.Kind() == SyntaxKind.BaseConstructorInitializer
? within.BaseType
: within;
if (type != null)
{
return type.InstanceConstructors.Where(c => c.IsAccessibleWithin(within))
.Select(c => c.Parameters);
}
}
return null;
}
private IEnumerable<ImmutableArray<IParameterSymbol>> GetInvocationExpressionParameterLists(
SemanticModel semanticModel,
int position,
InvocationExpressionSyntax invocationExpression,
CancellationToken cancellationToken)
{
var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken);
if (within != null)
{
var methodGroup = semanticModel.GetMemberGroup(invocationExpression.Expression, cancellationToken).OfType<IMethodSymbol>();
var expressionType = semanticModel.GetTypeInfo(invocationExpression.Expression, cancellationToken).Type as INamedTypeSymbol;
if (methodGroup.Any())
{
return methodGroup.Where(m => m.IsAccessibleWithin(within))
.Select(m => m.Parameters);
}
else if (expressionType.IsDelegateType())
{
var delegateType = (INamedTypeSymbol)expressionType;
return SpecializedCollections.SingletonEnumerable(delegateType.DelegateInvokeMethod.Parameters);
}
}
return null;
}
bool IEqualityComparer<IParameterSymbol>.Equals(IParameterSymbol x, IParameterSymbol y)
{
return x.Name.Equals(y.Name);
}
int IEqualityComparer<IParameterSymbol>.GetHashCode(IParameterSymbol obj)
{
return obj.Name.GetHashCode();
}
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2015 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT
#define UNITY
#endif
using System;
#if UNITY
using System.Collections;
#endif // UNITY
using System.Collections.Generic;
#if UNITY
using System.Reflection;
#endif // UNITY
namespace MsgPack.Serialization.CollectionSerializers
{
/// <summary>
/// Provides basic features for generic <see cref="IDictionary{TKey,TValue}"/> serializers.
/// </summary>
/// <typeparam name="TDictionary">The type of the dictionary.</typeparam>
/// <typeparam name="TKey">The type of the key of dictionary.</typeparam>
/// <typeparam name="TValue">The type of the value of dictionary.</typeparam>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes", Justification = "By design" )]
public abstract class DictionaryMessagePackSerializer<TDictionary, TKey, TValue> : DictionaryMessagePackSerializerBase<TDictionary, TKey, TValue>
where TDictionary : IDictionary<TKey, TValue>
#if UNITY
, IEnumerable<KeyValuePair<TKey, TValue>> // This is obvious from IDictionary<TKey, TValue>, but Unity compiler cannot recognize this.
#endif // UNITY
{
/// <summary>
/// Initializes a new instance of the <see cref="DictionaryMessagePackSerializer{TDictionary, TKey, TValue}"/> class.
/// </summary>
/// <param name="ownerContext">A <see cref="SerializationContext"/> which owns this serializer.</param>
/// <param name="schema">
/// The schema for collection itself or its items for the member this instance will be used to.
/// <c>null</c> will be considered as <see cref="PolymorphismSchema.Default"/>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="ownerContext"/> is <c>null</c>.
/// </exception>
protected DictionaryMessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema schema )
: base( ownerContext, schema ) { }
/// <summary>
/// Returns count of the dictionary.
/// </summary>
/// <param name="dictionary">A collection. This value will not be <c>null</c>.</param>
/// <returns>The count of the <paramref name="dictionary"/>.</returns>
protected override int GetCount( TDictionary dictionary )
{
#if ( !UNITY && !XAMIOS ) || AOT_CHECK
return dictionary.Count;
#else
// .constraind call for TDictionary.get_Count/TDictionary.GetEnumerator() causes AOT error.
// So use cast and invoke as normal call (it might cause boxing, but most collection should be reference type).
return ( dictionary as IDictionary<TKey, TValue> ).Count;
#endif // ( !UNITY && !XAMIOS ) || AOT_CHECK
}
/// <summary>
/// Adds the deserialized item to the collection on <typeparamref name="TDictionary"/> specific manner
/// to implement <see cref="DictionaryMessagePackSerializerBase{TDictionary,TKey,TValue}.UnpackToCore(MsgPack.Unpacker,TDictionary)"/>.
/// </summary>
/// <param name="dictionary">The dictionary to be added.</param>
/// <param name="key">The key to be added.</param>
/// <param name="value">The value to be added.</param>
/// <exception cref="NotSupportedException">
/// This implementation always throws it.
/// </exception>
protected override void AddItem( TDictionary dictionary, TKey key, TValue value )
{
#if ( !UNITY && !XAMIOS ) || AOT_CHECK
dictionary.Add( key, value );
#else
// .constraind call for TDictionary.Add causes AOT error.
// So use cast and invoke as normal call (it might cause boxing, but most collection should be reference type).
( dictionary as IDictionary<TKey, TValue> ).Add( key, value );
#endif // ( !UNITY && !XAMIOS ) || AOT_CHECK
}
}
#if UNITY
internal abstract class UnityDictionaryMessagePackSerializer : NonGenericMessagePackSerializer,
ICollectionInstanceFactory
{
private readonly IMessagePackSingleObjectSerializer _keySerializer;
private readonly IMessagePackSingleObjectSerializer _valueSerializer;
private readonly MethodInfo _add;
private readonly MethodInfo _getCount;
private readonly MethodInfo _getKey;
private readonly MethodInfo _getValue;
protected UnityDictionaryMessagePackSerializer(
SerializationContext ownerContext,
Type targetType,
Type keyType,
Type valueType,
CollectionTraits traits,
PolymorphismSchema schema
)
: base( ownerContext, targetType )
{
var safeSchema = schema ?? PolymorphismSchema.Default;
this._keySerializer = ownerContext.GetSerializer( keyType, safeSchema.KeySchema );
this._valueSerializer = ownerContext.GetSerializer( valueType, safeSchema.ItemSchema );
this._add = traits.AddMethod;
this._getCount = traits.CountPropertyGetter;
this._getKey = traits.ElementType.GetProperty( "Key" ).GetGetMethod();
this._getValue = traits.ElementType.GetProperty( "Value" ).GetGetMethod();
}
protected internal override sealed void PackToCore( Packer packer, object objectTree )
{
packer.PackMapHeader( ( int )this._getCount.InvokePreservingExceptionType( objectTree ) );
// ReSharper disable once PossibleNullReferenceException
foreach ( var item in objectTree as IEnumerable )
{
this._keySerializer.PackTo( packer, this._getKey.InvokePreservingExceptionType( item ) );
this._valueSerializer.PackTo( packer, this._getValue.InvokePreservingExceptionType( item ) );
}
}
protected internal override sealed object UnpackFromCore( Unpacker unpacker )
{
if ( !unpacker.IsMapHeader )
{
throw SerializationExceptions.NewIsNotArrayHeader();
}
return this.InternalUnpackFromCore( unpacker );
}
internal virtual object InternalUnpackFromCore( Unpacker unpacker )
{
var itemsCount = UnpackHelpers.GetItemsCount( unpacker );
var collection = this.CreateInstance( itemsCount );
this.UnpackToCore( unpacker, collection, itemsCount );
return collection;
}
protected abstract object CreateInstance( int initialCapacity );
object ICollectionInstanceFactory.CreateInstance( int initialCapacity )
{
return this.CreateInstance( initialCapacity );
}
protected internal override sealed void UnpackToCore( Unpacker unpacker, object collection )
{
if ( !unpacker.IsMapHeader )
{
throw SerializationExceptions.NewIsNotArrayHeader();
}
this.UnpackToCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ) );
}
private void UnpackToCore( Unpacker unpacker, object collection, int itemsCount )
{
for ( int i = 0; i < itemsCount; i++ )
{
if ( !unpacker.Read() )
{
throw SerializationExceptions.NewMissingItem( i );
}
object key;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
key = this._keySerializer.UnpackFrom( unpacker );
}
else
{
using ( var subtreeUnpacker = unpacker.ReadSubtree() )
{
key = this._keySerializer.UnpackFrom( subtreeUnpacker );
}
}
if ( !unpacker.Read() )
{
throw SerializationExceptions.NewMissingItem( i );
}
object value;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
value = this._valueSerializer.UnpackFrom( unpacker );
}
else
{
using ( var subtreeUnpacker = unpacker.ReadSubtree() )
{
value = this._valueSerializer.UnpackFrom( subtreeUnpacker );
}
}
this._add.InvokePreservingExceptionType( collection, key, value );
}
}
}
#endif // UNITY
}
| |
//
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.Storage;
using Microsoft.Azure.Management.Storage.Models;
namespace Microsoft.Azure.Management.Storage
{
/// <summary>
/// The Storage Management Client.
/// </summary>
public static partial class StorageAccountOperationsExtensions
{
/// <summary>
/// Asynchronously creates a new storage account with the specified
/// parameters. Existing accounts cannot be updated with this API and
/// should instead use the Update Storage Account API. If an account
/// is already created and subsequent PUT request is issued with exact
/// same set of properties, then HTTP 200 would be returned.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Storage.IStorageAccountOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group within the user's
/// subscription.
/// </param>
/// <param name='accountName'>
/// Required. The name of the storage account within the specified
/// resource group. Storage account names must be between 3 and 24
/// characters in length and use numbers and lower-case letters only.
/// </param>
/// <param name='parameters'>
/// Required. The parameters to provide for the created account.
/// </param>
/// <returns>
/// The Create storage account operation response.
/// </returns>
public static StorageAccountCreateResponse BeginCreate(this IStorageAccountOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IStorageAccountOperations)s).BeginCreateAsync(resourceGroupName, accountName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Asynchronously creates a new storage account with the specified
/// parameters. Existing accounts cannot be updated with this API and
/// should instead use the Update Storage Account API. If an account
/// is already created and subsequent PUT request is issued with exact
/// same set of properties, then HTTP 200 would be returned.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Storage.IStorageAccountOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group within the user's
/// subscription.
/// </param>
/// <param name='accountName'>
/// Required. The name of the storage account within the specified
/// resource group. Storage account names must be between 3 and 24
/// characters in length and use numbers and lower-case letters only.
/// </param>
/// <param name='parameters'>
/// Required. The parameters to provide for the created account.
/// </param>
/// <returns>
/// The Create storage account operation response.
/// </returns>
public static Task<StorageAccountCreateResponse> BeginCreateAsync(this IStorageAccountOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters)
{
return operations.BeginCreateAsync(resourceGroupName, accountName, parameters, CancellationToken.None);
}
/// <summary>
/// Checks that account name is valid and is not in use.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Storage.IStorageAccountOperations.
/// </param>
/// <param name='accountName'>
/// Required. The name of the storage account within the specified
/// resource group. Storage account names must be between 3 and 24
/// characters in length and use numbers and lower-case letters only.
/// </param>
/// <returns>
/// The CheckNameAvailability operation response.
/// </returns>
public static CheckNameAvailabilityResponse CheckNameAvailability(this IStorageAccountOperations operations, string accountName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IStorageAccountOperations)s).CheckNameAvailabilityAsync(accountName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Checks that account name is valid and is not in use.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Storage.IStorageAccountOperations.
/// </param>
/// <param name='accountName'>
/// Required. The name of the storage account within the specified
/// resource group. Storage account names must be between 3 and 24
/// characters in length and use numbers and lower-case letters only.
/// </param>
/// <returns>
/// The CheckNameAvailability operation response.
/// </returns>
public static Task<CheckNameAvailabilityResponse> CheckNameAvailabilityAsync(this IStorageAccountOperations operations, string accountName)
{
return operations.CheckNameAvailabilityAsync(accountName, CancellationToken.None);
}
/// <summary>
/// Asynchronously creates a new storage account with the specified
/// parameters. Existing accounts cannot be updated with this API and
/// should instead use the Update Storage Account API. If an account
/// is already created and subsequent create request is issued with
/// exact same set of properties, the request succeeds.The max number
/// of storage accounts that can be created per subscription is
/// limited to 100.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Storage.IStorageAccountOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group within the user's
/// subscription.
/// </param>
/// <param name='accountName'>
/// Required. The name of the storage account within the specified
/// resource group. Storage account names must be between 3 and 24
/// characters in length and use numbers and lower-case letters only.
/// </param>
/// <param name='parameters'>
/// Required. The parameters to provide for the created account.
/// </param>
/// <returns>
/// The Create storage account operation response.
/// </returns>
public static StorageAccountCreateResponse Create(this IStorageAccountOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IStorageAccountOperations)s).CreateAsync(resourceGroupName, accountName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Asynchronously creates a new storage account with the specified
/// parameters. Existing accounts cannot be updated with this API and
/// should instead use the Update Storage Account API. If an account
/// is already created and subsequent create request is issued with
/// exact same set of properties, the request succeeds.The max number
/// of storage accounts that can be created per subscription is
/// limited to 100.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Storage.IStorageAccountOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group within the user's
/// subscription.
/// </param>
/// <param name='accountName'>
/// Required. The name of the storage account within the specified
/// resource group. Storage account names must be between 3 and 24
/// characters in length and use numbers and lower-case letters only.
/// </param>
/// <param name='parameters'>
/// Required. The parameters to provide for the created account.
/// </param>
/// <returns>
/// The Create storage account operation response.
/// </returns>
public static Task<StorageAccountCreateResponse> CreateAsync(this IStorageAccountOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters)
{
return operations.CreateAsync(resourceGroupName, accountName, parameters, CancellationToken.None);
}
/// <summary>
/// Deletes a storage account in Microsoft Azure.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Storage.IStorageAccountOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group within the user's
/// subscription.
/// </param>
/// <param name='accountName'>
/// Required. The name of the storage account within the specified
/// resource group. Storage account names must be between 3 and 24
/// characters in length and use numbers and lower-case letters only.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IStorageAccountOperations operations, string resourceGroupName, string accountName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IStorageAccountOperations)s).DeleteAsync(resourceGroupName, accountName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a storage account in Microsoft Azure.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Storage.IStorageAccountOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group within the user's
/// subscription.
/// </param>
/// <param name='accountName'>
/// Required. The name of the storage account within the specified
/// resource group. Storage account names must be between 3 and 24
/// characters in length and use numbers and lower-case letters only.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IStorageAccountOperations operations, string resourceGroupName, string accountName)
{
return operations.DeleteAsync(resourceGroupName, accountName, CancellationToken.None);
}
/// <summary>
/// Returns the properties for the specified storage account including
/// but not limited to name, account type, location, and account
/// status. The ListKeys operation should be used to retrieve storage
/// keys.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Storage.IStorageAccountOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group within the user's
/// subscription.
/// </param>
/// <param name='accountName'>
/// Required. The name of the storage account within the specified
/// resource group. Storage account names must be between 3 and 24
/// characters in length and use numbers and lower-case letters only.
/// </param>
/// <returns>
/// The Get storage account operation response.
/// </returns>
public static StorageAccountGetPropertiesResponse GetProperties(this IStorageAccountOperations operations, string resourceGroupName, string accountName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IStorageAccountOperations)s).GetPropertiesAsync(resourceGroupName, accountName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns the properties for the specified storage account including
/// but not limited to name, account type, location, and account
/// status. The ListKeys operation should be used to retrieve storage
/// keys.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Storage.IStorageAccountOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group within the user's
/// subscription.
/// </param>
/// <param name='accountName'>
/// Required. The name of the storage account within the specified
/// resource group. Storage account names must be between 3 and 24
/// characters in length and use numbers and lower-case letters only.
/// </param>
/// <returns>
/// The Get storage account operation response.
/// </returns>
public static Task<StorageAccountGetPropertiesResponse> GetPropertiesAsync(this IStorageAccountOperations operations, string resourceGroupName, string accountName)
{
return operations.GetPropertiesAsync(resourceGroupName, accountName, CancellationToken.None);
}
/// <summary>
/// Lists all the storage accounts available under the subscription.
/// Note that storage keys are not returned; use the ListKeys
/// operation for this.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Storage.IStorageAccountOperations.
/// </param>
/// <returns>
/// The list storage accounts operation response.
/// </returns>
public static StorageAccountListResponse List(this IStorageAccountOperations operations)
{
return Task.Factory.StartNew((object s) =>
{
return ((IStorageAccountOperations)s).ListAsync();
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all the storage accounts available under the subscription.
/// Note that storage keys are not returned; use the ListKeys
/// operation for this.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Storage.IStorageAccountOperations.
/// </param>
/// <returns>
/// The list storage accounts operation response.
/// </returns>
public static Task<StorageAccountListResponse> ListAsync(this IStorageAccountOperations operations)
{
return operations.ListAsync(CancellationToken.None);
}
/// <summary>
/// Lists all the storage accounts available under the given resource
/// group. Note that storage keys are not returned; use the ListKeys
/// operation for this.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Storage.IStorageAccountOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group within the user's
/// subscription.
/// </param>
/// <returns>
/// The list storage accounts operation response.
/// </returns>
public static StorageAccountListResponse ListByResourceGroup(this IStorageAccountOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IStorageAccountOperations)s).ListByResourceGroupAsync(resourceGroupName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all the storage accounts available under the given resource
/// group. Note that storage keys are not returned; use the ListKeys
/// operation for this.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Storage.IStorageAccountOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group within the user's
/// subscription.
/// </param>
/// <returns>
/// The list storage accounts operation response.
/// </returns>
public static Task<StorageAccountListResponse> ListByResourceGroupAsync(this IStorageAccountOperations operations, string resourceGroupName)
{
return operations.ListByResourceGroupAsync(resourceGroupName, CancellationToken.None);
}
/// <summary>
/// Lists the access keys for the specified storage account.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Storage.IStorageAccountOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='accountName'>
/// Required. The name of the storage account.
/// </param>
/// <returns>
/// The ListKeys operation response.
/// </returns>
public static StorageAccountListKeysResponse ListKeys(this IStorageAccountOperations operations, string resourceGroupName, string accountName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IStorageAccountOperations)s).ListKeysAsync(resourceGroupName, accountName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the access keys for the specified storage account.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Storage.IStorageAccountOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='accountName'>
/// Required. The name of the storage account.
/// </param>
/// <returns>
/// The ListKeys operation response.
/// </returns>
public static Task<StorageAccountListKeysResponse> ListKeysAsync(this IStorageAccountOperations operations, string resourceGroupName, string accountName)
{
return operations.ListKeysAsync(resourceGroupName, accountName, CancellationToken.None);
}
/// <summary>
/// Regenerates the access keys for the specified storage account.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Storage.IStorageAccountOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group within the user's
/// subscription.
/// </param>
/// <param name='accountName'>
/// Required. The name of the storage account within the specified
/// resource group. Storage account names must be between 3 and 24
/// characters in length and use numbers and lower-case letters only.
/// </param>
/// <param name='regenerateKey'>
/// Required. Specifies name of the key which should be regenerated.
/// key1 or key2 for the default keys
/// </param>
/// <returns>
/// The RegenerateKey operation response.
/// </returns>
public static StorageAccountRegenerateKeyResponse RegenerateKey(this IStorageAccountOperations operations, string resourceGroupName, string accountName, string regenerateKey)
{
return Task.Factory.StartNew((object s) =>
{
return ((IStorageAccountOperations)s).RegenerateKeyAsync(resourceGroupName, accountName, regenerateKey);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Regenerates the access keys for the specified storage account.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Storage.IStorageAccountOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group within the user's
/// subscription.
/// </param>
/// <param name='accountName'>
/// Required. The name of the storage account within the specified
/// resource group. Storage account names must be between 3 and 24
/// characters in length and use numbers and lower-case letters only.
/// </param>
/// <param name='regenerateKey'>
/// Required. Specifies name of the key which should be regenerated.
/// key1 or key2 for the default keys
/// </param>
/// <returns>
/// The RegenerateKey operation response.
/// </returns>
public static Task<StorageAccountRegenerateKeyResponse> RegenerateKeyAsync(this IStorageAccountOperations operations, string resourceGroupName, string accountName, string regenerateKey)
{
return operations.RegenerateKeyAsync(resourceGroupName, accountName, regenerateKey, CancellationToken.None);
}
/// <summary>
/// Updates the account type or tags for a storage account. It can also
/// be used to add a custom domain (note that custom domains cannot be
/// added via the Create operation). Only one custom domain is
/// supported per storage account. In order to replace a custom
/// domain, the old value must be cleared before a new value may be
/// set. To clear a custom domain, simply update the custom domain
/// with empty string. Then call update again with the new cutsom
/// domain name. The update API can only be used to update one of
/// tags, accountType, or customDomain per call. To update multiple of
/// these properties, call the API multiple times with one change per
/// call. This call does not change the storage keys for the account.
/// If you want to change storage account keys, use the RegenerateKey
/// operation. The location and name of the storage account cannot be
/// changed after creation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Storage.IStorageAccountOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group within the user's
/// subscription.
/// </param>
/// <param name='accountName'>
/// Required. The name of the storage account within the specified
/// resource group. Storage account names must be between 3 and 24
/// characters in length and use numbers and lower-case letters only.
/// </param>
/// <param name='parameters'>
/// Required. The parameters to update on the account. Note that only
/// one property can be changed at a time using this API.
/// </param>
/// <returns>
/// The Update storage account operation response.
/// </returns>
public static StorageAccountUpdateResponse Update(this IStorageAccountOperations operations, string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IStorageAccountOperations)s).UpdateAsync(resourceGroupName, accountName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates the account type or tags for a storage account. It can also
/// be used to add a custom domain (note that custom domains cannot be
/// added via the Create operation). Only one custom domain is
/// supported per storage account. In order to replace a custom
/// domain, the old value must be cleared before a new value may be
/// set. To clear a custom domain, simply update the custom domain
/// with empty string. Then call update again with the new cutsom
/// domain name. The update API can only be used to update one of
/// tags, accountType, or customDomain per call. To update multiple of
/// these properties, call the API multiple times with one change per
/// call. This call does not change the storage keys for the account.
/// If you want to change storage account keys, use the RegenerateKey
/// operation. The location and name of the storage account cannot be
/// changed after creation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Storage.IStorageAccountOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group within the user's
/// subscription.
/// </param>
/// <param name='accountName'>
/// Required. The name of the storage account within the specified
/// resource group. Storage account names must be between 3 and 24
/// characters in length and use numbers and lower-case letters only.
/// </param>
/// <param name='parameters'>
/// Required. The parameters to update on the account. Note that only
/// one property can be changed at a time using this API.
/// </param>
/// <returns>
/// The Update storage account operation response.
/// </returns>
public static Task<StorageAccountUpdateResponse> UpdateAsync(this IStorageAccountOperations operations, string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters)
{
return operations.UpdateAsync(resourceGroupName, accountName, parameters, CancellationToken.None);
}
}
}
| |
// 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;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Concurrent.Tests
{
public class PartitionerStaticTests
{
[Fact]
public static void TestStaticPartitioningIList()
{
RunTestWithAlgorithm(dataSize: 11, partitionCount: 8, algorithm: 0);
RunTestWithAlgorithm(dataSize: 999, partitionCount: 1, algorithm: 0);
RunTestWithAlgorithm(dataSize: 10000, partitionCount: 11, algorithm: 0);
}
[Fact]
public static void TestStaticPartitioningArray()
{
RunTestWithAlgorithm(dataSize: 7, partitionCount: 4, algorithm: 1);
RunTestWithAlgorithm(dataSize: 123, partitionCount: 1, algorithm: 1);
RunTestWithAlgorithm(dataSize: 1000, partitionCount: 7, algorithm: 1);
}
[Fact]
public static void TestLoadBalanceIList()
{
RunTestWithAlgorithm(dataSize: 7, partitionCount: 4, algorithm: 2);
RunTestWithAlgorithm(dataSize: 123, partitionCount: 1, algorithm: 2);
RunTestWithAlgorithm(dataSize: 1000, partitionCount: 7, algorithm: 2);
}
[Fact]
public static void TestLoadBalanceArray()
{
RunTestWithAlgorithm(dataSize: 11, partitionCount: 8, algorithm: 3);
RunTestWithAlgorithm(dataSize: 999, partitionCount: 1, algorithm: 3);
RunTestWithAlgorithm(dataSize: 10000, partitionCount: 11, algorithm: 3);
}
[Fact]
public static void TestLoadBalanceEnumerator()
{
RunTestWithAlgorithm(dataSize: 7, partitionCount: 4, algorithm: 4);
RunTestWithAlgorithm(dataSize: 123, partitionCount: 1, algorithm: 4);
RunTestWithAlgorithm(dataSize: 1000, partitionCount: 7, algorithm: 4);
}
#region Dispose tests. The dispose logic of PartitionerStatic
// In the official dev unit test run, this test should be commented out
// - Each time we call GetDynamicPartitions method, we create an internal "reader enumerator" to read the
// source data, and we need to make sure that whenever the object returned by GetDynamicPartitions is disposed,
// the "reader enumerator" is also disposed.
[Fact]
public static void TestDisposeException()
{
var data = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var enumerable = new DisposeTrackingEnumerable<int>(data);
var partitioner = Partitioner.Create(enumerable);
var partition = partitioner.GetDynamicPartitions();
IDisposable d = partition as IDisposable;
Assert.NotNull(d);
d.Dispose();
Assert.Throws<ObjectDisposedException>(() => { var enum1 = partition.GetEnumerator(); });
}
/// <summary>
/// Race in Partitioner's dynamic partitioning Dispose logic
/// After the fix, the partitioner created through Partitioner.Create(IEnumerable) has the following behavior:
/// 1. reference counting in static partitioning. All partitions need to be disposed explicitly
/// 2. no reference counting in dynamic partitioning. The partitioner need to be disposed explicitly
/// </summary>
/// <returns></returns>
[Fact]
public static void RunDynamicPartitioningDispose()
{
var p = Partitioner.Create(new int[] { 0, 1 });
var d = p.GetDynamicPartitions();
using (var e = d.GetEnumerator())
{
while (e.MoveNext()) { }
}
// should not throw
using (var e = d.GetEnumerator()) { };
}
#endregion
[Fact]
public static void TestExceptions()
{
// Testing ArgumentNullException with data==null
// Test ArgumentNullException of source data
OrderablePartitioner<int> partitioner;
for (int algorithm = 0; algorithm < 5; algorithm++)
{
Assert.Throws<ArgumentNullException>(() => { partitioner = PartitioningWithAlgorithm<int>(null, algorithm); });
}
// Test NotSupportedException of Reset: already tested in RunTestWithAlgorithm
// Test InvalidOperationException: already tested in TestPartitioningCore
// Test ArgumentOutOfRangeException of partitionCount == 0
int[] data = new int[10000];
for (int i = 0; i < 10000; i++)
data[i] = i;
//test GetOrderablePartitions method for 0-4 algorithms, try to catch ArgumentOutOfRangeException
for (int algorithm = 0; algorithm < 5; algorithm++)
{
partitioner = PartitioningWithAlgorithm<int>(data, algorithm);
Assert.Throws<ArgumentOutOfRangeException>(() => { var partitions1 = partitioner.GetOrderablePartitions(0); });
}
}
[Fact]
public static void TestEmptyPartitions()
{
int[] data = new int[0];
// Test ArgumentNullException of source data
OrderablePartitioner<int> partitioner;
for (int algorithm = 0; algorithm < 5; algorithm++)
{
partitioner = PartitioningWithAlgorithm<int>(data, algorithm);
//test GetOrderablePartitions
var partitions1 = partitioner.GetOrderablePartitions(4);
//verify all partitions are empty
for (int i = 0; i < 4; i++)
{
Assert.False(partitions1[i].MoveNext(), "Should not be able to move next in an empty partition.");
}
//test GetOrderableDynamicPartitions
try
{
var partitions2 = partitioner.GetOrderableDynamicPartitions();
//verify all partitions are empty
var newPartition = partitions2.GetEnumerator();
Assert.False(newPartition.MoveNext(), "Should not be able to move next in an empty partition.");
}
catch (NotSupportedException)
{
Assert.True(IsStaticPartition(algorithm), "TestEmptyPartitions: IsStaticPartition(algorithm) should have been true.");
}
}
}
private static void RunTestWithAlgorithm(int dataSize, int partitionCount, int algorithm)
{
//we set up the KeyValuePair in the way that keys and values should always be the same
//for all partitioning algorithms. So that we can use a bitmap (boolarray) to check whether
//any elements are missing in the end.
int[] data = new int[dataSize];
for (int i = 0; i < dataSize; i++)
data[i] = i;
IEnumerator<KeyValuePair<long, int>>[] partitionsUnderTest = new IEnumerator<KeyValuePair<long, int>>[partitionCount];
//step 1: test GetOrderablePartitions
OrderablePartitioner<int> partitioner = PartitioningWithAlgorithm<int>(data, algorithm);
var partitions1 = partitioner.GetOrderablePartitions(partitionCount);
//convert it to partition array for testing
for (int i = 0; i < partitionCount; i++)
partitionsUnderTest[i] = partitions1[i];
Assert.Equal(partitionCount, partitions1.Count);
TestPartitioningCore(dataSize, partitionCount, data, IsStaticPartition(algorithm), partitionsUnderTest);
//step 2: test GetOrderableDynamicPartitions
bool gotException = false;
try
{
var partitions2 = partitioner.GetOrderableDynamicPartitions();
for (int i = 0; i < partitionCount; i++)
partitionsUnderTest[i] = partitions2.GetEnumerator();
TestPartitioningCore(dataSize, partitionCount, data, IsStaticPartition(algorithm), partitionsUnderTest);
}
catch (NotSupportedException)
{
//swallow this exception: static partitioning doesn't support GetOrderableDynamicPartitions
gotException = true;
}
Assert.False(IsStaticPartition(algorithm) && !gotException, "TestLoadBalanceIList: Failure: didn't catch \"NotSupportedException\" for static partitioning");
}
private static OrderablePartitioner<T> PartitioningWithAlgorithm<T>(T[] data, int algorithm)
{
switch (algorithm)
{
//static partitioning through IList
case (0):
return Partitioner.Create((IList<T>)data, false);
//static partitioning through Array
case (1):
return Partitioner.Create(data, false);
//dynamic partitioning through IList
case (2):
return Partitioner.Create((IList<T>)data, true);
//dynamic partitioning through Array
case (3):
return Partitioner.Create(data, true);
//dynamic partitioning through IEnumerator
case (4):
return Partitioner.Create((IEnumerable<T>)data);
default:
throw new InvalidOperationException("PartitioningWithAlgorithm: no such partitioning algorithm");
}
}
private static void TestPartitioningCore(int dataSize, int partitionCount, int[] data, bool staticPartitioning,
IEnumerator<KeyValuePair<long, int>>[] partitions)
{
bool[] boolarray = new bool[dataSize];
bool keysOrderedWithinPartition = true,
keysOrderedAcrossPartitions = true;
int enumCount = 0; //count how many elements are enumerated by all partitions
Task[] threadArray = new Task[partitionCount];
for (int i = 0; i < partitionCount; i++)
{
int my_i = i;
threadArray[i] = Task.Run(() =>
{
int localOffset = 0;
int lastElement = -1;
//variables to compute key/value consistency for static partitioning.
int quotient, remainder;
quotient = dataSize / partitionCount;
remainder = dataSize % partitionCount;
Assert.Throws<InvalidOperationException>(() => { var temp = partitions[my_i].Current; });
while (partitions[my_i].MoveNext())
{
int key = (int)partitions[my_i].Current.Key,
value = partitions[my_i].Current.Value;
Assert.Equal(key, value);
boolarray[key] = true;
Interlocked.Increment(ref enumCount);
//todo: check if keys are ordered increasingly within each partition.
keysOrderedWithinPartition &= (lastElement >= key);
lastElement = key;
//Only check this with static partitioning
//check keys are ordered across the partitions
if (staticPartitioning)
{
int originalPosition;
if (my_i < remainder)
originalPosition = localOffset + my_i * (quotient + 1);
else
originalPosition = localOffset + remainder * (quotient + 1) + (my_i - remainder) * quotient;
keysOrderedAcrossPartitions &= originalPosition == value;
}
localOffset++;
}
}
);
}
Task.WaitAll(threadArray);
if (keysOrderedWithinPartition)
Console.WriteLine("TestPartitioningCore: Keys are not strictly ordered within each partition");
// Only check this with static partitioning
//check keys are ordered across the partitions
Assert.False(staticPartitioning && !keysOrderedAcrossPartitions, "TestPartitioningCore: Keys are not strictly ordered across partitions");
//check data count
Assert.Equal(enumCount, dataSize);
//check if any elements are missing
foreach (var item in boolarray)
{
Assert.True(item);
}
}
//
// Try calling MoveNext on a Partitioner enumerator after that enumerator has already returned false.
//
[Fact]
public static void TestExtraMoveNext()
{
Partitioner<int>[] partitioners = new[]
{
Partitioner.Create(new int[] { 0 , 1, 2, 3, 4, 5}),
Partitioner.Create(new int[] { 0 , 1, 2, 3, 4, 5}, false),
Partitioner.Create(new int[] { 0 , 1, 2, 3, 4, 5}, true),
Partitioner.Create(new int[] { 0 }),
Partitioner.Create(new int[] { 0 }, false),
Partitioner.Create(new int[] { 0 }, true),
};
for (int i = 0; i < partitioners.Length; i++)
{
using (var ee = partitioners[i].GetPartitions(1)[0])
{
while (ee.MoveNext()) { }
Assert.False(ee.MoveNext(), "TestExtraMoveNext: FAILED. Partitioner " + i + ": First extra MoveNext expected to return false.");
Assert.False(ee.MoveNext(), "TestExtraMoveNext: FAILED. Partitioner " + i + ": Second extra MoveNext expected to return false.");
Assert.False(ee.MoveNext(), "TestExtraMoveNext: FAILED. Partitioner " + i + ": Third extra MoveNext expected to return false.");
}
}
}
#region Helper Methods / Classes
private class DisposeTrackingEnumerable<T> : IEnumerable<T>
{
protected IEnumerable<T> m_data;
List<DisposeTrackingEnumerator<T>> s_enumerators = new List<DisposeTrackingEnumerator<T>>();
public DisposeTrackingEnumerable(IEnumerable<T> enumerable)
{
m_data = enumerable;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
DisposeTrackingEnumerator<T> walker = new DisposeTrackingEnumerator<T>(m_data.GetEnumerator());
lock (s_enumerators)
{
s_enumerators.Add(walker);
}
return walker;
}
public IEnumerator<T> GetEnumerator()
{
DisposeTrackingEnumerator<T> walker = new DisposeTrackingEnumerator<T>(m_data.GetEnumerator());
lock (s_enumerators)
{
s_enumerators.Add(walker);
}
return walker;
}
public void AreEnumeratorsDisposed(string scenario)
{
for (int i = 0; i < s_enumerators.Count; i++)
{
Assert.True(s_enumerators[i].IsDisposed(),
string.Format("AreEnumeratorsDisposed: FAILED. enumerator {0} was not disposed for SCENARIO: {1}.", i, scenario));
}
}
}
/// <summary>
/// This is the Enumerator that DisposeTrackingEnumerable generates when GetEnumerator is called.
/// We are simply wrapping an Enumerator and tracking whether Dispose had been called or not.
/// </summary>
/// <typeparam name="T">The type of the element</typeparam>
private class DisposeTrackingEnumerator<T> : IEnumerator<T>
{
IEnumerator<T> m_elements;
bool disposed;
public DisposeTrackingEnumerator(IEnumerator<T> enumerator)
{
m_elements = enumerator;
disposed = false;
}
public bool MoveNext()
{
return m_elements.MoveNext();
}
public T Current
{
get { return m_elements.Current; }
}
object System.Collections.IEnumerator.Current
{
get { return m_elements.Current; }
}
/// <summary>
/// Dispose the underlying Enumerator, and suppresses finalization
/// so that we will not throw.
/// </summary>
public void Dispose()
{
GC.SuppressFinalize(this);
m_elements.Dispose();
disposed = true;
}
public void Reset()
{
m_elements.Reset();
}
public bool IsDisposed()
{
return disposed;
}
}
private static bool IsStaticPartition(int algorithm)
{
return algorithm < 2;
}
#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 AndNotUInt16()
{
var test = new SimpleBinaryOpTest__AndNotUInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using 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();
// 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__AndNotUInt16
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[ElementCount];
private static UInt16[] _data2 = new UInt16[ElementCount];
private static Vector128<UInt16> _clsVar1;
private static Vector128<UInt16> _clsVar2;
private Vector128<UInt16> _fld1;
private Vector128<UInt16> _fld2;
private SimpleBinaryOpTest__DataTable<UInt16> _dataTable;
static SimpleBinaryOpTest__AndNotUInt16()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__AndNotUInt16()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt16>(_data1, _data2, new UInt16[ElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.AndNot(
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.AndNot(
Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.AndNot(
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.AndNot(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr);
var result = Sse2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr));
var result = Sse2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr));
var result = Sse2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AndNotUInt16();
var result = Sse2.AndNot(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.AndNot(_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<UInt16> left, Vector128<UInt16> right, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[ElementCount];
UInt16[] inArray2 = new UInt16[ElementCount];
UInt16[] outArray = new UInt16[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, 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 = "")
{
UInt16[] inArray1 = new UInt16[ElementCount];
UInt16[] inArray2 = new UInt16[ElementCount];
UInt16[] outArray = new UInt16[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "")
{
if ((ushort)(~left[0] & right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((ushort)(~left[i] & right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.AndNot)}<UInt16>: {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.Buffers.Binary;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
namespace System
{
// Implements the Decimal data type. The Decimal data type can
// represent values ranging from -79,228,162,514,264,337,593,543,950,335 to
// 79,228,162,514,264,337,593,543,950,335 with 28 significant digits. The
// Decimal data type is ideally suited to financial calculations that
// require a large number of significant digits and no round-off errors.
//
// The finite set of values of type Decimal are of the form m
// / 10e, where m is an integer such that
// -296 <; m <; 296, and e is an integer
// between 0 and 28 inclusive.
//
// Contrary to the float and double data types, decimal
// fractional numbers such as 0.1 can be represented exactly in the
// Decimal representation. In the float and double
// representations, such numbers are often infinite fractions, making those
// representations more prone to round-off errors.
//
// The Decimal class implements widening conversions from the
// ubyte, char, short, int, and long types
// to Decimal. These widening conversions never loose any information
// and never throw exceptions. The Decimal class also implements
// narrowing conversions from Decimal to ubyte, char,
// short, int, and long. These narrowing conversions round
// the Decimal value towards zero to the nearest integer, and then
// converts that integer to the destination type. An OverflowException
// is thrown if the result is not within the range of the destination type.
//
// The Decimal class provides a widening conversion from
// Currency to Decimal. This widening conversion never loses any
// information and never throws exceptions. The Currency class provides
// a narrowing conversion from Decimal to Currency. This
// narrowing conversion rounds the Decimal to four decimals and then
// converts that number to a Currency. An OverflowException
// is thrown if the result is not within the range of the Currency type.
//
// The Decimal class provides narrowing conversions to and from the
// float and double types. A conversion from Decimal to
// float or double may loose precision, but will not loose
// information about the overall magnitude of the numeric value, and will never
// throw an exception. A conversion from float or double to
// Decimal throws an OverflowException if the value is not within
// the range of the Decimal type.
[StructLayout(LayoutKind.Sequential)]
[Serializable]
[System.Runtime.Versioning.NonVersionable] // This only applies to field layout
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public readonly partial struct Decimal : IFormattable, IComparable, IConvertible, IComparable<decimal>, IEquatable<decimal>, IDeserializationCallback, ISpanFormattable
{
// Sign mask for the flags field. A value of zero in this bit indicates a
// positive Decimal value, and a value of one in this bit indicates a
// negative Decimal value.
//
// Look at OleAut's DECIMAL_NEG constant to check for negative values
// in native code.
private const int SignMask = unchecked((int)0x80000000);
// Scale mask for the flags field. This byte in the flags field contains
// the power of 10 to divide the Decimal value by. The scale byte must
// contain a value between 0 and 28 inclusive.
private const int ScaleMask = 0x00FF0000;
// Number of bits scale is shifted by.
private const int ScaleShift = 16;
// Constant representing the Decimal value 0.
public const decimal Zero = 0m;
// Constant representing the Decimal value 1.
public const decimal One = 1m;
// Constant representing the Decimal value -1.
public const decimal MinusOne = -1m;
// Constant representing the largest possible Decimal value. The value of
// this constant is 79,228,162,514,264,337,593,543,950,335.
public const decimal MaxValue = 79228162514264337593543950335m;
// Constant representing the smallest possible Decimal value. The value of
// this constant is -79,228,162,514,264,337,593,543,950,335.
public const decimal MinValue = -79228162514264337593543950335m;
// The lo, mid, hi, and flags fields contain the representation of the
// Decimal value. The lo, mid, and hi fields contain the 96-bit integer
// part of the Decimal. Bits 0-15 (the lower word) of the flags field are
// unused and must be zero; bits 16-23 contain must contain a value between
// 0 and 28, indicating the power of 10 to divide the 96-bit integer part
// by to produce the Decimal value; bits 24-30 are unused and must be zero;
// and finally bit 31 indicates the sign of the Decimal value, 0 meaning
// positive and 1 meaning negative.
//
// NOTE: Do not change the order in which these fields are declared. The
// native methods in this class rely on this particular order.
// Do not rename (binary serialization).
private readonly int flags;
private readonly int hi;
private readonly int lo;
private readonly int mid;
// Constructs a Decimal from an integer value.
//
public Decimal(int value)
{
if (value >= 0)
{
flags = 0;
}
else
{
flags = SignMask;
value = -value;
}
lo = value;
mid = 0;
hi = 0;
}
// Constructs a Decimal from an unsigned integer value.
//
[CLSCompliant(false)]
public Decimal(uint value)
{
flags = 0;
lo = (int)value;
mid = 0;
hi = 0;
}
// Constructs a Decimal from a long value.
//
public Decimal(long value)
{
if (value >= 0)
{
flags = 0;
}
else
{
flags = SignMask;
value = -value;
}
lo = (int)value;
mid = (int)(value >> 32);
hi = 0;
}
// Constructs a Decimal from an unsigned long value.
//
[CLSCompliant(false)]
public Decimal(ulong value)
{
flags = 0;
lo = (int)value;
mid = (int)(value >> 32);
hi = 0;
}
// Constructs a Decimal from a float value.
//
public Decimal(float value)
{
DecCalc.VarDecFromR4(value, out AsMutable(ref this));
}
// Constructs a Decimal from a double value.
//
public Decimal(double value)
{
DecCalc.VarDecFromR8(value, out AsMutable(ref this));
}
//
// Decimal <==> Currency conversion.
//
// A Currency represents a positive or negative decimal value with 4 digits past the decimal point. The actual Int64 representation used by these methods
// is the currency value multiplied by 10,000. For example, a currency value of $12.99 would be represented by the Int64 value 129,900.
//
public static decimal FromOACurrency(long cy)
{
ulong absoluteCy; // has to be ulong to accommodate the case where cy == long.MinValue.
bool isNegative = false;
if (cy < 0)
{
isNegative = true;
absoluteCy = (ulong)(-cy);
}
else
{
absoluteCy = (ulong)cy;
}
// In most cases, FromOACurrency() produces a Decimal with Scale set to 4. Unless, that is, some of the trailing digits past the decimal point are zero,
// in which case, for compatibility with .Net, we reduce the Scale by the number of zeros. While the result is still numerically equivalent, the scale does
// affect the ToString() value. In particular, it prevents a converted currency value of $12.95 from printing uglily as "12.9500".
int scale = 4;
if (absoluteCy != 0) // For compatibility, a currency of 0 emits the Decimal "0.0000" (scale set to 4).
{
while (scale != 0 && ((absoluteCy % 10) == 0))
{
scale--;
absoluteCy /= 10;
}
}
return new decimal((int)absoluteCy, (int)(absoluteCy >> 32), 0, isNegative, (byte)scale);
}
public static long ToOACurrency(decimal value)
{
return DecCalc.VarCyFromDec(ref AsMutable(ref value));
}
private static bool IsValid(int flags) => (flags & ~(SignMask | ScaleMask)) == 0 && ((uint)(flags & ScaleMask) <= (28 << ScaleShift));
// Constructs a Decimal from an integer array containing a binary
// representation. The bits argument must be a non-null integer
// array with four elements. bits[0], bits[1], and
// bits[2] contain the low, middle, and high 32 bits of the 96-bit
// integer part of the Decimal. bits[3] contains the scale factor
// and sign of the Decimal: bits 0-15 (the lower word) are unused and must
// be zero; bits 16-23 must contain a value between 0 and 28, indicating
// the power of 10 to divide the 96-bit integer part by to produce the
// Decimal value; bits 24-30 are unused and must be zero; and finally bit
// 31 indicates the sign of the Decimal value, 0 meaning positive and 1
// meaning negative.
//
// Note that there are several possible binary representations for the
// same numeric value. For example, the value 1 can be represented as {1,
// 0, 0, 0} (integer value 1 with a scale factor of 0) and equally well as
// {1000, 0, 0, 0x30000} (integer value 1000 with a scale factor of 3).
// The possible binary representations of a particular value are all
// equally valid, and all are numerically equivalent.
//
public Decimal(int[] bits)
{
if (bits == null)
throw new ArgumentNullException(nameof(bits));
if (bits.Length == 4)
{
int f = bits[3];
if (IsValid(f))
{
lo = bits[0];
mid = bits[1];
hi = bits[2];
flags = f;
return;
}
}
throw new ArgumentException(SR.Arg_DecBitCtor);
}
// Constructs a Decimal from its constituent parts.
//
public Decimal(int lo, int mid, int hi, bool isNegative, byte scale)
{
if (scale > 28)
throw new ArgumentOutOfRangeException(nameof(scale), SR.ArgumentOutOfRange_DecimalScale);
this.lo = lo;
this.mid = mid;
this.hi = hi;
flags = ((int)scale) << 16;
if (isNegative)
flags |= SignMask;
}
void IDeserializationCallback.OnDeserialization(object? sender)
{
// OnDeserialization is called after each instance of this class is deserialized.
// This callback method performs decimal validation after being deserialized.
if (!IsValid(flags))
throw new SerializationException(SR.Overflow_Decimal);
}
// Constructs a Decimal from its constituent parts.
private Decimal(int lo, int mid, int hi, int flags)
{
if (IsValid(flags))
{
this.lo = lo;
this.mid = mid;
this.hi = hi;
this.flags = flags;
return;
}
throw new ArgumentException(SR.Arg_DecBitCtor);
}
private Decimal(in decimal d, int flags)
{
this = d;
this.flags = flags;
}
// Returns the absolute value of the given Decimal. If d is
// positive, the result is d. If d is negative, the result
// is -d.
//
internal static decimal Abs(in decimal d)
{
return new decimal(in d, d.flags & ~SignMask);
}
// Adds two Decimal values.
//
public static decimal Add(decimal d1, decimal d2)
{
DecCalc.DecAddSub(ref AsMutable(ref d1), ref AsMutable(ref d2), false);
return d1;
}
// Rounds a Decimal to an integer value. The Decimal argument is rounded
// towards positive infinity.
public static decimal Ceiling(decimal d)
{
int flags = d.flags;
if ((flags & ScaleMask) != 0)
DecCalc.InternalRound(ref AsMutable(ref d), (byte)(flags >> ScaleShift), MidpointRounding.ToPositiveInfinity);
return d;
}
// Compares two Decimal values, returning an integer that indicates their
// relationship.
//
public static int Compare(decimal d1, decimal d2)
{
return DecCalc.VarDecCmp(in d1, in d2);
}
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Decimal, this method throws an ArgumentException.
//
public int CompareTo(object? value)
{
if (value == null)
return 1;
if (!(value is decimal))
throw new ArgumentException(SR.Arg_MustBeDecimal);
decimal other = (decimal)value;
return DecCalc.VarDecCmp(in this, in other);
}
public int CompareTo(decimal value)
{
return DecCalc.VarDecCmp(in this, in value);
}
// Divides two Decimal values.
//
public static decimal Divide(decimal d1, decimal d2)
{
DecCalc.VarDecDiv(ref AsMutable(ref d1), ref AsMutable(ref d2));
return d1;
}
// Checks if this Decimal is equal to a given object. Returns true
// if the given object is a boxed Decimal and its value is equal to the
// value of this Decimal. Returns false otherwise.
//
public override bool Equals(object? value) =>
value is decimal other &&
DecCalc.VarDecCmp(in this, in other) == 0;
public bool Equals(decimal value) =>
DecCalc.VarDecCmp(in this, in value) == 0;
// Returns the hash code for this Decimal.
//
public override int GetHashCode() => DecCalc.GetHashCode(in this);
// Compares two Decimal values for equality. Returns true if the two
// Decimal values are equal, or false if they are not equal.
//
public static bool Equals(decimal d1, decimal d2)
{
return DecCalc.VarDecCmp(in d1, in d2) == 0;
}
// Rounds a Decimal to an integer value. The Decimal argument is rounded
// towards negative infinity.
//
public static decimal Floor(decimal d)
{
int flags = d.flags;
if ((flags & ScaleMask) != 0)
DecCalc.InternalRound(ref AsMutable(ref d), (byte)(flags >> ScaleShift), MidpointRounding.ToNegativeInfinity);
return d;
}
// Converts this Decimal to a string. The resulting string consists of an
// optional minus sign ("-") followed to a sequence of digits ("0" - "9"),
// optionally followed by a decimal point (".") and another sequence of
// digits.
//
public override string ToString()
{
return Number.FormatDecimal(this, null, NumberFormatInfo.CurrentInfo);
}
public string ToString(string? format)
{
return Number.FormatDecimal(this, format, NumberFormatInfo.CurrentInfo);
}
public string ToString(IFormatProvider? provider)
{
return Number.FormatDecimal(this, null, NumberFormatInfo.GetInstance(provider));
}
public string ToString(string? format, IFormatProvider? provider)
{
return Number.FormatDecimal(this, format, NumberFormatInfo.GetInstance(provider));
}
public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider? provider = null)
{
return Number.TryFormatDecimal(this, format, NumberFormatInfo.GetInstance(provider), destination, out charsWritten);
}
// Converts a string to a Decimal. The string must consist of an optional
// minus sign ("-") followed by a sequence of digits ("0" - "9"). The
// sequence of digits may optionally contain a single decimal point (".")
// character. Leading and trailing whitespace characters are allowed.
// Parse also allows a currency symbol, a trailing negative sign, and
// parentheses in the number.
//
public static decimal Parse(string s)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseDecimal(s, NumberStyles.Number, NumberFormatInfo.CurrentInfo);
}
public static decimal Parse(string s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseDecimal(s, style, NumberFormatInfo.CurrentInfo);
}
public static decimal Parse(string s, IFormatProvider? provider)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseDecimal(s, NumberStyles.Number, NumberFormatInfo.GetInstance(provider));
}
public static decimal Parse(string s, NumberStyles style, IFormatProvider? provider)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseDecimal(s, style, NumberFormatInfo.GetInstance(provider));
}
public static decimal Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Number, IFormatProvider? provider = null)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return Number.ParseDecimal(s, style, NumberFormatInfo.GetInstance(provider));
}
public static bool TryParse(string? s, out decimal result)
{
if (s == null)
{
result = 0;
return false;
}
return Number.TryParseDecimal(s, NumberStyles.Number, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK;
}
public static bool TryParse(ReadOnlySpan<char> s, out decimal result)
{
return Number.TryParseDecimal(s, NumberStyles.Number, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK;
}
public static bool TryParse(string? s, NumberStyles style, IFormatProvider? provider, out decimal result)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
if (s == null)
{
result = 0;
return false;
}
return Number.TryParseDecimal(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK;
}
public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider, out decimal result)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return Number.TryParseDecimal(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK;
}
// Returns a binary representation of a Decimal. The return value is an
// integer array with four elements. Elements 0, 1, and 2 contain the low,
// middle, and high 32 bits of the 96-bit integer part of the Decimal.
// Element 3 contains the scale factor and sign of the Decimal: bits 0-15
// (the lower word) are unused; bits 16-23 contain a value between 0 and
// 28, indicating the power of 10 to divide the 96-bit integer part by to
// produce the Decimal value; bits 24-30 are unused; and finally bit 31
// indicates the sign of the Decimal value, 0 meaning positive and 1
// meaning negative.
//
public static int[] GetBits(decimal d)
{
return new int[] { d.lo, d.mid, d.hi, d.flags };
}
internal static void GetBytes(in decimal d, byte[] buffer)
{
Debug.Assert(buffer != null && buffer.Length >= 16, "[GetBytes]buffer != null && buffer.Length >= 16");
buffer[0] = (byte)d.lo;
buffer[1] = (byte)(d.lo >> 8);
buffer[2] = (byte)(d.lo >> 16);
buffer[3] = (byte)(d.lo >> 24);
buffer[4] = (byte)d.mid;
buffer[5] = (byte)(d.mid >> 8);
buffer[6] = (byte)(d.mid >> 16);
buffer[7] = (byte)(d.mid >> 24);
buffer[8] = (byte)d.hi;
buffer[9] = (byte)(d.hi >> 8);
buffer[10] = (byte)(d.hi >> 16);
buffer[11] = (byte)(d.hi >> 24);
buffer[12] = (byte)d.flags;
buffer[13] = (byte)(d.flags >> 8);
buffer[14] = (byte)(d.flags >> 16);
buffer[15] = (byte)(d.flags >> 24);
}
internal static decimal ToDecimal(ReadOnlySpan<byte> span)
{
Debug.Assert(span.Length >= 16, "span.Length >= 16");
int lo = BinaryPrimitives.ReadInt32LittleEndian(span);
int mid = BinaryPrimitives.ReadInt32LittleEndian(span.Slice(4));
int hi = BinaryPrimitives.ReadInt32LittleEndian(span.Slice(8));
int flags = BinaryPrimitives.ReadInt32LittleEndian(span.Slice(12));
return new decimal(lo, mid, hi, flags);
}
// Returns the larger of two Decimal values.
//
internal static ref readonly decimal Max(in decimal d1, in decimal d2)
{
return ref DecCalc.VarDecCmp(in d1, in d2) >= 0 ? ref d1 : ref d2;
}
// Returns the smaller of two Decimal values.
//
internal static ref readonly decimal Min(in decimal d1, in decimal d2)
{
return ref DecCalc.VarDecCmp(in d1, in d2) < 0 ? ref d1 : ref d2;
}
public static decimal Remainder(decimal d1, decimal d2)
{
DecCalc.VarDecMod(ref AsMutable(ref d1), ref AsMutable(ref d2));
return d1;
}
// Multiplies two Decimal values.
//
public static decimal Multiply(decimal d1, decimal d2)
{
DecCalc.VarDecMul(ref AsMutable(ref d1), ref AsMutable(ref d2));
return d1;
}
// Returns the negated value of the given Decimal. If d is non-zero,
// the result is -d. If d is zero, the result is zero.
//
public static decimal Negate(decimal d)
{
return new decimal(in d, d.flags ^ SignMask);
}
// Rounds a Decimal value to a given number of decimal places. The value
// given by d is rounded to the number of decimal places given by
// decimals. The decimals argument must be an integer between
// 0 and 28 inclusive.
//
// By default a mid-point value is rounded to the nearest even number. If the mode is
// passed in, it can also round away from zero.
public static decimal Round(decimal d) => Round(ref d, 0, MidpointRounding.ToEven);
public static decimal Round(decimal d, int decimals) => Round(ref d, decimals, MidpointRounding.ToEven);
public static decimal Round(decimal d, MidpointRounding mode) => Round(ref d, 0, mode);
public static decimal Round(decimal d, int decimals, MidpointRounding mode) => Round(ref d, decimals, mode);
private static decimal Round(ref decimal d, int decimals, MidpointRounding mode)
{
if ((uint)decimals > 28)
throw new ArgumentOutOfRangeException(nameof(decimals), SR.ArgumentOutOfRange_DecimalRound);
if ((uint)mode > (uint)MidpointRounding.ToPositiveInfinity)
throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, nameof(MidpointRounding)), nameof(mode));
int scale = d.Scale - decimals;
if (scale > 0)
DecCalc.InternalRound(ref AsMutable(ref d), (uint)scale, mode);
return d;
}
internal static int Sign(in decimal d) => (d.lo | d.mid | d.hi) == 0 ? 0 : (d.flags >> 31) | 1;
// Subtracts two Decimal values.
//
public static decimal Subtract(decimal d1, decimal d2)
{
DecCalc.DecAddSub(ref AsMutable(ref d1), ref AsMutable(ref d2), true);
return d1;
}
// Converts a Decimal to an unsigned byte. The Decimal value is rounded
// towards zero to the nearest integer value, and the result of this
// operation is returned as a byte.
//
public static byte ToByte(decimal value)
{
uint temp;
try
{
temp = ToUInt32(value);
}
catch (OverflowException)
{
Number.ThrowOverflowException(TypeCode.Byte);
throw;
}
if (temp != (byte)temp) Number.ThrowOverflowException(TypeCode.Byte);
return (byte)temp;
}
// Converts a Decimal to a signed byte. The Decimal value is rounded
// towards zero to the nearest integer value, and the result of this
// operation is returned as a byte.
//
[CLSCompliant(false)]
public static sbyte ToSByte(decimal value)
{
int temp;
try
{
temp = ToInt32(value);
}
catch (OverflowException)
{
Number.ThrowOverflowException(TypeCode.SByte);
throw;
}
if (temp != (sbyte)temp) Number.ThrowOverflowException(TypeCode.SByte);
return (sbyte)temp;
}
// Converts a Decimal to a short. The Decimal value is
// rounded towards zero to the nearest integer value, and the result of
// this operation is returned as a short.
//
public static short ToInt16(decimal value)
{
int temp;
try
{
temp = ToInt32(value);
}
catch (OverflowException)
{
Number.ThrowOverflowException(TypeCode.Int16);
throw;
}
if (temp != (short)temp) Number.ThrowOverflowException(TypeCode.Int16);
return (short)temp;
}
// Converts a Decimal to a double. Since a double has fewer significant
// digits than a Decimal, this operation may produce round-off errors.
//
public static double ToDouble(decimal d)
{
return DecCalc.VarR8FromDec(in d);
}
// Converts a Decimal to an integer. The Decimal value is rounded towards
// zero to the nearest integer value, and the result of this operation is
// returned as an integer.
//
public static int ToInt32(decimal d)
{
Truncate(ref d);
if ((d.hi | d.mid) == 0)
{
int i = d.lo;
if (!d.IsNegative)
{
if (i >= 0) return i;
}
else
{
i = -i;
if (i <= 0) return i;
}
}
throw new OverflowException(SR.Overflow_Int32);
}
// Converts a Decimal to a long. The Decimal value is rounded towards zero
// to the nearest integer value, and the result of this operation is
// returned as a long.
//
public static long ToInt64(decimal d)
{
Truncate(ref d);
if (d.hi == 0)
{
long l = (long)d.Low64;
if (!d.IsNegative)
{
if (l >= 0) return l;
}
else
{
l = -l;
if (l <= 0) return l;
}
}
throw new OverflowException(SR.Overflow_Int64);
}
// Converts a Decimal to an ushort. The Decimal
// value is rounded towards zero to the nearest integer value, and the
// result of this operation is returned as an ushort.
//
[CLSCompliant(false)]
public static ushort ToUInt16(decimal value)
{
uint temp;
try
{
temp = ToUInt32(value);
}
catch (OverflowException)
{
Number.ThrowOverflowException(TypeCode.UInt16);
throw;
}
if (temp != (ushort)temp) Number.ThrowOverflowException(TypeCode.UInt16);
return (ushort)temp;
}
// Converts a Decimal to an unsigned integer. The Decimal
// value is rounded towards zero to the nearest integer value, and the
// result of this operation is returned as an unsigned integer.
//
[CLSCompliant(false)]
public static uint ToUInt32(decimal d)
{
Truncate(ref d);
if ((d.hi | d.mid) == 0)
{
uint i = d.Low;
if (!d.IsNegative || i == 0)
return i;
}
throw new OverflowException(SR.Overflow_UInt32);
}
// Converts a Decimal to an unsigned long. The Decimal
// value is rounded towards zero to the nearest integer value, and the
// result of this operation is returned as a long.
//
[CLSCompliant(false)]
public static ulong ToUInt64(decimal d)
{
Truncate(ref d);
if (d.hi == 0)
{
ulong l = d.Low64;
if (!d.IsNegative || l == 0)
return l;
}
throw new OverflowException(SR.Overflow_UInt64);
}
// Converts a Decimal to a float. Since a float has fewer significant
// digits than a Decimal, this operation may produce round-off errors.
//
public static float ToSingle(decimal d)
{
return DecCalc.VarR4FromDec(in d);
}
// Truncates a Decimal to an integer value. The Decimal argument is rounded
// towards zero to the nearest integer value, corresponding to removing all
// digits after the decimal point.
//
public static decimal Truncate(decimal d)
{
Truncate(ref d);
return d;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void Truncate(ref decimal d)
{
int flags = d.flags;
if ((flags & ScaleMask) != 0)
DecCalc.InternalRound(ref AsMutable(ref d), (byte)(flags >> ScaleShift), MidpointRounding.ToZero);
}
public static implicit operator decimal(byte value) => new decimal((uint)value);
[CLSCompliant(false)]
public static implicit operator decimal(sbyte value) => new decimal(value);
public static implicit operator decimal(short value) => new decimal(value);
[CLSCompliant(false)]
public static implicit operator decimal(ushort value) => new decimal((uint)value);
public static implicit operator decimal(char value) => new decimal((uint)value);
public static implicit operator decimal(int value) => new decimal(value);
[CLSCompliant(false)]
public static implicit operator decimal(uint value) => new decimal(value);
public static implicit operator decimal(long value) => new decimal(value);
[CLSCompliant(false)]
public static implicit operator decimal(ulong value) => new decimal(value);
public static explicit operator decimal(float value) => new decimal(value);
public static explicit operator decimal(double value) => new decimal(value);
public static explicit operator byte(decimal value) => ToByte(value);
[CLSCompliant(false)]
public static explicit operator sbyte(decimal value) => ToSByte(value);
public static explicit operator char(decimal value)
{
ushort temp;
try
{
temp = ToUInt16(value);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_Char, e);
}
return (char)temp;
}
public static explicit operator short(decimal value) => ToInt16(value);
[CLSCompliant(false)]
public static explicit operator ushort(decimal value) => ToUInt16(value);
public static explicit operator int(decimal value) => ToInt32(value);
[CLSCompliant(false)]
public static explicit operator uint(decimal value) => ToUInt32(value);
public static explicit operator long(decimal value) => ToInt64(value);
[CLSCompliant(false)]
public static explicit operator ulong(decimal value) => ToUInt64(value);
public static explicit operator float(decimal value) => ToSingle(value);
public static explicit operator double(decimal value) => ToDouble(value);
public static decimal operator +(decimal d) => d;
public static decimal operator -(decimal d) => new decimal(in d, d.flags ^ SignMask);
public static decimal operator ++(decimal d) => Add(d, One);
public static decimal operator --(decimal d) => Subtract(d, One);
public static decimal operator +(decimal d1, decimal d2)
{
DecCalc.DecAddSub(ref AsMutable(ref d1), ref AsMutable(ref d2), false);
return d1;
}
public static decimal operator -(decimal d1, decimal d2)
{
DecCalc.DecAddSub(ref AsMutable(ref d1), ref AsMutable(ref d2), true);
return d1;
}
public static decimal operator *(decimal d1, decimal d2)
{
DecCalc.VarDecMul(ref AsMutable(ref d1), ref AsMutable(ref d2));
return d1;
}
public static decimal operator /(decimal d1, decimal d2)
{
DecCalc.VarDecDiv(ref AsMutable(ref d1), ref AsMutable(ref d2));
return d1;
}
public static decimal operator %(decimal d1, decimal d2)
{
DecCalc.VarDecMod(ref AsMutable(ref d1), ref AsMutable(ref d2));
return d1;
}
public static bool operator ==(decimal d1, decimal d2) => DecCalc.VarDecCmp(in d1, in d2) == 0;
public static bool operator !=(decimal d1, decimal d2) => DecCalc.VarDecCmp(in d1, in d2) != 0;
public static bool operator <(decimal d1, decimal d2) => DecCalc.VarDecCmp(in d1, in d2) < 0;
public static bool operator <=(decimal d1, decimal d2) => DecCalc.VarDecCmp(in d1, in d2) <= 0;
public static bool operator >(decimal d1, decimal d2) => DecCalc.VarDecCmp(in d1, in d2) > 0;
public static bool operator >=(decimal d1, decimal d2) => DecCalc.VarDecCmp(in d1, in d2) >= 0;
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.Decimal;
}
bool IConvertible.ToBoolean(IFormatProvider? provider)
{
return Convert.ToBoolean(this);
}
char IConvertible.ToChar(IFormatProvider? provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Decimal", "Char"));
}
sbyte IConvertible.ToSByte(IFormatProvider? provider)
{
return Convert.ToSByte(this);
}
byte IConvertible.ToByte(IFormatProvider? provider)
{
return Convert.ToByte(this);
}
short IConvertible.ToInt16(IFormatProvider? provider)
{
return Convert.ToInt16(this);
}
ushort IConvertible.ToUInt16(IFormatProvider? provider)
{
return Convert.ToUInt16(this);
}
int IConvertible.ToInt32(IFormatProvider? provider)
{
return Convert.ToInt32(this);
}
uint IConvertible.ToUInt32(IFormatProvider? provider)
{
return Convert.ToUInt32(this);
}
long IConvertible.ToInt64(IFormatProvider? provider)
{
return Convert.ToInt64(this);
}
ulong IConvertible.ToUInt64(IFormatProvider? provider)
{
return Convert.ToUInt64(this);
}
float IConvertible.ToSingle(IFormatProvider? provider)
{
return Convert.ToSingle(this);
}
double IConvertible.ToDouble(IFormatProvider? provider)
{
return Convert.ToDouble(this);
}
decimal IConvertible.ToDecimal(IFormatProvider? provider)
{
return this;
}
DateTime IConvertible.ToDateTime(IFormatProvider? provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Decimal", "DateTime"));
}
object IConvertible.ToType(Type type, IFormatProvider? provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;
using System.Windows.Forms;
using System.IO;
namespace l2pvp
{
public partial class Client
{
public bool isAttacking = false;
public class htmcommand
{
public string s;
public DateTime t;
public uint currenttarget;
}
#region Threads
bool skill_use = false;
protected void useShotFunc()
{
if (useshot == null)
return;
ByteBuffer requse = new ByteBuffer(9);
requse.WriteByte(0x19);
requse.WriteUInt32(useshot.objid);
requse.WriteUInt32(0);
NewMessage(requse);
}
public void skillfunction()
{
ByteBuffer actionmsg = new ByteBuffer(18);
actionmsg.WriteByte(0x1f);
int actionindex = actionmsg.GetIndex();
ByteBuffer cancelpacket = new ByteBuffer(3);
cancelpacket.WriteByte(0x48);
cancelpacket.WriteInt16(1);
bool doskill;// = false;
while (true)
{
try
{
//isAttacking = false;
//Thread.Sleep(500);
if (gs.leader != null && gs.leader.targetid == 0)
Thread.Sleep(500);
while (startdance)
{
Thread.Sleep(100);
}
#region SelectTarget
if (gs.TargetterID != 0 && this == gs.leader && gs.allplayerinfo.ContainsKey(gs.TargetterID))
{
targetid = gs.allplayerinfo[gs.TargetterID].TargetID;
}
if (gs.battack == true)
{
CharInfo mytarget = gs.target;
if (mytarget != null && this == gs.leader)
{
if (targetid != mytarget.ID)
{
actionmsg.SetIndex(actionindex);
actionmsg.WriteUInt32(mytarget.ID);
actionmsg.WriteInt32(pinfo.X);
actionmsg.WriteInt32(pinfo.Y);
actionmsg.WriteInt32(pinfo.Z);
actionmsg.WriteByte(1);
NewMsgHP(actionmsg);
}
targetid = mytarget.ID;
if (mytarget.peace == 1 || ((mytarget.AbnormalEffects & gs.medusastate) != 0)
|| mytarget.isAlikeDead == 1)
{
//I am leader!
if (this == gs.leader)
{
if (gs.targetselection.ThreadState == ThreadState.WaitSleepJoin)
{
//NewMsgHP(cancelpacket);
// gs.targetselection.Interrupt();
}
continue;
}
else
{
isAttacking = false;
continue;
}
}
}
}
if (skillattack != true)
{
Thread.Sleep(1000);
continue;
}
#endregion
if ((gs.AssistLeader == true || gs.battack == true) && skillattack == true)
{
uint targ;
if (gs.leader != null)
targ = gs.leader.targetid;
else
continue;
if (targ != 0 && gs.enemylist.ContainsKey(targ))
{
//is an enemy
//ATTACK!
//if you are attacking you shouldn't be following
CharInfo mytarget2 = gs.enemylist[targ];
if (mytarget2.isAlikeDead == 1)
{
isAttacking = false;
NewMsgHP(cancelpacket);
continue;
}
isAttacking = true;
if (targetid != mytarget2.ID)
{
actionmsg.SetIndex(actionindex);
actionmsg.WriteUInt32(mytarget2.ID);
actionmsg.WriteInt32(pinfo.X);
actionmsg.WriteInt32(pinfo.Y);
actionmsg.WriteInt32(pinfo.Z);
actionmsg.WriteByte(1);
NewMsgHP(actionmsg);
}
lock (aslock)
{
foreach (AttackSkills a in askills)
{
if (mytarget2.peace == 1 || ((mytarget2.AbnormalEffects & gs.medusastate) != 0)
|| mytarget2.isAlikeDead == 1)
{
//I am leader!
//if (this == gs.leader)
//{
// if (gs.targetselection.ThreadState == ThreadState.WaitSleepJoin)
// gs.targetselection.Interrupt();
// break;
//}
//else
break;
}
doskill = false;
switch (a.condition)
{
case 0: //always
doskill = true;
break;
case 1: //HP
switch (a.comparison)
{
case 0: //==
if (mytarget2.Cur_HP == a.value)
doskill = true;
break;
case 1: //>
if (mytarget2.Cur_HP > a.value)
doskill = true;
break;
case 2: //<
if (mytarget2.Cur_HP < a.value)
doskill = true;
break;
}
break;
case 2: //distance
double distance =
System.Math.Sqrt(Math.Pow((pinfo.X - mytarget2.X), 2)
+ Math.Pow((pinfo.Y - mytarget2.Y), 2) + Math.Pow(pinfo.Z - mytarget2.Z, 2));
switch (a.comparison)
{
case 0: //==
if (distance == a.value)
doskill = true;
break;
case 1: //>
if (distance > a.value)
doskill = true;
break;
case 2: //<
if (distance < a.value)
doskill = true;
break;
}
break;
case 3://once
if (a.used == mytarget2.ID)
doskill = false;
else
doskill = true;
break;
}
if (doskill == true)
{
useShotFunc();
launchMagic(a.useskill, mytarget2.ID, Convert.ToInt32(shiftattack));
if (a.useskill.skillstate())
a.used = mytarget2.ID;
}
}
}
}
else if (targ != 0 && gs.moblist.ContainsKey(targ))
{
//attack the mob
NPC mob = gs.moblist[targ];
if (mob.isAlikeDead)
{
isAttacking = false;
NewMsgHP(cancelpacket);
continue;
}
isAttacking = true;
if (targetid != mob.objid)
{
actionmsg.SetIndex(actionindex);
actionmsg.WriteUInt32(mob.objid);
actionmsg.WriteInt32(pinfo.X);
actionmsg.WriteInt32(pinfo.Y);
actionmsg.WriteInt32(pinfo.Z);
actionmsg.WriteByte(1);
NewMsgHP(actionmsg);
}
lock (aslock)
{
foreach (AttackSkills a in askills)
{
if (mob.isAlikeDead == true)
{
//I am leader!
//if (this == gs.leader)
//{
// if (gs.targetselection.ThreadState == ThreadState.WaitSleepJoin)
// gs.targetselection.Interrupt();
// break;
//}
//else
isAttacking = false;
NewMsgHP(cancelpacket);
break;
}
doskill = false;
switch (a.condition)
{
case 0: //always
doskill = true;
break;
case 1: //HP
switch (a.comparison)
{
case 0: //==
if (mob.Cur_HP == a.value)
doskill = true;
break;
case 1: //>
if (mob.Cur_HP > a.value)
doskill = true;
break;
case 2: //<
if (mob.Cur_HP < a.value)
doskill = true;
break;
}
break;
case 2: //distance
double distance =
System.Math.Sqrt(Math.Pow((pinfo.X - mob.posX), 2)
+ Math.Pow((pinfo.Y - mob.posY), 2) + Math.Pow(pinfo.Z - mob.posZ, 2));
switch (a.comparison)
{
case 0: //==
if (distance == a.value)
doskill = true;
break;
case 1: //>
if (distance > a.value)
doskill = true;
break;
case 2: //<
if (distance < a.value)
doskill = true;
break;
}
break;
case 3://once
if (a.used == mob.objid)
doskill = false;
else
doskill = true;
break;
}
if (doskill == true)
{
skill_use = true;
useShotFunc();
launchMagic(a.useskill, mob.objid, Convert.ToInt32(shiftattack));
if (a.useskill.skillstate())
{
Console.WriteLine("Used skill {0}", a.useskill.name);
a.used = mob.objid;
}
else
{
Console.WriteLine("Couldn't use skill {0}", a.useskill.name);
}
skill_use = false;
}
}
}
}
else
{
isAttacking = false;
}
}
}
catch (ThreadAbortException e)
{
return;
}
catch
{
//Console.WriteLine("Thread interrupted");
}
}
}
ManualResetEvent attack_mre = new ManualResetEvent(false);
ManualResetEvent skill_mre = new ManualResetEvent(false);
public void attackfunction()
{
ByteBuffer actionmsg = new ByteBuffer(18);
actionmsg.WriteByte(0x1f);
int actionindex = actionmsg.GetIndex();
ByteBuffer cancelpacket = new ByteBuffer(3);
cancelpacket.WriteByte(0x48);
cancelpacket.WriteInt16(1);
ByteBuffer useskillmsg = new ByteBuffer(10);
useskillmsg.WriteByte(0x39);
int skillindex = useskillmsg.GetIndex();
useskillmsg.WriteUInt32(0);
useskillmsg.WriteUInt32(1);
int shiftindex = useskillmsg.GetIndex();
useskillmsg.WriteByte(0x00);
ByteBuffer validateposition = new ByteBuffer(21);
validateposition.WriteByte(0x59);
int valposindex = validateposition.GetIndex();
ByteBuffer data = new ByteBuffer(0x12);
data.WriteByte(0x01);
//data.WriteUInt32(target.ID);
int index = data.GetIndex();
useshot = null;
while (true)
{
// isAttacking = false;
try
{
while (skill_use)
Thread.Sleep(500);
Thread.Sleep(500);
if (gs.leader != null && gs.leader.targetid == 0)
Thread.Sleep(500);
while (startdance)
{
Thread.Sleep(100);
}
if (gs.TargetterID != 0 && this == gs.leader && gs.allplayerinfo.ContainsKey(gs.TargetterID))
{
targetid = gs.allplayerinfo[gs.TargetterID].TargetID;
}
if (gs.battack == true)
{
CharInfo mytarget = gs.target;
if (mytarget != null && this == gs.leader)
{
if (targetid != mytarget.ID)
{
actionmsg.SetIndex(actionindex);
actionmsg.WriteUInt32(mytarget.ID);
actionmsg.WriteInt32(pinfo.X);
actionmsg.WriteInt32(pinfo.Y);
actionmsg.WriteInt32(pinfo.Z);
actionmsg.WriteByte(1);
NewMessage(actionmsg);
}
targetid = mytarget.ID;
}
if (mytarget != null)
{
if (mytarget.peace == 1 || ((mytarget.AbnormalEffects & gs.medusastate) != 0)
|| mytarget.isAlikeDead == 1)
{
//I am leader!
if (this == gs.leader)
{
NewMessage(cancelpacket);
//if (gs.targetselection.ThreadState == ThreadState.WaitSleepJoin)
// gs.targetselection.Interrupt();
continue;
}
else
{
NewMessage(cancelpacket);
isAttacking = false;
continue;
}
}
}
}
if (battack != true)
{
Thread.Sleep(1000);
continue;
}
if (gs.leader != null && (gs.AssistLeader == true || gs.battack == true) && battack == true)
{
uint targ = gs.leader.targetid;
if (targ != 0 && gs.enemylist.ContainsKey(targ))
{
//is an enemy
//ATTACK!
//if you are attacking you shouldn't be following
CharInfo mytarget2 = gs.enemylist[targ];
if (mytarget2.isAlikeDead == 1)
{
NewMessage(cancelpacket);
isAttacking = false;
attacking = 0;
continue;
}
if (isAttacking && attacking == targ)
{
//auto attacking
attacking = 0;
Thread.Sleep(1000);
}
isAttacking = true;
if (targetid != pinfo.ObjID)
{
actionmsg.SetIndex(actionindex);
actionmsg.WriteUInt32(targ);
actionmsg.WriteInt32(pinfo.X);
actionmsg.WriteInt32(pinfo.Y);
actionmsg.WriteInt32(pinfo.Z);
actionmsg.WriteByte(1);
NewMessage(actionmsg);
}
data.SetIndex(index);
double distance = 0.0;
distance = System.Math.Sqrt(Math.Pow((pinfo.X - mytarget2.X), 2) + Math.Pow((pinfo.Y - mytarget2.Y), 2) + Math.Pow(pinfo.Z - mytarget2.Z, 2));
if (distance <= (adist + 25))
{
useShotFunc();
data.WriteUInt32(mytarget2.ID);
data.WriteInt32(pinfo.X);
data.WriteInt32(pinfo.Y);
data.WriteInt32(pinfo.Z);
if (shiftattack == true)
data.WriteByte(1);
else
data.WriteByte(0);
validateposition.SetIndex(valposindex);
validateposition.WriteInt32(pinfo.X);
validateposition.WriteInt32(pinfo.Y);
validateposition.WriteInt32(pinfo.Z);
validateposition.WriteInt32(pinfo.Heading);
validateposition.WriteInt32(0);
NewMessage(data);
attacking = targ;
}
}
else if (targ != 0 && gs.moblist.ContainsKey(targ))
{
//attack the mob
NPC mob = gs.moblist[targ];
if (mob.isAlikeDead)
{
NewMessage(cancelpacket);
isAttacking = false;
attacking = 0;
continue;
}
if(isAttacking && attacking == targ)
{
//auto attacking
attacking = 0;
Thread.Sleep(1000);
}
isAttacking = true;
if (targetid != mob.objid)
{
actionmsg.SetIndex(actionindex);
actionmsg.WriteUInt32(targ);
actionmsg.WriteInt32(pinfo.X);
actionmsg.WriteInt32(pinfo.Y);
actionmsg.WriteInt32(pinfo.Z);
actionmsg.WriteByte(1);
NewMessage(actionmsg);
}
data.SetIndex(index);
double distance = 0.0;
distance = System.Math.Sqrt(Math.Pow((pinfo.X - mob.posX), 2) + Math.Pow((pinfo.Y - mob.posY), 2) + Math.Pow(pinfo.Z - mob.posZ, 2));
if (distance <= (adist + 25))
{
useShotFunc();
data.WriteUInt32(targ);
data.WriteInt32(pinfo.X);
data.WriteInt32(pinfo.Y);
data.WriteInt32(pinfo.Z);
if (shiftattack == true)
data.WriteByte(1);
else
data.WriteByte(0);
NewMessage(data);
attacking = targ;
}
}
else
{
isAttacking = false;
}
}
else
{
isAttacking = false;
}
}
catch (ThreadAbortException e)
{
return;
}
catch
{
//Console.WriteLine("Exception but ignoring");
}
}
}
public void defendfunction()
{
ByteBuffer actionmsg = new ByteBuffer(18);
actionmsg.WriteByte(0x1f);
int actionindex = actionmsg.GetIndex();
ByteBuffer cancelpacket = new ByteBuffer(3);
cancelpacket.WriteByte(0x48);
cancelpacket.WriteInt16(1);
ByteBuffer useskillmsg = new ByteBuffer(10);
useskillmsg.WriteByte(0x39);
int skillindex = useskillmsg.GetIndex();
useskillmsg.WriteUInt32(0);
useskillmsg.WriteUInt32(1);
int shiftindex = useskillmsg.GetIndex();
useskillmsg.WriteByte(0x00);
ByteBuffer validateposition = new ByteBuffer(21);
validateposition.WriteByte(0x59);
int valposindex = validateposition.GetIndex();
bool doskill;// = false;
while (true)
{
Thread.Sleep(1000);
if (defense == false || gs.battack == false)
continue;
int count = gs.enemylist.Values.Count;
CharInfo[] attackers = new CharInfo[count + 10];
gs.enemylist.Values.CopyTo(attackers, 0);
foreach (CharInfo mytarget in attackers)
{
Thread.Sleep(100);
if (mytarget != null)
{
if (mytarget.peace == 1 || ((mytarget.AbnormalEffects & gs.medusastate) != 0)
|| mytarget.isAlikeDead == 1)
{
mytarget.peace = 0;
continue;
}
actionmsg.SetIndex(actionindex);
actionmsg.WriteUInt32(mytarget.ID);
actionmsg.WriteInt32(pinfo.X);
actionmsg.WriteInt32(pinfo.Y);
actionmsg.WriteInt32(pinfo.Z);
actionmsg.WriteByte(1);
NewMessage(actionmsg);
if (mytarget.peace == 1 || ((mytarget.AbnormalEffects & gs.medusastate) != 0)
|| mytarget.isAlikeDead == 1)
{
mytarget.peace = 0;
continue;
}
lock (dslock)
{
foreach (DefenseSkills a in dskills)
{
doskill = false;
switch (a.condition)
{
case 0: //always
doskill = true;
break;
case 1: //HP
switch (a.comparison)
{
case 0: //==
if (mytarget.Cur_HP == a.value)
doskill = true;
break;
case 1: //>
if (mytarget.Cur_HP > a.value)
doskill = true;
break;
case 2: //<
if (mytarget.Cur_HP < a.value)
doskill = true;
break;
}
break;
case 2: //distance
double distance =
System.Math.Sqrt(Math.Pow((pinfo.X - mytarget.X), 2)
+ Math.Pow((pinfo.Y - mytarget.Y), 2) + Math.Pow(pinfo.Z - mytarget.Z, 2));
switch (a.comparison)
{
case 0: //==
if (distance == a.value)
doskill = true;
break;
case 1: //>
if (distance > a.value)
doskill = true;
break;
case 2: //<
if (distance < a.value)
doskill = true;
break;
}
break;
}
if (doskill == true && (mytarget.AbnormalEffects & a.effect) == 0 && pinfo.Cur_MP >= a.MP)
{
useShotFunc();
actionmsg.SetIndex(actionindex);
actionmsg.WriteUInt32(mytarget.ID);
actionmsg.WriteInt32(pinfo.X);
actionmsg.WriteInt32(pinfo.Y);
actionmsg.WriteInt32(pinfo.Z);
actionmsg.WriteByte(1);
useskillmsg.SetIndex(shiftindex);
if (shiftattack)
useskillmsg.WriteByte(1);
else
useskillmsg.WriteByte(0);
useskillmsg.SetIndex(skillindex);
useskillmsg.WriteUInt32(a.useskill.id);
NewMessage(actionmsg);
NewMessage(useskillmsg);
validateposition.SetIndex(valposindex);
validateposition.WriteInt32(pinfo.X);
validateposition.WriteInt32(pinfo.Y);
validateposition.WriteInt32(pinfo.Z);
validateposition.WriteInt32(pinfo.Heading);
validateposition.WriteInt32(0);
NewMessage(validateposition);
}
Thread.Sleep(250);
}
}
}
}
}
}
public bool autofollow;
public bool autotalk;
public int followdistance;
public int talktime;
public Object commandlock;
public void movepawnthread()
{
int newx, newy;
int condition = x.Next(50);
List<htmcommand> discard = new List<htmcommand>();
while (true)
{
try
{
Thread.Sleep(500);
if (gs.leader == null || pinfo == null || gs.leader.pinfo == null)
continue;
while (gs.leader == this)
Thread.Sleep(10000);
if (autofollow && !isAttacking)
{
int fx = gs.leader.pinfo.X;
int fy = gs.leader.pinfo.Y;
int fz = gs.leader.pinfo.Z;
int ox = pinfo.X;
int oy = pinfo.Y;
int oz = pinfo.Z;
double distance = 0.0;
distance = System.Math.Sqrt(Math.Pow((pinfo.X - fx), 2) + Math.Pow((pinfo.Y - fy), 2) + Math.Pow(pinfo.Z - fz, 2));
int dx = pinfo.X - fx;
int dy = pinfo.Y - fy;
if (distance > (followdistance * 2) && distance < 2000)
{
double degree = convertHeadingToDegree(gs.leader.pinfo.Heading);
double perpendicular;
if (condition % 2 == 0)
{
perpendicular = degree - 90;
}
else
{
perpendicular = degree + 90;
}
int dxy = x.Next(0, followdistance);
newx = (int)(dxy * Math.Cos(perpendicular));
newy = (int)(dxy * Math.Sin(perpendicular));
newx += fx;
newy += fy;
ByteBuffer mpacket = new ByteBuffer(29);
mpacket.WriteByte(0x0f);
mpacket.WriteInt32(newx);
mpacket.WriteInt32(newy);
mpacket.WriteInt32(fz);
mpacket.WriteInt32(ox);
mpacket.WriteInt32(oy);
mpacket.WriteInt32(oz);
mpacket.WriteInt32(1);
this.NewMessage(mpacket);
//ByteBuffer movepacket = new ByteBuffer(29);
//movepacket.WriteByte(0x01);
//movepacket.WriteInt32(newx);
//movepacket.WriteInt32(newy);
//movepacket.WriteInt32(gs.leader.pinfo.Z);
//movepacket.WriteInt32(pinfo.X);
//movepacket.WriteInt32(pinfo.Y);
//movepacket.WriteInt32(pinfo.Z);
//movepacket.WriteInt32(1);
//this.NewMessage(movepacket);
//bwaiting = true;
}
//if (gs.current[1].pinfo != null && pinfo != null)
//{
// //if its null nothing we can do
// ByteBuffer autofollowpacket = new ByteBuffer(18);
// autofollowpacket.WriteByte(0x04);
// autofollowpacket.WriteUInt32(gs.current[1].pinfo.ObjID);
// autofollowpacket.WriteInt32(pinfo.X);
// autofollowpacket.WriteInt32(pinfo.Y);
// autofollowpacket.WriteInt32(pinfo.Z);
// autofollowpacket.WriteByte(0);
// this.NewMessage(autofollowpacket);
//}
}
if (autotalk && !isAttacking)
{
if (commandlist.Count > 0)
{
//command list has items
try
{
lock (commandlock)
{
foreach (htmcommand h in commandlist)
{
try
{
DateTime n = DateTime.Now;
double fudgefactor = x.NextDouble();
if (n >= h.t.AddSeconds(talktime + fudgefactor))
{
ByteBuffer action = new ByteBuffer();
action.WriteByte(0x1f);
action.WriteUInt32(h.currenttarget);
action.WriteInt32(pinfo.X);
action.WriteInt32(pinfo.Y);
action.WriteInt32(pinfo.Z);
action.WriteByte(0);
this.NewMessage(action);
this.NewMessage(action);
ByteBuffer htmlCommand = new ByteBuffer();
htmlCommand.WriteByte(0x23);
htmlCommand.WriteString(h.s);
this.NewMessage(htmlCommand);
discard.Add(h);
}
}
catch
{
}
}
try
{
foreach (htmcommand d in discard)
{
commandlist.Remove(d);
}
discard.Clear();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
catch
{
}
}
}
else
{
commandlist.Clear();
}
}
catch
{
Console.WriteLine("exiting move thread");
return;
}
}
}
private void useItem(uint itemID)
{
ByteBuffer requse = new ByteBuffer(9);
requse.WriteByte(0x19);
requse.WriteUInt32(itemID);
requse.WriteUInt32(0);
NewMessage(requse);
}
public void statusmonthread()
{
int sleeptime = 100;
int cpspamtime = 200;
DateTime cpelixirtime;
DateTime hpelixirtime;
DateTime qhptime;
DateTime gcptime;
DateTime cptime;
DateTime ghptime;
pinfo.qhptime = DateTime.Now.AddMinutes(-60);
pinfo.ghppottime = DateTime.Now.AddMinutes(-60);
pinfo.cppottime = DateTime.Now.AddMinutes(-60);
pinfo.smallcppottime = DateTime.Now.AddMinutes(-60);
pinfo.elixirCPtime = DateTime.Now.AddMinutes(-60);
pinfo.elixirHPtime = DateTime.Now.AddMinutes(-60);
while (true)
{
try
{
if (sleeptime < 0)
sleeptime = 10;
Thread.Sleep(sleeptime);
//Thread.Sleep(10);
sleeptime = 50;
if (pinfo == null)
continue;
if (gs.usebsoe && bsoeid != 0 && ((Convert.ToDouble(pinfo.Cur_CP * 100)) / Convert.ToDouble(pinfo.Max_CP)) < 50)
{
useItem(bsoeid);
bsoeid = 0;
}
if (pinfo.Cur_HP <= (pinfo.Max_HP - gs.qhphp))
{
if (pinfo.qhp > 0 && gs.qhp)
{
oldtime = pinfo.qhptime;
if (oldtime.AddMilliseconds(cpspamtime) <= DateTime.Now)
{
useItem(QHP);
pinfo.qhptime = DateTime.Now;
}
else
{
//not soon enough to use pot
sleeptime = (oldtime.AddMilliseconds(cpspamtime) - DateTime.Now).Milliseconds;
if (sleeptime > 100)
sleeptime = 100;
}
}
}
if (gs.bPercentRecover)
{
//recover to the given percentage by spamming both small and big CP together
if (pinfo.Cur_CP <= (gs.PercentRecover / 100.0) * pinfo.Max_CP)
{
if (pinfo.lesscppots > 0 && gs.cppots)
{
oldtime = pinfo.smallcppottime;
if (oldtime.AddMilliseconds(cpspamtime) <= DateTime.Now)
{
useItem(LCP);
pinfo.smallcppottime = DateTime.Now;
}
else
{
//not soon enough to use pot
sleeptime = (oldtime.AddMilliseconds(cpspamtime) - DateTime.Now).Milliseconds;
if (sleeptime > 100)
sleeptime = 100;
}
}
if (pinfo.cppots > 0 && gs.cppots)
{
oldtime = pinfo.cppottime;
if (oldtime.AddMilliseconds(cpspamtime) <= DateTime.Now)
{
useItem(GCP);
pinfo.cppottime = DateTime.Now;
}
else
{
//not soon enough to use pot
sleeptime = (oldtime.AddMilliseconds(cpspamtime) - DateTime.Now).Milliseconds;
if (sleeptime > 100)
sleeptime = 100;
}
}
}
}
if (!gs.bPercentRecover && pinfo.Cur_CP <= (pinfo.Max_CP - 50))
{
if (pinfo.lesscppots > 0 && gs.cppots)
{
oldtime = pinfo.smallcppottime;
if (oldtime.AddMilliseconds(cpspamtime) <= DateTime.Now)
{
useItem(LCP);
pinfo.smallcppottime = DateTime.Now;
}
else
{
//not soon enough to use pot
sleeptime = (oldtime.AddMilliseconds(cpspamtime) - DateTime.Now).Milliseconds;
if (sleeptime > 100)
sleeptime = 100;
}
}
}
if (!gs.bPercentRecover && pinfo.Cur_CP <= (pinfo.Max_CP - 200))
{
//use cp pot
if (pinfo.cppots > 0 && gs.cppots)
{
oldtime = pinfo.cppottime;
if (oldtime.AddMilliseconds(cpspamtime) <= DateTime.Now)
{
useItem(GCP);
pinfo.cppottime = DateTime.Now;
}
else
{
//not soon enough to use pot
sleeptime = (oldtime.AddMilliseconds(cpspamtime) - DateTime.Now).Milliseconds;
if (sleeptime > 100)
sleeptime = 100;
}
}
}
if (pinfo.Cur_HP <= (pinfo.Max_HP - gs.ghphp))
{
if (pinfo.ghppots > 0 && gs.ghppots)
{
oldtime = pinfo.ghppottime;
if (oldtime.AddSeconds(15) <= DateTime.Now)
{
useItem(GHP);
pinfo.ghppottime = DateTime.Now;
}
}
}
if (pinfo.Cur_CP <= (pinfo.Max_CP - gs.cpelixir))
{
if (pinfo.elixirCP_A > 0 && gs.elixir && pinfo.Level >= 61 && pinfo.Level < 76)
{
oldtime = pinfo.elixirCPtime;
if (oldtime.AddSeconds(301) <= DateTime.Now)
{
useItem(ECP_A);
pinfo.elixirCPtime = DateTime.Now;
}
}
if (pinfo.elixirCP_S > 0 && gs.elixir && pinfo.Level >= 76)
{
oldtime = pinfo.elixirCPtime;
if (oldtime.AddSeconds(301) <= DateTime.Now)
{
useItem(ECP_S);
pinfo.elixirCPtime = DateTime.Now;
}
}
}
if (pinfo.Cur_HP <= (pinfo.Max_HP - gs.hpelixir))
{
if (pinfo.elixirHP_A > 0 && gs.elixir && pinfo.Level >= 61 && pinfo.Level < 76)
{
oldtime = pinfo.elixirHPtime;
if (oldtime.AddSeconds(301) <= DateTime.Now)
{
useItem(EHP_A);
pinfo.elixirHPtime = DateTime.Now;
}
}
if (pinfo.elixirHP_S > 0 && gs.elixir && pinfo.Level >= 76)
{
oldtime = pinfo.elixirHPtime;
if (oldtime.AddSeconds(301) <= DateTime.Now)
{
useItem(EHP_S);
pinfo.elixirHPtime = DateTime.Now;
}
}
}
}
catch (ThreadAbortException e)
{
return;
}
catch (Exception e)
{
}
}
}
public void PeriodicFunction()
{
//return;
ByteBuffer requestaction = new ByteBuffer(10);
requestaction.WriteByte(0x56);
requestaction.WriteInt32(1007);
requestaction.WriteInt32(0);
requestaction.WriteByte(0);
while (true)
{
Thread.Sleep(60000);
if (pinfo != null && blessing == true)
this.NewMessage(requestaction);
}
}
public Queue<PlayerBuffs> rebuffqueue;
public object rebufflock;
public void singlebufffunction()
{
PlayerBuffs currentbuff = null;
ByteBuffer useskillmsg = new ByteBuffer(10);
useskillmsg.WriteByte(0x39);
int skillindex = useskillmsg.GetIndex();
useskillmsg.WriteUInt32(0);
useskillmsg.WriteUInt32(1);
int shiftindex = useskillmsg.GetIndex();
useskillmsg.WriteByte(0x00);
sbuff_mre.Reset();
while (true)
{
while (rebuffqueue.Count == 0)
sbuff_mre.WaitOne(1000, true);
sbuff_mre.Reset();
lock (rebufflock)
{
currentbuff = rebuffqueue.Dequeue();
if (currentbuff == null)
continue;
}
doBuff(useskillmsg, skillindex, currentbuff);
}
}
public void bufffunction()
{
ByteBuffer useskillmsg = new ByteBuffer(10);
useskillmsg.WriteByte(0x39);
int skillindex = useskillmsg.GetIndex();
useskillmsg.WriteUInt32(0);
useskillmsg.WriteUInt32(1);
int shiftindex = useskillmsg.GetIndex();
useskillmsg.WriteByte(0x00);
while (true)
{
//wait until this is signaled
try
{
buff_mre.WaitOne();
lock (bufflock)
{
foreach (PlayerBuffs p in bufflist)
{
doBuff(useskillmsg, skillindex, p);
}
}
buff_mre.Reset();
}
catch (ThreadAbortException e)
{
return;
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
}
}
}
private void doBuff(ByteBuffer useskillmsg, int skillindex, PlayerBuffs p)
{
if (p.objid == 0 && p.self != true)
{
//we haven't found the player yet
//search in allplayerinfo
CharInfo[] cinfos = new CharInfo[gs.allplayerinfo.Count];
gs.allplayerinfo.Values.CopyTo(cinfos, 0);
foreach (CharInfo cinfo in cinfos)
{
if (p.player == cinfo.Name)
{
p.objid = cinfo.ID;
}
}
}
if (p.objid != 0)
{
//target the guy
//execute the list of skills on him
ByteBuffer action = new ByteBuffer();
action.WriteByte(0x1f);
action.WriteUInt32(p.objid);
action.WriteInt32(pinfo.X);
action.WriteInt32(pinfo.Y);
action.WriteInt32(pinfo.Z);
action.WriteByte(0);
NewMessage(action);
p.lastuse = DateTime.Now;
foreach (skill s in p.bufflist.Values)
{
if (s.lastuse.AddMilliseconds(s.reuseDelay) > DateTime.Now)
{
ReSkill r = new ReSkill(s, p.objid);
lock (redolistlock)
{
redolist.Enqueue(r);
}
continue;
}
useskillmsg.SetIndex(skillindex);
useskillmsg.WriteUInt32(s.id);
NewMessage(useskillmsg);
s.mre.WaitOne(10000);
s.mre.Reset();
if (s.skillstate())
{
System.Threading.Thread.Sleep((int)s.hitTime);
}
else
{
ReSkill r = new ReSkill(s, p.objid);
lock (redolistlock)
{
redolist.Enqueue(r);
}
}
//wait for response
//s.lastuse = DateTime.Now;
}
}
else if (p.self)
{
p.lastuse = DateTime.Now;
foreach (skill s in p.bufflist.Values)
{
if (s.lastuse.AddMilliseconds(s.reuseDelay) > DateTime.Now)
{
ReSkill r = new ReSkill(s, p.objid);
lock (redolistlock)
{
redolist.Enqueue(r);
}
continue;
}
useskillmsg.SetIndex(skillindex);
useskillmsg.WriteUInt32(s.id);
NewMessage(useskillmsg);
s.mre.WaitOne(10000);
s.mre.Reset();
if (s.skillstate())
{
System.Threading.Thread.Sleep((int)s.hitTime);
}
else
{
ReSkill r = new ReSkill(s, p.objid);
lock (redolistlock)
{
redolist.Enqueue(r);
}
}
//wait for response
//s.lastuse = DateTime.Now;
}
}
}
private void launchBuff(skill s, uint objectid, int shift)
{
if (s.lastuse.AddMilliseconds(s.reuseDelay) > DateTime.Now)
{
ReSkill r = new ReSkill(s, objectid);
lock (redolistlock)
{
redolist.Enqueue(r);
}
return;
}
s.setstate(false);
s.mre.Reset();
useSkill(s.id, objectid, shift);
s.mre.WaitOne(2000);
s.mre.Reset();
if (s.skillstate())
{
//wait for response
s.lastuse = DateTime.Now;
System.Threading.Thread.Sleep((int)s.hitTime);
}
else
{
//System.Console.WriteLine("skill failed");
ReSkill r = new ReSkill(s, objectid);
lock (redolistlock)
{
redolist.Enqueue(r);
}
}
}
private void launchMagic(skill s, uint objectid, int shift)
{
if (s.lastuse.AddMilliseconds(s.reuseDelay) > DateTime.Now)
{
return;
}
s.setstate(false);
s.mre.Reset();
useSkill(s.id, objectid, shift);
s.mre.WaitOne(5000);
s.mre.Reset();
if (s.skillstate())
{
//wait for response
System.Threading.Thread.Sleep((int)s.hitTime);
}
else
{
//System.Console.WriteLine("skill failed");
}
}
private void useSkill(uint skillid,
uint objectid, int shift)
{
if (targetid != objectid && objectid != 0)
{
ByteBuffer action = new ByteBuffer();
action.WriteByte(0x1f);
action.WriteUInt32(objectid);
action.WriteInt32(pinfo.X);
action.WriteInt32(pinfo.Y);
action.WriteInt32(pinfo.Z);
action.WriteByte(1);
NewMessage(action);
}
ByteBuffer useskillmsg = new ByteBuffer(10);
useskillmsg.WriteByte(0x39);
useskillmsg.WriteUInt32(skillid);
useskillmsg.WriteUInt32(1);
int shiftindex = useskillmsg.GetIndex();
if (shift == 1)
useskillmsg.WriteByte(1);
else
useskillmsg.WriteByte(0);
NewMessage(useskillmsg);
ByteBuffer validateposition = new ByteBuffer(21);
validateposition.WriteByte(0x59);
validateposition.WriteInt32(pinfo.X);
validateposition.WriteInt32(pinfo.Y);
validateposition.WriteInt32(pinfo.Z);
validateposition.WriteInt32(pinfo.Heading);
validateposition.WriteInt32(0);
NewMessage(validateposition);
}
public void PartyMonitorFunction()
{
}
public void fightbufffunction()
{
ByteBuffer useskillmsg = new ByteBuffer(10);
useskillmsg.WriteByte(0x39);
int skillindex = useskillmsg.GetIndex();
useskillmsg.WriteUInt32(0);
useskillmsg.WriteUInt32(1);
int shiftindex = useskillmsg.GetIndex();
useskillmsg.WriteByte(0x00);
while (true)
{
//wait until this is signaled
try
{
fightbuff_mre.WaitOne();
foreach (PlayerBuffs p in fightbufflist)
{
doBuff(useskillmsg, skillindex, p);
}
fightbuff_mre.Reset();
}
catch (ThreadAbortException e)
{
return;
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
}
}
}
public ManualResetEvent item_mre;
public void itemfunction()
{
while (true)
{
item_mre.WaitOne();
item_mre.Reset();
foreach (ClientItems i in useItems)
{
useItem(i.inventory.ObjID);
}
}
}
System.Collections.Queue danceq;
System.Threading.ManualResetEvent dancemre;
bool startdance = false;
public void dancefunction()
{
danceq = new Queue();
dancemre = new ManualResetEvent(false);
evtSkill s;
while (true)
{
dancemre.WaitOne();
if (gs.buffs == false)
{
lock (dancelock)
{
danceq.Clear();
}
}
while (danceq.Count > 0)
{
startdance = true;
lock (dancelock)
{
if (danceq.Count == 0)
continue;
s = (evtSkill)danceq.Dequeue();
}
//System.Console.WriteLine("launching skill {0} - event {1}", s.act.name, s.evt.name);
s.succeed = false;
launchMagic(s.act, 0, 0);
//bool ret = s.mre.WaitOne(3000);
//s.mre.Reset();
if (s.succeed || s.act.skillstate())
{
////skill succeeded
//probably do nothing?
//Console.WriteLine("skill {0} succeeded", s.act.name);
s.act.setstate(false);
}
else
{
//skill failed .. requeue
// Console.WriteLine("skill {0} failed", s.act.name);
lock (dancelock)
{
ReSkill r = new ReSkill(s.act, 0);
redolist.Enqueue(r);
}
}
}
startdance = false;
dancemre.Reset();
}
}
Queue<ReSkill> redolist;
object redolistlock;
void timebufffunction()
{
ByteBuffer useskillmsg = new ByteBuffer(10);
useskillmsg.WriteByte(0x39);
int skillindex = useskillmsg.GetIndex();
useskillmsg.WriteUInt32(0);
useskillmsg.WriteUInt32(1);
int shiftindex = useskillmsg.GetIndex();
useskillmsg.WriteByte(0x00);
ReSkill redoskill = null;
while (true)
{
Thread.Sleep(1000);
lock (bufflock)
{
if (gs.buffs == false)
{
lock (redolistlock)
{
redolist.Clear();
}
continue;
}
foreach (PlayerBuffs p in bufflist)
{
if (p.lastuse.AddMinutes(p.bufftimer) <= DateTime.Now)
{
doBuff(useskillmsg, skillindex, p);
}
}
int count = redolist.Count;
for (int i = 0; i < count; i++)
{
lock (redolistlock)
{
redoskill = redolist.Dequeue();
}
launchBuff(redoskill.s, redoskill.objid, 0);
}
}
}
}
#endregion
}
class ReSkill
{
public uint objid;
public skill s;
public ReSkill(skill _s, uint _oid)
{
objid = _oid;
s = _s;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System.Text
{
using System;
using System.Text;
////using System.Runtime.Serialization;
////using System.Security.Permissions;
// A Decoder is used to decode a sequence of blocks of bytes into a
// sequence of blocks of characters. Following instantiation of a decoder,
// sequential blocks of bytes are converted into blocks of characters through
// calls to the GetChars method. The decoder maintains state between the
// conversions, allowing it to correctly decode byte sequences that span
// adjacent blocks.
//
// Instances of specific implementations of the Decoder abstract base
// class are typically obtained through calls to the GetDecoder method
// of Encoding objects.
//
[Serializable()]
internal class DecoderNLS : Decoder /*, ISerializable*/
{
// Remember our encoding
protected Encoding m_encoding;
[NonSerialized] protected bool m_mustFlush;
[NonSerialized] internal bool m_throwOnOverflow;
[NonSerialized] internal int m_bytesUsed;
#region Serialization
//// // Constructor called by serialization. called during deserialization.
//// internal DecoderNLS(SerializationInfo info, StreamingContext context)
//// {
//// throw new NotSupportedException(
//// String.Format(
//// System.Globalization.CultureInfo.CurrentCulture,
//// Environment.GetResourceString("NotSupported_TypeCannotDeserialized"), this.GetType()));
//// }
////
//// // ISerializable implementation. called during serialization.
//// [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.SerializationFormatter)]
//// void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
//// {
//// SerializeDecoder(info);
//// info.AddValue("encoding", this.m_encoding);
//// info.SetType(typeof(Encoding.DefaultDecoder));
//// }
#endregion Serialization
internal DecoderNLS( Encoding encoding )
{
this.m_encoding = encoding;
this.m_fallback = this.m_encoding.DecoderFallback;
this.Reset();
}
// This is used by our child deserializers
internal DecoderNLS( )
{
this.m_encoding = null;
this.Reset();
}
public override void Reset()
{
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
public override unsafe int GetCharCount(byte[] bytes, int index, int count)
{
return GetCharCount(bytes, index, count, false);
}
public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush)
{
// Validate Parameters
if (bytes == null)
{
#if EXCEPTION_STRINGS
throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array"));
#else
throw new ArgumentNullException();
#endif
}
if (index < 0 || count < 0)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
#else
throw new ArgumentOutOfRangeException();
#endif
}
if (bytes.Length - index < count)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
#else
throw new ArgumentOutOfRangeException();
#endif
}
// Avoid null fixed problem
if (bytes.Length == 0)
{
bytes = new byte[1];
}
// Just call pointer version
fixed (byte* pBytes = bytes)
{
return GetCharCount(pBytes + index, count, flush);
}
}
public unsafe override int GetCharCount(byte* bytes, int count, bool flush)
{
// Validate parameters
if (bytes == null)
{
#if EXCEPTION_STRINGS
throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array"));
#else
throw new ArgumentNullException();
#endif
}
if (count < 0)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
#else
throw new ArgumentOutOfRangeException();
#endif
}
// Remember the flush
this.m_mustFlush = flush;
this.m_throwOnOverflow = true;
// By default just call the encoding version, no flush by default
return m_encoding.GetCharCount(bytes, count, this);
}
public override unsafe int GetChars( byte[] bytes ,
int byteIndex ,
int byteCount ,
char[] chars ,
int charIndex )
{
return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false);
}
public override unsafe int GetChars( byte[] bytes ,
int byteIndex ,
int byteCount ,
char[] chars ,
int charIndex ,
bool flush )
{
// Validate Parameters
if (bytes == null || chars == null)
{
#if EXCEPTION_STRINGS
throw new ArgumentNullException(bytes == null ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array"));
#else
throw new ArgumentNullException();
#endif
}
if (byteIndex < 0 || byteCount < 0)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
#else
throw new ArgumentOutOfRangeException();
#endif
}
if ( bytes.Length - byteIndex < byteCount)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
#else
throw new ArgumentOutOfRangeException();
#endif
}
if (charIndex < 0 || charIndex > chars.Length)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException("charIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
#else
throw new ArgumentOutOfRangeException();
#endif
}
// Avoid empty input fixed problem
if (bytes.Length == 0)
{
bytes = new byte[1];
}
int charCount = chars.Length - charIndex;
if (chars.Length == 0)
{
chars = new char[1];
}
// Just call pointer version
fixed (byte* pBytes = bytes)
{
fixed (char* pChars = chars)
{
// Remember that charCount is # to decode, not size of array
return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush);
}
}
}
public unsafe override int GetChars( byte* bytes ,
int byteCount ,
char* chars ,
int charCount ,
bool flush )
{
// Validate parameters
if (chars == null || bytes == null)
{
#if EXCEPTION_STRINGS
throw new ArgumentNullException((chars == null ? "chars" : "bytes"), Environment.GetResourceString("ArgumentNull_Array"));
#else
throw new ArgumentNullException();
#endif
}
if (byteCount < 0 || charCount < 0)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException((byteCount<0 ? "byteCount" : "charCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
#else
throw new ArgumentOutOfRangeException();
#endif
}
// Remember our flush
m_mustFlush = flush;
m_throwOnOverflow = true;
// By default just call the encoding's version
return m_encoding.GetChars(bytes, byteCount, chars, charCount, this);
}
// This method is used when the output buffer might not be big enough.
// Just call the pointer version. (This gets chars)
public override unsafe void Convert( byte[] bytes ,
int byteIndex ,
int byteCount ,
char[] chars ,
int charIndex ,
int charCount ,
bool flush ,
out int bytesUsed ,
out int charsUsed ,
out bool completed )
{
// Validate parameters
if (bytes == null || chars == null)
{
#if EXCEPTION_STRINGS
throw new ArgumentNullException((bytes == null ? "bytes" : "chars"), Environment.GetResourceString("ArgumentNull_Array"));
#else
throw new ArgumentNullException();
#endif
}
if (byteIndex < 0 || byteCount < 0)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
#else
throw new ArgumentOutOfRangeException();
#endif
}
if (charIndex < 0 || charCount < 0)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
#else
throw new ArgumentOutOfRangeException();
#endif
}
if (bytes.Length - byteIndex < byteCount)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
#else
throw new ArgumentOutOfRangeException();
#endif
}
if (chars.Length - charIndex < charCount)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException("chars", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
#else
throw new ArgumentOutOfRangeException();
#endif
}
// Avoid empty input problem
if (bytes.Length == 0)
{
bytes = new byte[1];
}
if (chars.Length == 0)
{
chars = new char[1];
}
// Just call the pointer version (public overrides can't do this)
fixed (byte* pBytes = bytes)
{
fixed (char* pChars = chars)
{
Convert(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush, out bytesUsed, out charsUsed, out completed);
}
}
}
// This is the version that used pointers. We call the base encoding worker function
// after setting our appropriate internal variables. This is getting chars
public unsafe override void Convert( byte* bytes ,
int byteCount ,
char* chars ,
int charCount ,
bool flush ,
out int bytesUsed ,
out int charsUsed ,
out bool completed )
{
// Validate input parameters
if (chars == null || bytes == null)
{
#if EXCEPTION_STRINGS
throw new ArgumentNullException(chars == null ? "chars" : "bytes", Environment.GetResourceString("ArgumentNull_Array"));
#else
throw new ArgumentNullException();
#endif
}
if (byteCount < 0 || charCount < 0)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException((byteCount<0 ? "byteCount" : "charCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
#else
throw new ArgumentOutOfRangeException();
#endif
}
// We don't want to throw
this.m_mustFlush = flush;
this.m_throwOnOverflow = false;
this.m_bytesUsed = 0;
// Do conversion
charsUsed = this.m_encoding.GetChars(bytes, byteCount, chars, charCount, this);
bytesUsed = this.m_bytesUsed;
// Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed
completed = (bytesUsed == byteCount) && (!flush || !this.HasState) && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0);
// Our data thingys are now full, we can return
}
public bool MustFlush
{
get
{
return m_mustFlush;
}
}
// Anything left in our decoder?
internal virtual bool HasState
{
get
{
return false;
}
}
// Allow encoding to clear our must flush instead of throwing (in ThrowCharsOverflow)
internal void ClearMustFlush()
{
m_mustFlush = false;
}
}
}
| |
// ===========================================================
// Copyright (C) 2014-2015 Kendar.org
//
// 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 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.Concurrent;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Web.Routing;
using CoroutinesLib.Shared;
using CoroutinesLib.Shared.Enums;
using GenericHelpers;
using Http.Contexts;
using Http.Renderer.Razor.Helpers;
using Http.Renderer.Razor.Utils;
using Http.Shared.Contexts;
using Http.Shared.Controllers;
using Http.Shared.Optimizations;
using Http.Shared.Routing;
using HttpMvc.Controllers;
using NodeCs.Shared;
namespace Http.Renderer.Razor.Integration
{
public class RazorTemplateGenerator : IRazorTemplateGenerator
{
private readonly ConcurrentDictionary<string, RazorTemplateEntry> _templateItems =
new ConcurrentDictionary<string, RazorTemplateEntry>();
public void RegisterTemplate(string templateString, string templateName)
{
Type templateType = ModelTypeFromTemplate(ref templateString);
RegisterTemplate(templateName, templateString, templateType);
}
private Type ModelTypeFromTemplate(ref string templateString)
{
var splittedTemplate = templateString
.Split(new[] { '\r', '\f', '\n' }).ToList();
var modelIndex = -1;
for (int index = 0; index < splittedTemplate.Count; index++)
{
var item = splittedTemplate[index];
var trimmed = item.Trim();
if (trimmed.StartsWith("@model", StringComparison.InvariantCultureIgnoreCase))
{
modelIndex = index;
break;
}
}
if (modelIndex == -1) return null;
var modelString = splittedTemplate[modelIndex];
splittedTemplate.RemoveAt(modelIndex);
templateString = string.Join("\r\n", splittedTemplate);
modelString = modelString.Substring("@model ".Length);
return AssembliesManager.LoadType(modelString);
}
private void RegisterTemplate(string templateName, string templateString, Type modelType)
{
if (templateName == null)
throw new ArgumentNullException("templateName");
if (templateString == null)
throw new ArgumentNullException("templateString");
_templateItems[templateName] = new RazorTemplateEntry()
{
ModelType = modelType ?? typeof(object),
TemplateString = templateString,
TemplateName = "Rzr" + Guid.NewGuid().ToString("N"),
IsNoModel = modelType == null
};
}
public void CompileTemplates()
{
Compiler.Compile(_templateItems.Values);
}
private static readonly object _locker = new object();
private static MethodInfo _createMethod;
public IEnumerable<ICoroutineResult> GenerateOutput(object model, string templateName, IHttpContext context,
ModelStateDictionary modelStateDictionary, object viewBagPassed)
{
var viewBag = viewBagPassed as dynamic;
if (templateName == null)
throw new ArgumentNullException("templateName");
RazorTemplateEntry entry = null;
try
{
entry = _templateItems[templateName];
}
catch (KeyNotFoundException)
{
throw new ArgumentOutOfRangeException("No template has been registered under this model or name.");
}
var templateItem = _templateItems[templateName];
if (templateItem.TemplateType == null)
{
lock (_locker)
{
templateItem.TemplateType =
AssembliesManager.LoadType("Http.Renderer.Razor.Integration." + entry.TemplateName + "Template");
}
}
var type = templateItem.TemplateType;
var template = (RazorTemplateBase)Activator.CreateInstance(type);
InjectData(template, type, context, modelStateDictionary, viewBag);
template.ObjectModel = model;
template.Execute();
var layout = template.Layout;
if (!string.IsNullOrWhiteSpace(layout))
{
var sb = new StringBuilder();
foreach (var item in template.Buffer)
{
sb.Append(item.Value);
}
viewBag.ChildItem = sb.ToString();
foreach (var item in RenderLayout(layout, context, viewBag))
{
yield return item;
}
}
else
{
foreach (var item in template.Buffer)
{
var bytes = Encoding.UTF8.GetBytes(item.Value.ToString());
yield return CoroutineResult.YieldReturn(bytes);
}
}
}
static RazorTemplateGenerator()
{
Type type = Type.GetType("CoroutinesLib.RunnerFactory,CoroutinesLib");
if (!(type != (Type)null))
return;
_createMethod = type.GetMethod("Create", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
}
public IEnumerable<ICoroutineResult> RenderLayout(string name, IHttpContext mainContext, dynamic viewBag)
{
var http = ServiceLocator.Locator.Resolve<HttpModule>();
var context = new WrappedHttpContext(mainContext);
var newUrl = name.TrimStart('~');
((IHttpRequest)context.Request).SetUrl(new Uri(newUrl, UriKind.Relative));
((IHttpRequest)context.Request).SetQueryString(mainContext.Request.QueryString);
var internalCoroutine = http.SetupInternalRequestCoroutine(context, null, viewBag);
yield return CoroutineResult.RunCoroutine(internalCoroutine)
.WithTimeout(TimeSpan.FromMinutes(1))
.AndWait();
/*Exception problem = null;
Action<Exception> onError = (Action<Exception>)(ex => problem = ex);
((ICoroutinesManager)_createMethod.Invoke((object)null, new object[0])).StartCoroutine(internalCoroutine, onError);
ManualResetEventSlim waitSlim = new ManualResetEventSlim(false);
while (4L > (long)internalCoroutine.Status)
waitSlim.Wait(10);
while (!RunningStatusExtension.Is(internalCoroutine.Status, RunningStatus.NotRunning))
waitSlim.Wait(10);
if (problem != null)
throw new Exception("Error running subtask", problem);*/
//task.Wait();
var stream = context.Response.OutputStream as MemoryStream;
// ReSharper disable once PossibleNullReferenceException
//r result = Encoding.UTF8.GetString(stream.ToArray());
stream.Seek(0, SeekOrigin.Begin);
var bytes = stream.ToArray();
yield return CoroutineResult.Return(bytes);
//rn new BufferItem { Value = result };
}
private void InjectData(RazorTemplateBase template, Type type, IHttpContext context,
ModelStateDictionary modelStateDictionary, object viewBag)
{
string layout = null;
var routeHandler = ServiceLocator.Locator.Resolve<IRoutingHandler>();
var bundlesHandler = ServiceLocator.Locator.Resolve<IResourceBundles>(true);
var properties = type.GetProperties();
var model = properties.FirstOrDefault(p => p.Name == "Model");
var ga = type.GetGenericArguments();
if (ga.Length == 0)
{
ga = new[] { model != null ? model.PropertyType : typeof(object) };
}
foreach (var property in type.GetProperties())
{
if (!property.CanWrite) continue;
switch (property.Name)
{
case ("Styles"):
if (bundlesHandler != null)
{
property.SetValue(template, bundlesHandler.GetStyles());
}
break;
case ("Scripts"):
if (bundlesHandler != null)
{
property.SetValue(template, bundlesHandler.GetScripts());
}
break;
case ("Html"):
var urlHelper = typeof(HtmlHelper<>).MakeGenericType(ga);
//public HtmlHelper(IHttpContext context, ViewContext viewContext,
// object nodeCsTemplateBase, string localPath, dynamic viewBag,IRoutingHandler routingHandler)
property.SetValue(template, Activator.CreateInstance(urlHelper,
new object[]
{
context,new ViewContext(context,template,modelStateDictionary),
template,context==null?string.Empty:context.Request.Url.ToString(),new ExpandoObject(),routeHandler
}
));
break;
case ("Url"):
property.SetValue(template, new UrlHelper(context, routeHandler));
break;
case ("Context"):
property.SetValue(template, context);
break;
case ("ViewBag"):
property.SetValue(template, viewBag ?? new ExpandoObject());
break;
default:
var value = ServiceLocator.Locator.Resolve(property.PropertyType, true);
if (value != null)
{
property.SetValue(template, value);
}
break;
}
}
}
public IEnumerable<ICoroutineResult> GenerateOutputString(object model, string templateName, IHttpContext context, ModelStateDictionary modelStateDictionary, object viewBag)
{
foreach (var item in GenerateOutput(model, templateName, context, modelStateDictionary, viewBag))
{
yield return item;
}
}
}
}
| |
// 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 1.2.2.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Cdn
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Operations operations.
/// </summary>
internal partial class Operations : IServiceOperations<CdnManagementClient>, IOperations
{
/// <summary>
/// Initializes a new instance of the Operations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal Operations(CdnManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the CdnManagementClient
/// </summary>
public CdnManagementClient Client { get; private set; }
/// <summary>
/// Lists all of the available CDN REST API operations.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Operation>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Cdn/operations").ToString();
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", 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 (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Operation>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Operation>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists all of the available CDN REST API operations.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Operation>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", 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 (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Operation>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Operation>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ActiveXHost.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description:
// An ActiveXHost is a System.Windows.FrameworkElement which can
// host a windowed ActiveX control. This class provides a technology
// bridge between ActiveX controls and Avalon by wrapping ActiveX controls
// and exposing them as fully featured avalon elements. It implements both the
// container interfaces (via aggregation) required to host the ActiveXControl
// and also derives from HwndHost to support hosting an HWND in the avalon tree.
//
// Currently the activex hosting support is limited to windowed controls.
//
// Inheritors of this class simply need to concentrate on defining and implementing the
// properties/methods/events of the specific ActiveX control they are wrapping, the
// default properties etc and the code to implement the activation etc. are
// encapsulated in the class below.
//
// The classid of the ActiveX control is specified in the constructor.
//
//
// History
// 04/17/05 KusumaV Created
//
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Threading;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Markup;
using MS.Internal;
using MS.Internal.Controls;
using MS.Internal.Utility;
using MS.Win32;
using System.Security;
// Since we disable PreSharp warnings in this file, PreSharp warning is unknown to C# compiler.
// We first need to disable warnings about unknown message numbers and unknown pragmas.
#pragma warning disable 1634, 1691
namespace System.Windows.Interop
{
#region ActiveXHost
/// <summary>
/// An ActiveXHost is a Systew.Windows.FrameworkElement which can
/// host an ActiveX control. Currently the support is limited to
/// windowed controls. This class provides a technology bridge
/// between unmanaged ActiveXControls and Avalon framework.
///
/// The only reason we expose this class public in ArrowHead without public OM
/// is for the WebBrowser control. The WebBrowser class derives from ActiveXHost, and
/// we are exposing the WebBrowser class in ArrowHead. This class does not have public
/// constructor and OM. It may be enabled in future releases.
/// </summary>
public class ActiveXHost : HwndHost
{
//------------------------------------------------------
//
// Constructors and Finalizers
//
//------------------------------------------------------
#region Constructors and Finalizers
static ActiveXHost()
{
// We use this map to lookup which invalidator method to call
// when the Avalon parent's properties change.
invalidatorMap[UIElement.VisibilityProperty] = new PropertyInvalidator(OnVisibilityInvalidated);
invalidatorMap[FrameworkElement.IsEnabledProperty] = new PropertyInvalidator(OnIsEnabledInvalidated);
// register for access keys
EventManager.RegisterClassHandler(typeof(ActiveXHost), AccessKeyManager.AccessKeyPressedEvent, new AccessKeyPressedEventHandler(OnAccessKeyPressed));
Control.IsTabStopProperty.OverrideMetadata(typeof(ActiveXHost), new FrameworkPropertyMetadata(true));
FocusableProperty.OverrideMetadata(typeof(ActiveXHost), new FrameworkPropertyMetadata(true));
EventManager.RegisterClassHandler(typeof(ActiveXHost), Keyboard.GotKeyboardFocusEvent, new KeyboardFocusChangedEventHandler(OnGotFocus));
EventManager.RegisterClassHandler(typeof(ActiveXHost), Keyboard.LostKeyboardFocusEvent, new KeyboardFocusChangedEventHandler(OnLostFocus));
KeyboardNavigation.TabNavigationProperty.OverrideMetadata(typeof(ActiveXHost), new FrameworkPropertyMetadata(KeyboardNavigationMode.Once));
}
/// constructor for ActiveXHost
///<SecurityNote>
/// Critical - calls trusted HwndHost ctor.
/// Takes the clsid to instantiate as input.
/// NOT TAS. Individual controls ( like WebOC) can become TAS if they justify why.
///</SecurityNote>
[SecurityCritical]
internal ActiveXHost(Guid clsid, bool fTrusted ) : base( fTrusted )
{
// Thread.ApartmentState is [Obsolete]
#pragma warning disable 0618
//
if (Thread.CurrentThread.ApartmentState != ApartmentState.STA)
{
throw new ThreadStateException(SR.Get(SRID.AxRequiresApartmentThread, clsid.ToString()));
}
#pragma warning restore 0618
_clsid.Value = clsid;
// hookup so we are notified when loading is finished.
Initialized += new EventHandler(OnInitialized);
}
#endregion Constructors and Finalizers
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
#region Framework Related
/// <internalonly>
/// Overriden to push the values of invalidated properties down to our
/// ActiveX control.
/// </internalonly>
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
if (e.IsAValueChange || e.IsASubPropertyChange)
{
DependencyProperty dp = e.Property;
// We lookup the property in our invalidatorMap
// and call the appropriate method to push
// down the changed value to the hosted ActiveX control.
if (dp != null && invalidatorMap.ContainsKey(dp))
{
PropertyInvalidator invalidator = (PropertyInvalidator)invalidatorMap[dp];
invalidator(this);
}
}
}
/// <internalonly>
/// Overriden to create our window and parent it.
/// </internalonly>
///<SecurityNote>
/// Critical - calls methods on critical interface members
///</SecurityNote>
[SecurityCritical ]
protected override HandleRef BuildWindowCore(HandleRef hwndParent)
{
this.ParentHandle = hwndParent;
//BuildWindowCore should only be called if visible. Bug 1236445 tracks this.
TransitionUpTo(ActiveXHelper.ActiveXState.InPlaceActive);
//The above call should have set this interface
Invariant.Assert(_axOleInPlaceActiveObject != null, "InPlace activation of ActiveX control failed");
if (ControlHandle.Handle == IntPtr.Zero)
{
IntPtr inplaceWindow = IntPtr.Zero;
_axOleInPlaceActiveObject.GetWindow(out inplaceWindow);
AttachWindow(inplaceWindow);
}
return _axWindow;
}
/// <internalonly>
/// Overridden to plug the ActiveX control into Avalon's layout manager.
/// </internalonly>
/// <SecurityNote >
/// Critical - accesses ActiveXSite critical property
/// Not making TAS - you may be able to spoof content of web-pages if you could position any arbitrary
/// control over a WebOC.
/// </SecurityNote>
[ SecurityCritical ]
protected override void OnWindowPositionChanged(Rect bounds)
{
//Its okay to process this if we the control is not yet created
_boundRect = bounds;
//These are already transformed to client co-ordinate/device units for high dpi also
_bounds.left = (int) bounds.X;
_bounds.top = (int) bounds.Y;
_bounds.right = (int) (bounds.Width + bounds.X);
_bounds.bottom = (int) (bounds.Height + bounds.Y);
//SetExtent only sets height and width, can call it for perf if X, Y haven't changed
//We need to call SetObjectRects instead, which updates X, Y, width and height
//OnActiveXRectChange calls SetObjectRects
this.ActiveXSite.OnActiveXRectChange(_bounds);
}
/// <summary>
/// Derived classes override this method to destroy the
/// window being hosted.
/// </summary>
protected override void DestroyWindowCore(HandleRef hwnd)
{
}
/// <internalonly>
/// Overridden to plug the ActiveX control into Avalon's layout manager.
/// </internalonly>
protected override Size MeasureOverride(Size swConstraint)
{
base.MeasureOverride(swConstraint);
double newWidth, newHeight;
if (Double.IsPositiveInfinity(swConstraint.Width))
newWidth = 150;
else
newWidth = swConstraint.Width;
if (Double.IsPositiveInfinity(swConstraint.Height))
newHeight = 150;
else
newHeight = swConstraint.Height;
return new Size(newWidth, newHeight);
}
/// <internalOnly>
/// Forward the access key to our hosted ActiveX control
///</internalOnly>
protected override void OnAccessKey(AccessKeyEventArgs args)
{
Debug.Assert(args.Key.Length > 0, "got an empty access key");
//
}
#endregion Framework Related
#region ActiveX Related
protected override void Dispose(bool disposing)
{
try
{
if ((disposing) && (!_isDisposed))
{
TransitionDownTo(ActiveXHelper.ActiveXState.Passive);
_isDisposed = true;
}
}
finally
{
//This destroys the parent window, so call base after we have done our processing.
base.Dispose(disposing);
}
}
// The native ActiveX control QI's for interfaces on it's site to see if
// it needs to change it's behaviour. Since the AxSite class is generic,
// it only implements site interfaces that are generic to all sites. QI's
// for any more specific interfaces will fail. This is a problem if anyone
// wants to support any other interfaces on the site. In order to overcome
// this, one needs to extend AxSite and implement any additional interfaces
// needed.
//
// ActiveX wrapper controls that derive from this class should override the
// below method and return their own AxSite derived object.
//
// This method is protected by an InheritanceDemand (from HwndSource) and
// a LinkDemand because extending a site is strictly an advanced feature for
// which one needs UnmanagedCode permissions.
//
/// Returns an object that will be set as the site for the native ActiveX control.
/// Implementors of the site can derive from ActiveXSite class.
///<SecurityNote>
/// Critical - calls critical ctor.
///</SecurityNote>
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
[SecurityCritical]
internal virtual ActiveXSite CreateActiveXSite()
{
return new ActiveXSite(this);
}
[SecurityCritical]
internal virtual object CreateActiveXObject(Guid clsid)
{
return Activator.CreateInstance(Type.GetTypeFromCLSID(clsid));
}
/// This will be called when the native ActiveX control has just been created.
/// Inheritors of this class can override this method to cast the nativeActiveXObject
/// parameter to the appropriate interface. They can then cache this interface
/// value in a member variable. However, they must release this value when
/// DetachInterfaces is called (by setting the cached interface variable to null).
internal virtual void AttachInterfaces(object nativeActiveXObject)
{
}
/// See AttachInterfaces for a description of when to override DetachInterfaces.
internal virtual void DetachInterfaces()
{
}
/// This will be called when we are ready to start listening to events.
/// Inheritors can override this method to hook their own connection points.
internal virtual void CreateSink()
{
}
/// <summary>
/// This will be called when it is time to stop listening to events.
/// This is where inheritors have to disconnect their connection points.
/// </summary>
/// <SecurityNote>
/// Critical: Potentially unsafe. For example, disconnecting the event sink breaks the site-locking
/// feature of the WebBrowser control.
/// </SecurityNote>
[SecurityCritical]
internal virtual void DetachSink()
{
}
/// <summary>
/// Called whenever the ActiveX state changes. Subclasses can do additional hookup/cleanup depending
/// on the state transitions
/// </summary>
/// <param name="oldState"></param>
/// <param name="newState"></param>
internal virtual void OnActiveXStateChange(int oldState, int newState)
{
}
#endregion ActiveX Related
#endregion Protected Methods
//------------------------------------------------------
//
// Protected Properties
//
//------------------------------------------------------
#region Protected Properties
protected bool IsDisposed
{
get { return _isDisposed; }
}
#endregion Protected Properties
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
#region ActiveX Related
/// This method needs to be called by the user of ActiveXHost for each
/// hosted ActiveX control that has a mnemonic bound to it
internal void RegisterAccessKey(char key)
{
AccessKeyManager.Register(key.ToString(), this);
}
///<SecurityNote>
/// Critical - exposes critical _axSite member.
/// LinkDemand added, since without it, this property would make the LinkDemand on CreateActiveXSite meaningless.
///</SecurityNote>
internal ActiveXSite ActiveXSite
{
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
[SecurityCritical]
get
{
if (_axSite == null)
{
_axSite = CreateActiveXSite();
}
return _axSite;
}
}
///<SecurityNote>
/// Critical - exposes critical _axContainer member.
///</SecurityNote>
internal ActiveXContainer Container
{
[SecurityCritical]
get
{
if (_axContainer == null)
{
_axContainer = new ActiveXContainer(this);
}
return _axContainer;
}
}
internal ActiveXHelper.ActiveXState ActiveXState
{
get
{
return _axState;
}
set
{
_axState = value;
}
}
internal bool GetAxHostState(int mask)
{
return _axHostState[mask];
}
internal void SetAxHostState(int mask, bool value)
{
_axHostState[mask] = value;
}
internal void TransitionUpTo(ActiveXHelper.ActiveXState state)
{
if (!this.GetAxHostState(ActiveXHelper.inTransition))
{
this.SetAxHostState(ActiveXHelper.inTransition, true);
try
{
ActiveXHelper.ActiveXState oldState;
while (state > this.ActiveXState)
{
oldState = this.ActiveXState;
switch (this.ActiveXState)
{
case ActiveXHelper.ActiveXState.Passive:
TransitionFromPassiveToLoaded();
Debug.Assert(this.ActiveXState == ActiveXHelper.ActiveXState.Loaded, "Failed transition");
this.ActiveXState = ActiveXHelper.ActiveXState.Loaded;
break;
case ActiveXHelper.ActiveXState.Loaded:
TransitionFromLoadedToRunning();
Debug.Assert(this.ActiveXState == ActiveXHelper.ActiveXState.Running, "Failed transition");
this.ActiveXState = ActiveXHelper.ActiveXState.Running;
break;
case ActiveXHelper.ActiveXState.Running:
TransitionFromRunningToInPlaceActive();
Debug.Assert(this.ActiveXState == ActiveXHelper.ActiveXState.InPlaceActive, "Failed transition");
this.ActiveXState = ActiveXHelper.ActiveXState.InPlaceActive;
break;
case ActiveXHelper.ActiveXState.InPlaceActive:
TransitionFromInPlaceActiveToUIActive();
Debug.Assert(this.ActiveXState == ActiveXHelper.ActiveXState.UIActive, "Failed transition");
this.ActiveXState = ActiveXHelper.ActiveXState.UIActive;
break;
default:
Debug.Fail("bad state");
this.ActiveXState = this.ActiveXState + 1; // To exit the loop
break;
}
OnActiveXStateChange((int)oldState, (int)this.ActiveXState);
}
}
finally
{
this.SetAxHostState(ActiveXHelper.inTransition, false);
}
}
}
internal void TransitionDownTo(ActiveXHelper.ActiveXState state)
{
if (!this.GetAxHostState(ActiveXHelper.inTransition))
{
this.SetAxHostState(ActiveXHelper.inTransition, true);
try
{
ActiveXHelper.ActiveXState oldState;
while (state < this.ActiveXState)
{
oldState = this.ActiveXState;
switch (this.ActiveXState)
{
case ActiveXHelper.ActiveXState.Open:
Debug.Fail("how did we ever get into the open state?");
this.ActiveXState = ActiveXHelper.ActiveXState.UIActive;
break;
case ActiveXHelper.ActiveXState.UIActive:
TransitionFromUIActiveToInPlaceActive();
Debug.Assert(this.ActiveXState == ActiveXHelper.ActiveXState.InPlaceActive, "Failed transition");
this.ActiveXState = ActiveXHelper.ActiveXState.InPlaceActive;
break;
case ActiveXHelper.ActiveXState.InPlaceActive:
TransitionFromInPlaceActiveToRunning();
Debug.Assert(this.ActiveXState == ActiveXHelper.ActiveXState.Running, "Failed transition");
this.ActiveXState = ActiveXHelper.ActiveXState.Running;
break;
case ActiveXHelper.ActiveXState.Running:
TransitionFromRunningToLoaded();
Debug.Assert(this.ActiveXState == ActiveXHelper.ActiveXState.Loaded, "Failed transition");
this.ActiveXState = ActiveXHelper.ActiveXState.Loaded;
break;
case ActiveXHelper.ActiveXState.Loaded:
TransitionFromLoadedToPassive();
Debug.Assert(this.ActiveXState == ActiveXHelper.ActiveXState.Passive, "Failed transition");
this.ActiveXState = ActiveXHelper.ActiveXState.Passive;
break;
default:
Debug.Fail("bad state");
this.ActiveXState = this.ActiveXState - 1; // To exit the loop
break;
}
OnActiveXStateChange((int)oldState, (int)this.ActiveXState);
}
}
finally
{
this.SetAxHostState(ActiveXHelper.inTransition, false);
}
}
}
///<SecurityNote>
/// Critical - runs arbitrary code on critical _axOleObject member.
///</SecurityNote>
[SecurityCritical]
internal bool DoVerb(int verb)
{
int hr = _axOleObject.DoVerb(verb,
IntPtr.Zero,
this.ActiveXSite,
0,
this.ParentHandle.Handle,
_bounds);
Debug.Assert(hr == NativeMethods.S_OK, String.Format(CultureInfo.CurrentCulture, "DoVerb call failed for verb 0x{0:X}", verb));
return hr == NativeMethods.S_OK;
}
///<SecurityNote>
/// Critical - Calls setParent, accesses _axWindow.
///</SecurityNote>
[SecurityCritical]
internal void AttachWindow(IntPtr hwnd)
{
if (_axWindow.Handle == hwnd)
return;
//
_axWindow = new HandleRef(this, hwnd);
if (this.ParentHandle.Handle != IntPtr.Zero)
{
UnsafeNativeMethods.SetParent(_axWindow, this.ParentHandle);
}
}
///<SecurityNote>
/// Critical - calls ActiveXSite.StartEvents - critical code.
///</SecurityNote>
[ SecurityCritical ]
private void StartEvents()
{
if (!this.GetAxHostState(ActiveXHelper.sinkAttached))
{
this.SetAxHostState(ActiveXHelper.sinkAttached, true);
CreateSink();
}
this.ActiveXSite.StartEvents();
}
///<SecurityNote>
/// Critical - calls ActiveXSite.StopEvents - critical code.
/// NOT TAS: if you can stop listening to events - you could
/// potentially turn off a mitigation. On the WebOC this could
/// stop site-locking mitigation.
///</SecurityNote>
[ SecurityCritical ]
private void StopEvents()
{
if (this.GetAxHostState(ActiveXHelper.sinkAttached))
{
this.SetAxHostState(ActiveXHelper.sinkAttached, false);
DetachSink();
}
this.ActiveXSite.StopEvents();
}
///<SecurityNote>
/// Critical - Calls critical code (CreateActiveXObject) calls critical interface members, _axInstance
/// TreatAsSafe - although this method instantiates the control.
/// considered safe as the parameter that controls what to instantiate is critical for set.
/// and set only via the critical CTOR.
///</SecurityNote>
[SecurityCritical, SecurityTreatAsSafe ]
private void TransitionFromPassiveToLoaded()
{
Debug.Assert(this.ActiveXState == ActiveXHelper.ActiveXState.Passive, "Wrong start state to transition from");
if (this.ActiveXState == ActiveXHelper.ActiveXState.Passive)
{
//
// First, create the ActiveX control
Debug.Assert(_axInstance == null, "_axInstance must be null");
_axInstance = CreateActiveXObject(_clsid.Value);
Debug.Assert(_axInstance != null, "w/o an exception being thrown we must have an object...");
//
// We are now Loaded!
this.ActiveXState = ActiveXHelper.ActiveXState.Loaded;
//
// Lets give them a chance to cast the ActiveX object
// to the appropriate interfaces.
this.AttachInterfacesInternal();
}
}
///<SecurityNote>
/// Critical - accesses critical interface members, _axInstance
/// TreatAsSafe - state transitions considered safe.
/// Instantiating a control is considered critical.
/// However once instantiated, state transitions considered ok.
///</SecurityNote>
[SecurityCritical, SecurityTreatAsSafe ]
private void TransitionFromLoadedToPassive()
{
Debug.Assert(this.ActiveXState == ActiveXHelper.ActiveXState.Loaded, "Wrong start state to transition from");
if (this.ActiveXState == ActiveXHelper.ActiveXState.Loaded)
{
//
// Need to make sure that we don't handle any PropertyChanged
// notifications at this point.
//this.NoComponentChangeEvents++;
try
{
//
// Release the _axInstance
if (_axInstance != null)
{
//
// Lets first get the cached interface pointers of _axInstance released.
this.DetachInterfacesInternal();
Marshal.FinalReleaseComObject(_axInstance);
_axInstance = null;
}
}
finally
{
//
}
//
// We are now Passive!
this.ActiveXState = ActiveXHelper.ActiveXState.Passive;
}
}
///<SecurityNote>
/// Critical - calls critical code - SetClientSite.
/// TreatAsSafe - state transitions considered safe.
/// Instantiating a control is considered critical.
/// However once instantiated, state transitions considered ok.
///</SecurityNote>
[SecurityCritical, SecurityTreatAsSafe ]
private void TransitionFromLoadedToRunning()
{
Debug.Assert(this.ActiveXState == ActiveXHelper.ActiveXState.Loaded, "Wrong start state to transition from");
if (this.ActiveXState == ActiveXHelper.ActiveXState.Loaded)
{
//
// See if the ActiveX control returns OLEMISC_SETCLIENTSITEFIRST
int bits = 0;
int hr = _axOleObject.GetMiscStatus(NativeMethods.DVASPECT_CONTENT, out bits);
if (NativeMethods.Succeeded(hr) && ((bits & NativeMethods.OLEMISC_SETCLIENTSITEFIRST) != 0))
{
//
// Simply setting the site to the ActiveX control should activate it.
// And this will take us to the Running state.
_axOleObject.SetClientSite(this.ActiveXSite);
}
StartEvents();
//
// We are now Running!
this.ActiveXState = ActiveXHelper.ActiveXState.Running;
}
}
///<SecurityNote>
/// Critical - accesses critical code, _axOleOlebject, StopEvents
/// TreatAsSafe - state transitions considered safe.
/// Instantiating a control is considered critical.
/// However once instantiated, state transitions considered ok.
///</SecurityNote>
[SecurityCritical, SecurityTreatAsSafe ]
private void TransitionFromRunningToLoaded()
{
Debug.Assert(this.ActiveXState == ActiveXHelper.ActiveXState.Running, "Wrong start state to transition from");
if (this.ActiveXState == ActiveXHelper.ActiveXState.Running)
{
StopEvents();
//
// Inform the ActiveX control that it's been un-sited.
_axOleObject.SetClientSite(null);
//
// We are now Loaded!
this.ActiveXState = ActiveXHelper.ActiveXState.Loaded;
}
}
///<SecurityNote>
/// Critical - calls critical code - DoVerb.
/// TreatAsSafe - state transitions considered safe.
/// Instantiating a control is considered critical.
/// However once instantiated, state transitions considered ok.
///</SecurityNote>
[SecurityCritical, SecurityTreatAsSafe ]
private void TransitionFromRunningToInPlaceActive()
{
Debug.Assert(this.ActiveXState == ActiveXHelper.ActiveXState.Running, "Wrong start state to transition from");
if (this.ActiveXState == ActiveXHelper.ActiveXState.Running)
{
try
{
DoVerb(NativeMethods.OLEIVERB_INPLACEACTIVATE);
}
catch (Exception e)
{
if(CriticalExceptions.IsCriticalException(e))
{
throw;
}
else
{
throw new TargetInvocationException(SR.Get(SRID.AXNohWnd, GetType().Name), e);
}
}
//
// We are now InPlaceActive!
this.ActiveXState = ActiveXHelper.ActiveXState.InPlaceActive;
}
}
///<SecurityNote>
/// Critical - calls critical code - InPlaceDeactivate.
/// TreatAsSafe - state transitions considered safe.
/// Instantiating a control is considered critical.
/// However once instantiated, state transitions considered ok.
///</SecurityNote>
[SecurityCritical, SecurityTreatAsSafe ]
private void TransitionFromInPlaceActiveToRunning()
{
Debug.Assert(this.ActiveXState == ActiveXHelper.ActiveXState.InPlaceActive, "Wrong start state to transition from");
if (this.ActiveXState == ActiveXHelper.ActiveXState.InPlaceActive)
{
//
// InPlaceDeactivate.
_axOleInPlaceObject.InPlaceDeactivate();
//
// We are now Running!
this.ActiveXState = ActiveXHelper.ActiveXState.Running;
}
}
///<SecurityNote>
/// Critical - calls critical code - DoVerb.
/// TreatAsSafe - state transitions considered safe.
/// Instantiating a control is considered critical.
/// However once instantiated, state transitions considered ok.
///</SecurityNote>
[SecurityCritical, SecurityTreatAsSafe ]
private void TransitionFromInPlaceActiveToUIActive()
{
Debug.Assert(this.ActiveXState == ActiveXHelper.ActiveXState.InPlaceActive, "Wrong start state to transition from");
if (this.ActiveXState == ActiveXHelper.ActiveXState.InPlaceActive)
{
DoVerb(NativeMethods.OLEIVERB_UIACTIVATE);
//
// We are now UIActive!
this.ActiveXState = ActiveXHelper.ActiveXState.UIActive;
}
}
///<SecurityNote>
/// Critical - accesses critical interface members, _axOleInPlaceObject
/// TreatAsSafe - state transitions considered safe.
/// Instantiating a control is considered critical.
/// However once instantiated, state transitions considered ok.
///</SecurityNote>
[SecurityCritical, SecurityTreatAsSafe ]
private void TransitionFromUIActiveToInPlaceActive()
{
Debug.Assert(this.ActiveXState == ActiveXHelper.ActiveXState.UIActive, "Wrong start state to transition from");
if (this.ActiveXState == ActiveXHelper.ActiveXState.UIActive)
{
int hr = _axOleInPlaceObject.UIDeactivate();
Debug.Assert(NativeMethods.Succeeded(hr), "Failed in IOleInPlaceObject.UiDeactivate");
//
// We are now InPlaceActive!
this.ActiveXState = ActiveXHelper.ActiveXState.InPlaceActive;
}
}
#endregion ActiveX Related
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
#region Framework Related
/// <summary>
/// The DependencyProperty for the TabIndex property.
/// Flags: Can be used in style rules
/// Default Value: 1
/// </summary>
internal static readonly DependencyProperty TabIndexProperty
= Control.TabIndexProperty.AddOwner(typeof(ActiveXHost));
/// <summary>
/// TabIndex property change the order of Tab navigation between Controls.
/// Control with lower TabIndex will get focus before the Control with higher index
/// </summary>
internal int TabIndex
{
get { return (int) GetValue(TabIndexProperty); }
set { SetValue(TabIndexProperty, value); }
}
///<SecurityNote>
/// Critical - accesses _hwndParent critical member.
///</SecurityNote>
internal HandleRef ParentHandle
{
[ SecurityCritical ]
get { return _hwndParent; }
[ SecurityCritical ]
set { _hwndParent = value; }
}
// This returns a COMRECT.
internal NativeMethods.COMRECT Bounds
{
get { return _bounds; }
//How do we notify Avalon tree/layout that the control needs a new size?
set { _bounds = value; }
}
// This returns a Rect.
internal Rect BoundRect
{
get { return _boundRect; }
}
#endregion Framework Related
#region ActiveX Related
/// <summary>
/// Returns the hosted ActiveX control's handle
/// </summary>
///<SecurityNote>
/// Critical - returns critical _axWindow member
///</SecurityNote>
internal HandleRef ControlHandle
{
[ SecurityCritical ]
get { return _axWindow; }
}
///<summary>
///Returns the native webbrowser object that this control wraps. Needs FullTrust to access.
/// Internally we will access the private field directly for perf reasons, no security checks
///</summary>
///<SecurityNote>
/// Critical - returns critical Instance member.
///</SecurityNote>
internal object ActiveXInstance
{
[ SecurityCritical ]
get
{
return _axInstance;
}
}
///<SecurityNote>
/// Critical - returns critical Instance member.
///</SecurityNote>
internal UnsafeNativeMethods.IOleInPlaceObject ActiveXInPlaceObject
{
[ SecurityCritical ]
get
{
return _axOleInPlaceObject;
}
}
///<SecurityNote>
/// Critical - returns critical Instance member.
///</SecurityNote>
internal UnsafeNativeMethods.IOleInPlaceActiveObject ActiveXInPlaceActiveObject
{
[SecurityCritical]
get
{
return _axOleInPlaceActiveObject;
}
}
#endregion ActiveXRelated
#endregion Internal Properties
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
#region Framework Methods
private void OnInitialized(object sender, EventArgs e)
{
//
this.Initialized -= new EventHandler(this.OnInitialized);
//Cannot inplace activate yet, since BuildWindowCore is not called yet
//and we need that for getting the parent handle to pass on to the control.
}
private static void OnIsEnabledInvalidated(ActiveXHost axHost)
{
//
}
private static void OnVisibilityInvalidated(ActiveXHost axHost)
{
if (axHost != null)
{
switch (axHost.Visibility)
{
case Visibility.Visible:
//
break;
case Visibility.Collapsed:
//
break;
case Visibility.Hidden:
//
break;
}
}
}
/// This event handler forwards focus events to the hosted ActiveX control
private static void OnGotFocus(object sender, KeyboardFocusChangedEventArgs e)
{
ActiveXHost axhost = sender as ActiveXHost;
if (axhost != null)
{
Invariant.Assert(axhost.ActiveXState >= ActiveXHelper.ActiveXState.InPlaceActive, "Should at least be InPlaceActive when getting focus");
if (axhost.ActiveXState < ActiveXHelper.ActiveXState.UIActive)
{
axhost.TransitionUpTo(ActiveXHelper.ActiveXState.UIActive);
}
}
}
/// This event handler forwards focus events to the hosted WF controls
private static void OnLostFocus(object sender, KeyboardFocusChangedEventArgs e)
{
ActiveXHost axhost = sender as ActiveXHost;
if (axhost != null)
{
// If the focus goes from our control window to one of the child windows,
// we should not deactivate.
//
Invariant.Assert(axhost.ActiveXState >= ActiveXHelper.ActiveXState.UIActive, "Should at least be UIActive when losing focus");
bool uiDeactivate = !axhost.IsKeyboardFocusWithin;
if (uiDeactivate)
{
axhost.TransitionDownTo(ActiveXHelper.ActiveXState.InPlaceActive);
}
}
}
private static void OnAccessKeyPressed(object sender, AccessKeyPressedEventArgs args)
{
if (!args.Handled && args.Scope == null && args.Target == null)
{
args.Target = (UIElement)sender;
}
}
/*
private void GetMnemonicList(SWF.Control control, ArrayList mnemonicList) {
// Get the mnemonic for our control
//
char mnemonic = HostUtils.GetMnemonic(control.Text, true);
if (mnemonic != 0)
{
mnemonicList.Add(mnemonic);
}
// And recurse for our children, currently we only support one activex control
//
if (HostedControl != null) GetMnemonicList(HostedControl, mnemonicList);
}
*/
#endregion Framework Methods
#region ActiveX Related
///<SecurityNote>
/// Critical - accesses critical interface pointers.
///</SecurityNote>
[ SecurityCritical ]
private void AttachInterfacesInternal()
{
Debug.Assert(_axInstance != null, "The native control is null");
_axOleObject = (UnsafeNativeMethods.IOleObject)_axInstance;
_axOleInPlaceObject = (UnsafeNativeMethods.IOleInPlaceObject)_axInstance;
_axOleInPlaceActiveObject = (UnsafeNativeMethods.IOleInPlaceActiveObject)_axInstance;
//
// Lets give the inheriting classes a chance to cast
// the ActiveX object to the appropriate interfaces.
AttachInterfaces(_axInstance);
}
///<SecurityNote>
/// Critical - accesses critical interface members.
/// TreatAsSafe - clearing the interfaces is ok.
///</SecurityNote>
[ SecurityCritical, SecurityTreatAsSafe ]
private void DetachInterfacesInternal()
{
_axOleObject = null;
_axOleInPlaceObject = null;
_axOleInPlaceActiveObject = null;
//
// Lets give the inheriting classes a chance to release
// their cached interfaces of the ActiveX object.
DetachInterfaces();
}
///<SecurityNote>
/// Critical - calls calls critical interface members.
///</SecurityNote>
[ SecurityCritical ]
private NativeMethods.SIZE SetExtent(int width, int height)
{
NativeMethods.SIZE sz = new NativeMethods.SIZE();
sz.cx = width;
sz.cy = height;
bool resetExtents = false;
try
{
_axOleObject.SetExtent(NativeMethods.DVASPECT_CONTENT, sz);
}
catch (COMException)
{
resetExtents = true;
}
if (resetExtents)
{
_axOleObject.GetExtent(NativeMethods.DVASPECT_CONTENT, sz);
try
{
_axOleObject.SetExtent(NativeMethods.DVASPECT_CONTENT, sz);
}
catch (COMException e)
{
Debug.Fail(e.ToString());
}
}
return GetExtent();
}
///<SecurityNote>
/// Critical - accesses critical interface member _axOleObject
/// TreatAsSafe - getting the size of the control is considered ok.
///</SecurityNote>
[ SecurityCritical, SecurityTreatAsSafe ]
private NativeMethods.SIZE GetExtent()
{
NativeMethods.SIZE sz = new NativeMethods.SIZE();
_axOleObject.GetExtent(NativeMethods.DVASPECT_CONTENT, sz);
return sz;
}
#endregion ActiveX Related
#endregion Private Methods
//------------------------------------------------------
//
// Private Properties
//
//------------------------------------------------------
#region Private Properties
#endregion Private Properties
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
#region Framework Related
private static Hashtable invalidatorMap = new Hashtable();
private delegate void PropertyInvalidator(ActiveXHost axhost);
private NativeMethods.COMRECT _bounds = new NativeMethods.COMRECT(0, 0, 0, 0);
private Rect _boundRect = new Rect(0, 0, 0, 0);
private Size _cachedSize = Size.Empty;
///<SecurityNote>
/// Critical - _hwndParent considered critical.
///</SecurityNote>
[SecurityCritical ]
private HandleRef _hwndParent;
private bool _isDisposed;
#endregion Framework Related
#region ActiveX Related
///<SecurityNote>
/// Critical - _clsId controls what code to run and instantiate.
///</SecurityNote>
private SecurityCriticalDataForSet<Guid> _clsid;
///<SecurityNote>
/// Critical - hwnd of control
///</SecurityNote>
[ SecurityCritical ]
private HandleRef _axWindow;
private BitVector32 _axHostState = new BitVector32();
private ActiveXHelper.ActiveXState _axState = ActiveXHelper.ActiveXState.Passive;
///<SecurityNote>
/// Critical - ActiveXSite interfaces of control
///</SecurityNote>
[ SecurityCritical ]
private ActiveXSite _axSite;
///<SecurityNote>
/// Critical - ActiveXContainer of control
///</SecurityNote>
[ SecurityCritical ]
private ActiveXContainer _axContainer;
///<SecurityNote>
/// Critical - all methods on this Interface are critical
///</SecurityNote>
[SecurityCritical]
private object _axInstance;
// Pointers to the ActiveX object: Interface pointers are cached for perf.
///<SecurityNote>
/// Critical - all methods on this Interface are critical
///</SecurityNote>
[SecurityCritical]
private UnsafeNativeMethods.IOleObject _axOleObject;
///<SecurityNote>
/// Critical - all methods on this Interface are critical
///</SecurityNote>
[SecurityCritical]
private UnsafeNativeMethods.IOleInPlaceObject _axOleInPlaceObject;
///<SecurityNote>
/// Critical - all methods on this Interface are critical
///</SecurityNote>
[SecurityCritical]
private UnsafeNativeMethods.IOleInPlaceActiveObject _axOleInPlaceActiveObject;
#endregion ActiveX Related
#endregion Private Fields
}
#endregion ActiveXHost
}
| |
//
// 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 Microsoft.Azure.Commands.Compute.Automation.Models;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet
{
protected object CreateVirtualMachineScaleSetDeleteInstancesDynamicParameters()
{
dynamicParameters = new RuntimeDefinedParameterDictionary();
var pResourceGroupName = new RuntimeDefinedParameter();
pResourceGroupName.Name = "ResourceGroupName";
pResourceGroupName.ParameterType = typeof(string);
pResourceGroupName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 1,
Mandatory = true
});
pResourceGroupName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ResourceGroupName", pResourceGroupName);
var pVMScaleSetName = new RuntimeDefinedParameter();
pVMScaleSetName.Name = "VMScaleSetName";
pVMScaleSetName.ParameterType = typeof(string);
pVMScaleSetName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 2,
Mandatory = true
});
pVMScaleSetName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("VMScaleSetName", pVMScaleSetName);
var pInstanceIds = new RuntimeDefinedParameter();
pInstanceIds.Name = "InstanceId";
pInstanceIds.ParameterType = typeof(string[]);
pInstanceIds.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 3,
Mandatory = true
});
pInstanceIds.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("InstanceId", pInstanceIds);
var pArgumentList = new RuntimeDefinedParameter();
pArgumentList.Name = "ArgumentList";
pArgumentList.ParameterType = typeof(object[]);
pArgumentList.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByStaticParameters",
Position = 4,
Mandatory = true
});
pArgumentList.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ArgumentList", pArgumentList);
return dynamicParameters;
}
protected void ExecuteVirtualMachineScaleSetDeleteInstancesMethod(object[] invokeMethodInputParameters)
{
string resourceGroupName = (string)ParseParameter(invokeMethodInputParameters[0]);
string vmScaleSetName = (string)ParseParameter(invokeMethodInputParameters[1]);
System.Collections.Generic.IList<string> instanceIds = null;
if (invokeMethodInputParameters[2] != null)
{
var inputArray2 = Array.ConvertAll((object[]) ParseParameter(invokeMethodInputParameters[2]), e => e.ToString());
instanceIds = inputArray2.ToList();
}
if (!string.IsNullOrEmpty(resourceGroupName) && !string.IsNullOrEmpty(vmScaleSetName) && instanceIds != null)
{
VirtualMachineScaleSetsClient.DeleteInstances(resourceGroupName, vmScaleSetName, instanceIds);
}
else
{
VirtualMachineScaleSetsClient.Delete(resourceGroupName, vmScaleSetName);
}
}
}
public partial class NewAzureComputeArgumentListCmdlet : ComputeAutomationBaseCmdlet
{
protected PSArgument[] CreateVirtualMachineScaleSetDeleteInstancesParameters()
{
string resourceGroupName = string.Empty;
string vmScaleSetName = string.Empty;
var instanceIds = new string[0];
return ConvertFromObjectsToArguments(
new string[] { "ResourceGroupName", "VMScaleSetName", "InstanceIds" },
new object[] { resourceGroupName, vmScaleSetName, instanceIds });
}
}
[Cmdlet(VerbsCommon.Remove, "AzureRmVmss", DefaultParameterSetName = "InvokeByDynamicParameters", SupportsShouldProcess = true)]
public partial class RemoveAzureRmVmss : InvokeAzureComputeMethodCmdlet
{
public override string MethodName { get; set; }
protected override void ProcessRecord()
{
this.MethodName = "VirtualMachineScaleSetDeleteInstances";
if (ShouldProcess(this.dynamicParameters["ResourceGroupName"].Value.ToString(), VerbsCommon.Remove)
&& (this.dynamicParameters["Force"].IsSet ||
this.ShouldContinue(Properties.Resources.ResourceRemovalConfirmation,
"Remove-AzureRmVmss operation")))
{
base.ProcessRecord();
}
}
public override object GetDynamicParameters()
{
dynamicParameters = new RuntimeDefinedParameterDictionary();
var pResourceGroupName = new RuntimeDefinedParameter();
pResourceGroupName.Name = "ResourceGroupName";
pResourceGroupName.ParameterType = typeof(string);
pResourceGroupName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 1,
Mandatory = true,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = false
});
pResourceGroupName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ResourceGroupName", pResourceGroupName);
var pVMScaleSetName = new RuntimeDefinedParameter();
pVMScaleSetName.Name = "VMScaleSetName";
pVMScaleSetName.ParameterType = typeof(string);
pVMScaleSetName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 2,
Mandatory = true,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = false
});
pVMScaleSetName.Attributes.Add(new AliasAttribute("Name"));
pVMScaleSetName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("VMScaleSetName", pVMScaleSetName);
var pInstanceIds = new RuntimeDefinedParameter();
pInstanceIds.Name = "InstanceId";
pInstanceIds.ParameterType = typeof(string[]);
pInstanceIds.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 3,
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = false
});
pInstanceIds.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("InstanceId", pInstanceIds);
var pForce = new RuntimeDefinedParameter();
pForce.Name = "Force";
pForce.ParameterType = typeof(SwitchParameter);
pForce.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 4,
Mandatory = false
});
pForce.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("Force", pForce);
return dynamicParameters;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
using Xamarin.Forms;
using RestaurantGuide;
using System.IO;
using System.Xml.Serialization;
using Xamarin.Forms.Platform.iOS;
using CoreSpotlight;
namespace RestaurantGuide.iOS
{
[Register ("AppDelegate")]
public partial class AppDelegate : FormsApplicationDelegate
{
public static AppDelegate Current {get;set;}
public UIWindow window;
List<Restaurant> restaurants;
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
Current = this;
Forms.Init ();
window = new UIWindow (UIScreen.MainScreen.Bounds);
restaurants = LoadXml ();
App.SetContent (restaurants);
LoadApplication (new App ());
// for debugging Application.Properties
var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
Console.WriteLine (documents);
// then look in /.config/.isolated-storage/PropertyStore.forms
// Index content for CoreSpotlight search!
if (UIDevice.CurrentDevice.CheckSystemVersion (9, 0)) {
// Code that requires iOS 9, like CoreSpotlight or 3D Touch
SearchModel = new SpotlightHelper (restaurants);
} else {
// Code for earlier versions
Console.WriteLine ("CoreSpotlight not supported");
}
return base.FinishedLaunching(app, options);
}
List<Restaurant> LoadXml() {
var restaurants = new List<Restaurant> ();
#region load data from XML
using (TextReader reader = new StreamReader("restaurants.xml"))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Restaurant>));
restaurants = (List<Restaurant>)serializer.Deserialize(reader);
}
#endregion
return restaurants;
}
public override bool ContinueUserActivity (UIApplication application, NSUserActivity userActivity, UIApplicationRestorationHandler completionHandler)
{
if (userActivity.ActivityType == CSSearchableItem.ActionType) {
#region Spotlight
var uuid = userActivity.UserInfo.ObjectForKey (CSSearchableItem.ActivityIdentifier);
Xamarin.Insights.Track("SearchResult", new Dictionary<string, string> {
{"Type", "CoreSpotlight"}
});
System.Console.WriteLine ("Show the page for " + uuid);
var restaurantName = SearchModel.Lookup (uuid.ToString ());
System.Console.WriteLine ("which is " + restaurantName);
MessagingCenter.Send<RestaurantGuide.App, string>
(App.Current as RestaurantGuide.App, "show", restaurantName);
#endregion
} else {
#region NSUserActivity
// dang it, the userInfo is blank unless I hack the UserActivity_iOS.Start() method
// https://forums.developer.apple.com/thread/9690
if (userActivity.ActivityType == ActivityTypes.View)
{
Xamarin.Insights.Track("SearchResult", new Dictionary<string, string> {
{"Type", "NSUserActivity"}
});
var uid = "0";
if (userActivity.UserInfo.Count == 0) {
// new item
} else {
uid = userActivity.UserInfo.ObjectForKey (ActivityKeys.Id).ToString ();
if (uid == "0") {
Console.WriteLine ("No userinfo found for " + ActivityTypes.View);
} else {
Console.WriteLine ("Should display id " + uid);
// handled in DetailViewController.RestoreUserActivityState
}
}
ContinueNavigation (uid);
}
if (userActivity.ActivityType == CSSearchableItem.ActionType) {
Xamarin.Insights.Track("SearchResult", new Dictionary<string, string> {
{"Type", "CoreSpotlight"}
});
var uid = userActivity.UserInfo.ObjectForKey (CSSearchableItem.ActivityIdentifier).ToString();
System.Console.WriteLine ("Show the detail for id:" + uid);
ContinueNavigation (uid);
}
completionHandler(null); // TODO: display UI in Forms somehow
#endregion
}
return true;
}
#region Spotlight
public SpotlightHelper SearchModel {
get;
private set;
}
#endregion
#region Quick Action
public UIApplicationShortcutItem LaunchedShortcutItem { get; set; }
public override void OnActivated (UIApplication application)
{
Console.WriteLine ("ccccccc OnActivated");
// Handle any shortcut item being selected
HandleShortcutItem(LaunchedShortcutItem);
Xamarin.Insights.Track("3DTouch", new Dictionary<string, string> {
{"Type", "Random"}
});
// Clear shortcut after it's been handled
LaunchedShortcutItem = null;
}
// if app is already running
public override void PerformActionForShortcutItem (UIApplication application, UIApplicationShortcutItem shortcutItem, UIOperationHandler completionHandler)
{
Console.WriteLine ("dddddddd PerformActionForShortcutItem");
// Perform action
var handled = HandleShortcutItem(shortcutItem);
completionHandler(handled);
}
public bool HandleShortcutItem(UIApplicationShortcutItem shortcutItem) {
Console.WriteLine ("eeeeeeeeeee HandleShortcutItem ");
var handled = false;
// Anything to process?
if (shortcutItem == null) return false;
// Take action based on the shortcut type
switch (shortcutItem.Type) {
case RestaurantGuide.iOS.ShortcutHelper.ShortcutIdentifiers.Random:
Console.WriteLine ("QUICKACTION: Choose Random Restaurant");
//HACK: show the detail with a random restaurant showing
ContinueNavigation ("-1");
handled = true;
break;
}
Console.Write (handled);
// Return results
return handled;
}
#endregion
void ContinueNavigation (string uid){
Console.WriteLine ("gggggggggg ContinueNavigation");
// TODO: display UI in Forms somehow
System.Console.WriteLine ("Show the page for " + uid);
var restaurantName = "";
if (uid == "-1")
restaurantName = SearchModel.Random ();
else
restaurantName = SearchModel.Lookup (uid.ToString());
System.Console.WriteLine ("which is " + restaurantName);
MessagingCenter.Send<RestaurantGuide.App, string> (App.Current as RestaurantGuide.App, "show", restaurantName);
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gcov = Google.Cloud.OsConfig.V1;
using sys = System;
namespace Google.Cloud.OsConfig.V1
{
/// <summary>Resource name for the <c>PatchJob</c> resource.</summary>
public sealed partial class PatchJobName : gax::IResourceName, sys::IEquatable<PatchJobName>
{
/// <summary>The possible contents of <see cref="PatchJobName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/patchJobs/{patch_job}</c>.</summary>
ProjectPatchJob = 1,
}
private static gax::PathTemplate s_projectPatchJob = new gax::PathTemplate("projects/{project}/patchJobs/{patch_job}");
/// <summary>Creates a <see cref="PatchJobName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="PatchJobName"/> containing the provided <paramref name="unparsedResourceName"/>
/// .
/// </returns>
public static PatchJobName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new PatchJobName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="PatchJobName"/> with the pattern <c>projects/{project}/patchJobs/{patch_job}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="patchJobId">The <c>PatchJob</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="PatchJobName"/> constructed from the provided ids.</returns>
public static PatchJobName FromProjectPatchJob(string projectId, string patchJobId) =>
new PatchJobName(ResourceNameType.ProjectPatchJob, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), patchJobId: gax::GaxPreconditions.CheckNotNullOrEmpty(patchJobId, nameof(patchJobId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="PatchJobName"/> with pattern
/// <c>projects/{project}/patchJobs/{patch_job}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="patchJobId">The <c>PatchJob</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="PatchJobName"/> with pattern
/// <c>projects/{project}/patchJobs/{patch_job}</c>.
/// </returns>
public static string Format(string projectId, string patchJobId) => FormatProjectPatchJob(projectId, patchJobId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="PatchJobName"/> with pattern
/// <c>projects/{project}/patchJobs/{patch_job}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="patchJobId">The <c>PatchJob</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="PatchJobName"/> with pattern
/// <c>projects/{project}/patchJobs/{patch_job}</c>.
/// </returns>
public static string FormatProjectPatchJob(string projectId, string patchJobId) =>
s_projectPatchJob.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(patchJobId, nameof(patchJobId)));
/// <summary>Parses the given resource name string into a new <see cref="PatchJobName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/patchJobs/{patch_job}</c></description></item>
/// </list>
/// </remarks>
/// <param name="patchJobName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="PatchJobName"/> if successful.</returns>
public static PatchJobName Parse(string patchJobName) => Parse(patchJobName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="PatchJobName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/patchJobs/{patch_job}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="patchJobName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="PatchJobName"/> if successful.</returns>
public static PatchJobName Parse(string patchJobName, bool allowUnparsed) =>
TryParse(patchJobName, allowUnparsed, out PatchJobName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="PatchJobName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/patchJobs/{patch_job}</c></description></item>
/// </list>
/// </remarks>
/// <param name="patchJobName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="PatchJobName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string patchJobName, out PatchJobName result) => TryParse(patchJobName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="PatchJobName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/patchJobs/{patch_job}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="patchJobName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="PatchJobName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string patchJobName, bool allowUnparsed, out PatchJobName result)
{
gax::GaxPreconditions.CheckNotNull(patchJobName, nameof(patchJobName));
gax::TemplatedResourceName resourceName;
if (s_projectPatchJob.TryParseName(patchJobName, out resourceName))
{
result = FromProjectPatchJob(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(patchJobName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private PatchJobName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string patchJobId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
PatchJobId = patchJobId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="PatchJobName"/> class from the component parts of pattern
/// <c>projects/{project}/patchJobs/{patch_job}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="patchJobId">The <c>PatchJob</c> ID. Must not be <c>null</c> or empty.</param>
public PatchJobName(string projectId, string patchJobId) : this(ResourceNameType.ProjectPatchJob, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), patchJobId: gax::GaxPreconditions.CheckNotNullOrEmpty(patchJobId, nameof(patchJobId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>PatchJob</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string PatchJobId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectPatchJob: return s_projectPatchJob.Expand(ProjectId, PatchJobId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as PatchJobName);
/// <inheritdoc/>
public bool Equals(PatchJobName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(PatchJobName a, PatchJobName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(PatchJobName a, PatchJobName b) => !(a == b);
}
public partial class ExecutePatchJobRequest
{
/// <summary>
/// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::ProjectName ParentAsProjectName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetPatchJobRequest
{
/// <summary>
/// <see cref="gcov::PatchJobName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcov::PatchJobName PatchJobName
{
get => string.IsNullOrEmpty(Name) ? null : gcov::PatchJobName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListPatchJobInstanceDetailsRequest
{
/// <summary>
/// <see cref="PatchJobName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public PatchJobName ParentAsPatchJobName
{
get => string.IsNullOrEmpty(Parent) ? null : PatchJobName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class PatchJobInstanceDetails
{
/// <summary>
/// <see cref="gcov::InstanceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcov::InstanceName InstanceName
{
get => string.IsNullOrEmpty(Name) ? null : gcov::InstanceName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListPatchJobsRequest
{
/// <summary>
/// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::ProjectName ParentAsProjectName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class PatchJob
{
/// <summary>
/// <see cref="gcov::PatchJobName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcov::PatchJobName PatchJobName
{
get => string.IsNullOrEmpty(Name) ? null : gcov::PatchJobName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="PatchDeploymentName"/>-typed view over the <see cref="PatchDeployment"/> resource name property.
/// </summary>
public PatchDeploymentName PatchDeploymentAsPatchDeploymentName
{
get => string.IsNullOrEmpty(PatchDeployment) ? null : PatchDeploymentName.Parse(PatchDeployment, allowUnparsed: true);
set => PatchDeployment = value?.ToString() ?? "";
}
}
public partial class CancelPatchJobRequest
{
/// <summary>
/// <see cref="gcov::PatchJobName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcov::PatchJobName PatchJobName
{
get => string.IsNullOrEmpty(Name) ? null : gcov::PatchJobName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
#region license
// Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * 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 Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
//
// DO NOT EDIT THIS FILE!
//
// This file was generated automatically by astgen.boo.
//
namespace Boo.Lang.Compiler.Ast
{
using System.Collections;
using System.Runtime.Serialization;
[System.Serializable]
public partial class BinaryExpression : Expression
{
protected BinaryOperatorType _operator;
protected Expression _left;
protected Expression _right;
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public BinaryExpression CloneNode()
{
return (BinaryExpression)Clone();
}
/// <summary>
/// <see cref="Node.CleanClone"/>
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public BinaryExpression CleanClone()
{
return (BinaryExpression)base.CleanClone();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get { return NodeType.BinaryExpression; }
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.OnBinaryExpression(this);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Matches(Node node)
{
if (node == null) return false;
if (NodeType != node.NodeType) return false;
var other = ( BinaryExpression)node;
if (_operator != other._operator) return NoMatch("BinaryExpression._operator");
if (!Node.Matches(_left, other._left)) return NoMatch("BinaryExpression._left");
if (!Node.Matches(_right, other._right)) return NoMatch("BinaryExpression._right");
return true;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Replace(Node existing, Node newNode)
{
if (base.Replace(existing, newNode))
{
return true;
}
if (_left == existing)
{
this.Left = (Expression)newNode;
return true;
}
if (_right == existing)
{
this.Right = (Expression)newNode;
return true;
}
return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
BinaryExpression clone = (BinaryExpression)FormatterServices.GetUninitializedObject(typeof(BinaryExpression));
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
clone._entity = _entity;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
clone._expressionType = _expressionType;
clone._operator = _operator;
if (null != _left)
{
clone._left = _left.Clone() as Expression;
clone._left.InitializeParent(clone);
}
if (null != _right)
{
clone._right = _right.Clone() as Expression;
clone._right.InitializeParent(clone);
}
return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
_entity = null;
_expressionType = null;
if (null != _left)
{
_left.ClearTypeSystemBindings();
}
if (null != _right)
{
_right.ClearTypeSystemBindings();
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public BinaryOperatorType Operator
{
get { return _operator; }
set { _operator = value; }
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Expression Left
{
get { return _left; }
set
{
if (_left != value)
{
_left = value;
if (null != _left)
{
_left.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Expression Right
{
get { return _right; }
set
{
if (_right != value)
{
_right = value;
if (null != _right)
{
_right.InitializeParent(this);
}
}
}
}
}
}
| |
/*
* 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.Text;
using System.IO;
using System.Threading;
using System.Timers;
using OpenMetaverse;
using OpenMetaverse.Assets;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using Timer=System.Timers.Timer;
namespace pCampBot
{
public class PhysicsBot
{
public delegate void AnEvent(PhysicsBot callbot, EventType someevent); // event delegate for bot events
public IConfig startupConfig; // bot config, passed from BotManager
public string firstname;
public string lastname;
public string password;
public string loginURI;
public string saveDir;
public string wear;
public event AnEvent OnConnected;
public event AnEvent OnDisconnected;
protected Timer m_action; // Action Timer
protected List<uint> objectIDs = new List<uint>();
protected Random somthing = new Random(Environment.TickCount);// We do stuff randomly here
//New instance of a SecondLife client
public GridClient client = new GridClient();
protected string[] talkarray;
/// <summary>
///
/// </summary>
/// <param name="bsconfig">nini config for the bot</param>
public PhysicsBot(IConfig bsconfig)
{
startupConfig = bsconfig;
readconfig();
talkarray = readexcuses();
}
//We do our actions here. This is where one would
//add additional steps and/or things the bot should do
void m_action_Elapsed(object sender, ElapsedEventArgs e)
{
while (true)
{
int walkorrun = somthing.Next(4); // Randomize between walking and running. The greater this number,
// the greater the bot's chances to walk instead of run.
client.Self.Jump(false);
if (walkorrun == 0)
{
client.Self.Movement.AlwaysRun = true;
}
else
{
client.Self.Movement.AlwaysRun = false;
}
// TODO: unused: Vector3 pos = client.Self.SimPosition;
Vector3 newpos = new Vector3(somthing.Next(255), somthing.Next(255), somthing.Next(255));
client.Self.Movement.TurnToward(newpos);
client.Self.Movement.AtPos = true;
Thread.Sleep(somthing.Next(3000,13000));
client.Self.Movement.AtPos = false;
client.Self.Jump(true);
string randomf = talkarray[somthing.Next(talkarray.Length)];
if (talkarray.Length > 1 && randomf.Length > 1)
client.Self.Chat(randomf, 0, ChatType.Normal);
Thread.Sleep(somthing.Next(1000, 10000));
}
}
/// <summary>
/// Read the Nini config and initialize
/// </summary>
public void readconfig()
{
firstname = startupConfig.GetString("firstname", "random");
lastname = startupConfig.GetString("lastname", "random");
password = startupConfig.GetString("password", "12345");
loginURI = startupConfig.GetString("loginuri");
wear = startupConfig.GetString("wear","no");
}
/// <summary>
/// Tells LibSecondLife to logout and disconnect. Raises the disconnect events once it finishes.
/// </summary>
public void shutdown()
{
client.Network.Logout();
}
/// <summary>
/// This is the bot startup loop.
/// </summary>
public void startup()
{
client.Settings.LOGIN_SERVER = loginURI;
client.Settings.ALWAYS_DECODE_OBJECTS = false;
client.Settings.AVATAR_TRACKING = false;
client.Settings.OBJECT_TRACKING = false;
client.Settings.SEND_AGENT_THROTTLE = true;
client.Settings.SEND_PINGS = true;
client.Settings.STORE_LAND_PATCHES = false;
client.Settings.USE_ASSET_CACHE = false;
client.Settings.MULTIPLE_SIMS = true;
client.Throttle.Asset = 100000;
client.Throttle.Land = 100000;
client.Throttle.Task = 100000;
client.Throttle.Texture = 100000;
client.Throttle.Wind = 100000;
client.Throttle.Total = 400000;
client.Network.OnConnected += new NetworkManager.ConnectedCallback(this.Network_OnConnected);
client.Network.OnSimConnected += new NetworkManager.SimConnectedCallback(this.Network_OnConnected);
client.Network.OnDisconnected += new NetworkManager.DisconnectedCallback(this.Network_OnDisconnected);
client.Objects.ObjectUpdate += Objects_NewPrim;
//client.Assets.OnAssetReceived += Asset_ReceivedCallback;
if (client.Network.Login(firstname, lastname, password, "pCampBot", "Your name"))
{
if (OnConnected != null)
{
m_action = new Timer(somthing.Next(1000, 10000));
m_action.Enabled = true;
m_action.AutoReset = false;
m_action.Elapsed += new ElapsedEventHandler(m_action_Elapsed);
m_action.Start();
OnConnected(this, EventType.CONNECTED);
if (wear == "save")
{
client.Appearance.SetPreviousAppearance();
SaveDefaultAppearance();
}
else if (wear != "no")
{
MakeDefaultAppearance(wear);
}
client.Self.Jump(true);
}
}
else
{
MainConsole.Instance.Output(firstname + " " + lastname + " Can't login: " + client.Network.LoginMessage);
if (OnDisconnected != null)
{
OnDisconnected(this, EventType.DISCONNECTED);
}
}
}
public void SaveDefaultAppearance()
{
saveDir = "MyAppearance/" + firstname + "_" + lastname;
if (!Directory.Exists(saveDir))
{
Directory.CreateDirectory(saveDir);
}
Array wtypes = Enum.GetValues(typeof(WearableType));
foreach (WearableType wtype in wtypes)
{
UUID wearable = client.Appearance.GetWearableAsset(wtype);
if (wearable != UUID.Zero)
{
client.Assets.RequestAsset(wearable, AssetType.Clothing, false, Asset_ReceivedCallback);
client.Assets.RequestAsset(wearable, AssetType.Bodypart, false, Asset_ReceivedCallback);
}
}
}
public void SaveAsset(AssetWearable asset)
{
if (asset != null)
{
try
{
if (asset.Decode())
{
File.WriteAllBytes(Path.Combine(saveDir, String.Format("{1}.{0}",
asset.AssetType.ToString().ToLower(),
asset.WearableType)), asset.AssetData);
}
else
{
MainConsole.Instance.Output(String.Format("Failed to decode {0} asset {1}", asset.AssetType, asset.AssetID));
}
}
catch (Exception e)
{
MainConsole.Instance.Output(String.Format("Exception: {0}",e.ToString()));
}
}
}
public WearableType GetWearableType(string path)
{
string type = ((((path.Split('/'))[2]).Split('.'))[0]).Trim();
switch (type)
{
case "Eyes":
return WearableType.Eyes;
case "Hair":
return WearableType.Hair;
case "Pants":
return WearableType.Pants;
case "Shape":
return WearableType.Shape;
case "Shirt":
return WearableType.Shirt;
case "Skin":
return WearableType.Skin;
default:
return WearableType.Shape;
}
}
public void MakeDefaultAppearance(string wear)
{
try
{
if (wear == "yes")
{
//TODO: Implement random outfit picking
MainConsole.Instance.Output("Picks a random outfit. Not yet implemented.");
}
else if (wear != "save")
saveDir = "MyAppearance/" + wear;
saveDir = saveDir + "/";
string[] clothing = Directory.GetFiles(saveDir, "*.clothing", SearchOption.TopDirectoryOnly);
string[] bodyparts = Directory.GetFiles(saveDir, "*.bodypart", SearchOption.TopDirectoryOnly);
InventoryFolder clothfolder = FindClothingFolder();
UUID transid = UUID.Random();
List<InventoryBase> listwearables = new List<InventoryBase>();
for (int i = 0; i < clothing.Length; i++)
{
UUID assetID = UUID.Random();
AssetClothing asset = new AssetClothing(assetID, File.ReadAllBytes(clothing[i]));
asset.Decode();
asset.Owner = client.Self.AgentID;
asset.WearableType = GetWearableType(clothing[i]);
asset.Encode();
transid = client.Assets.RequestUpload(asset,true);
client.Inventory.RequestCreateItem(clothfolder.UUID, "MyClothing" + i.ToString(), "MyClothing", AssetType.Clothing,
transid, InventoryType.Wearable, asset.WearableType, PermissionMask.All, delegate(bool success, InventoryItem item)
{
if (success)
{
listwearables.Add(item);
}
else
MainConsole.Instance.Output(String.Format("Failed to create item {0}",item.Name));
}
);
}
for (int i = 0; i < bodyparts.Length; i++)
{
UUID assetID = UUID.Random();
AssetBodypart asset = new AssetBodypart(assetID, File.ReadAllBytes(bodyparts[i]));
asset.Decode();
asset.Owner = client.Self.AgentID;
asset.WearableType = GetWearableType(bodyparts[i]);
asset.Encode();
transid = client.Assets.RequestUpload(asset,true);
client.Inventory.RequestCreateItem(clothfolder.UUID, "MyBodyPart" + i.ToString(), "MyBodyPart", AssetType.Bodypart,
transid, InventoryType.Wearable, asset.WearableType, PermissionMask.All, delegate(bool success, InventoryItem item)
{
if (success)
{
listwearables.Add(item);
}
else
MainConsole.Instance.Output(String.Format("Failed to create item {0}",item.Name));
}
);
}
Thread.Sleep(1000);
if (listwearables == null || listwearables.Count == 0)
MainConsole.Instance.Output("Nothing to send on this folder!");
else
{
MainConsole.Instance.Output(String.Format("Sending {0} wearables...",listwearables.Count));
client.Appearance.WearOutfit(listwearables, false);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
public InventoryFolder FindClothingFolder()
{
UUID rootfolder = client.Inventory.Store.RootFolder.UUID;
List<InventoryBase> listfolders = client.Inventory.Store.GetContents(rootfolder);
InventoryFolder clothfolder = new InventoryFolder(UUID.Random());
foreach (InventoryBase folder in listfolders)
{
if (folder.Name == "Clothing")
{
clothfolder = (InventoryFolder)folder;
break;
}
}
return clothfolder;
}
public void Network_OnConnected(object sender)
{
if (OnConnected != null)
{
OnConnected(this, EventType.CONNECTED);
}
}
public void Simulator_Connected(object sender)
{
}
public void Network_OnDisconnected(NetworkManager.DisconnectType reason, string message)
{
if (OnDisconnected != null)
{
OnDisconnected(this, EventType.DISCONNECTED);
}
}
public void Objects_NewPrim(object sender, PrimEventArgs args)
{
Primitive prim = args.Prim;
if (prim != null)
{
if (prim.Textures != null)
{
if (prim.Textures.DefaultTexture.TextureID != UUID.Zero)
{
client.Assets.RequestImage(prim.Textures.DefaultTexture.TextureID, ImageType.Normal, Asset_TextureCallback_Texture);
}
for (int i = 0; i < prim.Textures.FaceTextures.Length; i++)
{
if (prim.Textures.FaceTextures[i] != null)
{
if (prim.Textures.FaceTextures[i].TextureID != UUID.Zero)
{
client.Assets.RequestImage(prim.Textures.FaceTextures[i].TextureID, ImageType.Normal, Asset_TextureCallback_Texture);
}
}
}
}
if (prim.Sculpt.SculptTexture != UUID.Zero)
{
client.Assets.RequestImage(prim.Sculpt.SculptTexture, ImageType.Normal, Asset_TextureCallback_Texture);
}
}
}
public void Asset_TextureCallback_Texture(TextureRequestState state, AssetTexture assetTexture)
{
//TODO: Implement texture saving and applying
}
public void Asset_ReceivedCallback(AssetDownload transfer,Asset asset)
{
if (wear == "save")
{
SaveAsset((AssetWearable) asset);
}
}
public string[] readexcuses()
{
string allexcuses = "";
string file = Path.Combine(Util.configDir(), "pCampBotSentences.txt");
if (File.Exists(file))
{
StreamReader csr = File.OpenText(file);
allexcuses = csr.ReadToEnd();
csr.Close();
}
return allexcuses.Split(Environment.NewLine.ToCharArray());
}
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers
{
/// <summary>
/// A table of known extensions, searchable by name or field number. When
/// parsing a protocol message that might have extensions, you must provide
/// an <see cref="ExtensionRegistry"/> in which you have registered any extensions
/// that you want to be able to parse. Otherwise, those extensions will just
/// be treated like unknown fields.
/// </summary>
/// <example>
/// For example, if you had the <c>.proto</c> file:
/// <code>
/// option java_class = "MyProto";
///
/// message Foo {
/// extensions 1000 to max;
/// }
///
/// extend Foo {
/// optional int32 bar;
/// }
/// </code>
///
/// Then you might write code like:
///
/// <code>
/// ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
/// registry.Add(MyProto.Bar);
/// MyProto.Foo message = MyProto.Foo.ParseFrom(input, registry);
/// </code>
/// </example>
///
/// <remarks>
/// <para>You might wonder why this is necessary. Two alternatives might come to
/// mind. First, you might imagine a system where generated extensions are
/// automatically registered when their containing classes are loaded. This
/// is a popular technique, but is bad design; among other things, it creates a
/// situation where behavior can change depending on what classes happen to be
/// loaded. It also introduces a security vulnerability, because an
/// unprivileged class could cause its code to be called unexpectedly from a
/// privileged class by registering itself as an extension of the right type.
/// </para>
/// <para>Another option you might consider is lazy parsing: do not parse an
/// extension until it is first requested, at which point the caller must
/// provide a type to use. This introduces a different set of problems. First,
/// it would require a mutex lock any time an extension was accessed, which
/// would be slow. Second, corrupt data would not be detected until first
/// access, at which point it would be much harder to deal with it. Third, it
/// could violate the expectation that message objects are immutable, since the
/// type provided could be any arbitrary message class. An unprivileged user
/// could take advantage of this to inject a mutable object into a message
/// belonging to privileged code and create mischief.</para>
/// </remarks>
public sealed partial class ExtensionRegistry
{
/// <summary>
/// Finds an extension by fully-qualified field name, in the
/// proto namespace, i.e. result.Descriptor.FullName will match
/// <paramref name="fullName"/> if a match is found. A null
/// reference is returned if the extension can't be found.
/// </summary>
[Obsolete("Please use the FindByName method instead.", true)]
public ExtensionInfo this[string fullName]
{
get
{
foreach (IGeneratedExtensionLite ext in extensionsByNumber.Values)
{
if (StringComparer.Ordinal.Equals(ext.Descriptor.FullName, fullName))
{
return ext as ExtensionInfo;
}
}
return null;
}
}
#if !LITE
/// <summary>
/// Finds an extension by containing type and field number.
/// A null reference is returned if the extension can't be found.
/// </summary>
public ExtensionInfo this[MessageDescriptor containingType, int fieldNumber]
{
get
{
IGeneratedExtensionLite ret;
extensionsByNumber.TryGetValue(new ExtensionIntPair(containingType, fieldNumber), out ret);
return ret as ExtensionInfo;
}
}
public ExtensionInfo FindByName(MessageDescriptor containingType, string fieldName)
{
return FindExtensionByName(containingType, fieldName) as ExtensionInfo;
}
#endif
/// <summary>
/// Add an extension from a generated file to the registry.
/// </summary>
public void Add<TExtension>(GeneratedExtensionBase<TExtension> extension)
{
if (extension.Descriptor.MappedType == MappedType.Message)
{
Add(new ExtensionInfo(extension.Descriptor, extension.MessageDefaultInstance));
}
else
{
Add(new ExtensionInfo(extension.Descriptor, null));
}
}
/// <summary>
/// Adds a non-message-type extension to the registry by descriptor.
/// </summary>
/// <param name="type"></param>
public void Add(FieldDescriptor type)
{
if (type.MappedType == MappedType.Message)
{
throw new ArgumentException("ExtensionRegistry.Add() must be provided a default instance "
+ "when adding an embedded message extension.");
}
Add(new ExtensionInfo(type, null));
}
/// <summary>
/// Adds a message-type-extension to the registry by descriptor.
/// </summary>
/// <param name="type"></param>
/// <param name="defaultInstance"></param>
public void Add(FieldDescriptor type, IMessage defaultInstance)
{
if (type.MappedType != MappedType.Message)
{
throw new ArgumentException("ExtensionRegistry.Add() provided a default instance for a "
+ "non-message extension.");
}
Add(new ExtensionInfo(type, defaultInstance));
}
private void Add(ExtensionInfo extension)
{
if (readOnly)
{
throw new InvalidOperationException("Cannot add entries to a read-only extension registry");
}
if (!extension.Descriptor.IsExtension)
{
throw new ArgumentException("ExtensionRegistry.add() was given a FieldDescriptor for a "
+ "regular (non-extension) field.");
}
IGeneratedExtensionLite liteExtension = extension;
Add(liteExtension);
FieldDescriptor field = extension.Descriptor;
if (field.ContainingType.Options.MessageSetWireFormat
&& field.FieldType == FieldType.Message
&& field.IsOptional
&& field.ExtensionScope == field.MessageType)
{
// This is an extension of a MessageSet type defined within the extension
// type's own scope. For backwards-compatibility, allow it to be looked
// up by type name.
Dictionary<string, IGeneratedExtensionLite> map;
if (extensionsByName.TryGetValue(liteExtension.ContainingType, out map))
{
map[field.MessageType.FullName] = extension;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace ContextOptimised.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
/*
* Created by Alexandre Rocha Lima e Marcondes
* User: Administrator
* Date: 12/08/2005
* Time: 16:13
*
* Description: An SQL Builder, Object Interface to Database Tables
* Its based on DataObjects from php PEAR
* 1. Builds SQL statements based on the objects vars and the builder methods.
* 2. acts as a datastore for a table row.
* The core class is designed to be extended for each of your tables so that you put the
* data logic inside the data classes.
* included is a Generator to make your configuration files and your base classes.
*
* CSharp DataObject
* Copyright (c) 2005, Alessandro de Oliveira Binhara
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* - Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &AS IS& AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Data;
using System.Configuration;
using System.Reflection;
using CsDO.Lib;
using System.Text;
using System.Data.Common;
namespace CsDO.Drivers
{
/// <summary>
/// Summary description for CsDO.
/// </summary>
public class Generic : IDataBase, IDisposable
{
DbConnection conn = null;
public DbConnection Connection { get { return getConnection(); } }
public Generic() {}
public DbCommand getCommand(String sql) {
DbCommand command = objectCommand();
if (command != null)
{
command.CommandText = sql;
conn = getConnection();
try
{
command.Connection = conn;
if (command.Connection != null &&
(command.Connection.State == ConnectionState.Broken
|| command.Connection.State == ConnectionState.Closed))
{
command.Connection.Open();
}
}
catch (DataException)
{
conn.Dispose();
}
}
else
command.Connection = getConnection();
return command;
}
public DbDataAdapter getDataAdapter(DbCommand command)
{
DbDataAdapter da = objectDataAdapter(command);
return da;
}
public DbCommand getSystemCommand(String sql) {
return this.getCommand(sql);
}
public DbConnection getConnection()
{
if (conn == null)
{
if (ConfigurationManager.AppSettings["connection"] != null)
{
return getConnection(ConfigurationManager.AppSettings["connection"].ToString());
}
}
return conn;
}
protected DbConnection getConnection(string URL) {
if (conn != null)
return conn;
Assembly assembly;
string prefix;
if (ConfigurationManager.AppSettings["dbNameSpace"] != null)
{
prefix = ConfigurationManager.AppSettings["dbNameSpace"].ToString();
}
else {
prefix = null;
}
assembly = Assembly.Load(ConfigurationManager.AppSettings["dbAssembly"].ToString());
Type[] tipos = assembly.GetTypes();
foreach (Type tipo in tipos) {
Type getInterface = tipo.GetInterface("IDbConnection");
if (getInterface != null) {
Assembly assCon = Assembly.Load(tipo.Assembly.GetName().FullName);
if (prefix != null && prefix != string.Empty) {
string[] namespaces = tipo.Namespace.Split('.');
if (namespaces[namespaces.Length - 1] == prefix) {
StringBuilder obj = new StringBuilder(tipo.Namespace);
obj.Append(".");
obj.Append(tipo.Name);
conn = (DbConnection)assCon.CreateInstance(obj.ToString());
break;
}
}
else {
StringBuilder obj = new StringBuilder(tipo.Namespace);
obj.Append(".");
obj.Append(tipo.Name);
conn = (DbConnection)assCon.CreateInstance(obj.ToString());
break;
}
}
}
if (URL != null)
{
conn.ConnectionString = URL;
}
return conn;
}
protected DbCommand objectCommand() {
Assembly assembly;
string prefix;
if (ConfigurationManager.AppSettings["dbNameSpace"] != null)
{
prefix = ConfigurationManager.AppSettings["dbNameSpace"].ToString();
}
else {
prefix = null;
}
assembly = Assembly.Load(ConfigurationManager.AppSettings["dbAssembly"].ToString());
Type[] tipos = assembly.GetTypes();
DbCommand comando = null;
foreach (Type tipo in tipos) {
Type getInterface = tipo.GetInterface("IDbCommand");
if (getInterface != null) {
Assembly assCon = Assembly.Load(tipo.Assembly.GetName());
if (prefix != null && prefix != string.Empty) {
string[] namespaces = tipo.Namespace.Split('.');
if (namespaces[namespaces.Length - 1] == prefix) {
StringBuilder obj = new StringBuilder(tipo.Namespace);
obj.Append(".");
obj.Append(tipo.Name);
return comando = (DbCommand) assCon.CreateInstance(obj.ToString());
}
}
else {
StringBuilder obj = new StringBuilder(tipo.Namespace);
obj.Append(".");
obj.Append(tipo.Name);
return comando = (DbCommand) assCon.CreateInstance(obj.ToString());
}
}
}
return comando;
}
protected DbDataAdapter objectDataAdapter() {
Assembly assembly;
string prefix;
if (ConfigurationManager.AppSettings["dbNameSpace"] != null)
{
prefix = ConfigurationManager.AppSettings["dbNameSpace"].ToString();
}
else {
prefix = null;
}
assembly = Assembly.Load(ConfigurationManager.AppSettings["dbAssembly"].ToString());
Type[] tipos = assembly.GetTypes();
DbDataAdapter dataAdapter = null;
foreach (Type tipo in tipos) {
Type getInterface = tipo.GetInterface("IDbDataAdapter");
if (getInterface != null) {
Assembly assCon = Assembly.Load(tipo.Assembly.GetName());
if (prefix != null && prefix != string.Empty) {
string[] namespaces = tipo.Namespace.Split('.');
if (namespaces[namespaces.Length - 1] == prefix) {
StringBuilder obj = new StringBuilder(tipo.Namespace);
obj.Append(".");
obj.Append(tipo.Name);
return dataAdapter = (DbDataAdapter) assCon.CreateInstance(obj.ToString());
}
}
else {
StringBuilder obj = new StringBuilder(tipo.Namespace);
obj.Append(".");
obj.Append(tipo.Name);
return dataAdapter = (DbDataAdapter) assCon.CreateInstance(obj.ToString());
}
}
}
return dataAdapter;
}
protected DbDataAdapter objectDataAdapter(DbCommand command)
{
Assembly assembly;
string prefix;
if (ConfigurationManager.AppSettings["dbNameSpace"] != null)
{
prefix = ConfigurationManager.AppSettings["dbNameSpace"].ToString();
}
else
{
prefix = null;
}
assembly = Assembly.Load(ConfigurationManager.AppSettings["dbAssembly"].ToString());
Type[] tipos = assembly.GetTypes();
DbDataAdapter dataAdapter = null;
foreach (Type tipo in tipos)
{
Type getInterface = tipo.GetInterface("IDbDataAdapter");
if (getInterface != null)
{
Assembly assCon = Assembly.Load(tipo.Assembly.GetName());
if (prefix != null && prefix != string.Empty)
{
string[] namespaces = tipo.Namespace.Split('.');
if (namespaces[namespaces.Length - 1] == prefix)
{
StringBuilder obj = new StringBuilder(tipo.Namespace);
obj.Append(".");
obj.Append(tipo.Name);
return dataAdapter = (DbDataAdapter)assCon.
CreateInstance(obj.ToString(), false, BindingFlags.InvokeMethod,
null, new object[] { command }, null, null);
}
}
else
{
StringBuilder obj = new StringBuilder(tipo.Namespace);
obj.Append(".");
obj.Append(tipo.Name);
return dataAdapter = (DbDataAdapter)assCon.
CreateInstance(obj.ToString(), false, BindingFlags.InvokeMethod,
null, new object[] { command }, null, null);
}
}
}
return dataAdapter;
}
protected DbParameter objectParameter()
{
Assembly assembly;
string prefix;
if (ConfigurationManager.AppSettings["dbNameSpace"] != null)
{
prefix = ConfigurationManager.AppSettings["dbNameSpace"].ToString();
}
else
{
prefix = null;
}
assembly = Assembly.Load(ConfigurationManager.AppSettings["dbAssembly"].ToString());
Type[] tipos = assembly.GetTypes();
DbParameter paramter = null;
foreach (Type tipo in tipos)
{
Type getInterface = tipo.GetInterface("IDbParameter");
if (getInterface != null)
{
Assembly assCon = Assembly.Load(tipo.Assembly.GetName());
if (prefix != null && prefix != string.Empty)
{
string[] namespaces = tipo.Namespace.Split('.');
if (namespaces[namespaces.Length - 1] == prefix)
{
StringBuilder obj = new StringBuilder(tipo.Namespace);
obj.Append(".");
obj.Append(tipo.Name);
return paramter = (DbParameter)assCon.
CreateInstance(obj.ToString(), false, BindingFlags.InvokeMethod,
null, new object[] {}, null, null);
}
}
else
{
StringBuilder obj = new StringBuilder(tipo.Namespace);
obj.Append(".");
obj.Append(tipo.Name);
return paramter = (DbParameter)assCon.
CreateInstance(obj.ToString(), false, BindingFlags.InvokeMethod,
null, new object[] { }, null, null);
}
}
}
return paramter;
}
#region IDisposable Members
public void Dispose()
{
if (conn != null)
conn.Dispose();
}
#endregion
#region IDataBase Members
public DataTable getSchema()
{
try
{
return (DataTable) conn.GetType().InvokeMember("GetSchema", BindingFlags.InvokeMethod, null, conn, new object[] {});
}
catch (Exception)
{
return new DataTable();
}
}
public DataTable getSchema(string collectionName)
{
try
{
return (DataTable)conn.GetType().InvokeMember("GetSchema", BindingFlags.InvokeMethod, null, conn, new object[] { collectionName });
}
catch (Exception)
{
return new DataTable();
}
}
public DataTable getSchema(string collectionName, string[] restrictions)
{
try
{
return (DataTable)conn.GetType().InvokeMember("GetSchema", BindingFlags.InvokeMethod, null, conn, new object[] { collectionName, restrictions });
}
catch (Exception)
{
return new DataTable();
}
}
public void open(string URL)
{
conn = getConnection(URL);
conn.Open();
}
public void close()
{
if (conn != null)
conn.Close();
}
public DbParameter getParameter()
{
return objectParameter();
}
public DbParameter getParameter(string name, DbType type, int size)
{
DbParameter parameter = objectParameter();
parameter.ParameterName = name;
parameter.DbType = type;
parameter.Size = size;
return parameter;
}
#endregion
}
}
| |
using System;
using System.Windows.Forms;
using System.Diagnostics;
namespace gView.Framework.UI.Controls
{
/////////////////////////////////////////////////////////////////////////////
// Selection
/// <summary>
/// Encapsulates a textbox's selection. </summary>
/// <seealso cref="Saver" />
public class Selection
{
// Fields
private TextBoxBase m_textBox;
/// <summary>
/// Event used to notify that the selected text is about to change. </summary>
/// <remarks>
/// This event is fired by Replace right before it replaces the textbox's text. </remarks>
/// <seealso cref="Replace" />
public event EventHandler TextChanging;
/// <summary>
/// Initializes a new instance of the Selection class by associating it with a TextBoxBase derived object. </summary>
/// <param name="textBox">
/// The TextBoxBase object for which the selection is being manipulated. </param>
/// <seealso cref="System.Windows.Forms.TextBoxBase" />
public Selection(TextBoxBase textBox)
{
m_textBox = textBox;
}
/// <summary>
/// Initializes a new instance of the Selection class by associating it with a TextBoxBase derived object.
/// and then selecting text on it. </summary>
/// <param name="textBox">
/// The TextBoxBase object for which the selection is being manipulated. </param>
/// <param name="start">
/// The zero-based position where to start the selection. </param>
/// <param name="end">
/// The zero-based position where to end the selection. If it's equal to the start position, no text is selected. </param>
/// <seealso cref="System.Windows.Forms.TextBoxBase" />
public Selection(TextBoxBase textBox, int start, int end)
{
m_textBox = textBox;
Set(start, end);
}
/// <summary>
/// Selects the textbox's text. </summary>
/// <param name="start">
/// The zero-based position where to start the selection. </param>
/// <param name="end">
/// The zero-based position where to end the selection. If it's equal to the start position, no text is selected. </param>
/// <remarks>
/// The end must be greater than or equal to the start position. </remarks>
/// <seealso cref="Get" />
public void Set(int start, int end)
{
m_textBox.SelectionStart = start;
m_textBox.SelectionLength = end - start;
}
/// <summary>
/// Retrieves the start and end position of the selection. </summary>
/// <param name="start">
/// The zero-based position where the selection starts. </param>
/// <param name="end">
/// The zero-based position where selection ends. If it's equal to the start position, no text is selected. </param>
/// <seealso cref="Set" />
public void Get(out int start, out int end)
{
start = m_textBox.SelectionStart;
end = start + m_textBox.SelectionLength;
if (start < 0)
start = 0;
if (end < start)
end = start;
}
/// <summary>
/// Replaces the text selected on the textbox. </summary>
/// <param name="text">
/// The text to replace the selection with. </param>
/// <remarks>
/// If nothing is selected, the text is inserted at the caret's position. </remarks>
/// <seealso cref="SetAndReplace" />
public void Replace(string text)
{
if (TextChanging != null)
TextChanging(this, null);
m_textBox.SelectedText = text;
}
/// <summary>
/// Selects the textbox's text and replaces it. </summary>
/// <param name="start">
/// The zero-based position where to start the selection. </param>
/// <param name="end">
/// The zero-based position where to end the selection. If it's equal to the start position, no text is selected. </param>
/// <param name="text">
/// The text to replace the selection with. </param>
/// <remarks>
/// The end must be greater than or equal to the start position.
/// If nothing gets selected, the text is inserted at the caret's position. </remarks>
/// <seealso cref="Set" />
/// <seealso cref="Replace" />
public void SetAndReplace(int start, int end, string text)
{
Set(start, end);
Replace(text);
}
/// <summary>
/// Changes the selection's start and end positions by an offset. </summary>
/// <param name="start">
/// How much to change the start of the selection by. </param>
/// <param name="end">
/// How much to change the end of the selection by. </param>
/// <seealso cref="Set" />
public void MoveBy(int start, int end)
{
End += end;
Start += start;
}
/// <summary>
/// Changes the internal start and end positions by an offset. </summary>
/// <param name="pos">
/// How much to change the start and end of the selection by. </param>
/// <seealso cref="Set" />
public void MoveBy(int pos)
{
MoveBy(pos, pos);
}
/// <summary>
/// Creates a new Selection object with the internal start and end
/// positions changed by an offset. </summary>
/// <param name="selection">
/// The object with the original selection. </param>
/// <param name="pos">
/// How much to change the start and end of the selection by on the resulting object. </param>
/// <seealso cref="MoveBy" />
/// <seealso cref="Set" />
public static Selection operator+(Selection selection, int pos)
{
return new Selection(selection.m_textBox, selection.Start + pos, selection.End + pos);
}
/// <summary>
/// Gets the TextBoxBase object associated with this Selection object. </summary>
public TextBoxBase TextBox
{
get
{
return m_textBox;
}
}
/// <summary>
/// Gets or sets the zero-based position for the start of the selection. </summary>
/// <seealso cref="End" />
/// <seealso cref="Length" />
public int Start
{
get
{
return m_textBox.SelectionStart;
}
set
{
m_textBox.SelectionStart = value;
}
}
/// <summary>
/// Gets or sets the zero-based position for the end of the selection. </summary>
/// <seealso cref="Start" />
/// <seealso cref="Length" />
public int End
{
get
{
return m_textBox.SelectionStart + m_textBox.SelectionLength;
}
set
{
m_textBox.SelectionLength = value - m_textBox.SelectionStart;
}
}
/// <summary>
/// Gets or sets the length of the selection. </summary>
/// <seealso cref="Start" />
/// <seealso cref="End" />
public int Length
{
get
{
return m_textBox.SelectionLength;
}
set
{
m_textBox.SelectionLength = value;
}
}
/// <summary>
/// Saves (and later restores) the current start and end position of a textbox selection. </summary>
/// <remarks>
/// This class saves the start and end position of the textbox with which it is constructed
/// and then restores it when Restore is called. Since this is a IDisposable class, it can also
/// be used inside a <c>using</c> statement to Restore the selection (via Dispose). </remarks>
public class Saver : IDisposable
{
// Fields
private TextBoxBase m_textBox;
private Selection m_selection;
private int m_start, m_end;
/// <summary>
/// Initializes a new instance of the Saver class by associating it with a TextBoxBase derived object. </summary>
/// <param name="textBox">
/// The TextBoxBase object for which the selection is being saved. </param>
/// <remarks>
/// This constructor saves the textbox's start and end position of the selection inside private fields. </remarks>
/// <seealso cref="System.Windows.Forms.TextBoxBase" />
public Saver(TextBoxBase textBox)
{
m_textBox = textBox;
m_selection = new Selection(textBox);
m_selection.Get(out m_start, out m_end);
}
/// <summary>
/// Initializes a new instance of the Saver class by associating it with a TextBoxBase derived object
/// and passing the start and end position of the selection. </summary>
/// <param name="textBox">
/// The TextBoxBase object for which the selection is being saved. </param>
/// <param name="start">
/// The zero-based start position of the selection. </param>
/// <param name="end">
/// The zero-based end position of the selection. It must not be less than the start position. </param>
/// <remarks>
/// This constructor does not save the textbox's start and end position of the selection.
/// Instead, it saves the two given parameters. </remarks>
/// <seealso cref="System.Windows.Forms.TextBoxBase" />
public Saver(TextBoxBase textBox, int start, int end)
{
m_textBox = textBox;
m_selection = new Selection(textBox);
Debug.Assert(start <= end);
m_start = start;
m_end = end;
}
/// <summary>
/// Restores the selection on the textbox to the saved start and end values. </summary>
/// <remarks>
/// This method checks that the textbox is still <see cref="Disable">available</see>
/// and if so restores the selection. </remarks>
/// <seealso cref="Disable" />
public void Restore()
{
if (m_textBox == null)
return;
m_selection.Set(m_start, m_end);
m_textBox = null;
}
/// <summary>
/// Calls the <see cref="Restore" /> method. </summary>
public void Dispose()
{
Restore();
}
/// <summary>
/// Changes the internal start and end positions. </summary>
/// <param name="start">
/// The new zero-based position for the start of the selection. </param>
/// <param name="end">
/// The new zero-based position for the end of the selection. It must not be less than the start position. </param>
/// <seealso cref="MoveBy" />
public void MoveTo(int start, int end)
{
Debug.Assert(start <= end);
m_start = start;
m_end = end;
}
/// <summary>
/// Changes the internal start and end positions by an offset. </summary>
/// <param name="start">
/// How much to change the start of the selection by. </param>
/// <param name="end">
/// How much to change the end of the selection by. </param>
/// <seealso cref="MoveTo" />
public void MoveBy(int start, int end)
{
m_start += start;
m_end += end;
Debug.Assert(m_start <= m_end);
}
/// <summary>
/// Changes the internal start and end positions by an offset. </summary>
/// <param name="pos">
/// How much to change the start and end of the selection by. </param>
/// <seealso cref="MoveTo" />
public void MoveBy(int pos)
{
m_start += pos;
m_end += pos;
}
/// <summary>
/// Creates a new Saver object with the internal start and end
/// positions changed by an offset. </summary>
/// <param name="saver">
/// The object with the original saved selection. </param>
/// <param name="pos">
/// How much to change the start and end of the selection by on the resulting object. </param>
/// <seealso cref="MoveTo" />
public static Saver operator+(Saver saver, int pos)
{
return new Saver(saver.m_textBox, saver.m_start + pos, saver.m_end + pos);
}
/// <summary>
/// Gets the TextBoxBase object associated with this Saver object. </summary>
public TextBoxBase TextBox
{
get
{
return m_textBox;
}
}
/// <summary>
/// Gets or sets the zero-based position for the start of the selection. </summary>
/// <seealso cref="End" />
public int Start
{
get
{
return m_start;
}
set
{
m_start = value;
}
}
/// <summary>
/// Gets or sets the zero-based position for the end of the selection. </summary>
/// <seealso cref="Start" />
public int End
{
get
{
return m_end;
}
set
{
m_end = value;
}
}
/// <summary>
/// Updates the internal start and end positions with the current selection on the textbox. </summary>
/// <seealso cref="Disable" />
public void Update()
{
if (m_textBox != null)
m_selection.Get(out m_start, out m_end);
}
/// <summary>
/// Disables restoring of the textbox's selection when <see cref="Dispose" /> is called. </summary>
/// <seealso cref="Dispose" />
/// <seealso cref="Update" />
public void Disable()
{
m_textBox = null;
}
}
}
}
| |
/******************************************************************************
* Copyright (C) Leap Motion, Inc. 2011-2018. *
* Leap Motion proprietary and confidential. *
* *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
******************************************************************************/
namespace Leap {
using System;
using LeapInternal;
/// <summary>
/// The Device class represents a physically connected device.
///
/// The Device class contains information related to a particular connected
/// device such as device id, field of view relative to the device,
/// and the position and orientation of the device in relative coordinates.
///
/// The position and orientation describe the alignment of the device relative to the user.
/// The alignment relative to the user is only descriptive. Aligning devices to users
/// provides consistency in the parameters that describe user interactions.
///
/// Note that Device objects can be invalid, which means that they do not contain
/// valid device information and do not correspond to a physical device.
/// @since 1.0
/// </summary>
public class Device :
IEquatable<Device> {
/// <summary>
/// Constructs a default Device object.
///
/// Get valid Device objects from a DeviceList object obtained using the
/// Controller.Devices() method.
///
/// @since 1.0
/// </summary>
public Device() { }
public Device(IntPtr deviceHandle,
float horizontalViewAngle,
float verticalViewAngle,
float range,
float baseline,
DeviceType type,
bool isStreaming,
string serialNumber) {
Handle = deviceHandle;
HorizontalViewAngle = horizontalViewAngle;
VerticalViewAngle = verticalViewAngle;
Range = range;
Baseline = baseline;
Type = type;
IsStreaming = isStreaming;
SerialNumber = serialNumber;
}
/// <summary>
/// For internal use only.
/// </summary>
public void Update(
float horizontalViewAngle,
float verticalViewAngle,
float range,
float baseline,
bool isStreaming,
string serialNumber) {
HorizontalViewAngle = horizontalViewAngle;
VerticalViewAngle = verticalViewAngle;
Range = range;
Baseline = baseline;
IsStreaming = isStreaming;
SerialNumber = serialNumber;
}
/// <summary>
/// For internal use only.
/// </summary>
public void Update(Device updatedDevice) {
HorizontalViewAngle = updatedDevice.HorizontalViewAngle;
VerticalViewAngle = updatedDevice.VerticalViewAngle;
Range = updatedDevice.Range;
Baseline = updatedDevice.Baseline;
IsStreaming = updatedDevice.IsStreaming;
SerialNumber = updatedDevice.SerialNumber;
}
/// <summary>
/// For internal use only.
/// </summary>
public IntPtr Handle { get; private set; }
public bool SetPaused(bool pause) {
ulong prior_state = 0;
ulong set_flags = 0;
ulong clear_flags = 0;
if (pause) {
set_flags = (ulong)eLeapDeviceFlag.eLeapDeviceFlag_Stream;
} else {
clear_flags = (ulong)eLeapDeviceFlag.eLeapDeviceFlag_Stream;
}
eLeapRS result = LeapC.SetDeviceFlags(Handle, set_flags, clear_flags, out prior_state);
return result == eLeapRS.eLeapRS_Success;
}
/// <summary>
/// Compare Device object equality.
///
/// Two Device objects are equal if and only if both Device objects represent the
/// exact same Device and both Devices are valid.
///
/// @since 1.0
/// </summary>
public bool Equals(Device other) {
return SerialNumber == other.SerialNumber;
}
/// <summary>
/// A string containing a brief, human readable description of the Device object.
/// @since 1.0
/// </summary>
public override string ToString() {
return "Device serial# " + this.SerialNumber;
}
/// <summary>
/// The angle in radians of view along the x axis of this device.
///
/// The Leap Motion controller scans a region in the shape of an inverted pyramid
/// centered at the device's center and extending upwards. The horizontalViewAngle
/// reports the view angle along the long dimension of the device.
///
/// @since 1.0
/// </summary>
public float HorizontalViewAngle { get; private set; }
/// <summary>
/// The angle in radians of view along the z axis of this device.
///
/// The Leap Motion controller scans a region in the shape of an inverted pyramid
/// centered at the device's center and extending upwards. The verticalViewAngle
/// reports the view angle along the short dimension of the device.
///
/// @since 1.0
/// </summary>
public float VerticalViewAngle { get; private set; }
/// <summary>
/// The maximum reliable tracking range from the center of this device.
///
/// The range reports the maximum recommended distance from the device center
/// for which tracking is expected to be reliable. This distance is not a hard limit.
/// Tracking may be still be functional above this distance or begin to degrade slightly
/// before this distance depending on calibration and extreme environmental conditions.
///
/// @since 1.0
/// </summary>
public float Range { get; private set; }
/// <summary>
/// The distance in mm between the center points of the stereo sensors.
///
/// The baseline value, together with the maximum resolution, influence the
/// maximum range.
///
/// @since 2.2.5
/// </summary>
public float Baseline { get; private set; }
/// <summary>
/// Reports whether this device is streaming data to your application.
///
/// Currently only one controller can provide data at a time.
/// @since 1.2
/// </summary>
public bool IsStreaming { get; private set; }
/// <summary>
/// The device type.
///
/// Use the device type value in the (rare) circumstances that you
/// have an application feature which relies on a particular type of device.
/// Current types of device include the original Leap Motion peripheral,
/// keyboard-embedded controllers, and laptop-embedded controllers.
///
/// @since 1.2
/// </summary>
public DeviceType Type { get; private set; }
/// <summary>
/// An alphanumeric serial number unique to each device.
///
/// Consumer device serial numbers consist of 2 letters followed by 11 digits.
///
/// When using multiple devices, the serial number provides an unambiguous
/// identifier for each device.
/// @since 2.2.2
/// </summary>
public string SerialNumber { get; private set; }
/// <summary>
/// The software has detected a possible smudge on the translucent cover
/// over the Leap Motion cameras.
///
/// Not implemented yet.
/// @since 3.0
/// </summary>
public bool IsSmudged {
get {
throw new NotImplementedException();
}
}
/// <summary>
/// The software has detected excessive IR illumination, which may interfere
/// with tracking. If robust mode is enabled, the system will enter robust mode when
/// isLightingBad() is true.
///
/// Not implemented yet.
/// @since 3.0
/// </summary>
public bool IsLightingBad {
get {
throw new NotImplementedException();
}
}
/// <summary>
/// The available types of Leap Motion controllers.
/// </summary>
public enum DeviceType {
TYPE_INVALID = -1,
/// <summary>
/// A standalone USB peripheral. The original Leap Motion controller device.
/// @since 1.2
/// </summary>
TYPE_PERIPHERAL = (int)eLeapDeviceType.eLeapDeviceType_Peripheral,
/// <summary>
/// Internal research product codename "Dragonfly".
/// </summary>
TYPE_DRAGONFLY = (int)eLeapDeviceType.eLeapDeviceType_Dragonfly,
/// <summary>
/// Internal research product codename "Nightcrawler".
/// </summary>
TYPE_NIGHTCRAWLER = (int)eLeapDeviceType.eLeapDeviceType_Nightcrawler,
/// <summary>
/// Research product codename "Rigel".
/// </summary>
TYPE_RIGEL = (int)eLeapDeviceType.eLeapDevicePID_Rigel,
[Obsolete]
TYPE_LAPTOP,
[Obsolete]
TYPE_KEYBOARD
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Serialization;
namespace System
{
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public abstract class StringComparer : IComparer, IEqualityComparer, IComparer<string>, IEqualityComparer<string>
{
private static readonly CultureAwareComparer s_invariantCulture = new CultureAwareComparer(CultureInfo.InvariantCulture, CompareOptions.None);
private static readonly CultureAwareComparer s_invariantCultureIgnoreCase = new CultureAwareComparer(CultureInfo.InvariantCulture, CompareOptions.IgnoreCase);
private static readonly OrdinalCaseSensitiveComparer s_ordinal = new OrdinalCaseSensitiveComparer();
private static readonly OrdinalIgnoreCaseComparer s_ordinalIgnoreCase = new OrdinalIgnoreCaseComparer();
public static StringComparer InvariantCulture
{
get
{
return s_invariantCulture;
}
}
public static StringComparer InvariantCultureIgnoreCase
{
get
{
return s_invariantCultureIgnoreCase;
}
}
public static StringComparer CurrentCulture
{
get
{
return new CultureAwareComparer(CultureInfo.CurrentCulture, CompareOptions.None);
}
}
public static StringComparer CurrentCultureIgnoreCase
{
get
{
return new CultureAwareComparer(CultureInfo.CurrentCulture, CompareOptions.IgnoreCase);
}
}
public static StringComparer Ordinal
{
get
{
return s_ordinal;
}
}
public static StringComparer OrdinalIgnoreCase
{
get
{
return s_ordinalIgnoreCase;
}
}
// Convert a StringComparison to a StringComparer
public static StringComparer FromComparison(StringComparison comparisonType)
{
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CurrentCulture;
case StringComparison.CurrentCultureIgnoreCase:
return CurrentCultureIgnoreCase;
case StringComparison.InvariantCulture:
return InvariantCulture;
case StringComparison.InvariantCultureIgnoreCase:
return InvariantCultureIgnoreCase;
case StringComparison.Ordinal:
return Ordinal;
case StringComparison.OrdinalIgnoreCase:
return OrdinalIgnoreCase;
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
public static StringComparer Create(CultureInfo culture, bool ignoreCase)
{
if (culture == null)
{
throw new ArgumentNullException(nameof(culture));
}
return new CultureAwareComparer(culture, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
}
public static StringComparer Create(CultureInfo culture, CompareOptions options)
{
if (culture == null)
{
throw new ArgumentException(nameof(culture));
}
return new CultureAwareComparer(culture, options);
}
public int Compare(object x, object y)
{
if (x == y) return 0;
if (x == null) return -1;
if (y == null) return 1;
if (x is string sa)
{
if (y is string sb)
{
return Compare(sa, sb);
}
}
if (x is IComparable ia)
{
return ia.CompareTo(y);
}
throw new ArgumentException(SR.Argument_ImplementIComparable);
}
public new bool Equals(object x, object y)
{
if (x == y) return true;
if (x == null || y == null) return false;
if (x is string sa)
{
if (y is string sb)
{
return Equals(sa, sb);
}
}
return x.Equals(y);
}
public int GetHashCode(object obj)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}
if (obj is string s)
{
return GetHashCode(s);
}
return obj.GetHashCode();
}
public abstract int Compare(string x, string y);
public abstract bool Equals(string x, string y);
public abstract int GetHashCode(string obj);
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed class CultureAwareComparer : StringComparer, ISerializable
{
private const CompareOptions ValidCompareMaskOffFlags = ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort);
private readonly CompareInfo _compareInfo; // Do not rename (binary serialization)
private CompareOptions _options;
internal CultureAwareComparer(CultureInfo culture, CompareOptions options) : this(culture.CompareInfo, options) { }
internal CultureAwareComparer(CompareInfo compareInfo, CompareOptions options)
{
_compareInfo = compareInfo;
if ((options & ValidCompareMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
_options = options;
}
private CultureAwareComparer(SerializationInfo info, StreamingContext context)
{
_compareInfo = (CompareInfo)info.GetValue("_compareInfo", typeof(CompareInfo));
bool ignoreCase = info.GetBoolean("_ignoreCase");
var obj = info.GetValueNoThrow("_options", typeof(CompareOptions));
if (obj != null)
_options = (CompareOptions)obj;
// fix up the _options value in case we are getting old serialized object not having _options
_options |= ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
}
public override int Compare(string x, string y)
{
if (object.ReferenceEquals(x, y)) return 0;
if (x == null) return -1;
if (y == null) return 1;
return _compareInfo.Compare(x, y, _options);
}
public override bool Equals(string x, string y)
{
if (object.ReferenceEquals(x, y)) return true;
if (x == null || y == null) return false;
return _compareInfo.Compare(x, y, _options) == 0;
}
public override int GetHashCode(string obj)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}
return _compareInfo.GetHashCodeOfString(obj, _options);
}
// Equals method for the comparer itself.
public override bool Equals(object obj)
{
return
obj is CultureAwareComparer comparer &&
_options == comparer._options &&
_compareInfo.Equals(comparer._compareInfo);
}
public override int GetHashCode()
{
return _compareInfo.GetHashCode() ^ ((int)_options & 0x7FFFFFFF);
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("_compareInfo", _compareInfo);
info.AddValue("_options", _options);
info.AddValue("_ignoreCase", (_options & CompareOptions.IgnoreCase) != 0);
}
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class OrdinalComparer : StringComparer
{
private readonly bool _ignoreCase; // Do not rename (binary serialization)
internal OrdinalComparer(bool ignoreCase)
{
_ignoreCase = ignoreCase;
}
public override int Compare(string x, string y)
{
if (ReferenceEquals(x, y))
return 0;
if (x == null)
return -1;
if (y == null)
return 1;
if (_ignoreCase)
{
return string.Compare(x, y, StringComparison.OrdinalIgnoreCase);
}
return string.CompareOrdinal(x, y);
}
public override bool Equals(string x, string y)
{
if (ReferenceEquals(x, y))
return true;
if (x == null || y == null)
return false;
if (_ignoreCase)
{
if (x.Length != y.Length)
{
return false;
}
return CompareInfo.EqualsOrdinalIgnoreCase(ref x.GetRawStringData(), ref y.GetRawStringData(), x.Length);
}
return x.Equals(y);
}
public override int GetHashCode(string obj)
{
if (obj == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj);
}
if (_ignoreCase)
{
return obj.GetHashCodeOrdinalIgnoreCase();
}
return obj.GetHashCode();
}
// Equals method for the comparer itself.
public override bool Equals(object obj)
{
if (!(obj is OrdinalComparer comparer))
{
return false;
}
return (this._ignoreCase == comparer._ignoreCase);
}
public override int GetHashCode()
{
int hashCode = nameof(OrdinalComparer).GetHashCode();
return _ignoreCase ? (~hashCode) : hashCode;
}
}
[Serializable]
internal sealed class OrdinalCaseSensitiveComparer : OrdinalComparer, ISerializable
{
public OrdinalCaseSensitiveComparer() : base(false)
{
}
public override int Compare(string x, string y) => string.CompareOrdinal(x, y);
public override bool Equals(string x, string y) => string.Equals(x, y);
public override int GetHashCode(string obj)
{
if (obj == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj);
}
return obj.GetHashCode();
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.SetType(typeof(OrdinalComparer));
info.AddValue("_ignoreCase", false);
}
}
[Serializable]
internal sealed class OrdinalIgnoreCaseComparer : OrdinalComparer, ISerializable
{
public OrdinalIgnoreCaseComparer() : base(true)
{
}
public override int Compare(string x, string y) => string.Compare(x, y, StringComparison.OrdinalIgnoreCase);
public override bool Equals(string x, string y)
{
if (ReferenceEquals(x, y))
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (x.Length != y.Length)
{
return false;
}
return CompareInfo.EqualsOrdinalIgnoreCase(ref x.GetRawStringData(), ref y.GetRawStringData(), x.Length);
}
public override int GetHashCode(string obj)
{
if (obj == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj);
}
return obj.GetHashCodeOrdinalIgnoreCase();
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.SetType(typeof(OrdinalComparer));
info.AddValue("_ignoreCase", true);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Development;
using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Online.API;
using osu.Game.Replays.Legacy;
using osu.Game.Rulesets.Replays;
using osu.Game.Rulesets.Replays.Types;
using osu.Game.Scoring;
using osu.Game.Screens.Play;
namespace osu.Game.Online.Spectator
{
public abstract class SpectatorClient : Component, ISpectatorClient
{
/// <summary>
/// The maximum milliseconds between frame bundle sends.
/// </summary>
public const double TIME_BETWEEN_SENDS = 200;
/// <summary>
/// Whether the <see cref="SpectatorClient"/> is currently connected.
/// This is NOT thread safe and usage should be scheduled.
/// </summary>
public abstract IBindable<bool> IsConnected { get; }
private readonly List<int> watchingUsers = new List<int>();
public IBindableList<int> PlayingUsers => playingUsers;
private readonly BindableList<int> playingUsers = new BindableList<int>();
public IBindableDictionary<int, SpectatorState> PlayingUserStates => playingUserStates;
private readonly BindableDictionary<int, SpectatorState> playingUserStates = new BindableDictionary<int, SpectatorState>();
private IBeatmap? currentBeatmap;
private Score? currentScore;
private readonly SpectatorState currentState = new SpectatorState();
/// <summary>
/// Whether the local user is playing.
/// </summary>
protected bool IsPlaying { get; private set; }
/// <summary>
/// Called whenever new frames arrive from the server.
/// </summary>
public event Action<int, FrameDataBundle>? OnNewFrames;
/// <summary>
/// Called whenever a user starts a play session, or immediately if the user is being watched and currently in a play session.
/// </summary>
public event Action<int, SpectatorState>? OnUserBeganPlaying;
/// <summary>
/// Called whenever a user finishes a play session.
/// </summary>
public event Action<int, SpectatorState>? OnUserFinishedPlaying;
[BackgroundDependencyLoader]
private void load()
{
IsConnected.BindValueChanged(connected => Schedule(() =>
{
if (connected.NewValue)
{
// get all the users that were previously being watched
int[] users = watchingUsers.ToArray();
watchingUsers.Clear();
// resubscribe to watched users.
foreach (var userId in users)
WatchUser(userId);
// re-send state in case it wasn't received
if (IsPlaying)
BeginPlayingInternal(currentState);
}
else
{
playingUsers.Clear();
playingUserStates.Clear();
}
}), true);
}
Task ISpectatorClient.UserBeganPlaying(int userId, SpectatorState state)
{
Schedule(() =>
{
if (!playingUsers.Contains(userId))
playingUsers.Add(userId);
// UserBeganPlaying() is called by the server regardless of whether the local user is watching the remote user, and is called a further time when the remote user is watched.
// This may be a temporary thing (see: https://github.com/ppy/osu-server-spectator/blob/2273778e02cfdb4a9c6a934f2a46a8459cb5d29c/osu.Server.Spectator/Hubs/SpectatorHub.cs#L28-L29).
// We don't want the user states to update unless the player is being watched, otherwise calling BindUserBeganPlaying() can lead to double invocations.
if (watchingUsers.Contains(userId))
playingUserStates[userId] = state;
OnUserBeganPlaying?.Invoke(userId, state);
});
return Task.CompletedTask;
}
Task ISpectatorClient.UserFinishedPlaying(int userId, SpectatorState state)
{
Schedule(() =>
{
playingUsers.Remove(userId);
playingUserStates.Remove(userId);
OnUserFinishedPlaying?.Invoke(userId, state);
});
return Task.CompletedTask;
}
Task ISpectatorClient.UserSentFrames(int userId, FrameDataBundle data)
{
Schedule(() => OnNewFrames?.Invoke(userId, data));
return Task.CompletedTask;
}
public void BeginPlaying(GameplayState state, Score score)
{
Debug.Assert(ThreadSafety.IsUpdateThread);
if (IsPlaying)
throw new InvalidOperationException($"Cannot invoke {nameof(BeginPlaying)} when already playing");
IsPlaying = true;
// transfer state at point of beginning play
currentState.BeatmapID = score.ScoreInfo.BeatmapInfo.OnlineBeatmapID;
currentState.RulesetID = score.ScoreInfo.RulesetID;
currentState.Mods = score.ScoreInfo.Mods.Select(m => new APIMod(m)).ToArray();
currentBeatmap = state.Beatmap;
currentScore = score;
BeginPlayingInternal(currentState);
}
public void SendFrames(FrameDataBundle data) => lastSend = SendFramesInternal(data);
public void EndPlaying()
{
// This method is most commonly called via Dispose(), which is asynchronous.
// Todo: This should not be a thing, but requires framework changes.
Schedule(() =>
{
if (!IsPlaying)
return;
IsPlaying = false;
currentBeatmap = null;
EndPlayingInternal(currentState);
});
}
public void WatchUser(int userId)
{
Debug.Assert(ThreadSafety.IsUpdateThread);
if (watchingUsers.Contains(userId))
return;
watchingUsers.Add(userId);
WatchUserInternal(userId);
}
public void StopWatchingUser(int userId)
{
// This method is most commonly called via Dispose(), which is asynchronous.
// Todo: This should not be a thing, but requires framework changes.
Schedule(() =>
{
watchingUsers.Remove(userId);
playingUserStates.Remove(userId);
StopWatchingUserInternal(userId);
});
}
protected abstract Task BeginPlayingInternal(SpectatorState state);
protected abstract Task SendFramesInternal(FrameDataBundle data);
protected abstract Task EndPlayingInternal(SpectatorState state);
protected abstract Task WatchUserInternal(int userId);
protected abstract Task StopWatchingUserInternal(int userId);
private readonly Queue<LegacyReplayFrame> pendingFrames = new Queue<LegacyReplayFrame>();
private double lastSendTime;
private Task? lastSend;
private const int max_pending_frames = 30;
protected override void Update()
{
base.Update();
if (pendingFrames.Count > 0 && Time.Current - lastSendTime > TIME_BETWEEN_SENDS)
purgePendingFrames();
}
public void HandleFrame(ReplayFrame frame)
{
Debug.Assert(ThreadSafety.IsUpdateThread);
if (!IsPlaying)
return;
if (frame is IConvertibleReplayFrame convertible)
pendingFrames.Enqueue(convertible.ToLegacy(currentBeatmap));
if (pendingFrames.Count > max_pending_frames)
purgePendingFrames();
}
private void purgePendingFrames()
{
if (lastSend?.IsCompleted == false)
return;
var frames = pendingFrames.ToArray();
pendingFrames.Clear();
Debug.Assert(currentScore != null);
SendFrames(new FrameDataBundle(currentScore.ScoreInfo, frames));
lastSendTime = Time.Current;
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace NorthwindAccess{
/// <summary>
/// Strongly-typed collection for the OrderDetailsExtended class.
/// </summary>
[Serializable]
public partial class OrderDetailsExtendedCollection : ReadOnlyList<OrderDetailsExtended, OrderDetailsExtendedCollection>
{
public OrderDetailsExtendedCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the Order Details Extended view.
/// </summary>
[Serializable]
public partial class OrderDetailsExtended : ReadOnlyRecord<OrderDetailsExtended>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
{
SetSQLProps();
}
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Order Details Extended", TableType.View, DataService.GetInstance("NorthwindAccess"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"";
//columns
TableSchema.TableColumn colvarOrderID = new TableSchema.TableColumn(schema);
colvarOrderID.ColumnName = "OrderID";
colvarOrderID.DataType = DbType.Int32;
colvarOrderID.MaxLength = 0;
colvarOrderID.AutoIncrement = false;
colvarOrderID.IsNullable = true;
colvarOrderID.IsPrimaryKey = false;
colvarOrderID.IsForeignKey = false;
colvarOrderID.IsReadOnly = false;
schema.Columns.Add(colvarOrderID);
TableSchema.TableColumn colvarProductID = new TableSchema.TableColumn(schema);
colvarProductID.ColumnName = "ProductID";
colvarProductID.DataType = DbType.Int32;
colvarProductID.MaxLength = 0;
colvarProductID.AutoIncrement = false;
colvarProductID.IsNullable = true;
colvarProductID.IsPrimaryKey = false;
colvarProductID.IsForeignKey = false;
colvarProductID.IsReadOnly = false;
schema.Columns.Add(colvarProductID);
TableSchema.TableColumn colvarProductName = new TableSchema.TableColumn(schema);
colvarProductName.ColumnName = "ProductName";
colvarProductName.DataType = DbType.String;
colvarProductName.MaxLength = 40;
colvarProductName.AutoIncrement = false;
colvarProductName.IsNullable = true;
colvarProductName.IsPrimaryKey = false;
colvarProductName.IsForeignKey = false;
colvarProductName.IsReadOnly = false;
schema.Columns.Add(colvarProductName);
TableSchema.TableColumn colvarUnitPrice = new TableSchema.TableColumn(schema);
colvarUnitPrice.ColumnName = "UnitPrice";
colvarUnitPrice.DataType = DbType.Currency;
colvarUnitPrice.MaxLength = 0;
colvarUnitPrice.AutoIncrement = false;
colvarUnitPrice.IsNullable = true;
colvarUnitPrice.IsPrimaryKey = false;
colvarUnitPrice.IsForeignKey = false;
colvarUnitPrice.IsReadOnly = false;
schema.Columns.Add(colvarUnitPrice);
TableSchema.TableColumn colvarQuantity = new TableSchema.TableColumn(schema);
colvarQuantity.ColumnName = "Quantity";
colvarQuantity.DataType = DbType.Int16;
colvarQuantity.MaxLength = 0;
colvarQuantity.AutoIncrement = false;
colvarQuantity.IsNullable = true;
colvarQuantity.IsPrimaryKey = false;
colvarQuantity.IsForeignKey = false;
colvarQuantity.IsReadOnly = false;
schema.Columns.Add(colvarQuantity);
TableSchema.TableColumn colvarDiscount = new TableSchema.TableColumn(schema);
colvarDiscount.ColumnName = "Discount";
colvarDiscount.DataType = DbType.Single;
colvarDiscount.MaxLength = 0;
colvarDiscount.AutoIncrement = false;
colvarDiscount.IsNullable = true;
colvarDiscount.IsPrimaryKey = false;
colvarDiscount.IsForeignKey = false;
colvarDiscount.IsReadOnly = false;
schema.Columns.Add(colvarDiscount);
TableSchema.TableColumn colvarExtendedPrice = new TableSchema.TableColumn(schema);
colvarExtendedPrice.ColumnName = "ExtendedPrice";
colvarExtendedPrice.DataType = DbType.Currency;
colvarExtendedPrice.MaxLength = 0;
colvarExtendedPrice.AutoIncrement = false;
colvarExtendedPrice.IsNullable = true;
colvarExtendedPrice.IsPrimaryKey = false;
colvarExtendedPrice.IsForeignKey = false;
colvarExtendedPrice.IsReadOnly = false;
schema.Columns.Add(colvarExtendedPrice);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["NorthwindAccess"].AddSchema("Order Details Extended",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public OrderDetailsExtended()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public OrderDetailsExtended(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public OrderDetailsExtended(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public OrderDetailsExtended(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("OrderID")]
[Bindable(true)]
public int? OrderID
{
get
{
return GetColumnValue<int?>("OrderID");
}
set
{
SetColumnValue("OrderID", value);
}
}
[XmlAttribute("ProductID")]
[Bindable(true)]
public int? ProductID
{
get
{
return GetColumnValue<int?>("ProductID");
}
set
{
SetColumnValue("ProductID", value);
}
}
[XmlAttribute("ProductName")]
[Bindable(true)]
public string ProductName
{
get
{
return GetColumnValue<string>("ProductName");
}
set
{
SetColumnValue("ProductName", value);
}
}
[XmlAttribute("UnitPrice")]
[Bindable(true)]
public decimal? UnitPrice
{
get
{
return GetColumnValue<decimal?>("UnitPrice");
}
set
{
SetColumnValue("UnitPrice", value);
}
}
[XmlAttribute("Quantity")]
[Bindable(true)]
public short? Quantity
{
get
{
return GetColumnValue<short?>("Quantity");
}
set
{
SetColumnValue("Quantity", value);
}
}
[XmlAttribute("Discount")]
[Bindable(true)]
public float? Discount
{
get
{
return GetColumnValue<float?>("Discount");
}
set
{
SetColumnValue("Discount", value);
}
}
[XmlAttribute("ExtendedPrice")]
[Bindable(true)]
public decimal? ExtendedPrice
{
get
{
return GetColumnValue<decimal?>("ExtendedPrice");
}
set
{
SetColumnValue("ExtendedPrice", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string OrderID = @"OrderID";
public static string ProductID = @"ProductID";
public static string ProductName = @"ProductName";
public static string UnitPrice = @"UnitPrice";
public static string Quantity = @"Quantity";
public static string Discount = @"Discount";
public static string ExtendedPrice = @"ExtendedPrice";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using Vault.Endpoints.Sys;
using Vault.Models.Secret.Pki;
using Xunit;
namespace Vault.Tests.Secret
{
public class PkiTests
{
[Fact]
public async Task SecretPki_SetUpRootCA_CanIssueCertificates()
{
using (var server = new VaultTestServer())
{
var client = server.TestClient();
var mountPoint = Guid.NewGuid().ToString();
await client.Sys.Mount(mountPoint, new MountInfo {Type = "pki"});
var mountConfig = new MountConfig
{
MaxLeaseTtl = "87600h"
};
await client.Sys.TuneMount(mountPoint, mountConfig);
var rootCaConfig = new RootGenerateRequest
{
CommonName = "Vault Testing Root Certificate Authority",
Ttl = "87600h"
};
await client.Secret.Write($"{mountPoint}/root/generate/internal", rootCaConfig);
var roleName = Guid.NewGuid().ToString();
var role = new RolesRequest
{
AllowAnyDomain = true,
EnforceHostnames = false,
MaxTtl = "1h"
};
await client.Secret.Write($"{mountPoint}/roles/{roleName}", role);
var certRequest = new IssueRequest
{
CommonName = "Test Cert"
};
var cert =
await
client.Secret.Write<IssueRequest, IssueResponse>($"{mountPoint}/issue/{roleName}",
certRequest);
Assert.NotNull(cert.Data);
Assert.NotNull(cert.Data.Certificate);
Assert.NotNull(cert.Data.PrivateKey);
}
}
[Fact]
public async Task SecretPki_SetUpRootCA_CanIssueCertificatesWithAltNames()
{
using (var server = new VaultTestServer())
{
var client = server.TestClient();
var mountPoint = Guid.NewGuid().ToString();
await client.Sys.Mount(mountPoint, new MountInfo { Type = "pki" });
var mountConfig = new MountConfig
{
MaxLeaseTtl = "87600h"
};
await client.Sys.TuneMount(mountPoint, mountConfig);
var rootCaConfig = new RootGenerateRequest
{
CommonName = "Vault Testing Root Certificate Authority",
Ttl = "87600h"
};
await client.Secret.Write($"{mountPoint}/root/generate/internal", rootCaConfig);
var roleName = Guid.NewGuid().ToString();
var role = new RolesRequest
{
AllowAnyDomain = true,
EnforceHostnames = false,
MaxTtl = "1h"
};
await client.Secret.Write($"{mountPoint}/roles/{roleName}", role);
var commonName = Guid.NewGuid().ToString();
var certRequest = new IssueRequest
{
CommonName = commonName,
AltNames = new List<string> { "example.com", "test.example.com" },
Format = CertificateFormat.Der
};
var cert =
await
client.Secret.Write<IssueRequest, IssueResponse>($"{mountPoint}/issue/{roleName}",
certRequest);
Assert.NotNull(cert.Data);
Assert.NotNull(cert.Data.Certificate);
Assert.NotNull(cert.Data.PrivateKey);
var x509Cert = new X509Certificate2(Convert.FromBase64String(cert.Data.Certificate));
Assert.Equal($"CN={commonName}", x509Cert.SubjectName.Name);
}
}
[Fact]
public async Task SecretPki_BuildIntermediateCAChain_CanIssueCertificatesWithChain()
{
using (var server = new VaultTestServer())
{
var client = server.TestClient();
await client.Sys.Mount("pki", new MountInfo { Type = "pki" });
await client.Sys.Mount("pki1", new MountInfo { Type = "pki" });
await client.Sys.Mount("pki2", new MountInfo { Type = "pki" });
await client.Sys.Mount("pki3", new MountInfo { Type = "pki" });
var mountConfig = new MountConfig
{
MaxLeaseTtl = "87600h"
};
await client.Sys.TuneMount("pki", mountConfig);
await client.Sys.TuneMount("pki1", mountConfig);
await client.Sys.TuneMount("pki2", mountConfig);
await client.Sys.TuneMount("pki3", mountConfig);
// Root CA
var rootCaConfig = new RootGenerateRequest
{
CommonName = "Vault Testing Root Certificate Authority",
Ttl = "87600h"
};
await client.Secret.Write($"pki/root/generate/internal", rootCaConfig);
// Intermediate CA
var pki1CaConfig = new IntermediateGenerateRequest
{
CommonName = "Vault Testing Intermediate CA"
};
var pki1Request =
await
client.Secret.Write<IntermediateGenerateRequest, IntermediateGenerateInternalResponse>(
"pki1/intermediate/generate/internal", pki1CaConfig);
var pki1SignRequest = new RootSignIntermediateRequest
{
Csr = pki1Request.Data.Csr,
Format = CertificateFormat.PemBundle,
Ttl = "87500h"
};
var pki1SignResponse =
await
client.Secret.Write<RootSignIntermediateRequest, RootSignIntermediateResponse>(
"pki/root/sign-intermediate", pki1SignRequest);
var pki1SetSigned = new IntermediateSetSignedRequest
{
Certificate = pki1SignResponse.Data.Certificate
};
await client.Secret.Write("pki1/intermediate/set-signed", pki1SetSigned);
// PKI2 - Sub Intermediate CA
var pki2CaConfig = new IntermediateGenerateRequest
{
CommonName = "Vault Testing Sub Intermediate CA"
};
var pki2Request =
await
client.Secret.Write<IntermediateGenerateRequest, IntermediateGenerateInternalResponse>(
"pki2/intermediate/generate/internal", pki2CaConfig);
var pki2SignRequest = new RootSignIntermediateRequest
{
Csr = pki2Request.Data.Csr,
Format = CertificateFormat.PemBundle,
Ttl = "87400h"
};
var pki2SignResponse =
await
client.Secret.Write<RootSignIntermediateRequest, RootSignIntermediateResponse>(
"pki1/root/sign-intermediate", pki2SignRequest);
var pki2SetSigned = new IntermediateSetSignedRequest
{
Certificate = pki2SignResponse.Data.Certificate
};
await client.Secret.Write("pki2/intermediate/set-signed", pki2SetSigned);
var roleName = Guid.NewGuid().ToString();
var role = new RolesRequest
{
AllowAnyDomain = true,
EnforceHostnames = false,
MaxTtl = "1h"
};
await client.Secret.Write($"pki2/roles/{roleName}", role);
var commonName = Guid.NewGuid().ToString();
var certRequest = new IssueRequest
{
CommonName = commonName,
AltNames = new List<string> { "example.com", "test.example.com" },
Format = CertificateFormat.Der
};
var cert =
await
client.Secret.Write<IssueRequest, IssueResponse>($"pki2/issue/{roleName}",
certRequest);
Assert.NotNull(cert.Data);
Assert.NotNull(cert.Data.Certificate);
Assert.NotNull(cert.Data.PrivateKey);
Assert.Equal(2, cert.Data.CaChain.Count);
}
}
[Fact]
public async Task SecretPki_SetUpRootCA_ReadCaCertificate()
{
using (var server = new VaultTestServer())
{
var client = server.TestClient();
var mountPoint = Guid.NewGuid().ToString();
await client.Sys.Mount(mountPoint, new MountInfo {Type = "pki"});
var mountConfig = new MountConfig
{
MaxLeaseTtl = "87600h"
};
await client.Sys.TuneMount(mountPoint, mountConfig);
var rootCaConfig = new RootGenerateRequest
{
CommonName = "Vault Testing Root Certificate Authority",
Ttl = "87600h"
};
await client.Secret.Write($"{mountPoint}/root/generate/internal", rootCaConfig);
var roleName = Guid.NewGuid().ToString();
var role = new RolesRequest
{
AllowAnyDomain = true,
EnforceHostnames = false,
MaxTtl = "1h"
};
await client.Secret.Write($"{mountPoint}/roles/{roleName}", role);
var caCert = await client.Secret.ReadRaw($"{mountPoint}/ca/pem");
Assert.StartsWith("-----", System.Text.Encoding.Default.GetString(caCert));
}
}
}
}
| |
using System;
using System.IO;
using SharpCompress.IO;
namespace SharpCompress.Common.Rar.Headers
{
internal class FileHeader : RarHeader
{
private const byte SALT_SIZE = 8;
private const byte NEWLHD_SIZE = 32;
protected override void ReadFromReader(MarkingBinaryReader reader)
{
uint lowUncompressedSize = reader.ReadUInt32();
HostOS = (HostOS)reader.ReadByte();
FileCRC = reader.ReadUInt32();
FileLastModifiedTime = Utility.DosDateToDateTime(reader.ReadInt32());
RarVersion = reader.ReadByte();
PackingMethod = reader.ReadByte();
short nameSize = reader.ReadInt16();
FileAttributes = reader.ReadInt32();
uint highCompressedSize = 0;
uint highUncompressedkSize = 0;
if (FileFlags_HasFlag(FileFlags.LARGE))
{
highCompressedSize = reader.ReadUInt32();
highUncompressedkSize = reader.ReadUInt32();
}
else
{
if (lowUncompressedSize == 0xffffffff)
{
lowUncompressedSize = 0xffffffff;
highUncompressedkSize = int.MaxValue;
}
}
CompressedSize = UInt32To64(highCompressedSize, AdditionalSize);
UncompressedSize = UInt32To64(highUncompressedkSize, lowUncompressedSize);
nameSize = nameSize > 4 * 1024 ? (short)(4 * 1024) : nameSize;
byte[] fileNameBytes = reader.ReadBytes(nameSize);
switch (HeaderType)
{
case HeaderType.FileHeader:
{
if (FileFlags_HasFlag(FileFlags.UNICODE))
{
int length = 0;
while (length < fileNameBytes.Length
&& fileNameBytes[length] != 0)
{
length++;
}
if (length != nameSize)
{
length++;
FileName = FileNameDecoder.Decode(fileNameBytes, length);
}
else
{
FileName = DecodeDefault(fileNameBytes);
}
}
else
{
FileName = DecodeDefault(fileNameBytes);
}
FileName = ConvertPath(FileName, HostOS);
}
break;
case HeaderType.NewSubHeader:
{
int datasize = HeaderSize - NEWLHD_SIZE - nameSize;
if (FileFlags_HasFlag(FileFlags.SALT))
{
datasize -= SALT_SIZE;
}
if (datasize > 0)
{
SubData = reader.ReadBytes(datasize);
}
if (NewSubHeaderType.SUBHEAD_TYPE_RR.Equals(fileNameBytes))
{
RecoverySectors = SubData[8] + (SubData[9] << 8)
+ (SubData[10] << 16) + (SubData[11] << 24);
}
}
break;
}
if (FileFlags_HasFlag(FileFlags.SALT))
{
Salt = reader.ReadBytes(SALT_SIZE);
}
if (FileFlags_HasFlag(FileFlags.EXTTIME))
{
// verify that the end of the header hasn't been reached before reading the Extended Time.
// some tools incorrectly omit Extended Time despite specifying FileFlags.EXTTIME, which most parsers tolerate.
if (ReadBytes + reader.CurrentReadByteCount <= HeaderSize - 2)
{
ushort extendedFlags = reader.ReadUInt16();
FileLastModifiedTime = ProcessExtendedTime(extendedFlags, FileLastModifiedTime, reader, 0);
FileCreatedTime = ProcessExtendedTime(extendedFlags, null, reader, 1);
FileLastAccessedTime = ProcessExtendedTime(extendedFlags, null, reader, 2);
FileArchivedTime = ProcessExtendedTime(extendedFlags, null, reader, 3);
}
}
}
private bool FileFlags_HasFlag(Headers.FileFlags fileFlags) {
return (FileFlags&fileFlags)==fileFlags;
}
//only the full .net framework will do other code pages than unicode/utf8
private string DecodeDefault(byte[] bytes)
{
return ArchiveEncoding.Default.GetString(bytes, 0, bytes.Length);
}
private long UInt32To64(uint x, uint y)
{
long l = x;
l <<= 32;
return l + y;
}
private static DateTime? ProcessExtendedTime(ushort extendedFlags, DateTime? time, MarkingBinaryReader reader,
int i)
{
uint rmode = (uint)extendedFlags >> (3 - i) * 4;
if ((rmode & 8) == 0)
{
return null;
}
if (i != 0)
{
uint DosTime = reader.ReadUInt32();
time = Utility.DosDateToDateTime(DosTime);
}
if ((rmode & 4) == 0)
{
time = time.Value.AddSeconds(1);
}
uint nanosecondHundreds = 0;
int count = (int)rmode & 3;
for (int j = 0; j < count; j++)
{
byte b = reader.ReadByte();
nanosecondHundreds |= (((uint)b) << ((j + 3 - count) * 8));
}
//10^-7 to 10^-3
return time.Value.AddMilliseconds(nanosecondHundreds * Math.Pow(10, -4));
}
private static string ConvertPath(string path, HostOS os)
{
#if PORTABLE || NETFX_CORE
return path.Replace('\\', '/');
#else
switch (os)
{
case HostOS.MacOS:
case HostOS.Unix:
{
if (Path.DirectorySeparatorChar == '\\')
{
return path.Replace('/', '\\');
}
}
break;
default:
{
if (Path.DirectorySeparatorChar == '/')
{
return path.Replace('\\', '/');
}
}
break;
}
return path;
#endif
}
internal long DataStartPosition { get; set; }
internal HostOS HostOS { get; private set; }
internal uint FileCRC { get; private set; }
internal DateTime? FileLastModifiedTime { get; private set; }
internal DateTime? FileCreatedTime { get; private set; }
internal DateTime? FileLastAccessedTime { get; private set; }
internal DateTime? FileArchivedTime { get; private set; }
internal byte RarVersion { get; private set; }
internal byte PackingMethod { get; private set; }
internal int FileAttributes { get; private set; }
internal FileFlags FileFlags
{
get { return (FileFlags)base.Flags; }
}
internal long CompressedSize { get; private set; }
internal long UncompressedSize { get; private set; }
internal string FileName { get; private set; }
internal byte[] SubData { get; private set; }
internal int RecoverySectors { get; private set; }
internal byte[] Salt { get; private set; }
public override string ToString()
{
return FileName;
}
public Stream PackedStream { get; set; }
}
}
| |
using System;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Text;
namespace DevTreks.Exceptions
{
/// <summary>
///Purpose: generic error handling class
///Author: www.devtreks.org
///Date: 2016, June
///References: https://docs.asp.net/en/1.0.0-rc2/fundamentals/localization.html
/// </summary>
public sealed class DevTreksErrors
{
private DevTreksErrors()
{
//no private instances needed; this class uses static methods only
}
// static and constant variable declarations
//error messages returned to clients are displayed in Home.Master.spanDisplayError
public const string DISPLAY_ERROR_ID = "spanDisplayError";
//error messages that are generated while writing an html response are displayed in:
public const string DISPLAY_ERROR_ID2 = "spanDisplayError2";
public const string ERRORFOLDERNAME = "Errors";
private readonly static string EXCEPTIONMANAGER_NAME = typeof(DevTreksErrors).Name;
private const string EXCEPTIONMANAGEMENT_CONFIG_SECTION = "exceptionManagement";
private readonly static string HTML_BREAK = "<br />";
// Resource Manager for localized text.
private static ResourceManager rm = new ResourceManager(typeof(DevTreksErrors).Namespace
+ ".DevTreksErrors", Assembly.GetAssembly(typeof(DevTreksErrors)));
//error message delimiters
private const string STRING_DELIMITER = ";";
private static char[] STRING_DELIMITERS = new char[] {';'};
/// <summary>
/// Static method to publish the exception information.
/// </summary>
/// <param name="exception">The exception object whose information should be published.</param>
/// <param name="errorName">The name of the string resource holding ui error message.</param>
public static string Publish(Exception exception, string errorName,
string defaultErrorRootFullPath)
{
int iIndex = -1;
//see if the error name is a delimited string
if (errorName != null) iIndex = errorName.IndexOf(STRING_DELIMITER);
string sFullError = string.Empty;
if (iIndex != -1)
{
StringBuilder oString = new StringBuilder();
string[] aMessages = errorName.Split(STRING_DELIMITERS);
if (aMessages.Length >= 0)
{
oString.Append(GetMessage("TITLE_MESSAGE"));
oString.Append(aMessages[0]);
oString.Append(HTML_BREAK);
oString.Append(GetMessage("TAB_CLICK_TO_ERASE"));
oString.Append(HTML_BREAK);
}
if (aMessages.Length >= 1)
{
oString.Append(GetMessage("TITLE_APPLICATION"));
oString.Append(aMessages[1]);
oString.Append(HTML_BREAK);
}
if (aMessages.Length >= 2)
{
oString.Append(GetMessage("TITLE_SUBAPPLICATION"));
oString.Append(aMessages[2]);
oString.Append(HTML_BREAK);
}
if (aMessages.Length >= 3)
{
oString.Append(GetMessage("TITLE_NODENAME"));
oString.Append(aMessages[3]);
oString.Append(HTML_BREAK);
}
if (aMessages.Length >= 4)
{
oString.Append(GetMessage("TITLE_ID"));
oString.Append(aMessages[4]);
oString.Append(HTML_BREAK);
}
if (aMessages.Length >= 5)
{
oString.Append(GetMessage("TITLE_SERVICEID"));
oString.Append(aMessages[5]);
oString.Append(HTML_BREAK);
}
if (aMessages.Length >= 6)
{
oString.Append(GetMessage("TITLE_ACCOUNTID"));
oString.Append(aMessages[6]);
oString.Append(HTML_BREAK);
}
if (aMessages.Length >= 7)
{
oString.Append(GetMessage("TITLE_FULLMSG"));
string sAdminMsg = aMessages[7];
//keep 20% of the full error message (don't intimidate the customer too much)
// int iLength = sAdminMsg.Length;
// int iKeepLength = (iLength / 50);
// iLength = iLength - iKeepLength;
// string sKeepMsg = sAdminMsg.Remove(iKeepLength, iLength);
// oString.Append(sKeepMsg);
oString.Append(sAdminMsg);
oString.Append(HTML_BREAK);
// sKeepMsg = string.Empty;
sAdminMsg = string.Empty;
}
sFullError = oString.ToString();
}
else
{
sFullError = string.Concat(GetMessage("TITLE_MESSAGE"), exception.ToString(),
GetMessage("TAB_CLICK_TO_ERASE"), HTML_BREAK);
}
if (Path.IsPathRooted(defaultErrorRootFullPath))
{
AppendToErrorLog(sFullError, 2, defaultErrorRootFullPath);
}
else
{
System.Diagnostics.Trace.TraceInformation("Error '{0}'", sFullError);
}
return sFullError;
}
public static string Publish(string errorName,
string defaultErrorRootFullPath)
{
int iIndex = -1;
//see if the error name is a delimited string
if (errorName != null) iIndex = errorName.IndexOf(STRING_DELIMITER);
string sFullError = string.Empty;
if (iIndex != -1)
{
StringBuilder oString = new StringBuilder();
string[] aMessages = errorName.Split(STRING_DELIMITERS);
if (aMessages.Length >= 0)
{
oString.Append(GetMessage("TITLE_MESSAGE"));
oString.Append(aMessages[0]);
oString.Append(HTML_BREAK);
oString.Append(GetMessage("TAB_CLICK_TO_ERASE"));
oString.Append(HTML_BREAK);
}
if (aMessages.Length >= 1)
{
oString.Append(GetMessage("TITLE_APPLICATION"));
oString.Append(aMessages[1]);
oString.Append(HTML_BREAK);
}
if (aMessages.Length >= 2)
{
oString.Append(GetMessage("TITLE_SUBAPPLICATION"));
oString.Append(aMessages[2]);
oString.Append(HTML_BREAK);
}
if (aMessages.Length >= 3)
{
oString.Append(GetMessage("TITLE_NODENAME"));
oString.Append(aMessages[3]);
oString.Append(HTML_BREAK);
}
if (aMessages.Length >= 4)
{
oString.Append(GetMessage("TITLE_ID"));
oString.Append(aMessages[4]);
oString.Append(HTML_BREAK);
}
if (aMessages.Length >= 5)
{
oString.Append(GetMessage("TITLE_SERVICEID"));
oString.Append(aMessages[5]);
oString.Append(HTML_BREAK);
}
if (aMessages.Length >= 6)
{
oString.Append(GetMessage("TITLE_ACCOUNTID"));
oString.Append(aMessages[6]);
oString.Append(HTML_BREAK);
}
if (aMessages.Length >= 7)
{
oString.Append(GetMessage("TITLE_FULLMSG"));
oString.Append(aMessages[7]);
oString.Append(HTML_BREAK);
}
sFullError = oString.ToString();
}
if (Path.IsPathRooted(defaultErrorRootFullPath))
{
AppendToErrorLog(sFullError, 2, defaultErrorRootFullPath);
}
else
{
System.Diagnostics.Trace.TraceInformation("Error '{0}'", sFullError);
}
return sFullError;
}
public static string MakeStandardErrorMsg(string resourceName)
{
string sErrorMsg = string.Empty;
sErrorMsg = GetMessage(resourceName);
return sErrorMsg;
}
public static string MakeStandardErrorMsg(string errorMessage, string resourceName)
{
string sErrorMsg = string.Empty;
if (string.IsNullOrEmpty(resourceName) == false)
{
//errors should be translated and generated here
sErrorMsg = string.Concat(GetMessage("TITLE_MESSAGE"), GetMessage(resourceName),
errorMessage, GetMessage("TAB_CLICK_TO_ERASE"));
}
else
{
sErrorMsg = string.Concat(GetMessage("TITLE_MESSAGE"), errorMessage,
GetMessage("TAB_CLICK_TO_ERASE"));
}
int iKeepLength = (errorMessage.Length > 100) ? 100 : errorMessage.Length - 1;
if (iKeepLength > 0)
{
sErrorMsg += sErrorMsg.Remove(iKeepLength);
}
return sErrorMsg;
}
/// <summary>
/// return a localized string exception message to the client
/// </summary>
/// <param name="resourceName"></param>
/// <returns></returns>
public static string GetMessage(string resourceName)
{
string sResourceValue = rm.GetString(resourceName);
return sResourceValue;
}
//public static string GetMessage(string resourceName, CultureInfo culture)
//{
// //keep for debugging embedded resources
// string sResourceValue = string.Empty;
// try
// {
// sResourceValue = rm.GetString(resourceName);
// }
// catch (Exception x)
// {
// string sErr = x.Message;
// }
// if (sResourceValue == null)
// {
// sResourceValue = string.Empty;
// }
// return sResourceValue;
//}
/// <summary>
/// Append a new error message to the log file
/// </summary>
/// <param name="errMessage"></param>
public static void AppendToErrorLog(string errMessage, int recursions,
string defaultErrorRootFullPath)
{
//relative path to standard write directory
string sToday = GetTodaysDate();
StringBuilder oString = new StringBuilder();
oString.Append(defaultErrorRootFullPath);
oString.Append(sToday);
oString.Append(".txt");
string sLogFile = oString.ToString();
oString = null;
try
{
//azure has blobdirectory in name
if (Path.IsPathRooted(defaultErrorRootFullPath))
{
string sDirectoryName = Path.GetDirectoryName(defaultErrorRootFullPath);
if (Directory.Exists(sDirectoryName) == false)
{
Directory.CreateDirectory(defaultErrorRootFullPath);
}
}
FileStream oFileStream = null;
if (File.Exists(sLogFile))
{
oFileStream = new FileStream(sLogFile, FileMode.Append,
FileAccess.Write, FileShare.Write);
}
else
{
oFileStream = new FileStream(sLogFile, FileMode.CreateNew,
FileAccess.Write, FileShare.Write);
}
if (oFileStream != null)
{
using (oFileStream)
{
//don't use asynchronous unless log file shows this class is generating errors
StreamWriter oLogWriter = new StreamWriter(oFileStream);
if (oLogWriter != null)
{
using (oLogWriter)
{
LogError(errMessage, oLogWriter);
}
}
}
}
}
catch (Exception x)
{
if (recursions == 1)
{
//162 removed: no reason to recurse
//AppendToErrorLog(errMessage, 1, defaultErrorRootFullPath);
}
}
}
private static string GetTodaysDate()
{
DateTime dtToday = new DateTime();
dtToday = (DateTime) DateTime.Today;
string sToday = dtToday.ToString("yyyy-MM-dd");
sToday = sToday.Replace("-", "_");
return sToday;
}
private static void LogError(string errMessage, TextWriter logWriter)
{
logWriter.Write("\r\nLog Entry : ");
logWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
DateTime.Now.ToLongDateString());
logWriter.WriteLine(" :");
logWriter.WriteLine(" :{0}", errMessage);
logWriter.WriteLine ("-------------------------------");
// Update the underlying file.
logWriter.Flush();
}
}
}
| |
// 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 RoundToZeroDouble()
{
var test = new SimpleUnaryOpTest__RoundToZeroDouble();
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 works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__RoundToZeroDouble
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Double);
private const int RetElementCount = VectorSize / sizeof(Double);
private static Double[] _data = new Double[Op1ElementCount];
private static Vector128<Double> _clsVar;
private Vector128<Double> _fld;
private SimpleUnaryOpTest__DataTable<Double, Double> _dataTable;
static SimpleUnaryOpTest__RoundToZeroDouble()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar), ref Unsafe.As<Double, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__RoundToZeroDouble()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld), ref Unsafe.As<Double, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); }
_dataTable = new SimpleUnaryOpTest__DataTable<Double, Double>(_data, new Double[RetElementCount], VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.RoundToZero(
Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse41.RoundToZero(
Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.RoundToZero(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToZero), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToZero), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToZero), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse41.RoundToZero(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr);
var result = Sse41.RoundToZero(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr));
var result = Sse41.RoundToZero(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr));
var result = Sse41.RoundToZero(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__RoundToZeroDouble();
var result = Sse41.RoundToZero(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse41.RoundToZero(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Double> firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "")
{
if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits((firstOp[0] > 0) ? Math.Floor(firstOp[0]) : Math.Ceiling(firstOp[0])))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits((firstOp[i] > 0) ? Math.Floor(firstOp[i]) : Math.Ceiling(firstOp[i])))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.RoundToZero)}<Double>(Vector128<Double>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
namespace Revit.SDK.Samples.ObjectViewer.CS
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Autodesk.Revit.DB;
/// <summary>
/// a class inherit from Form is used to
/// display an element and its parameters
/// </summary>
public partial class ObjectViewerForm : System.Windows.Forms.Form, IMessageFilter
{
private ObjectViewer m_viewer;
private SortableBindingList<Para> m_paras;
private Sketch3D m_currentSketch;
// key down code
private const int WM_KEYDOWN = 0X0100;
/// <summary>
/// constructor
/// </summary>
/// <param name="viewer"></param>
public ObjectViewerForm(ObjectViewer viewer)
{
InitializeComponent();
m_viewer = viewer;
m_paras = viewer.Params;
m_currentSketch = viewer.CurrentSketch3D;
Application.AddMessageFilter(this);
}
/// <summary>
/// initialize the controller
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ObjectViewerForm_Load(object sender, EventArgs e)
{
// detailLevelComboBox
detailLevelComboBox.SelectedIndex = (int)m_viewer.DetailLevel;
// viewListBox
viewListBox.DataSource = m_viewer.AllViews;
viewListBox.DisplayMember = "Name";
viewListBox.SelectedItem = m_viewer.CurrentView;
// physicalModelRadioButton and analyticalModelRadioButton
physicalModelRadioButton.Checked =
(m_viewer.DisplayKind == ObjectViewer.DisplayKinds.GeometryModel);
analyticalModelRadioButton.Checked =
(m_viewer.DisplayKind == ObjectViewer.DisplayKinds.AnalyticalModel);
// viewDirectionComboBox
viewDirectionComboBox.SelectedIndex = (int)Graphics3DData.ViewDirections.IsoMetric;
// m_currentSketch
m_currentSketch = m_viewer.CurrentSketch3D;
m_currentSketch.DisplayBBox = new RectangleF(new PointF(0.0f, 0.0f), previewBox.Size);
m_currentSketch.UpdateViewEvent += delegate
{
previewBox.Invalidate();
};
// parametersDataGridView
parametersDataGridView.DataSource = m_paras;
parametersDataGridView.Columns[0].Width = parametersDataGridView.Width / 2;
parametersDataGridView.Columns[0].HeaderText = "Parameter Name";
parametersDataGridView.Columns[1].Width = parametersDataGridView.Width / 2;
parametersDataGridView.Columns[1].HeaderText = "Value";
}
/// <summary>
/// Prefilter the message, action zoom, transform, rotate etc.
/// </summary>
/// <param name="m">The message captured</param>
/// <returns>Informs if this message is used. </returns>
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == WM_KEYDOWN)
{
// mouse is out of previewBox
if (Cursor.Current != Cursors.Cross)
{
return false;
}
// deal with key down event
System.Windows.Forms.Keys k = (System.Windows.Forms.Keys)(int)m.WParam;
KeyEventArgs e = new KeyEventArgs(k);
switch (e.KeyCode)
{
case Keys.Left:
m_currentSketch.Data3D.RotateY(true);
break;
case Keys.Right:
m_currentSketch.Data3D.RotateY(false);
break;
case Keys.Up:
m_currentSketch.Data3D.RotateX(true);
break;
case Keys.Down:
m_currentSketch.Data3D.RotateX(false);
break;
case Keys.PageUp:
m_currentSketch.Data3D.RotateZ(true);
break;
case Keys.PageDown:
m_currentSketch.Data3D.RotateZ(false);
break;
case Keys.S:
m_currentSketch.MoveY(true);
break;
case Keys.W:
m_currentSketch.MoveY(false);
break;
case Keys.A:
m_currentSketch.MoveX(true);
break;
case Keys.D:
m_currentSketch.MoveX(false);
break;
case Keys.Home:
m_currentSketch.Zoom(true);
break;
case Keys.End:
m_currentSketch.Zoom(false);
break;
case Keys.Escape:
this.Close();
break;
default:
return false;
}
return true;
}
return false;
}
/// <summary>
/// remove message map
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ObjectViewerForm_FormClosed(object sender, FormClosedEventArgs e)
{
Application.RemoveMessageFilter(this);
}
/// <summary>
/// previewBox redraw
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void previewBox_Paint(object sender, PaintEventArgs e)
{
m_currentSketch.Draw(e.Graphics);
}
/// <summary>
/// display physicalModel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void physicalModelRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (physicalModelRadioButton.Checked)
{
m_viewer.DisplayKind = ObjectViewer.DisplayKinds.GeometryModel;
}
}
/// <summary>
/// display analyticalModel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void analyticalModelRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (analyticalModelRadioButton.Checked)
{
m_viewer.DisplayKind = ObjectViewer.DisplayKinds.AnalyticalModel;
}
}
/// <summary>
/// Change the View to show the element
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void viewListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if(!viewListBox.Focused)
{
return;
}
m_viewer.CurrentView = viewListBox.SelectedItem as Autodesk.Revit.DB.View;
detailLevelComboBox.SelectedIndex = (int)m_viewer.DetailLevel;
}
/// <summary>
/// Change the camera direction to the view
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void viewDirectionComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
m_currentSketch.Data3D.SetViewDirection(
(Graphics3DData.ViewDirections)viewDirectionComboBox.SelectedIndex);
}
/// <summary>
/// Change the detail level to show the element
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void detailLevelComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if(!detailLevelComboBox.Focused)
{
return;
}
m_viewer.DetailLevel = (DetailLevels)detailLevelComboBox.SelectedIndex;
viewListBox.SelectedItem = m_viewer.CurrentView;
}
/// <summary>
/// Submit the edition of parameters
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OKButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
Close();
}
/// <summary>
/// Cancel all edit
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void closeButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}
| |
//------------------------------------------------------------------------------
// Microsoft Avalon
// Copyright (c) Microsoft Corporation, 2001
//
// File: DrawingVisual.cs
//------------------------------------------------------------------------------
using System;
using System.Windows.Threading;
using System.Windows.Media;
using System.Windows.Media.Composition;
using System.Diagnostics;
using System.Collections.Generic;
using MS.Internal;
using MS.Win32;
using System.Resources;
using System.Runtime.InteropServices;
namespace System.Windows.Media
{
/// <summary>
/// A DrawingVisual is a Visual that can be used to render Vector graphics on the screen.
/// The content is persistet by the System.
/// </summary>
public class DrawingVisual : ContainerVisual
{
// bbox in inner coordinate space. Note that this bbox does not
// contain the childrens extent.
IDrawingContent _content;
/// <summary>
/// HitTestCore implements precise hit testing against render contents
/// </summary>
protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters)
{
if (hitTestParameters == null)
{
throw new ArgumentNullException("hitTestParameters");
}
if (_content != null)
{
if (_content.HitTestPoint(hitTestParameters.HitPoint))
{
return new PointHitTestResult(this, hitTestParameters.HitPoint);
}
}
return null;
}
/// <summary>
/// HitTestCore implements precise hit testing against render contents
/// </summary>
protected override GeometryHitTestResult HitTestCore(GeometryHitTestParameters hitTestParameters)
{
if (hitTestParameters == null)
{
throw new ArgumentNullException("hitTestParameters");
}
if ((_content != null) && GetHitTestBounds().IntersectsWith(hitTestParameters.Bounds))
{
IntersectionDetail intersectionDetail;
intersectionDetail = _content.HitTestGeometry(hitTestParameters.InternalHitGeometry);
Debug.Assert(intersectionDetail != IntersectionDetail.NotCalculated);
if (intersectionDetail != IntersectionDetail.Empty)
{
return new GeometryHitTestResult(this, intersectionDetail);
}
}
return null;
}
/// <summary>
/// Opens the DrawingVisual for rendering. The returned DrawingContext can be used to
/// render into the DrawingVisual.
/// </summary>
public DrawingContext RenderOpen()
{
VerifyAPIReadWrite();
return new VisualDrawingContext(this);
}
/// <summary>
/// Called from the DrawingContext when the DrawingContext is closed.
/// </summary>
internal override void RenderClose(IDrawingContent newContent)
{
IDrawingContent oldContent;
//
// First cleanup the old content and the state associate with this node
// related to it's content.
//
oldContent = _content;
_content = null;
if (oldContent != null)
{
//
// Remove the notification handlers.
//
oldContent.PropagateChangedHandler(ContentsChangedHandler, false /* remove */);
//
// Disconnect the old content from this visual.
//
DisconnectAttachedResource(
VisualProxyFlags.IsContentConnected,
((DUCE.IResource)oldContent));
}
//
// Prepare the new content.
//
if (newContent != null)
{
// Propagate notification handlers.
newContent.PropagateChangedHandler(ContentsChangedHandler, true /* adding */);
}
_content = newContent;
//
// Mark the visual dirty on all channels and propagate
// the flags up the parent chain.
//
SetFlagsOnAllChannels(true, VisualProxyFlags.IsContentDirty);
PropagateFlags(
this,
VisualFlags.IsSubtreeDirtyForPrecompute,
VisualProxyFlags.IsSubtreeDirtyForRender);
}
/// <summary>
/// Overriding this function to release DUCE resources during Dispose and during removal of a subtree.
/// </summary>
internal override void FreeContent(DUCE.Channel channel)
{
Debug.Assert(_proxy.IsOnChannel(channel));
if (_content != null)
{
if (CheckFlagsAnd(channel, VisualProxyFlags.IsContentConnected))
{
DUCE.CompositionNode.SetContent(
_proxy.GetHandle(channel),
DUCE.ResourceHandle.Null,
channel);
SetFlags(
channel,
false,
VisualProxyFlags.IsContentConnected);
((DUCE.IResource)_content).ReleaseOnChannel(channel);
}
}
// Call the base method too
base.FreeContent(channel);
}
/// <summary>
/// Returns the bounding box of the content.
/// </summary>
internal override Rect GetContentBounds()
{
if (_content != null)
{
Rect resultRect = Rect.Empty;
MediaContext mediaContext = MediaContext.From(Dispatcher);
BoundsDrawingContextWalker ctx = mediaContext.AcquireBoundsDrawingContextWalker();
resultRect = _content.GetContentBounds(ctx);
mediaContext.ReleaseBoundsDrawingContextWalker(ctx);
return resultRect;
}
else
{
return Rect.Empty;
}
}
/// <summary>
/// WalkContent - method which walks the content (if present) and calls out to the
/// supplied DrawingContextWalker.
/// </summary>
/// <param name="walker">
/// DrawingContextWalker - the target of the calls which occur during
/// the content walk.
/// </param>
internal void WalkContent(DrawingContextWalker walker)
{
VerifyAPIReadOnly();
if (_content != null)
{
_content.WalkContent(walker);
}
}
/// <summary>
/// RenderContent is implemented by derived classes to hook up their
/// content. The implementer of this function can assert that the _hCompNode
/// is valid on a channel when the function is executed.
/// </summary>
internal override void RenderContent(RenderContext ctx, bool isOnChannel)
{
DUCE.Channel channel = ctx.Channel;
Debug.Assert(!CheckFlagsAnd(channel, VisualProxyFlags.IsContentConnected));
Debug.Assert(_proxy.IsOnChannel(channel));
//
// Create the content on the channel.
//
if (_content != null)
{
DUCE.CompositionNode.SetContent(
_proxy.GetHandle(channel),
((DUCE.IResource)_content).AddRefOnChannel(channel),
channel);
SetFlags(
channel,
true,
VisualProxyFlags.IsContentConnected);
}
else if (isOnChannel) /*_content == null*/
{
DUCE.CompositionNode.SetContent(
_proxy.GetHandle(channel),
DUCE.ResourceHandle.Null,
channel);
}
}
/// <summary>
/// GetDrawing - Returns the drawing content of this Visual.
/// </summary>
/// <remarks>
/// Changes to this DrawingGroup will not be propagated to the Visual's content.
/// This method is called by both the Drawing property, and VisualTreeHelper.GetDrawing()
/// </remarks>
internal override DrawingGroup GetDrawing()
{
//
VerifyAPIReadOnly();
DrawingGroup drawingGroupContent = null;
// Convert our content to a DrawingGroup, if content exists
if (_content != null)
{
drawingGroupContent = DrawingServices.DrawingGroupFromRenderData((RenderData) _content);
}
return drawingGroupContent;
}
/// <summary>
/// Drawing - Returns the drawing content of this Visual.
/// </summary>
/// <remarks>
/// Changes to this DrawingGroup will not propagated to the Visual's content.
/// </remarks>
public DrawingGroup Drawing
{
get
{
return GetDrawing();
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.DDF
{
using System;
using System.Text;
using System.Collections.Generic;
using System.IO;
using NUnit.Framework;
using NPOI.DDF;
using NPOI.Util;
using System.Configuration;
[TestFixture]
public class TestEscherContainerRecord
{
private String ESCHER_DATA_PATH;
public TestEscherContainerRecord()
{
ESCHER_DATA_PATH = ConfigurationManager.AppSettings["escher.data.path"];
}
[Test]
public void TestFillFields()
{
IEscherRecordFactory f = new DefaultEscherRecordFactory();
byte[] data = HexRead.ReadFromString("0F 02 11 F1 00 00 00 00");
EscherRecord r = f.CreateRecord(data, 0);
r.FillFields(data, 0, f);
Assert.IsTrue(r is EscherContainerRecord);
Assert.AreEqual((short)0x020F, r.Options);
Assert.AreEqual(unchecked((short)0xF111), r.RecordId);
data = HexRead.ReadFromString("0F 02 11 F1 08 00 00 00" +
" 02 00 22 F2 00 00 00 00");
r = f.CreateRecord(data, 0);
r.FillFields(data, 0, f);
EscherRecord c = r.GetChild(0);
Assert.IsFalse(c is EscherContainerRecord);
Assert.AreEqual(unchecked((short)0x0002), c.Options);
Assert.AreEqual(unchecked((short)0xF222), c.RecordId);
}
[Test]
public void TestSerialize()
{
UnknownEscherRecord r = new UnknownEscherRecord();
r.Options=(short)0x123F;
r.RecordId=unchecked((short)0xF112);
byte[] data = new byte[8];
r.Serialize(0, data);
Assert.AreEqual("[3F, 12, 12, F1, 00, 00, 00, 00]", HexDump.ToHex(data));
EscherRecord childRecord = new UnknownEscherRecord();
childRecord.Options=unchecked((short)0x9999);
childRecord.RecordId=unchecked((short)0xFF01);
r.AddChildRecord(childRecord);
data = new byte[16];
r.Serialize(0, data);
Assert.AreEqual("[3F, 12, 12, F1, 08, 00, 00, 00, 99, 99, 01, FF, 00, 00, 00, 00]", HexDump.ToHex(data));
}
[Test]
public void TestToString()
{
EscherContainerRecord r = new EscherContainerRecord();
r.RecordId=EscherContainerRecord.SP_CONTAINER;
r.Options=(short)0x000F;
String nl = Environment.NewLine;
Assert.AreEqual("EscherContainerRecord (SpContainer):" + nl +
" isContainer: True" + nl +
" version: 0x000F" + nl +
" instance: 0x0000" + nl +
" recordId: 0xF004" + nl +
" numchildren: 0" + nl
, r.ToString());
EscherOptRecord r2 = new EscherOptRecord();
// don't try to shoot in foot, please -- vlsergey
// r2.setOptions((short) 0x9876);
r2.RecordId=EscherOptRecord.RECORD_ID;
String expected;
r.AddChildRecord(r2);
expected = "EscherContainerRecord (SpContainer):" + nl +
" isContainer: True" + nl +
" version: 0x000F" + nl +
" instance: 0x0000" + nl +
" recordId: 0xF004" + nl +
" numchildren: 1" + nl +
" children: " + nl +
" Child 0:" + nl +
" EscherOptRecord:" + nl +
" isContainer: False" + nl +
" version: 0x0003" + nl +
" instance: 0x0000" + nl +
" recordId: 0xF00B" + nl +
" numchildren: 0" + nl +
" properties:" + nl +
" " + nl;
Assert.AreEqual(expected, r.ToString());
r.AddChildRecord(r2);
expected = "EscherContainerRecord (SpContainer):" + nl +
" isContainer: True" + nl +
" version: 0x000F" + nl +
" instance: 0x0000" + nl +
" recordId: 0xF004" + nl +
" numchildren: 2" + nl +
" children: " + nl +
" Child 0:" + nl +
" EscherOptRecord:" + nl +
" isContainer: False" + nl +
" version: 0x0003" + nl +
" instance: 0x0000" + nl +
" recordId: 0xF00B" + nl +
" numchildren: 0" + nl +
" properties:" + nl +
" " + nl +
" Child 1:" + nl +
" EscherOptRecord:" + nl +
" isContainer: False" + nl +
" version: 0x0003" + nl +
" instance: 0x0000" + nl +
" recordId: 0xF00B" + nl +
" numchildren: 0" + nl +
" properties:" + nl +
" " + nl;
Assert.AreEqual(expected, r.ToString());
}
private class DummyEscherRecord : EscherRecord
{
public DummyEscherRecord() { }
public override int FillFields(byte[] data, int offset, IEscherRecordFactory recordFactory)
{ return 0; }
public override int Serialize(int offset, byte[] data, EscherSerializationListener listener)
{ return 0; }
public override int RecordSize { get { return 10; } }
public override String RecordName { get { return ""; } }
}
[Test]
public void TestRecordSize()
{
EscherContainerRecord r = new EscherContainerRecord();
r.AddChildRecord(new DummyEscherRecord());
Assert.AreEqual(18, r.RecordSize);
}
/**
* Ensure {@link EscherContainerRecord} doesn't spill its guts everywhere
*/
[Test]
public void TestChildren()
{
EscherContainerRecord ecr = new EscherContainerRecord();
List<EscherRecord> children0 = ecr.ChildRecords;
Assert.AreEqual(0, children0.Count);
EscherRecord chA = new DummyEscherRecord();
EscherRecord chB = new DummyEscherRecord();
EscherRecord chC = new DummyEscherRecord();
ecr.AddChildRecord(chA);
ecr.AddChildRecord(chB);
children0.Add(chC);
List<EscherRecord> children1 = ecr.ChildRecords;
Assert.IsTrue(children0 != children1);
Assert.AreEqual(2, children1.Count);
Assert.AreEqual(chA, children1[0]);
Assert.AreEqual(chB, children1[1]);
Assert.AreEqual(1, children0.Count); // first copy unchanged
ecr.ChildRecords=(children0);
ecr.AddChildRecord(chA);
List<EscherRecord> children2 = ecr.ChildRecords;
Assert.AreEqual(2, children2.Count);
Assert.AreEqual(chC, children2[0]);
Assert.AreEqual(chA, children2[1]);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Xml;
using OLEDB.Test.ModuleCore;
namespace XmlReaderTest.Common
{
public partial class TCInvalidXML : TCXMLReaderBaseGeneral
{
// Type is XmlReaderTest.Common.TCInvalidXML
// Test Case
public override void AddChildren()
{
// for function Read36a
{
this.AddChild(new CVariation(Read36a) { Attribute = new Variation("Read with surrogate in attr.val.begin") });
}
// for function Read36b
{
this.AddChild(new CVariation(Read36b) { Attribute = new Variation("Read with surrogate in attr.val.mid") });
}
// for function Read36c
{
this.AddChild(new CVariation(Read36c) { Attribute = new Variation("Read with surrogate in attr.val.end") });
}
// for function Read37
{
this.AddChild(new CVariation(Read37) { Attribute = new Variation("Read with surrogate in a DTD") });
}
// for function Read37a
{
this.AddChild(new CVariation(Read37a) { Attribute = new Variation("Read with surrogate in a DTD.begin") });
}
// for function Read37b
{
this.AddChild(new CVariation(Read37b) { Attribute = new Variation("Read with surrogate in a DTD.mid") });
}
// for function Read37c
{
this.AddChild(new CVariation(Read37c) { Attribute = new Variation("Read with surrogate in a DTD.end") });
}
// for function InvalidCommentCharacters
{
this.AddChild(new CVariation(InvalidCommentCharacters) { Attribute = new Variation("For non-wellformed XMLs, check for the line info in the error message") });
}
// for function FactoryReaderInvalidCharacter
{
this.AddChild(new CVariation(FactoryReaderInvalidCharacter) { Attribute = new Variation("The XmlReader is reporting errors with -ve column values") });
}
// for function Read1
{
this.AddChild(new CVariation(Read1) { Attribute = new Variation("Read with invalid content") });
}
// for function Read2
{
this.AddChild(new CVariation(Read2) { Attribute = new Variation("Read with invalid end tag") });
}
// for function Read3
{
this.AddChild(new CVariation(Read3) { Attribute = new Variation("Read with invalid name") });
}
// for function Read4
{
this.AddChild(new CVariation(Read4) { Attribute = new Variation("Read with invalid characters") });
}
// for function Read6
{
this.AddChild(new CVariation(Read6) { Attribute = new Variation("Read with missing root end element") });
}
// for function Read11
{
this.AddChild(new CVariation(Read11) { Attribute = new Variation("Read with invalid namespace") });
}
// for function Read12
{
this.AddChild(new CVariation(Read12) { Attribute = new Variation("Attribute containing invalid character &") });
}
// for function Read13
{
this.AddChild(new CVariation(Read13) { Attribute = new Variation("Incomplete DOCTYPE") });
}
// for function Read14
{
this.AddChild(new CVariation(Read14) { Attribute = new Variation("Undefined namespace") });
}
// for function Read15
{
this.AddChild(new CVariation(Read15) { Attribute = new Variation("Read an XML Fragment which has unclosed elements") });
}
// for function Read21
{
this.AddChild(new CVariation(Read21) { Attribute = new Variation("Read invalid PIs") });
}
// for function Read22
{
this.AddChild(new CVariation(Read22) { Attribute = new Variation("Tag name > 4K, invalid") });
}
// for function Read22a
{
this.AddChild(new CVariation(Read22a) { Attribute = new Variation("Surrogate char in name > 4K, invalid") });
}
// for function Read23
{
this.AddChild(new CVariation(Read23) { Attribute = new Variation("Line number/position of whitespace before external entity (regression)") });
}
// for function Read24a
{
this.AddChild(new CVariation(Read24a) { Attribute = new Variation("1.Valid XML declaration.Errata5") { Param = "1.0" } });
}
// for function Read25b
{
this.AddChild(new CVariation(Read25b) { Attribute = new Variation("4.Invalid XML declaration.version") { Param = "0.9" } });
this.AddChild(new CVariation(Read25b) { Attribute = new Variation("3.Invalid XML declaration.version") { Param = "0.1" } });
this.AddChild(new CVariation(Read25b) { Attribute = new Variation("1.Invalid XML declaration.version") { Param = "2.0" } });
this.AddChild(new CVariation(Read25b) { Attribute = new Variation("5.Invalid XML declaration.version") { Param = "1" } });
this.AddChild(new CVariation(Read25b) { Attribute = new Variation("6.Invalid XML declaration.version") { Param = "1.a" } });
this.AddChild(new CVariation(Read25b) { Attribute = new Variation("7.Invalid XML declaration.version") { Param = "#45" } });
this.AddChild(new CVariation(Read25b) { Attribute = new Variation("8.Invalid XML declaration.version") { Param = "\\uD812" } });
this.AddChild(new CVariation(Read25b) { Attribute = new Variation("2.Invalid XML declaration.version") { Param = "1.1." } });
}
// for function Read26b
{
this.AddChild(new CVariation(Read26b) { Attribute = new Variation("6.Invalid XML declaration.standalone") { Param = "0" } });
this.AddChild(new CVariation(Read26b) { Attribute = new Variation("2.Invalid XML declaration.standalone") { Param = "false" } });
this.AddChild(new CVariation(Read26b) { Attribute = new Variation("4.Invalid XML declaration.standalone") { Param = "No" } });
this.AddChild(new CVariation(Read26b) { Attribute = new Variation("5.Invalid XML declaration.standalone") { Param = "1" } });
this.AddChild(new CVariation(Read26b) { Attribute = new Variation("3.Invalid XML declaration.standalone") { Param = "Yes" } });
this.AddChild(new CVariation(Read26b) { Attribute = new Variation("7.Invalid XML declaration.standalone") { Param = "#45" } });
this.AddChild(new CVariation(Read26b) { Attribute = new Variation("8.Invalid XML declaration.standalone") { Param = "\\uD812" } });
this.AddChild(new CVariation(Read26b) { Attribute = new Variation("1.Invalid XML declaration.standalone") { Param = "true" } });
}
// for function Read28
{
this.AddChild(new CVariation(Read28) { Attribute = new Variation("Read with invalid surrogate inside comment") });
}
// for function Read29a
{
this.AddChild(new CVariation(Read29a) { Attribute = new Variation("Read with invalid surrogate inside comment.begin") });
}
// for function Read29b
{
this.AddChild(new CVariation(Read29b) { Attribute = new Variation("Read with invalid surrogate inside comment.mid") });
}
// for function Read29c
{
this.AddChild(new CVariation(Read29c) { Attribute = new Variation("Read with invalid surrogate inside comment.end") });
}
// for function Read30
{
this.AddChild(new CVariation(Read30) { Attribute = new Variation("Read with invalid surrogate inside PI") });
}
// for function Read30a
{
this.AddChild(new CVariation(Read30a) { Attribute = new Variation("Read with invalid surrogate inside PI.begin") });
}
// for function Read30b
{
this.AddChild(new CVariation(Read30b) { Attribute = new Variation("Read with invalid surrogate inside PI.mid") });
}
// for function Read30c
{
this.AddChild(new CVariation(Read30c) { Attribute = new Variation("Read with invalid surrogate inside PI.end") });
}
// for function Read31
{
this.AddChild(new CVariation(Read31) { Attribute = new Variation("Read an invalid character which is a lower part of the surrogate pair") });
}
// for function Read31a
{
this.AddChild(new CVariation(Read31a) { Attribute = new Variation("Read an invalid character which is a lower part of the surrogate pair.begin") });
}
// for function Read31b
{
this.AddChild(new CVariation(Read31b) { Attribute = new Variation("Read an invalid character which is a lower part of the surrogate pair.mid") });
}
// for function Read31c
{
this.AddChild(new CVariation(Read31c) { Attribute = new Variation("Read an invalid character which is a lower part of the surrogate pair.end") });
}
// for function Read32
{
this.AddChild(new CVariation(Read32) { Attribute = new Variation("Read with surrogate in a name") });
}
// for function Read32a
{
this.AddChild(new CVariation(Read32a) { Attribute = new Variation("Read with surrogate in a name.begin") });
}
// for function Read32b
{
this.AddChild(new CVariation(Read32b) { Attribute = new Variation("Read with surrogate in a name.mid") });
}
// for function Read32c
{
this.AddChild(new CVariation(Read32c) { Attribute = new Variation("Read with surrogate in a name.end") });
}
// for function Read33
{
this.AddChild(new CVariation(Read33) { Attribute = new Variation("Read with invalid surrogate inside text") });
}
// for function Read33a
{
this.AddChild(new CVariation(Read33a) { Attribute = new Variation("Read with invalid surrogate inside text.begin") });
}
// for function Read33b
{
this.AddChild(new CVariation(Read33b) { Attribute = new Variation("Read with invalid surrogate inside text.mid") });
}
// for function Read33c
{
this.AddChild(new CVariation(Read33c) { Attribute = new Variation("Read with invalid surrogate inside text.end") });
}
// for function Read34
{
this.AddChild(new CVariation(Read34) { Attribute = new Variation("Read with invalid surrogate inside CDATA") });
}
// for function Read34a
{
this.AddChild(new CVariation(Read34a) { Attribute = new Variation("Read with invalid surrogate inside CDATA.begin") });
}
// for function Read34b
{
this.AddChild(new CVariation(Read34b) { Attribute = new Variation("Read with invalid surrogate inside CDATA.mid") });
}
// for function Read34c
{
this.AddChild(new CVariation(Read34c) { Attribute = new Variation("Read with invalid surrogate inside CDATA.end") });
}
// for function Read35
{
this.AddChild(new CVariation(Read35) { Attribute = new Variation("Read with surrogate in attr.name") });
}
// for function Read35a
{
this.AddChild(new CVariation(Read35a) { Attribute = new Variation("Read with surrogate in attr.name.begin") });
}
// for function Read35b
{
this.AddChild(new CVariation(Read35b) { Attribute = new Variation("Read with surrogate in attr.name.mid") });
}
// for function Read35c
{
this.AddChild(new CVariation(Read35c) { Attribute = new Variation("Read with surrogate in attr.name.end") });
}
// for function Read36
{
this.AddChild(new CVariation(Read36) { Attribute = new Variation("Read with surrogate in attr.val") });
}
}
}
}
| |
/* Copyright 2006 Mark Elliot
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace BackTrackSat
{
public class DPSearch
{
int m, // vars
n; // clauses
Clause[] c;
bool[] final;
public bool[] EmptyXArray()
{
int i;
bool[] x = new bool[m];
for(i = 0; i < m; i++)
{
x[i] = false;
}
return x;
}
public bool Run()
{
bool[] x;
bool[] a;
x = this.EmptyXArray();
a = this.EmptyXArray();
return this.Run(x, a, 0);
}
/**
* bool[] x variable assignment
* bool[] a assigned variable?
* int i number of variables assigned
*/
public bool Run(bool[] x, bool[] a, int i)
{
int res, unit, difi;
res = Truth(x, a);
if(res < 0){ // early termination
return false;
}
if(res > 0){
this.final = x;
return true; // if this is a satisfying assignment, stop
}
if(i < m){
// does a unit clause exist?
if((unit = FindUnitClause(x, a)) != 0){
// found a unit clause, set var
a[Math.Abs(unit)-1] = true;
x[Math.Abs(unit)-1] = (unit > 0);
if( Run(x, a, i+1) )
{
return true;
}else{
a[Math.Abs(unit)-1] = false;
return false;
}
}
//Console.WriteLine(i + " " + PrintX(x));
difi = GetFirstUnassigned(a); // gets an unset var.
//if(difi == -1){ return false; }
difi = i;
a[difi] = true;
x[difi] = false;
if( Run(x, a, i+1) ){ return true; }
// if we get here, we need to flip the var.
x[difi] = true;
if( Run(x, a, i+1) ){ return true; }else{ a[difi] = false; return false; }
}
return false;
}
public bool[] Final()
{
return this.final;
}
public string PrintX(bool[] x)
{
int i;
string output = "";
for(i = 0; i < x.Length; i++)
{
output += (x[i]) ? "1" : "0";
}
return output;
}
/**
* string filepath Path to definition file
*
* returns alpha
*
* Post: Populates m, n, c and inits x
*/
public float LoadFile(string filepath)
{
int i;
String my_line; // storage for reading a line.
String[] my_expl; // explosion storage
int vars;
bool[] var_used;
try{
System.IO.StreamReader sr = System.IO.File.OpenText(filepath);
my_line = sr.ReadLine();
// first line contains some very necessary vars (namely #clauses, #vars)
my_expl = my_line.Split(' ');
m = int.Parse(my_expl[2]);
n = int.Parse(my_expl[3]);
c = new Clause[n]; // n clauses
var_used = new bool[m];
vars = 0;
for(i = 0; i < m; i++){ var_used[i] = false; }
i = 0;
my_line = sr.ReadLine();
while( my_line != null )
{
my_expl = my_line.Split(' ');
c[i] = new Clause(int.Parse(my_expl[0]),
int.Parse(my_expl[1]),
int.Parse(my_expl[2]));
if(!var_used[c[i].c1-1]){
var_used[c[i].c1-1] = true;
vars++;
}
if(!var_used[c[i].c2-1]){
var_used[c[i].c2-1] = true;
vars++;
}
if(!var_used[c[i].c3-1]){
var_used[c[i].c3-1] = true;
vars++;
}
my_line = sr.ReadLine();
i++;
}
sr.Close();
return (float)n / (float)vars;
}catch(Exception e){
Console.WriteLine("" + e.Message);
}
return 0;
}
int Truth(bool[] x, bool[] a)
{
int i, r;
for(i = 0; i < n; i++)
{
r = c[i].Eval(x, a);
if(r == 0){ return 0; }
if(r == -1){ return -1; }
}
return 1;
}
int FindUnitClause(bool[] x, bool[] a)
{
int i, r;
for(i = 0; i < n; i++)
{
r = c[i].UnitClause(x, a);
if(r != 0){ return r; }
}
return 0;
}
static int GetFirstUnassigned(bool[] a)
{
int i;
for(i = 0; i < a.Length; i++)
{
if(!a[i]) return i;
}
return -1;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2008 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
using NUnit.Framework.Interfaces;
using NUnit.TestData.TestMethodSignatureFixture;
using NUnit.TestUtilities;
namespace NUnit.Framework.Internal
{
[TestFixture]
public class TestMethodSignatureTests
{
private static Type fixtureType = typeof(TestMethodSignatureFixture);
[Test]
public void InstanceTestMethodIsRunnable()
{
TestAssert.IsRunnable( fixtureType, "InstanceTestMethod" );
}
[Test]
public void StaticTestMethodIsRunnable()
{
TestAssert.IsRunnable( fixtureType, "StaticTestMethod" );
}
[Test]
public void TestMethodWithoutParametersWithArgumentsProvidedIsNotRunnable()
{
TestAssert.ChildNotRunnable(fixtureType, "TestMethodWithoutParametersWithArgumentsProvided");
}
[Test]
public void TestMethodWithArgumentsNotProvidedIsNotRunnable()
{
TestAssert.IsNotRunnable(fixtureType, "TestMethodWithArgumentsNotProvided");
}
[Test]
public void TestMethodHasAttributesAppliedCorrectlyEvenIfNotRunnable()
{
var test = TestBuilder.MakeTestCase(fixtureType, "TestMethodWithArgumentsNotProvidedAndExtraAttributes");
// NOTE: IgnoreAttribute has no effect, either on RunState or on the reason
Assert.That(test.RunState == RunState.NotRunnable);
Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("No arguments were provided"));
Assert.That(test.Properties.Get(PropertyNames.Description), Is.EqualTo("My test"));
Assert.That(test.Properties.Get(PropertyNames.MaxTime), Is.EqualTo(47));
}
[Test]
public void TestMethodWithArgumentsProvidedIsRunnable()
{
TestAssert.IsRunnable(fixtureType, "TestMethodWithArgumentsProvided");
}
[Test]
public void TestMethodWithWrongNumberOfArgumentsProvidedIsNotRunnable()
{
TestAssert.ChildNotRunnable(fixtureType, "TestMethodWithWrongNumberOfArgumentsProvided");
}
[Test]
public void TestMethodWithWrongArgumentTypesProvidedGivesError()
{
TestAssert.IsRunnable(fixtureType, "TestMethodWithWrongArgumentTypesProvided", ResultState.Error);
}
[Test]
public void StaticTestMethodWithArgumentsNotProvidedIsNotRunnable()
{
TestAssert.IsNotRunnable(fixtureType, "StaticTestMethodWithArgumentsNotProvided");
}
[Test]
public void StaticTestMethodWithArgumentsProvidedIsRunnable()
{
TestAssert.IsRunnable(fixtureType, "StaticTestMethodWithArgumentsProvided");
}
[Test]
public void StaticTestMethodWithWrongNumberOfArgumentsProvidedIsNotRunnable()
{
TestAssert.ChildNotRunnable(fixtureType, "StaticTestMethodWithWrongNumberOfArgumentsProvided");
}
[Test]
public void StaticTestMethodWithWrongArgumentTypesProvidedGivesError()
{
TestAssert.IsRunnable(fixtureType, "StaticTestMethodWithWrongArgumentTypesProvided", ResultState.Error);
}
[Test]
public void TestMethodWithConvertibleArgumentsIsRunnable()
{
TestAssert.IsRunnable(fixtureType, "TestMethodWithConvertibleArguments");
}
[Test]
public void TestMethodWithNonConvertibleArgumentsGivesError()
{
TestAssert.IsRunnable(fixtureType, "TestMethodWithNonConvertibleArguments", ResultState.Error);
}
[Test]
public void ProtectedTestMethodIsNotRunnable()
{
TestAssert.IsNotRunnable( fixtureType, "ProtectedTestMethod" );
}
[Test]
public void PrivateTestMethodIsNotRunnable()
{
TestAssert.IsNotRunnable( fixtureType, "PrivateTestMethod" );
}
[Test]
public void TestMethodWithReturnTypeIsNotRunnable()
{
TestAssert.IsNotRunnable( fixtureType, "TestMethodWithReturnType" );
}
[Test]
public void TestMethodWithExpectedReturnTypeIsRunnable()
{
TestAssert.IsRunnable(fixtureType, "TestMethodWithExpectedReturnType");
}
[Test]
public void TestMethodWithMultipleTestCasesExecutesMultipleTimes()
{
ITestResult result = TestBuilder.RunParameterizedMethodSuite(fixtureType, "TestMethodWithMultipleTestCases");
Assert.That( result.ResultState, Is.EqualTo(ResultState.Success) );
ResultSummary summary = new ResultSummary(result);
Assert.That(summary.TestsRun, Is.EqualTo(3));
}
[Test]
public void TestMethodWithMultipleTestCasesUsesCorrectNames()
{
string name = "TestMethodWithMultipleTestCases";
string fullName = typeof (TestMethodSignatureFixture).FullName + "." + name;
TestSuite suite = TestBuilder.MakeParameterizedMethodSuite(fixtureType, name);
Assert.That(suite.TestCaseCount, Is.EqualTo(3));
var names = new List<string>();
var fullNames = new List<string>();
foreach (Test test in suite.Tests)
{
names.Add(test.Name);
fullNames.Add(test.FullName);
}
Assert.That(names, Has.Member(name + "(12,3,4)"));
Assert.That(names, Has.Member(name + "(12,2,6)"));
Assert.That(names, Has.Member(name + "(12,4,3)"));
Assert.That(fullNames, Has.Member(fullName + "(12,3,4)"));
Assert.That(fullNames, Has.Member(fullName + "(12,2,6)"));
Assert.That(fullNames, Has.Member(fullName + "(12,4,3)"));
}
[Test]
public void RunningTestsThroughFixtureGivesCorrectResults()
{
ITestResult result = TestBuilder.RunTestFixture(fixtureType);
ResultSummary summary = new ResultSummary(result);
Assert.That(
summary.ResultCount,
Is.EqualTo(TestMethodSignatureFixture.Tests));
Assert.That(
summary.TestsRun,
Is.EqualTo(TestMethodSignatureFixture.Tests));
Assert.That(
summary.Failed,
Is.EqualTo(TestMethodSignatureFixture.Failures + TestMethodSignatureFixture.Errors + TestMethodSignatureFixture.NotRunnable));
Assert.That(
summary.Skipped,
Is.EqualTo(0));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Dynamsoft.UVC;
using Dynamsoft.Core;
using System.IO;
using System.Runtime.InteropServices;
using Dynamsoft.Common;
namespace WebcamDemo
{
public partial class Form1 : Form
{
private int m_iDesignWidth = 755;
private int iControlWidth = 275;
private int iControlHeight = 295;
private CameraManager m_CameraManager = null;
private ImageCore m_ImageCore = null;
private string m_StrProductKey = "t0068UwAAAEQABDxqjGfgEzhVYureL0kGxugcsvIqCDGTPTsR5nLaQsNupIc17Y5vpMZAWBDsd6Xw3NMYzdHlHwiKUrfe/cU=";
private Camera m_CurrentCamera = null;
public Form1()
{
InitializeComponent();
m_CameraManager = new CameraManager(m_StrProductKey);
m_ImageCore = new ImageCore();
dsViewer1.Bind(m_ImageCore);
this.Load += new EventHandler(Form1_Load);
}
void Form1_Load(object sender, EventArgs e)
{
try
{
m_iDesignWidth = this.Width;
if (m_CameraManager.GetCameraNames()!=null)
{
foreach (string temp in m_CameraManager.GetCameraNames())
{
cbxSources.Items.Add(temp);
}
cbxSources.SelectedIndexChanged += cbxSources_SelectedIndexChanged;
if (cbxSources.Items.Count > 0)
cbxSources.SelectedIndex = 0;
}
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
private void btnRemoveAllImages_Click(object sender, EventArgs e)
{
m_ImageCore.ImageBuffer.RemoveAllImages();
}
private void btnCaptureImage_Click(object sender, EventArgs e)
{
if(m_CurrentCamera!=null)
{
Bitmap tempBmp = m_CurrentCamera.GrabImage();
m_ImageCore.IO.LoadImage(tempBmp);
}
}
private void cbxSources_SelectedIndexChanged(object sender, EventArgs e)
{
if (m_CurrentCamera != null)
{
m_CurrentCamera.OnFrameCaptrue -= m_CurrentCamera_OnFrameCaptrue;
m_CurrentCamera.Close();
}
if (m_CameraManager != null)
{
m_CurrentCamera = m_CameraManager.SelectCamera((short)cbxSources.SelectedIndex);
m_CurrentCamera.Open();
m_CurrentCamera.OnFrameCaptrue += m_CurrentCamera_OnFrameCaptrue;
ResizePictureBox();
}
if (m_CurrentCamera != null)
{
cbxResolution.Items.Clear();
foreach (CamResolution camR in m_CurrentCamera.SupportedResolutions)
{
cbxResolution.Items.Add(camR.ToString());
}
cbxResolution.SelectedIndexChanged += cbxResolution_SelectedIndexChanged;
if (cbxResolution.Items.Count > 0)
cbxResolution.SelectedIndex = 0;
ResizePictureBox();
}
}
private void cbxResolution_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbxResolution.Text != null)
{
string[] strWXH = cbxResolution.Text.Split(new char[] { ' ' });
if (strWXH.Length == 3)
{
try
{
m_CurrentCamera.CurrentResolution = new CamResolution(int.Parse(strWXH[0]), int.Parse(strWXH[2]));
}
catch { }
}
m_CurrentCamera.RotateVideo(Dynamsoft.UVC.Enums.EnumVideoRotateType.Rotate_0);
ResizePictureBox();
}
}
private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
Point tempPoint = new Point(e.X,e.Y);
float tempWidth = pictureBox1.Width;
float tempHeight = pictureBox1.Height;
float imageWidth = m_CurrentCamera.CurrentResolution.Width;
float imageHeight = m_CurrentCamera.CurrentResolution.Height;
float zoomX = imageWidth / tempWidth;
float zoomY = imageHeight / tempHeight;
Point tempFocusPoint = new Point((int)(e.X * imageWidth),(int)(e.Y*imageHeight));
Rectangle tempRect = new Rectangle(tempFocusPoint,new Size(50,50));
m_CurrentCamera.FocusOnArea(tempRect);
}
private void ResizePictureBox()
{
if (m_CurrentCamera != null)
{
CamResolution camResolution = m_CurrentCamera.CurrentResolution;
if (camResolution != null && camResolution.Width > 0 && camResolution.Height > 0)
{
{
int iVideoWidth = iControlWidth;
int iVideoHeight = iControlWidth * camResolution.Height / camResolution.Width;
int iContentHeight = panel1.Height - panel1.Margin.Top - panel1.Margin.Bottom - panel1.Padding.Top - panel1.Padding.Bottom;
if (iVideoHeight < iContentHeight)
{
pictureBox1.Location = new Point(0, (iContentHeight - iVideoHeight) / 2);
pictureBox1.Size = new Size(iVideoWidth, iVideoHeight);
}
else
{
pictureBox1.Location = new Point(0, 0);
pictureBox1.Size = new Size(pictureBox1.Width, pictureBox1.Height);
}
}
}
}
}
private void RotatePictureBox()
{
if (m_CurrentCamera != null)
{
CamResolution camResolution = m_CurrentCamera.CurrentResolution;
if (camResolution != null && camResolution.Width > 0 && camResolution.Height > 0)
{
if (camResolution.Width / camResolution.Height > iControlWidth / iControlHeight)
{
int iVideoHeight = iControlHeight;
int iVideoWidth = iControlHeight * camResolution.Height / camResolution.Width;
int iContentWidth = panel1.Width - panel1.Margin.Left - panel1.Margin.Right - panel1.Padding.Left - panel1.Padding.Right;
pictureBox1.Location = new Point((iContentWidth - iVideoWidth) / 2, 0);
pictureBox1.Size = new Size(iVideoWidth, iVideoHeight);
}
else
{
int iVideoWidth = iControlWidth;
int iVideoHeight = iControlWidth * camResolution.Width / camResolution.Height;
int iContentHeight = panel1.Height - panel1.Margin.Top - panel1.Margin.Bottom - panel1.Padding.Top - panel1.Padding.Bottom;
pictureBox1.Location = new Point(0, (iContentHeight - iVideoHeight) / 2);
pictureBox1.Size = new Size(iVideoWidth, iVideoHeight);
}
}
}
}
private void SetPicture(Image img)
{
Bitmap temp = ((Bitmap)(img)).Clone(new Rectangle(0, 0, img.Width, img.Height), img.PixelFormat);
if (pictureBox1.InvokeRequired)
{
pictureBox1.BeginInvoke(new MethodInvoker(
delegate ()
{
pictureBox1.Image = temp;
}));
}
else
{
pictureBox1.Image = temp;
}
}
private void picbox90_Click(object sender, EventArgs e)
{
m_CurrentCamera.RotateVideo(Dynamsoft.UVC.Enums.EnumVideoRotateType.Rotate_90);
RotatePictureBox();
}
private void picbox180_Click(object sender, EventArgs e)
{
m_CurrentCamera.RotateVideo(Dynamsoft.UVC.Enums.EnumVideoRotateType.Rotate_180);
ResizePictureBox();
}
private void picbox270_Click(object sender, EventArgs e)
{
m_CurrentCamera.RotateVideo(Dynamsoft.UVC.Enums.EnumVideoRotateType.Rotate_270);
RotatePictureBox();
}
void m_CurrentCamera_OnFrameCaptrue(Bitmap bitmap)
{
SetPicture(bitmap);
}
private void picbox90_MouseHover(object sender, EventArgs e)
{
picbox90.Image = global::WebcamDemo.Properties.Resources._90_hover;
}
private void picbox90_MouseLeave(object sender, EventArgs e)
{
picbox90.Image = global::WebcamDemo.Properties.Resources._90_normal;
}
private void picbox180_MouseHover(object sender, EventArgs e)
{
picbox180.Image = global::WebcamDemo.Properties.Resources._180_hover;
}
private void picbox180_MouseLeave(object sender, EventArgs e)
{
picbox180.Image = global::WebcamDemo.Properties.Resources._180_normal;
}
private void picbox270_MouseHover(object sender, EventArgs e)
{
picbox270.Image = global::WebcamDemo.Properties.Resources._270_hover;
}
private void picbox270_MouseLeave(object sender, EventArgs e)
{
picbox270.Image = global::WebcamDemo.Properties.Resources._270_normal;
}
}
}
| |
// 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 OLEDB.Test.ModuleCore;
using System.IO;
using System.Text;
using XmlCoreTest.Common;
namespace System.Xml.Tests
{
/// <summary>
/// Summary description for WriterFactory.
/// </summary>
public class CWriterFactory : CFactory
{
protected enum WriterType
{
UTF8Writer,
UnicodeWriter
};
protected enum WriteThru
{
Stream,
StringBuilder,
TextWriter,
XmlWriter
};
protected enum WriterOverload
{
StringBuilder,
StringWriter,
StreamWriter,
MemoryStream,
TextWriter,
UTF8Writer,
UnicodeWriter
};
private XmlWriter _factoryWriter = null;
private XmlWriter _underlyingWriter = null;
private Stream _stream = null;
private StringBuilder _stringBuilder = null;
private TextWriter _textWriter = null;
private XmlWriterSettings _settings = new XmlWriterSettings();
private XmlWriterSettings _underlyingSettings = new XmlWriterSettings();
private WriterOverload _overload;
protected override void PreTest()
{
Log("In Pretest...");
SetupSettings();
Log("SetupSettings Done");
SetupWriterOverload();
Log("SetupWriterOverload Done");
pstate = TestState.PreTest;
}
protected override void Test()
{
Log("Testing : " + TestFileName);
Log("Overload : " + _overload);
switch (_overload)
{
case WriterOverload.MemoryStream:
_stream = new MemoryStream();
CreateWriter(WriteThru.Stream);
break;
case WriterOverload.StreamWriter:
_textWriter = new StreamWriter(new MemoryStream());
CreateWriter(WriteThru.TextWriter);
break;
case WriterOverload.StringBuilder:
_stringBuilder = new StringBuilder();
CreateWriter(WriteThru.StringBuilder);
break;
case WriterOverload.StringWriter:
_textWriter = new StringWriter();
CreateWriter(WriteThru.TextWriter);
break;
case WriterOverload.UnicodeWriter:
_underlyingSettings = new XmlWriterSettings();
_underlyingSettings.Encoding = Encoding.Unicode;
_underlyingWriter = WriterHelper.Create(TestFileName, _underlyingSettings);
CreateWriter(WriteThru.XmlWriter);
break;
case WriterOverload.UTF8Writer:
_underlyingSettings = new XmlWriterSettings();
_underlyingSettings.Encoding = Encoding.UTF8;
_underlyingWriter = WriterHelper.Create(TestFileName, _underlyingSettings);
CreateWriter(WriteThru.XmlWriter);
break;
default:
throw new CTestFailedException("Unknown WriterOverload: " + _overload);
}
if (pstate == TestState.Pass)
return;
CError.Compare(pstate, TestState.CreateSuccess, "Invalid State after Create: " + pstate);
//By this time the factory Reader is already set up correctly. So we must go Consume it now.
CError.Compare(pstate != TestState.Pass && pstate == TestState.CreateSuccess, "Invalid state before Consuming Reader: " + pstate);
//Call TestWriter to Consume Reader;
TestWriter();
if (pstate == TestState.Pass) return;
CError.Compare(pstate != TestState.Pass && pstate == TestState.Consume, "Invalid state after Consuming Reader: " + pstate);
}
protected void TestWriter()
{
pstate = TestState.Consume;
try
{
WriteNodes();
if (!IsVariationValid)
{
//Invalid Case didn't throw exception.
pstate = TestState.Error;
DumpVariationInfo();
throw new CTestFailedException("Invalid Variation didn't throw exception");
}
else
{
pstate = TestState.Pass;
}
}
catch (XmlException writerException)
{
Log(writerException.Message);
Log(writerException.StackTrace);
if (!IsVariationValid)
{
if (!CheckException(writerException))
{
pstate = TestState.Error;
DumpVariationInfo();
throw new CTestFailedException("Invalid Exception Type thrown");
}
else
{
pstate = TestState.Pass;
}
}
else //Variation was valid
{
pstate = TestState.Error;
DumpVariationInfo();
throw new CTestFailedException("Valid Variation throws Unspecified Exception");
}
}
finally
{
if (_factoryWriter != null && _factoryWriter.WriteState != WriteState.Closed && _factoryWriter.WriteState != WriteState.Error)
{
if (_textWriter == null)
{
CError.WriteLineIgnore(_factoryWriter.WriteState.ToString());
_factoryWriter.Flush();
_factoryWriter.Dispose();
}
else
{
_textWriter.Flush();
_textWriter.Dispose();
}
}
if (_underlyingWriter != null && _underlyingWriter.WriteState != WriteState.Closed && _underlyingWriter.WriteState != WriteState.Error)
{
_underlyingWriter.Flush();
_underlyingWriter.Dispose();
}
}
//If you are not in PASS state at this point you are in Error.
if (pstate != TestState.Pass)
pstate = TestState.Error;
}
protected void CompareSettings()
{
XmlWriterSettings actual = _factoryWriter.Settings;
CError.Compare(actual.CheckCharacters, _settings.CheckCharacters, "CheckCharacters");
//This actually checks Conformance Level DCR to some extent.
if (_settings.ConformanceLevel != ConformanceLevel.Auto)
CError.Compare(actual.ConformanceLevel, _settings.ConformanceLevel, "ConformanceLevel");
CError.Compare(actual.Encoding, _settings.Encoding, "Encoding");
CError.Compare(actual.Indent, _settings.Indent, "Indent");
CError.Compare(actual.IndentChars, _settings.IndentChars, "IndentChars");
CError.Compare(actual.NewLineChars, _settings.NewLineChars, "NewLineChars");
CError.Compare(actual.NewLineOnAttributes, _settings.NewLineOnAttributes, "NewLineOnAttributes");
CError.Compare(actual.NewLineHandling, _settings.NewLineHandling, "NormalizeNewLines");
CError.Compare(actual.OmitXmlDeclaration, _settings.OmitXmlDeclaration, "OmitXmlDeclaration");
}
protected void CreateWriter(WriteThru writeThru)
{
// Assumption is that the Create method doesn't throw NullReferenceException and
// it is not the goal of this framework to test if they are thrown anywhere.
// but if they are thrown that's a problem and they shouldn't be caught but exposed.
Log("Writing thru : " + writeThru);
try
{
switch (writeThru)
{
case WriteThru.Stream:
_factoryWriter = WriterHelper.Create(_stream, _settings);
break;
case WriteThru.StringBuilder:
_factoryWriter = WriterHelper.Create(_stringBuilder, _settings);
break;
case WriteThru.TextWriter:
_factoryWriter = WriterHelper.Create(_textWriter, _settings);
break;
case WriteThru.XmlWriter:
_factoryWriter = WriterHelper.Create(_underlyingWriter, _settings);
break;
}
pstate = TestState.CreateSuccess;
}
catch (Exception ane)
{
Log(ane.ToString());
if (!IsVariationValid)
{
if (!CheckException(ane))
{
pstate = TestState.Error;
DumpVariationInfo();
throw new CTestFailedException(
"Exception Thrown in CreateMethod, is your variation data correct?");
}
else
{
//This means that the Exception was checked and everything is fine.
pstate = TestState.Pass;
}
}//Else valid variation threw exception
else
{
pstate = TestState.Error;
DumpVariationInfo();
throw new CTestFailedException(
"Exception Thrown in CreateMethod, is your variation data correct?");
}
}
}
protected override void PostTest()
{
pstate = TestState.Complete;
}
protected void SetupSettings()
{
_settings.ConformanceLevel = (ConformanceLevel)Enum.Parse(typeof(ConformanceLevel), ReadFilterCriteria("ConformanceLevel", true));
_settings.CheckCharacters = Boolean.Parse(ReadFilterCriteria("CheckCharacters", true));
_settings.CloseOutput = false;
_settings.Indent = Boolean.Parse(ReadFilterCriteria("Indent", true));
_settings.IndentChars = new String(Convert.ToChar(Int32.Parse(ReadFilterCriteria("IndentChars", true))), 1);
_settings.NewLineChars = new String(Convert.ToChar(Int32.Parse(ReadFilterCriteria("NewLineChars", true))), 1);
_settings.NewLineOnAttributes = Boolean.Parse(ReadFilterCriteria("NewLineOnAttributes", true));
if (Boolean.Parse(ReadFilterCriteria("NormalizeNewlines", true)))
_settings.NewLineHandling = NewLineHandling.Replace;
else
_settings.NewLineHandling = NewLineHandling.None;
_settings.OmitXmlDeclaration = Boolean.Parse(ReadFilterCriteria("OmitXmlDeclaration", true));
//Reading Writer Type to determine encoding and if the writer type is binary writer.
string wt = ReadFilterCriteria("WriterType", true);
if (wt == "TextWriter" || wt == "XmlDocumentWriter")
{
throw new CTestSkippedException("Skipped: WriterType " + wt);
}
WriterType writerType = (WriterType)Enum.Parse(typeof(WriterType), wt);
switch (writerType)
{
case WriterType.UnicodeWriter:
_settings.Encoding = Encoding.Unicode;
break;
default:
break;
}
}
protected void SetupWriterOverload()
{
string ol = ReadFilterCriteria("Load", true);
if (ol == "FileName" || ol == "XmlDocumentWriter" || ol == "InvalidUri")
{
throw new CTestSkippedException("Skipped: OverLoad " + ol);
}
_overload = (WriterOverload)Enum.Parse(typeof(WriterOverload), ol); //ReadFilterCriteria("Load", true));
}
/// <summary>
/// This function writes the test nodes on the factoryWriter.
/// This will be called from Test(). If successful it will just return,
/// else it will throw an appropriate XmlException. This function can use
/// the knowledge of the current writertype to write appropriate data if
/// really needed.
/// </summary>
protected void WriteNodes()
{
_factoryWriter.WriteStartElement("a", "b", "c");
_factoryWriter.WriteStartElement("d", "e");
_factoryWriter.WriteStartElement("f");
_factoryWriter.WriteStartAttribute("g", "h", "i");
_factoryWriter.WriteStartAttribute("j", "k");
_factoryWriter.WriteStartAttribute("l");
_factoryWriter.WriteString("Some String");
_factoryWriter.WriteEndElement();
_factoryWriter.WriteRaw("<thisisraw/>");
_factoryWriter.WriteProcessingInstruction("somepiname", "somepitext");
_factoryWriter.WriteValue(1000);
_factoryWriter.WriteComment("SomeComment");
_factoryWriter.WriteEndElement();
_factoryWriter.WriteCData("< is not a valid thing");
_factoryWriter.WriteCharEntity('a');
_factoryWriter.WriteWhitespace(" ");
_factoryWriter.WriteEndElement();
}
}
}
| |
/*
* 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.Drawing;
using System.Drawing.Imaging;
using System.Reflection;
using System.Xml.Serialization;
using log4net;
using OpenMetaverse;
namespace OpenSim.Framework
{
public enum ProfileShape : byte
{
Circle = 0,
Square = 1,
IsometricTriangle = 2,
EquilateralTriangle = 3,
RightTriangle = 4,
HalfCircle = 5
}
public enum HollowShape : byte
{
Same = 0,
Circle = 16,
Square = 32,
Triangle = 48
}
public enum PCodeEnum : byte
{
Primitive = 9,
Avatar = 47,
Grass = 95,
NewTree = 111,
ParticleSystem = 143,
Tree = 255
}
public enum Extrusion : byte
{
Straight = 16,
Curve1 = 32,
Curve2 = 48,
Flexible = 128
}
[Serializable]
public class PrimitiveBaseShape
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly Primitive.TextureEntry m_defaultTexture;
private byte[] m_textureEntry;
private ushort _pathBegin;
private byte _pathCurve;
private ushort _pathEnd;
private sbyte _pathRadiusOffset;
private byte _pathRevolutions;
private byte _pathScaleX;
private byte _pathScaleY;
private byte _pathShearX;
private byte _pathShearY;
private sbyte _pathSkew;
private sbyte _pathTaperX;
private sbyte _pathTaperY;
private sbyte _pathTwist;
private sbyte _pathTwistBegin;
private byte _pCode;
private ushort _profileBegin;
private ushort _profileEnd;
private ushort _profileHollow;
private Vector3 _scale;
private byte _state;
private ProfileShape _profileShape;
private HollowShape _hollowShape;
// Sculpted
[XmlIgnore] private UUID _sculptTexture = UUID.Zero;
[XmlIgnore] private byte _sculptType = (byte)0;
[XmlIgnore] private byte[] _sculptData = new byte[0];
[XmlIgnore] private Image _sculptBitmap = null;
// Flexi
[XmlIgnore] private int _flexiSoftness = 0;
[XmlIgnore] private float _flexiTension = 0f;
[XmlIgnore] private float _flexiDrag = 0f;
[XmlIgnore] private float _flexiGravity = 0f;
[XmlIgnore] private float _flexiWind = 0f;
[XmlIgnore] private float _flexiForceX = 0f;
[XmlIgnore] private float _flexiForceY = 0f;
[XmlIgnore] private float _flexiForceZ = 0f;
//Bright n sparkly
[XmlIgnore] private float _lightColorR = 0f;
[XmlIgnore] private float _lightColorG = 0f;
[XmlIgnore] private float _lightColorB = 0f;
[XmlIgnore] private float _lightColorA = 1f;
[XmlIgnore] private float _lightRadius = 0f;
[XmlIgnore] private float _lightCutoff = 0f;
[XmlIgnore] private float _lightFalloff = 0f;
[XmlIgnore] private float _lightIntensity = 1f;
[XmlIgnore] private bool _flexiEntry = false;
[XmlIgnore] private bool _lightEntry = false;
[XmlIgnore] private bool _sculptEntry = false;
public byte ProfileCurve
{
get { return (byte)((byte)HollowShape | (byte)ProfileShape); }
set
{
// Handle hollow shape component
byte hollowShapeByte = (byte)(value & 0xf0);
if (!Enum.IsDefined(typeof(HollowShape), hollowShapeByte))
{
m_log.WarnFormat(
"[SHAPE]: Attempt to set a ProfileCurve with a hollow shape value of {0}, which isn't a valid enum. Replacing with default shape.",
hollowShapeByte);
this._hollowShape = HollowShape.Same;
}
else
{
this._hollowShape = (HollowShape)hollowShapeByte;
}
// Handle profile shape component
byte profileShapeByte = (byte)(value & 0xf);
if (!Enum.IsDefined(typeof(ProfileShape), profileShapeByte))
{
m_log.WarnFormat(
"[SHAPE]: Attempt to set a ProfileCurve with a profile shape value of {0}, which isn't a valid enum. Replacing with square.",
profileShapeByte);
this._profileShape = ProfileShape.Square;
}
else
{
this._profileShape = (ProfileShape)profileShapeByte;
}
}
}
static PrimitiveBaseShape()
{
m_defaultTexture =
new Primitive.TextureEntry(new UUID("89556747-24cb-43ed-920b-47caed15465f"));
}
public PrimitiveBaseShape()
{
PCode = (byte) PCodeEnum.Primitive;
ExtraParams = new byte[1];
Textures = m_defaultTexture;
}
public PrimitiveBaseShape(bool noShape)
{
if (noShape)
return;
PCode = (byte)PCodeEnum.Primitive;
ExtraParams = new byte[1];
Textures = m_defaultTexture;
}
[XmlIgnore]
public Primitive.TextureEntry Textures
{
get
{
//m_log.DebugFormat("[PRIMITIVE BASE SHAPE]: get m_textureEntry length {0}", m_textureEntry.Length);
return new Primitive.TextureEntry(m_textureEntry, 0, m_textureEntry.Length);
}
set { m_textureEntry = value.GetBytes(); }
}
public byte[] TextureEntry
{
get { return m_textureEntry; }
set
{
if (value == null)
m_textureEntry = new byte[1];
else
m_textureEntry = value;
}
}
public static PrimitiveBaseShape Default
{
get
{
PrimitiveBaseShape boxShape = CreateBox();
boxShape.SetScale(0.5f);
return boxShape;
}
}
public static PrimitiveBaseShape Create()
{
PrimitiveBaseShape shape = new PrimitiveBaseShape();
return shape;
}
public static PrimitiveBaseShape CreateBox()
{
PrimitiveBaseShape shape = Create();
shape._pathCurve = (byte) Extrusion.Straight;
shape._profileShape = ProfileShape.Square;
shape._pathScaleX = 100;
shape._pathScaleY = 100;
return shape;
}
public static PrimitiveBaseShape CreateSphere()
{
PrimitiveBaseShape shape = Create();
shape._pathCurve = (byte) Extrusion.Curve1;
shape._profileShape = ProfileShape.HalfCircle;
shape._pathScaleX = 100;
shape._pathScaleY = 100;
return shape;
}
public static PrimitiveBaseShape CreateCylinder()
{
PrimitiveBaseShape shape = Create();
shape._pathCurve = (byte) Extrusion.Curve1;
shape._profileShape = ProfileShape.Square;
shape._pathScaleX = 100;
shape._pathScaleY = 100;
return shape;
}
public void SetScale(float side)
{
_scale = new Vector3(side, side, side);
}
public void SetHeigth(float heigth)
{
_scale.Z = heigth;
}
public void SetRadius(float radius)
{
_scale.X = _scale.Y = radius * 2f;
}
// TODO: void returns need to change of course
public virtual void GetMesh()
{
}
public PrimitiveBaseShape Copy()
{
return (PrimitiveBaseShape) MemberwiseClone();
}
public static PrimitiveBaseShape CreateCylinder(float radius, float heigth)
{
PrimitiveBaseShape shape = CreateCylinder();
shape.SetHeigth(heigth);
shape.SetRadius(radius);
return shape;
}
public void SetPathRange(Vector3 pathRange)
{
_pathBegin = Primitive.PackBeginCut(pathRange.X);
_pathEnd = Primitive.PackEndCut(pathRange.Y);
}
public void SetPathRange(float begin, float end)
{
_pathBegin = Primitive.PackBeginCut(begin);
_pathEnd = Primitive.PackEndCut(end);
}
public void SetSculptData(byte sculptType, UUID SculptTextureUUID)
{
_sculptType = sculptType;
_sculptTexture = SculptTextureUUID;
}
public void SetProfileRange(Vector3 profileRange)
{
_profileBegin = Primitive.PackBeginCut(profileRange.X);
_profileEnd = Primitive.PackEndCut(profileRange.Y);
}
public void SetProfileRange(float begin, float end)
{
_profileBegin = Primitive.PackBeginCut(begin);
_profileEnd = Primitive.PackEndCut(end);
}
public byte[] ExtraParams
{
get
{
return ExtraParamsToBytes();
}
set
{
ReadInExtraParamsBytes(value);
}
}
public ushort PathBegin {
get {
return _pathBegin;
}
set {
_pathBegin = value;
}
}
public byte PathCurve {
get {
return _pathCurve;
}
set {
_pathCurve = value;
}
}
public ushort PathEnd {
get {
return _pathEnd;
}
set {
_pathEnd = value;
}
}
public sbyte PathRadiusOffset {
get {
return _pathRadiusOffset;
}
set {
_pathRadiusOffset = value;
}
}
public byte PathRevolutions {
get {
return _pathRevolutions;
}
set {
_pathRevolutions = value;
}
}
public byte PathScaleX {
get {
return _pathScaleX;
}
set {
_pathScaleX = value;
}
}
public byte PathScaleY {
get {
return _pathScaleY;
}
set {
_pathScaleY = value;
}
}
public byte PathShearX {
get {
return _pathShearX;
}
set {
_pathShearX = value;
}
}
public byte PathShearY {
get {
return _pathShearY;
}
set {
_pathShearY = value;
}
}
public sbyte PathSkew {
get {
return _pathSkew;
}
set {
_pathSkew = value;
}
}
public sbyte PathTaperX {
get {
return _pathTaperX;
}
set {
_pathTaperX = value;
}
}
public sbyte PathTaperY {
get {
return _pathTaperY;
}
set {
_pathTaperY = value;
}
}
public sbyte PathTwist {
get {
return _pathTwist;
}
set {
_pathTwist = value;
}
}
public sbyte PathTwistBegin {
get {
return _pathTwistBegin;
}
set {
_pathTwistBegin = value;
}
}
public byte PCode {
get {
return _pCode;
}
set {
_pCode = value;
}
}
public ushort ProfileBegin {
get {
return _profileBegin;
}
set {
_profileBegin = value;
}
}
public ushort ProfileEnd {
get {
return _profileEnd;
}
set {
_profileEnd = value;
}
}
public ushort ProfileHollow {
get {
return _profileHollow;
}
set {
_profileHollow = value;
}
}
public Vector3 Scale {
get {
return _scale;
}
set {
_scale = value;
}
}
public byte State {
get {
return _state;
}
set {
_state = value;
}
}
public ProfileShape ProfileShape {
get {
return _profileShape;
}
set {
_profileShape = value;
}
}
public HollowShape HollowShape {
get {
return _hollowShape;
}
set {
_hollowShape = value;
}
}
public UUID SculptTexture {
get {
return _sculptTexture;
}
set {
_sculptTexture = value;
}
}
public byte SculptType {
get {
return _sculptType;
}
set {
_sculptType = value;
}
}
public byte[] SculptData {
get {
return _sculptData;
}
set {
_sculptData = value;
}
}
public Image SculptBitmap {
get {
return _sculptBitmap;
}
set {
_sculptBitmap = value;
}
}
public int FlexiSoftness {
get {
return _flexiSoftness;
}
set {
_flexiSoftness = value;
}
}
public float FlexiTension {
get {
return _flexiTension;
}
set {
_flexiTension = value;
}
}
public float FlexiDrag {
get {
return _flexiDrag;
}
set {
_flexiDrag = value;
}
}
public float FlexiGravity {
get {
return _flexiGravity;
}
set {
_flexiGravity = value;
}
}
public float FlexiWind {
get {
return _flexiWind;
}
set {
_flexiWind = value;
}
}
public float FlexiForceX {
get {
return _flexiForceX;
}
set {
_flexiForceX = value;
}
}
public float FlexiForceY {
get {
return _flexiForceY;
}
set {
_flexiForceY = value;
}
}
public float FlexiForceZ {
get {
return _flexiForceZ;
}
set {
_flexiForceZ = value;
}
}
public float LightColorR {
get {
return _lightColorR;
}
set {
_lightColorR = value;
}
}
public float LightColorG {
get {
return _lightColorG;
}
set {
_lightColorG = value;
}
}
public float LightColorB {
get {
return _lightColorB;
}
set {
_lightColorB = value;
}
}
public float LightColorA {
get {
return _lightColorA;
}
set {
_lightColorA = value;
}
}
public float LightRadius {
get {
return _lightRadius;
}
set {
_lightRadius = value;
}
}
public float LightCutoff {
get {
return _lightCutoff;
}
set {
_lightCutoff = value;
}
}
public float LightFalloff {
get {
return _lightFalloff;
}
set {
_lightFalloff = value;
}
}
public float LightIntensity {
get {
return _lightIntensity;
}
set {
_lightIntensity = value;
}
}
public bool FlexiEntry {
get {
return _flexiEntry;
}
set {
_flexiEntry = value;
}
}
public bool LightEntry {
get {
return _lightEntry;
}
set {
_lightEntry = value;
}
}
public bool SculptEntry {
get {
return _sculptEntry;
}
set {
_sculptEntry = value;
}
}
public byte[] ExtraParamsToBytes()
{
ushort FlexiEP = 0x10;
ushort LightEP = 0x20;
ushort SculptEP = 0x30;
int i = 0;
uint TotalBytesLength = 1; // ExtraParamsNum
uint ExtraParamsNum = 0;
if (_flexiEntry)
{
ExtraParamsNum++;
TotalBytesLength += 16;// data
TotalBytesLength += 2 + 4; // type
}
if (_lightEntry)
{
ExtraParamsNum++;
TotalBytesLength += 16;// data
TotalBytesLength += 2 + 4; // type
}
if (_sculptEntry)
{
ExtraParamsNum++;
TotalBytesLength += 17;// data
TotalBytesLength += 2 + 4; // type
}
byte[] returnbytes = new byte[TotalBytesLength];
// uint paramlength = ExtraParamsNum;
// Stick in the number of parameters
returnbytes[i++] = (byte)ExtraParamsNum;
if (_flexiEntry)
{
byte[] FlexiData = GetFlexiBytes();
returnbytes[i++] = (byte)(FlexiEP % 256);
returnbytes[i++] = (byte)((FlexiEP >> 8) % 256);
returnbytes[i++] = (byte)(FlexiData.Length % 256);
returnbytes[i++] = (byte)((FlexiData.Length >> 8) % 256);
returnbytes[i++] = (byte)((FlexiData.Length >> 16) % 256);
returnbytes[i++] = (byte)((FlexiData.Length >> 24) % 256);
Array.Copy(FlexiData, 0, returnbytes, i, FlexiData.Length);
i += FlexiData.Length;
}
if (_lightEntry)
{
byte[] LightData = GetLightBytes();
returnbytes[i++] = (byte)(LightEP % 256);
returnbytes[i++] = (byte)((LightEP >> 8) % 256);
returnbytes[i++] = (byte)(LightData.Length % 256);
returnbytes[i++] = (byte)((LightData.Length >> 8) % 256);
returnbytes[i++] = (byte)((LightData.Length >> 16) % 256);
returnbytes[i++] = (byte)((LightData.Length >> 24) % 256);
Array.Copy(LightData, 0, returnbytes, i, LightData.Length);
i += LightData.Length;
}
if (_sculptEntry)
{
byte[] SculptData = GetSculptBytes();
returnbytes[i++] = (byte)(SculptEP % 256);
returnbytes[i++] = (byte)((SculptEP >> 8) % 256);
returnbytes[i++] = (byte)(SculptData.Length % 256);
returnbytes[i++] = (byte)((SculptData.Length >> 8) % 256);
returnbytes[i++] = (byte)((SculptData.Length >> 16) % 256);
returnbytes[i++] = (byte)((SculptData.Length >> 24) % 256);
Array.Copy(SculptData, 0, returnbytes, i, SculptData.Length);
i += SculptData.Length;
}
if (!_flexiEntry && !_lightEntry && !_sculptEntry)
{
byte[] returnbyte = new byte[1];
returnbyte[0] = 0;
return returnbyte;
}
return returnbytes;
//m_log.Info("[EXTRAPARAMS]: Length = " + m_shape.ExtraParams.Length.ToString());
}
public void ReadInUpdateExtraParam(ushort type, bool inUse, byte[] data)
{
const ushort FlexiEP = 0x10;
const ushort LightEP = 0x20;
const ushort SculptEP = 0x30;
switch (type)
{
case FlexiEP:
if (!inUse)
{
_flexiEntry = false;
return;
}
ReadFlexiData(data, 0);
break;
case LightEP:
if (!inUse)
{
_lightEntry = false;
return;
}
ReadLightData(data, 0);
break;
case SculptEP:
if (!inUse)
{
_sculptEntry = false;
return;
}
ReadSculptData(data, 0);
break;
}
}
public void ReadInExtraParamsBytes(byte[] data)
{
if (data == null || data.Length == 1)
return;
const ushort FlexiEP = 0x10;
const ushort LightEP = 0x20;
const ushort SculptEP = 0x30;
bool lGotFlexi = false;
bool lGotLight = false;
bool lGotSculpt = false;
int i = 0;
byte extraParamCount = 0;
if (data.Length > 0)
{
extraParamCount = data[i++];
}
for (int k = 0; k < extraParamCount; k++)
{
ushort epType = Utils.BytesToUInt16(data, i);
i += 2;
// uint paramLength = Helpers.BytesToUIntBig(data, i);
i += 4;
switch (epType)
{
case FlexiEP:
ReadFlexiData(data, i);
i += 16;
lGotFlexi = true;
break;
case LightEP:
ReadLightData(data, i);
i += 16;
lGotLight = true;
break;
case SculptEP:
ReadSculptData(data, i);
i += 17;
lGotSculpt = true;
break;
}
}
if (!lGotFlexi)
_flexiEntry = false;
if (!lGotLight)
_lightEntry = false;
if (!lGotSculpt)
_sculptEntry = false;
}
public void ReadSculptData(byte[] data, int pos)
{
byte[] SculptTextureUUID = new byte[16];
UUID SculptUUID = UUID.Zero;
byte SculptTypel = data[16+pos];
if (data.Length+pos >= 17)
{
_sculptEntry = true;
SculptTextureUUID = new byte[16];
SculptTypel = data[16 + pos];
Array.Copy(data, pos, SculptTextureUUID,0, 16);
SculptUUID = new UUID(SculptTextureUUID, 0);
}
else
{
_sculptEntry = false;
SculptUUID = UUID.Zero;
SculptTypel = 0x00;
}
if (_sculptEntry)
{
if (_sculptType != (byte)1 && _sculptType != (byte)2 && _sculptType != (byte)3 && _sculptType != (byte)4)
_sculptType = 4;
}
_sculptTexture = SculptUUID;
_sculptType = SculptTypel;
//m_log.Info("[SCULPT]:" + SculptUUID.ToString());
}
public byte[] GetSculptBytes()
{
byte[] data = new byte[17];
_sculptTexture.GetBytes().CopyTo(data, 0);
data[16] = (byte)_sculptType;
return data;
}
public void ReadFlexiData(byte[] data, int pos)
{
if (data.Length-pos >= 16)
{
_flexiEntry = true;
_flexiSoftness = ((data[pos] & 0x80) >> 6) | ((data[pos + 1] & 0x80) >> 7);
_flexiTension = (float)(data[pos++] & 0x7F) / 10.0f;
_flexiDrag = (float)(data[pos++] & 0x7F) / 10.0f;
_flexiGravity = (float)(data[pos++] / 10.0f) - 10.0f;
_flexiWind = (float)data[pos++] / 10.0f;
Vector3 lForce = new Vector3(data, pos);
_flexiForceX = lForce.X;
_flexiForceY = lForce.Y;
_flexiForceZ = lForce.Z;
}
else
{
_flexiEntry = false;
_flexiSoftness = 0;
_flexiTension = 0.0f;
_flexiDrag = 0.0f;
_flexiGravity = 0.0f;
_flexiWind = 0.0f;
_flexiForceX = 0f;
_flexiForceY = 0f;
_flexiForceZ = 0f;
}
}
public byte[] GetFlexiBytes()
{
byte[] data = new byte[16];
int i = 0;
// Softness is packed in the upper bits of tension and drag
data[i] = (byte)((_flexiSoftness & 2) << 6);
data[i + 1] = (byte)((_flexiSoftness & 1) << 7);
data[i++] |= (byte)((byte)(_flexiTension * 10.01f) & 0x7F);
data[i++] |= (byte)((byte)(_flexiDrag * 10.01f) & 0x7F);
data[i++] = (byte)((_flexiGravity + 10.0f) * 10.01f);
data[i++] = (byte)(_flexiWind * 10.01f);
Vector3 lForce = new Vector3(_flexiForceX, _flexiForceY, _flexiForceZ);
lForce.GetBytes().CopyTo(data, i);
return data;
}
public void ReadLightData(byte[] data, int pos)
{
if (data.Length - pos >= 16)
{
_lightEntry = true;
Color4 lColor = new Color4(data, pos, false);
_lightIntensity = lColor.A;
_lightColorA = 1f;
_lightColorR = lColor.R;
_lightColorG = lColor.G;
_lightColorB = lColor.B;
_lightRadius = Utils.BytesToFloat(data, pos + 4);
_lightCutoff = Utils.BytesToFloat(data, pos + 8);
_lightFalloff = Utils.BytesToFloat(data, pos + 12);
}
else
{
_lightEntry = false;
_lightColorA = 1f;
_lightColorR = 0f;
_lightColorG = 0f;
_lightColorB = 0f;
_lightRadius = 0f;
_lightCutoff = 0f;
_lightFalloff = 0f;
_lightIntensity = 0f;
}
}
public byte[] GetLightBytes()
{
byte[] data = new byte[16];
// Alpha channel in color is intensity
Color4 tmpColor = new Color4(_lightColorR,_lightColorG,_lightColorB,_lightIntensity);
tmpColor.GetBytes().CopyTo(data, 0);
Utils.FloatToBytes(_lightRadius).CopyTo(data, 4);
Utils.FloatToBytes(_lightCutoff).CopyTo(data, 8);
Utils.FloatToBytes(_lightFalloff).CopyTo(data, 12);
return data;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.IO;
using System.Reflection;
using Microsoft.Win32;
#if true
#endif
namespace NUnit.Framework.Internal
{
/// <summary>
/// Enumeration identifying a common language
/// runtime implementation.
/// </summary>
public enum RuntimeType
{
/// <summary>Any supported runtime framework</summary>
Any,
/// <summary>Microsoft .NET Framework</summary>
Net,
/// <summary>Microsoft .NET Compact Framework</summary>
NetCF,
/// <summary>Microsoft Shared Source CLI</summary>
SSCLI,
/// <summary>Mono</summary>
Mono
}
/// <summary>
/// RuntimeFramework represents a particular version
/// of a common language runtime implementation.
/// </summary>
[Serializable]
public sealed class RuntimeFramework
{
#region Static and Instance Fields
/// <summary>
/// DefaultVersion is an empty Version, used to indicate that
/// NUnit should select the CLR version to use for the test.
/// </summary>
public static readonly Version DefaultVersion = new Version(0,0);
private static RuntimeFramework currentFramework;
private static RuntimeFramework[] availableFrameworks;
private static Version[] knownVersions = new Version[] {
new Version(1, 0, 3705),
new Version(1, 1, 4322),
new Version(2, 0, 50727),
new Version(4, 0, 30319)
};
private RuntimeType runtime;
private Version frameworkVersion;
private Version clrVersion;
private string displayName;
#endregion
#region Constructor
/// <summary>
/// Construct from a runtime type and version
/// </summary>
/// <param name="runtime">The runtime type of the framework</param>
/// <param name="version">The version of the framework</param>
public RuntimeFramework( RuntimeType runtime, Version version)
{
this.runtime = runtime;
if (version.Build < 0)
InitFromFrameworkVersion(version);
else
InitFromClrVersion(version);
if (version.Major == 3)
this.clrVersion = new Version(2, 0, 50727);
this.displayName = GetDefaultDisplayName(runtime, version);
}
private void InitFromFrameworkVersion(Version version)
{
this.frameworkVersion = this.clrVersion = version;
foreach (Version v in knownVersions)
if (v.Major == version.Major && v.Minor == version.Minor)
{
this.clrVersion = v;
break;
}
if (this.runtime == RuntimeType.Mono && version.Major == 1)
{
this.frameworkVersion = new Version(1, 0);
this.clrVersion = new Version(1, 1, 4322);
}
}
private void InitFromClrVersion(Version version)
{
this.frameworkVersion = new Version(version.Major, version.Minor);
this.clrVersion = version;
if (runtime == RuntimeType.Mono && version.Major == 1)
this.frameworkVersion = new Version(1, 0);
}
#endregion
#region Properties
/// <summary>
/// Static method to return a RuntimeFramework object
/// for the framework that is currently in use.
/// </summary>
public static RuntimeFramework CurrentFramework
{
get
{
if (currentFramework == null)
{
Type monoRuntimeType = Type.GetType("Mono.Runtime", false);
bool isMono = monoRuntimeType != null;
RuntimeType runtime = isMono
? RuntimeType.Mono
: Environment.OSVersion.Platform == PlatformID.WinCE
? RuntimeType.NetCF
: RuntimeType.Net;
int major = Environment.Version.Major;
int minor = Environment.Version.Minor;
if (isMono)
{
switch (major)
{
case 1:
minor = 0;
break;
case 2:
major = 3;
minor = 5;
break;
}
}
currentFramework = new RuntimeFramework(runtime, new Version(major, minor));
currentFramework.clrVersion = Environment.Version;
if (isMono)
{
MethodInfo getDisplayNameMethod = monoRuntimeType.GetMethod(
"GetDisplayName", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding);
if (getDisplayNameMethod != null)
currentFramework.displayName = (string)getDisplayNameMethod.Invoke(null, new object[0]);
}
}
return currentFramework;
}
}
/// <summary>
/// Gets an array of all available frameworks
/// </summary>
// TODO: Special handling for netcf
public static RuntimeFramework[] AvailableFrameworks
{
get
{
if (availableFrameworks == null)
{
FrameworkList frameworks = new FrameworkList();
AppendDotNetFrameworks(frameworks);
#if !NETCF
AppendDefaultMonoFramework(frameworks);
#endif
// NYI
//AppendMonoFrameworks(frameworks);
availableFrameworks = frameworks.ToArray();
}
return availableFrameworks;
}
}
/// <summary>
/// Returns true if the current RuntimeFramework is available.
/// In the current implementation, only Mono and Microsoft .NET
/// are supported.
/// </summary>
/// <returns>True if it's available, false if not</returns>
public bool IsAvailable
{
get
{
foreach (RuntimeFramework framework in AvailableFrameworks)
if (this.Supports(framework))
return true;
return false;
}
}
/// <summary>
/// The type of this runtime framework
/// </summary>
public RuntimeType Runtime
{
get { return runtime; }
}
/// <summary>
/// The framework version for this runtime framework
/// </summary>
public Version FrameworkVersion
{
get { return frameworkVersion; }
}
/// <summary>
/// The CLR version for this runtime framework
/// </summary>
public Version ClrVersion
{
get { return clrVersion; }
}
/// <summary>
/// Return true if any CLR version may be used in
/// matching this RuntimeFramework object.
/// </summary>
public bool AllowAnyVersion
{
get { return this.clrVersion == DefaultVersion; }
}
/// <summary>
/// Returns the Display name for this framework
/// </summary>
public string DisplayName
{
get { return displayName; }
}
#endregion
#region Public Methods
/// <summary>
/// Parses a string representing a RuntimeFramework.
/// The string may be just a RuntimeType name or just
/// a Version or a hyphentated RuntimeType-Version or
/// a Version prefixed by 'v'.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static RuntimeFramework Parse(string s)
{
RuntimeType runtime = RuntimeType.Any;
Version version = DefaultVersion;
string[] parts = s.Split(new char[] { '-' });
if (parts.Length == 2)
{
runtime = (RuntimeType)System.Enum.Parse(typeof(RuntimeType), parts[0], true);
string vstring = parts[1];
if (vstring != "")
version = new Version(vstring);
}
else if (char.ToLower(s[0]) == 'v')
{
version = new Version(s.Substring(1));
}
else if (IsRuntimeTypeName(s))
{
runtime = (RuntimeType)System.Enum.Parse(typeof(RuntimeType), s, true);
}
else
{
version = new Version(s);
}
return new RuntimeFramework(runtime, version);
}
/// <summary>
/// Returns the best available framework that matches a target framework.
/// If the target framework has a build number specified, then an exact
/// match is needed. Otherwise, the matching framework with the highest
/// build number is used.
/// </summary>
/// <param name="target"></param>
/// <returns></returns>
public static RuntimeFramework GetBestAvailableFramework(RuntimeFramework target)
{
RuntimeFramework result = target;
if (target.ClrVersion.Build < 0)
{
foreach (RuntimeFramework framework in AvailableFrameworks)
if (framework.Supports(target) &&
framework.ClrVersion.Build > result.ClrVersion.Build)
{
result = framework;
}
}
return result;
}
/// <summary>
/// Overridden to return the short name of the framework
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (this.AllowAnyVersion)
{
return runtime.ToString().ToLower();
}
else
{
string vstring = frameworkVersion.ToString();
if (runtime == RuntimeType.Any)
return "v" + vstring;
else
return runtime.ToString().ToLower() + "-" + vstring;
}
}
/// <summary>
/// Returns true if the current framework matches the
/// one supplied as an argument. Two frameworks match
/// if their runtime types are the same or either one
/// is RuntimeType.Any and all specified version components
/// are equal. Negative (i.e. unspecified) version
/// components are ignored.
/// </summary>
/// <param name="other">The RuntimeFramework to be matched.</param>
/// <returns>True on match, otherwise false</returns>
public bool Supports(RuntimeFramework target)
{
if (this.Runtime != RuntimeType.Any
&& target.Runtime != RuntimeType.Any
&& this.Runtime != target.Runtime)
return false;
if (this.AllowAnyVersion || target.AllowAnyVersion)
return true;
return VersionsMatch(this.ClrVersion, target.ClrVersion)
&& this.FrameworkVersion.Major >= target.FrameworkVersion.Major
&& this.FrameworkVersion.Minor >= target.FrameworkVersion.Minor;
}
#endregion
#region Helper Methods
private static bool IsRuntimeTypeName(string name)
{
#if NETCF
//return Enum.IsDefined(typeof(RuntimeType), name);
switch (name.ToUpper())
{
case "NET":
case "MONO":
case "SSCLI":
case "NETCF":
case "ANY":
return true;
default:
return false;
}
#else
foreach (string item in Enum.GetNames(typeof(RuntimeType)))
if (item.ToLower() == name.ToLower())
return true;
return false;
#endif
}
private static string GetDefaultDisplayName(RuntimeType runtime, Version version)
{
if (version == DefaultVersion)
return runtime.ToString();
else if (runtime == RuntimeType.Any)
return "v" + version.ToString();
else
return runtime.ToString() + " " + version.ToString();
}
private static bool VersionsMatch(Version v1, Version v2)
{
return v1.Major == v2.Major &&
v1.Minor == v2.Minor &&
(v1.Build < 0 || v2.Build < 0 || v1.Build == v2.Build) &&
(v1.Revision < 0 || v2.Revision < 0 || v1.Revision == v2.Revision);
}
#if !NETCF
private static void AppendMonoFrameworks(FrameworkList frameworks)
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
AppendAllMonoFrameworks(frameworks);
else
AppendDefaultMonoFramework(frameworks);
}
private static void AppendAllMonoFrameworks(FrameworkList frameworks)
{
AppendDefaultMonoFramework(frameworks);
}
// This method works for Windows and Linux but currently
// is only called under Linux.
private static void AppendDefaultMonoFramework(FrameworkList frameworks)
{
string monoPrefix = null;
string version = null;
string libMonoDir = Path.GetDirectoryName(typeof (object).Assembly.Location);
monoPrefix = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(libMonoDir)));
AppendMonoFramework(frameworks, monoPrefix, version);
}
private static void AppendMonoFramework(FrameworkList frameworks, string monoPrefix, string version)
{
if (monoPrefix != null)
{
string displayFmt = version != null
? "Mono " + version + " - {0} Profile"
: "Mono {0} Profile";
if (File.Exists(Path.Combine(monoPrefix, "lib/mono/1.0/mscorlib.dll")))
{
RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(1, 1, 4322));
framework.displayName = string.Format(displayFmt, "1.0");
frameworks.Add(framework);
}
if (File.Exists(Path.Combine(monoPrefix, "lib/mono/2.0/mscorlib.dll")))
{
RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(2, 0, 50727));
framework.displayName = string.Format(displayFmt, "2.0");
frameworks.Add(framework);
}
if (File.Exists(Path.Combine(monoPrefix, "lib/mono/4.0/mscorlib.dll")))
{
RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(4, 0, 30319));
framework.displayName = string.Format(displayFmt, "4.0");
frameworks.Add(framework);
}
}
}
#endif
private static void AppendDotNetFrameworks(FrameworkList frameworks)
{
// EMPTY
}
#if true
class FrameworkList : System.Collections.Generic.List<RuntimeFramework> { }
#else
class FrameworkList : System.Collections.ArrayList
{
public new RuntimeFramework[] ToArray()
{
return (RuntimeFramework[])base.ToArray(typeof(RuntimeFramework));
}
}
#endif
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Globalization;
using Xunit;
namespace System.Tests
{
public static class CharTests
{
[Theory]
[InlineData('h', 'h', 0)]
[InlineData('h', 'a', 1)]
[InlineData('h', 'z', -1)]
[InlineData('h', null, 1)]
public static void CompareTo(char c, object value, int expected)
{
if (value is char)
{
Assert.Equal(expected, Math.Sign(c.CompareTo((char)value)));
}
IComparable comparable = c;
Assert.Equal(expected, Math.Sign(comparable.CompareTo(value)));
}
[Fact]
public static void CompareTo_ObjectNotChar_ThrowsArgumentException()
{
IComparable comparable = 'h';
Assert.Throws<ArgumentException>(null, () => comparable.CompareTo("H")); // Value not a char
}
[Fact]
public static void ConvertFromUtf32_InvalidChar()
{
// TODO: add this as [InlineData] when #7166 is fixed
ConvertFromUtf32(0xFFFF, "\uFFFF");
}
[Theory]
[InlineData(0x10000, "\uD800\uDC00")]
[InlineData(0x103FF, "\uD800\uDFFF")]
[InlineData(0xFFFFF, "\uDBBF\uDFFF")]
[InlineData(0x10FC00, "\uDBFF\uDC00")]
[InlineData(0x10FFFF, "\uDBFF\uDFFF")]
[InlineData(0, "\0")]
[InlineData(0x3FF, "\u03FF")]
[InlineData(0xE000, "\uE000")]
public static void ConvertFromUtf32(int utf32, string expected)
{
// TODO: add this as [InlineData] when #7166 is fixed
Assert.Equal(expected, char.ConvertFromUtf32(utf32));
}
[Theory]
[InlineData(0xD800)]
[InlineData(0xDC00)]
[InlineData(0xDFFF)]
[InlineData(0x110000)]
[InlineData(-1)]
[InlineData(int.MaxValue)]
[InlineData(int.MinValue)]
public static void ConvertFromUtf32_InvalidUtf32_ThrowsArgumentOutOfRangeException(int utf32)
{
Assert.Throws<ArgumentOutOfRangeException>("utf32", () => char.ConvertFromUtf32(utf32));
}
[Fact]
public static void ConvertToUtf32_String_Int()
{
// TODO: add this as [InlineData] when #7166 is fixed
ConvertToUtf32_String_Int("\uD800\uD800\uDFFF", 1, 0x103FF);
ConvertToUtf32_String_Int("\uD800\uD7FF", 1, 0xD7FF); // High, non-surrogate
ConvertToUtf32_String_Int("\uD800\u0000", 1, 0); // High, non-surrogate
ConvertToUtf32_String_Int("\uDF01\u0000", 1, 0); // Low, non-surrogate
}
[Theory]
[InlineData("\uD800\uDC00", 0, 0x10000)]
[InlineData("\uDBBF\uDFFF", 0, 0xFFFFF)]
[InlineData("\uDBBF\uDFFF", 0, 0xFFFFF)]
[InlineData("\uDBFF\uDC00", 0, 0x10FC00)]
[InlineData("\uDBFF\uDFFF", 0, 0x10FFFF)]
[InlineData("\u0000\u0001", 0, 0)]
[InlineData("\u0000\u0001", 1, 1)]
[InlineData("\u0000", 0, 0)]
[InlineData("\u0020\uD7FF", 0, 32)]
[InlineData("\u0020\uD7FF", 1, 0xD7FF)]
[InlineData("abcde", 4, 'e')]
public static void ConvertToUtf32_String_Int(string s, int index, int expected)
{
Assert.Equal(expected, char.ConvertToUtf32(s, index));
}
[Fact]
public static void ConvertToUtf32_String_Int_Invalid()
{
Assert.Throws<ArgumentNullException>("s", () => char.ConvertToUtf32(null, 0)); // String is null
Assert.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\uD800", 0)); // High, high
Assert.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\uD800", 1)); // High, high
Assert.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\uD7FF", 0)); // High, non-surrogate
Assert.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\u0000", 0)); // High, non-surrogate
Assert.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDC01\uD940", 0)); // Low, high
Assert.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDC01\uD940", 1)); // Low, high
Assert.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDD00\uDE00", 0)); // Low, low
Assert.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDD00\uDE00", 1)); // Low, hig
Assert.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDF01\u0000", 0)); // Low, non-surrogateh
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.ConvertToUtf32("abcde", -1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.ConvertToUtf32("abcde", 5)); // Index >= string.Length
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.ConvertToUtf32("", 0)); // Index >= string.Length
}
[Fact]
public static void ConvertToUtf32_Char_Char()
{
// TODO: add this as [InlineData] when #7166 is fixed
TestConvertToUtf32_Char_Char('\uD800', '\uDC00', 0x10000);
TestConvertToUtf32_Char_Char('\uD800', '\uDC00', 0x10000);
TestConvertToUtf32_Char_Char('\uD800', '\uDFFF', 0x103FF);
TestConvertToUtf32_Char_Char('\uDBBF', '\uDFFF', 0xFFFFF);
TestConvertToUtf32_Char_Char('\uDBFF', '\uDC00', 0x10FC00);
TestConvertToUtf32_Char_Char('\uDBFF', '\uDFFF', 0x10FFFF);
}
private static void TestConvertToUtf32_Char_Char(char highSurrogate, char lowSurrogate, int expected)
{
Assert.Equal(expected, char.ConvertToUtf32(highSurrogate, lowSurrogate));
}
[Fact]
public static void ConvertToUtf32_Char_Char_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("lowSurrogate", () => char.ConvertToUtf32('\uD800', '\uD800')); // High, high
Assert.Throws<ArgumentOutOfRangeException>("lowSurrogate", () => char.ConvertToUtf32('\uD800', '\uD7FF')); // High, non-surrogate
Assert.Throws<ArgumentOutOfRangeException>("lowSurrogate", () => char.ConvertToUtf32('\uD800', '\u0000')); // High, non-surrogate
Assert.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\uDD00', '\uDE00')); // Low, low
Assert.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\uDC01', '\uD940')); // Low, high
Assert.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\uDF01', '\u0000')); // Low, non-surrogate
Assert.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\u0032', '\uD7FF')); // Non-surrogate, non-surrogate
Assert.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\u0000', '\u0000')); // Non-surrogate, non-surrogate
}
[Theory]
[InlineData('a', 'a', true)]
[InlineData('a', 'A', false)]
[InlineData('a', 'b', false)]
[InlineData('a', (int)'a', false)]
[InlineData('a', "a", false)]
[InlineData('a', null, false)]
public static void Equals(char c, object obj, bool expected)
{
if (obj is char)
{
Assert.Equal(expected, c.Equals((char)obj));
Assert.Equal(expected, c.GetHashCode().Equals(obj.GetHashCode()));
}
Assert.Equal(expected, c.Equals(obj));
}
[Theory]
[InlineData('0', 0)]
[InlineData('9', 9)]
[InlineData('T', -1)]
public static void GetNumericValue_Char(char c, int expected)
{
Assert.Equal(expected, char.GetNumericValue(c));
}
[Theory]
[InlineData("\uD800\uDD07", 0, 1)]
[InlineData("9", 0, 9)]
[InlineData("99", 1, 9)]
[InlineData(" 7 ", 1, 7)]
[InlineData("Test 7", 5, 7)]
[InlineData("T", 0, -1)]
public static void GetNumericValue_String_Int(string s, int index, int expected)
{
Assert.Equal(expected, char.GetNumericValue(s, index));
}
[Fact]
public static void GetNumericValue_String_Int_Invalid()
{
Assert.Throws<ArgumentNullException>("s", () => char.GetNumericValue(null, 0)); // String is null
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.GetNumericValue("abc", -1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.GetNumericValue("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsControl_Char()
{
foreach (char c in GetTestChars(UnicodeCategory.Control))
Assert.True(char.IsControl(c));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.Control))
Assert.False(char.IsControl(c));
}
[Fact]
public static void IsControl_String_Int()
{
foreach (char c in GetTestChars(UnicodeCategory.Control))
Assert.True(char.IsControl(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.Control))
Assert.False(char.IsControl(c.ToString(), 0));
}
[Fact]
public static void IsControl_String_Int_Invalid()
{
Assert.Throws<ArgumentNullException>("s", () => char.IsControl(null, 0)); // String is null
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsControl("abc", -1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsControl("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsDigit_Char()
{
foreach (char c in GetTestChars(UnicodeCategory.DecimalDigitNumber))
Assert.True(char.IsDigit(c));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber))
Assert.False(char.IsDigit(c));
}
[Fact]
public static void IsDigit_String_Int()
{
foreach (char c in GetTestChars(UnicodeCategory.DecimalDigitNumber))
Assert.True(char.IsDigit(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber))
Assert.False(char.IsDigit(c.ToString(), 0));
}
[Fact]
public static void IsDigit_String_Int_Invalid()
{
Assert.Throws<ArgumentNullException>("s", () => char.IsDigit(null, 0)); // String is null
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsDigit("abc", -1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsDigit("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsLetter_Char()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsLetter(c));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsLetter(c));
}
[Fact]
public static void IsLetter_String_Int()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsLetter(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsLetter(c.ToString(), 0));
}
[Fact]
public static void IsLetter_String_Int_Invalid()
{
Assert.Throws<ArgumentNullException>("s", () => char.IsLetter(null, 0)); // String is null
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetter("abc", -1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetter("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsLetterOrDigit_Char()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter,
UnicodeCategory.DecimalDigitNumber
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsLetterOrDigit(c));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsLetterOrDigit(c));
}
[Fact]
public static void IsLetterOrDigit_String_Int()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter,
UnicodeCategory.DecimalDigitNumber
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsLetterOrDigit(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsLetterOrDigit(c.ToString(), 0));
}
[Fact]
public static void IsLetterOrDigit_String_Int_Invalid()
{
Assert.Throws<ArgumentNullException>("s", () => char.IsLetterOrDigit(null, 0)); // String is null
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetterOrDigit("abc", -1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetterOrDigit("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsLower_Char()
{
foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter))
Assert.True(char.IsLower(c));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter))
Assert.False(char.IsLower(c));
}
[Fact]
public static void IsLower_String_Int()
{
foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter))
Assert.True(char.IsLower(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter))
Assert.False(char.IsLower(c.ToString(), 0));
}
[Fact]
public static void IsLower_String_Int_Invalid()
{
Assert.Throws<ArgumentNullException>("s", () => char.IsLower(null, 0)); // String is null
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsLower("abc", -1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsLower("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsNumber_Char()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.DecimalDigitNumber,
UnicodeCategory.LetterNumber,
UnicodeCategory.OtherNumber
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsNumber(c));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsNumber(c));
}
[Fact]
public static void IsNumber_String_Int()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.DecimalDigitNumber,
UnicodeCategory.LetterNumber,
UnicodeCategory.OtherNumber
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsNumber(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsNumber(c.ToString(), 0));
}
[Fact]
public static void IsNumber_String_Int_Invalid()
{
Assert.Throws<ArgumentNullException>("s", () => char.IsNumber(null, 0)); // String is null
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsNumber("abc", -1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsNumber("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsPunctuation_Char()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.ConnectorPunctuation,
UnicodeCategory.DashPunctuation,
UnicodeCategory.OpenPunctuation,
UnicodeCategory.ClosePunctuation,
UnicodeCategory.InitialQuotePunctuation,
UnicodeCategory.FinalQuotePunctuation,
UnicodeCategory.OtherPunctuation
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsPunctuation(c));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsPunctuation(c));
}
[Fact]
public static void IsPunctuation_String_Int()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.ConnectorPunctuation,
UnicodeCategory.DashPunctuation,
UnicodeCategory.OpenPunctuation,
UnicodeCategory.ClosePunctuation,
UnicodeCategory.InitialQuotePunctuation,
UnicodeCategory.FinalQuotePunctuation,
UnicodeCategory.OtherPunctuation
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsPunctuation(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsPunctuation(c.ToString(), 0));
}
[Fact]
public static void IsPunctuation_String_Int_Invalid()
{
Assert.Throws<ArgumentNullException>("s", () => char.IsPunctuation(null, 0)); // String is null
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsPunctuation("abc", -1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsPunctuation("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsSeparator_Char()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsSeparator(c));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsSeparator(c));
}
[Fact]
public static void IsSeparator_String_Int()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsSeparator(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsSeparator(c.ToString(), 0));
}
[Fact]
public static void IsSeparator_String_Int_Invalid()
{
Assert.Throws<ArgumentNullException>("s", () => char.IsSeparator(null, 0)); // String is null
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsSeparator("abc", -1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsSeparator("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsLowSurrogate_Char()
{
foreach (char c in s_lowSurrogates)
Assert.True(char.IsLowSurrogate(c));
foreach (char c in s_highSurrogates)
Assert.False(char.IsLowSurrogate(c));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsLowSurrogate(c));
}
[Fact]
public static void IsLowSurrogate_String_Int()
{
foreach (char c in s_lowSurrogates)
Assert.True(char.IsLowSurrogate(c.ToString(), 0));
foreach (char c in s_highSurrogates)
Assert.False(char.IsLowSurrogate(c.ToString(), 0));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsLowSurrogate(c.ToString(), 0));
}
[Fact]
public static void IsLowSurrogate_String_Int_Invalid()
{
Assert.Throws<ArgumentNullException>("s", () => char.IsLowSurrogate(null, 0)); // String is null
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsLowSurrogate("abc", -1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsLowSurrogate("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsHighSurrogate_Char()
{
foreach (char c in s_highSurrogates)
Assert.True(char.IsHighSurrogate(c));
foreach (char c in s_lowSurrogates)
Assert.False(char.IsHighSurrogate(c));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsHighSurrogate(c));
}
[Fact]
public static void IsHighSurrogate_String_Int()
{
foreach (char c in s_highSurrogates)
Assert.True(char.IsHighSurrogate(c.ToString(), 0));
foreach (char c in s_lowSurrogates)
Assert.False(char.IsHighSurrogate(c.ToString(), 0));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsHighSurrogate(c.ToString(), 0));
}
[Fact]
public static void IsHighSurrogate_String_Int_Invalid()
{
Assert.Throws<ArgumentNullException>("s", () => char.IsHighSurrogate(null, 0)); // String is null
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsHighSurrogate("abc", -1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsHighSurrogate("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsSurrogate_Char()
{
foreach (char c in s_highSurrogates)
Assert.True(char.IsSurrogate(c));
foreach (char c in s_lowSurrogates)
Assert.True(char.IsSurrogate(c));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsSurrogate(c));
}
[Fact]
public static void IsSurrogate_String_Int()
{
foreach (char c in s_highSurrogates)
Assert.True(char.IsSurrogate(c.ToString(), 0));
foreach (char c in s_lowSurrogates)
Assert.True(char.IsSurrogate(c.ToString(), 0));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsSurrogate(c.ToString(), 0));
}
[Fact]
public static void IsSurrogate_String_Int_Invalid()
{
Assert.Throws<ArgumentNullException>("s", () => char.IsSurrogate(null, 0)); // String is null
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogate("abc", -1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogate("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsSurrogatePair_Char()
{
foreach (char hs in s_highSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.True(char.IsSurrogatePair(hs, ls));
foreach (char hs in s_nonSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.False(char.IsSurrogatePair(hs, ls));
foreach (char hs in s_highSurrogates)
foreach (char ls in s_nonSurrogates)
Assert.False(char.IsSurrogatePair(hs, ls));
}
[Fact]
public static void IsSurrogatePair_String_Int()
{
foreach (char hs in s_highSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.True(char.IsSurrogatePair(hs.ToString() + ls, 0));
foreach (char hs in s_nonSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.False(char.IsSurrogatePair(hs.ToString() + ls, 0));
foreach (char hs in s_highSurrogates)
foreach (char ls in s_nonSurrogates)
Assert.False(char.IsSurrogatePair(hs.ToString() + ls, 0));
Assert.False(char.IsSurrogatePair("\ud800\udc00", 1)); // Index + 1 >= s.Length
}
[Fact]
public static void IsSurrogatePair_String_Int_Invalid()
{
Assert.Throws<ArgumentNullException>("s", () => char.IsSurrogatePair(null, 0)); // String is null
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogatePair("abc", -1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogatePair("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsSymbol_Char()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.MathSymbol,
UnicodeCategory.ModifierSymbol,
UnicodeCategory.CurrencySymbol,
UnicodeCategory.OtherSymbol
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsSymbol(c));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsSymbol(c));
}
[Fact]
public static void IsSymbol_String_Int()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.MathSymbol,
UnicodeCategory.ModifierSymbol,
UnicodeCategory.CurrencySymbol,
UnicodeCategory.OtherSymbol
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsSymbol(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsSymbol(c.ToString(), 0));
}
[Fact]
public static void IsSymbol_String_Int_Invalid()
{
Assert.Throws<ArgumentNullException>("s", () => char.IsSymbol(null, 0)); // String is null
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsSymbol("abc", -1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsSymbol("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsUpper_Char()
{
foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter))
Assert.True(char.IsUpper(c));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter))
Assert.False(char.IsUpper(c));
}
[Fact]
public static void IsUpper_String_Int()
{
foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter))
Assert.True(char.IsUpper(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter))
Assert.False(char.IsUpper(c.ToString(), 0));
}
[Fact]
public static void IsUpper_String_Int_Invalid()
{
Assert.Throws<ArgumentNullException>("s", () => char.IsUpper(null, 0)); // String is null
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsUpper("abc", -1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsUpper("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsWhitespace_Char()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsWhiteSpace(c));
foreach (char c in GetTestCharsNotInCategory(categories))
{
// Need to special case some control chars that are treated as whitespace
if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') continue;
Assert.False(char.IsWhiteSpace(c));
}
}
[Fact]
public static void IsWhiteSpace_String_Int()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsWhiteSpace(c.ToString(), 0));
// Some control chars are also considered whitespace for legacy reasons.
// if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085')
Assert.True(char.IsWhiteSpace("\u000b", 0));
Assert.True(char.IsWhiteSpace("\u0085", 0));
foreach (char c in GetTestCharsNotInCategory(categories))
{
// Need to special case some control chars that are treated as whitespace
if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') continue;
Assert.False(char.IsWhiteSpace(c.ToString(), 0));
}
}
[Fact]
public static void IsWhiteSpace_String_Int_Invalid()
{
Assert.Throws<ArgumentNullException>("s", () => char.IsWhiteSpace(null, 0)); // String is null
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsWhiteSpace("abc", -1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => char.IsWhiteSpace("abc", 3)); // Index >= string.Length
}
[Fact]
public static void MaxValue()
{
Assert.Equal(0xffff, char.MaxValue);
}
[Fact]
public static void MinValue()
{
Assert.Equal(0, char.MinValue);
}
[Fact]
public static void ToLower()
{
Assert.Equal('a', char.ToLower('A'));
Assert.Equal('a', char.ToLower('a'));
foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter))
{
char lc = char.ToLower(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsLower(lc));
}
// TitlecaseLetter can have a lower case form (e.g. \u01C8 'Lj' letter which will be 'lj')
// LetterNumber can have a lower case form (e.g. \u2162 'III' letter which will be 'iii')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
Assert.Equal(c, char.ToLower(c));
}
}
[Fact]
public static void ToLowerInvariant()
{
Assert.Equal('a', char.ToLowerInvariant('A'));
Assert.Equal('a', char.ToLowerInvariant('a'));
foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter))
{
char lc = char.ToLowerInvariant(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsLower(lc));
}
// TitlecaseLetter can have a lower case form (e.g. \u01C8 'Lj' letter which will be 'lj')
// LetterNumber can have a lower case form (e.g. \u2162 'III' letter which will be 'iii')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
Assert.Equal(c, char.ToLowerInvariant(c));
}
}
[Theory]
[InlineData('a', "a")]
[InlineData('\uabcd', "\uabcd")]
public static void ToString(char c, string expected)
{
Assert.Equal(expected, c.ToString());
Assert.Equal(expected, char.ToString(c));
}
[Fact]
public static void ToUpper()
{
Assert.Equal('A', char.ToUpper('A'));
Assert.Equal('A', char.ToUpper('a'));
foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter))
{
char lc = char.ToUpper(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsUpper(lc));
}
// TitlecaseLetter can have a uppercase form (e.g. \u01C8 'Lj' letter which will be 'LJ')
// LetterNumber can have a uppercase form (e.g. \u2172 'iii' letter which will be 'III')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
Assert.Equal(c, char.ToUpper(c));
}
}
[Fact]
public static void ToUpperInvariant()
{
Assert.Equal('A', char.ToUpperInvariant('A'));
Assert.Equal('A', char.ToUpperInvariant('a'));
foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter))
{
char lc = char.ToUpperInvariant(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsUpper(lc));
}
// TitlecaseLetter can have a uppercase form (e.g. \u01C8 'Lj' letter which will be 'LJ')
// LetterNumber can have a uppercase form (e.g. \u2172 'iii' letter which will be 'III')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
Assert.Equal(c, char.ToUpperInvariant(c));
}
}
[Theory]
[InlineData("a", 'a')]
[InlineData("4", '4')]
[InlineData(" ", ' ')]
[InlineData("\n", '\n')]
[InlineData("\0", '\0')]
[InlineData("\u0135", '\u0135')]
[InlineData("\u05d9", '\u05d9')]
[InlineData("\ue001", '\ue001')] // Private use codepoint
public static void Parse(string s, char expected)
{
char c;
Assert.True(char.TryParse(s, out c));
Assert.Equal(expected, c);
Assert.Equal(expected, char.Parse(s));
}
[Fact]
public static void Parse_Surrogate()
{
// TODO: add this as [InlineData] when #7166 is fixed
Parse("\ud801", '\ud801'); // High surrogate
Parse("\udc01", '\udc01'); // Low surrogate
}
[Theory]
[InlineData(null, typeof(ArgumentNullException))]
[InlineData("", typeof(FormatException))]
[InlineData("\n\r", typeof(FormatException))]
[InlineData("kj", typeof(FormatException))]
[InlineData(" a", typeof(FormatException))]
[InlineData("a ", typeof(FormatException))]
[InlineData("\\u0135", typeof(FormatException))]
[InlineData("\u01356", typeof(FormatException))]
[InlineData("\ud801\udc01", typeof(FormatException))] // Surrogate pair
public static void Parse_Invalid(string s, Type exceptionType)
{
char c;
Assert.False(char.TryParse(s, out c));
Assert.Equal(default(char), c);
Assert.Throws(exceptionType, () => char.Parse(s));
}
private static IEnumerable<char> GetTestCharsNotInCategory(params UnicodeCategory[] categories)
{
Assert.Equal(s_latinTestSet.Length, s_unicodeTestSet.Length);
for (int i = 0; i < s_latinTestSet.Length; i++)
{
if (Array.Exists(categories, uc => uc == (UnicodeCategory)i))
continue;
char[] latinSet = s_latinTestSet[i];
for (int j = 0; j < latinSet.Length; j++)
yield return latinSet[j];
char[] unicodeSet = s_unicodeTestSet[i];
for (int k = 0; k < unicodeSet.Length; k++)
yield return unicodeSet[k];
}
}
private static IEnumerable<char> GetTestChars(params UnicodeCategory[] categories)
{
for (int i = 0; i < categories.Length; i++)
{
char[] latinSet = s_latinTestSet[(int)categories[i]];
for (int j = 0; j < latinSet.Length; j++)
yield return latinSet[j];
char[] unicodeSet = s_unicodeTestSet[(int)categories[i]];
for (int k = 0; k < unicodeSet.Length; k++)
yield return unicodeSet[k];
}
}
private static char[][] s_latinTestSet = new char[][]
{
new char[] {'\u0047','\u004c','\u0051','\u0056','\u00c0','\u00c5','\u00ca','\u00cf','\u00d4','\u00da'}, // UnicodeCategory.UppercaseLetter
new char[] {'\u0062','\u0068','\u006e','\u0074','\u007a','\u00e1','\u00e7','\u00ed','\u00f3','\u00fa'}, // UnicodeCategory.LowercaseLetter
new char[] {}, // UnicodeCategory.TitlecaseLetter
new char[] {}, // UnicodeCategory.ModifierLetter
new char[] {}, // UnicodeCategory.OtherLetter
new char[] {}, // UnicodeCategory.NonSpacingMark
new char[] {}, // UnicodeCategory.SpacingCombiningMark
new char[] {}, // UnicodeCategory.EnclosingMark
new char[] {'\u0030','\u0031','\u0032','\u0033','\u0034','\u0035','\u0036','\u0037','\u0038','\u0039'}, // UnicodeCategory.DecimalDigitNumber
new char[] {}, // UnicodeCategory.LetterNumber
new char[] {'\u00b2','\u00b3','\u00b9','\u00bc','\u00bd','\u00be'}, // UnicodeCategory.OtherNumber
new char[] {'\u0020','\u00a0'}, // UnicodeCategory.SpaceSeparator
new char[] {}, // UnicodeCategory.LineSeparator
new char[] {}, // UnicodeCategory.ParagraphSeparator
new char[] {'\u0005','\u000b','\u0011','\u0017','\u001d','\u0082','\u0085','\u008e','\u0094','\u009a'}, // UnicodeCategory.Control
new char[] {}, // UnicodeCategory.Format
new char[] {}, // UnicodeCategory.Surrogate
new char[] {}, // UnicodeCategory.PrivateUse
new char[] {'\u005f'}, // UnicodeCategory.ConnectorPunctuation
new char[] {'\u002d','\u00ad'}, // UnicodeCategory.DashPunctuation
new char[] {'\u0028','\u005b','\u007b'}, // UnicodeCategory.OpenPunctuation
new char[] {'\u0029','\u005d','\u007d'}, // UnicodeCategory.ClosePunctuation
new char[] {'\u00ab'}, // UnicodeCategory.InitialQuotePunctuation
new char[] {'\u00bb'}, // UnicodeCategory.FinalQuotePunctuation
new char[] {'\u002e','\u002f','\u003a','\u003b','\u003f','\u0040','\u005c','\u00a1','\u00b7','\u00bf'}, // UnicodeCategory.OtherPunctuation
new char[] {'\u002b','\u003c','\u003d','\u003e','\u007c','\u007e','\u00ac','\u00b1','\u00d7','\u00f7'}, // UnicodeCategory.MathSymbol
new char[] {'\u0024','\u00a2','\u00a3','\u00a4','\u00a5'}, // UnicodeCategory.CurrencySymbol
new char[] {'\u005e','\u0060','\u00a8','\u00af','\u00b4','\u00b8'}, // UnicodeCategory.ModifierSymbol
new char[] {'\u00a6','\u00a7','\u00a9','\u00ae','\u00b0','\u00b6'}, // UnicodeCategory.OtherSymbol
new char[] {}, // UnicodeCategory.OtherNotAssigned
};
private static char[][] s_unicodeTestSet = new char[][]
{
new char[] {'\u0102','\u01ac','\u0392','\u0428','\u0508','\u10c4','\u1eb4','\u1fba','\u2c28','\ua668'}, // UnicodeCategory.UppercaseLetter
new char[] { '\u0107', '\u012D', '\u0140', '\u0151', '\u013A', '\u01A1', '\u01F9', '\u022D', '\u1E09','\uFF45' }, // UnicodeCategory.LowercaseLetter
new char[] {'\u01c8','\u1f88','\u1f8b','\u1f8e','\u1f99','\u1f9c','\u1f9f','\u1faa','\u1fad','\u1fbc'}, // UnicodeCategory.TitlecaseLetter
new char[] {'\u02b7','\u02cd','\u07f4','\u1d2f','\u1d41','\u1d53','\u1d9d','\u1daf','\u2091','\u30fe'}, // UnicodeCategory.ModifierLetter
new char[] {'\u01c0','\u37be','\u4970','\u5b6c','\u6d1e','\u7ed0','\u9082','\ua271','\ub985','\ucb37'}, // UnicodeCategory.OtherLetter
new char[] {'\u0303','\u034e','\u05b5','\u0738','\u0a4d','\u0e49','\u0fad','\u180b','\u1dd5','\u2dfd'}, // UnicodeCategory.NonSpacingMark
new char[] {'\u0982','\u0b03','\u0c41','\u0d40','\u0df3','\u1083','\u1925','\u1b44','\ua8b5' }, // UnicodeCategory.SpacingCombiningMark
new char[] {'\u20dd','\u20de','\u20df','\u20e0','\u20e2','\u20e3','\u20e4','\ua670','\ua671','\ua672'}, // UnicodeCategory.EnclosingMark
new char[] {'\u0660','\u0966','\u0ae6','\u0c66','\u0e50','\u1040','\u1810','\u1b50','\u1c50','\ua900'}, // UnicodeCategory.DecimalDigitNumber
new char[] {'\u2162','\u2167','\u216c','\u2171','\u2176','\u217b','\u2180','\u2187','\u3023','\u3028'}, // UnicodeCategory.LetterNumber
new char[] {'\u0c78','\u136b','\u17f7','\u2158','\u2471','\u248a','\u24f1','\u2780','\u3220','\u3280'}, // UnicodeCategory.OtherNumber
new char[] {'\u2004','\u2005','\u2006','\u2007','\u2008','\u2009','\u200a','\u202f','\u205f','\u3000'}, // UnicodeCategory.SpaceSeparator
new char[] {'\u2028'}, // UnicodeCategory.LineSeparator
new char[] {'\u2029'}, // UnicodeCategory.ParagraphSeparator
new char[] {}, // UnicodeCategory.Control
new char[] {'\u0603','\u17b4','\u200c','\u200f','\u202c','\u2060','\u2063','\u206b','\u206e','\ufff9'}, // UnicodeCategory.Format
new char[] {'\ud808','\ud8d4','\ud9a0','\uda6c','\udb38','\udc04','\udcd0','\udd9c','\ude68','\udf34'}, // UnicodeCategory.Surrogate
new char[] {'\ue000','\ue280','\ue500','\ue780','\uea00','\uec80','\uef00','\uf180','\uf400','\uf680'}, // UnicodeCategory.PrivateUse
new char[] {'\u203f','\u2040','\u2054','\ufe33','\ufe34','\ufe4d','\ufe4e','\ufe4f','\uff3f'}, // UnicodeCategory.ConnectorPunctuation
new char[] {'\u2e17','\u2e1a','\u301c','\u3030','\u30a0','\ufe31','\ufe32','\ufe58','\ufe63','\uff0d'}, // UnicodeCategory.DashPunctuation
new char[] {'\u2768','\u2774','\u27ee','\u298d','\u29d8','\u2e28','\u3014','\ufe17','\ufe3f','\ufe5d'}, // UnicodeCategory.OpenPunctuation
new char[] {'\u276b','\u27c6','\u2984','\u2990','\u29db','\u3009','\u3017','\ufe18','\ufe40','\ufe5e'}, // UnicodeCategory.ClosePunctuation
new char[] {'\u201b','\u201c','\u201f','\u2039','\u2e02','\u2e04','\u2e09','\u2e0c','\u2e1c','\u2e20'}, // UnicodeCategory.InitialQuotePunctuation
new char[] {'\u2019','\u201d','\u203a','\u2e03','\u2e05','\u2e0a','\u2e0d','\u2e1d','\u2e21'}, // UnicodeCategory.FinalQuotePunctuation
new char[] {'\u0589','\u0709','\u0f10','\u16ec','\u1b5b','\u2034','\u2058','\u2e16','\ua8cf','\ufe55'}, // UnicodeCategory.OtherPunctuation
new char[] {'\u2052','\u2234','\u2290','\u22ec','\u27dd','\u2943','\u29b5','\u2a17','\u2a73','\u2acf'}, // UnicodeCategory.MathSymbol
new char[] {'\u17db','\u20a2','\u20a5','\u20a8','\u20ab','\u20ae','\u20b1','\u20b4','\ufe69','\uffe1'}, // UnicodeCategory.CurrencySymbol
new char[] {'\u02c5','\u02da','\u02e8','\u02f3','\u02fc','\u1fc0','\u1fee','\ua703','\ua70c','\ua715'}, // UnicodeCategory.ModifierSymbol
new char[] {'\u0bf3','\u2316','\u24ac','\u25b2','\u26af','\u285c','\u2e8f','\u2f8c','\u3292','\u3392'}, // UnicodeCategory.OtherSymbol
new char[] {'\u09c6','\u0dfa','\u2e5c'}, // UnicodeCategory.OtherNotAssigned
};
private static char[] s_highSurrogates = new char[] { '\ud800', '\udaaa', '\udbff' }; // Range from '\ud800' to '\udbff'
private static char[] s_lowSurrogates = new char[] { '\udc00', '\udeee', '\udfff' }; // Range from '\udc00' to '\udfff'
private static char[] s_nonSurrogates = new char[] { '\u0000', '\ud7ff', '\ue000', '\uffff' };
}
}
| |
// 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.AcceptanceTestsBodyComplex
{
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for Primitive.
/// </summary>
public static partial class PrimitiveExtensions
{
/// <summary>
/// Get complex types with integer properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IntWrapper GetInt(this IPrimitive operations)
{
return Task.Factory.StartNew(s => ((IPrimitive)s).GetIntAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with integer properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IntWrapper> GetIntAsync(this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetIntWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with integer properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put -1 and 2
/// </param>
public static void PutInt(this IPrimitive operations, IntWrapper complexBody)
{
Task.Factory.StartNew(s => ((IPrimitive)s).PutIntAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with integer properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put -1 and 2
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutIntAsync(this IPrimitive operations, IntWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutIntWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get complex types with long properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static LongWrapper GetLong(this IPrimitive operations)
{
return Task.Factory.StartNew(s => ((IPrimitive)s).GetLongAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with long properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LongWrapper> GetLongAsync(this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetLongWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with long properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put 1099511627775 and -999511627788
/// </param>
public static void PutLong(this IPrimitive operations, LongWrapper complexBody)
{
Task.Factory.StartNew(s => ((IPrimitive)s).PutLongAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with long properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put 1099511627775 and -999511627788
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutLongAsync(this IPrimitive operations, LongWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutLongWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get complex types with float properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static FloatWrapper GetFloat(this IPrimitive operations)
{
return Task.Factory.StartNew(s => ((IPrimitive)s).GetFloatAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with float properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<FloatWrapper> GetFloatAsync(this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetFloatWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with float properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put 1.05 and -0.003
/// </param>
public static void PutFloat(this IPrimitive operations, FloatWrapper complexBody)
{
Task.Factory.StartNew(s => ((IPrimitive)s).PutFloatAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with float properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put 1.05 and -0.003
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutFloatAsync(this IPrimitive operations, FloatWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutFloatWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get complex types with double properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DoubleWrapper GetDouble(this IPrimitive operations)
{
return Task.Factory.StartNew(s => ((IPrimitive)s).GetDoubleAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with double properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DoubleWrapper> GetDoubleAsync(this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetDoubleWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with double properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put 3e-100 and
/// -0.000000000000000000000000000000000000000000000000000000005
/// </param>
public static void PutDouble(this IPrimitive operations, DoubleWrapper complexBody)
{
Task.Factory.StartNew(s => ((IPrimitive)s).PutDoubleAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with double properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put 3e-100 and
/// -0.000000000000000000000000000000000000000000000000000000005
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutDoubleAsync(this IPrimitive operations, DoubleWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutDoubleWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get complex types with bool properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static BooleanWrapper GetBool(this IPrimitive operations)
{
return Task.Factory.StartNew(s => ((IPrimitive)s).GetBoolAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with bool properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<BooleanWrapper> GetBoolAsync(this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetBoolWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with bool properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put true and false
/// </param>
public static void PutBool(this IPrimitive operations, BooleanWrapper complexBody)
{
Task.Factory.StartNew(s => ((IPrimitive)s).PutBoolAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with bool properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put true and false
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutBoolAsync(this IPrimitive operations, BooleanWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutBoolWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get complex types with string properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static StringWrapper GetString(this IPrimitive operations)
{
return Task.Factory.StartNew(s => ((IPrimitive)s).GetStringAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with string properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<StringWrapper> GetStringAsync(this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetStringWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with string properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put 'goodrequest', '', and null
/// </param>
public static void PutString(this IPrimitive operations, StringWrapper complexBody)
{
Task.Factory.StartNew(s => ((IPrimitive)s).PutStringAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with string properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put 'goodrequest', '', and null
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutStringAsync(this IPrimitive operations, StringWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutStringWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get complex types with date properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateWrapper GetDate(this IPrimitive operations)
{
return Task.Factory.StartNew(s => ((IPrimitive)s).GetDateAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with date properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateWrapper> GetDateAsync(this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with date properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put '0001-01-01' and '2016-02-29'
/// </param>
public static void PutDate(this IPrimitive operations, DateWrapper complexBody)
{
Task.Factory.StartNew(s => ((IPrimitive)s).PutDateAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with date properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put '0001-01-01' and '2016-02-29'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutDateAsync(this IPrimitive operations, DateWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutDateWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get complex types with datetime properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DatetimeWrapper GetDateTime(this IPrimitive operations)
{
return Task.Factory.StartNew(s => ((IPrimitive)s).GetDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with datetime properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DatetimeWrapper> GetDateTimeAsync(this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with datetime properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put '0001-01-01T12:00:00-04:00' and '2015-05-18T11:38:00-08:00'
/// </param>
public static void PutDateTime(this IPrimitive operations, DatetimeWrapper complexBody)
{
Task.Factory.StartNew(s => ((IPrimitive)s).PutDateTimeAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with datetime properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put '0001-01-01T12:00:00-04:00' and '2015-05-18T11:38:00-08:00'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutDateTimeAsync(this IPrimitive operations, DatetimeWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutDateTimeWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get complex types with datetimeRfc1123 properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Datetimerfc1123Wrapper GetDateTimeRfc1123(this IPrimitive operations)
{
return Task.Factory.StartNew(s => ((IPrimitive)s).GetDateTimeRfc1123Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with datetimeRfc1123 properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Datetimerfc1123Wrapper> GetDateTimeRfc1123Async(this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetDateTimeRfc1123WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with datetimeRfc1123 properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put 'Mon, 01 Jan 0001 12:00:00 GMT' and 'Mon, 18 May 2015 11:38:00
/// GMT'
/// </param>
public static void PutDateTimeRfc1123(this IPrimitive operations, Datetimerfc1123Wrapper complexBody)
{
Task.Factory.StartNew(s => ((IPrimitive)s).PutDateTimeRfc1123Async(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with datetimeRfc1123 properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put 'Mon, 01 Jan 0001 12:00:00 GMT' and 'Mon, 18 May 2015 11:38:00
/// GMT'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutDateTimeRfc1123Async(this IPrimitive operations, Datetimerfc1123Wrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutDateTimeRfc1123WithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get complex types with duration properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DurationWrapper GetDuration(this IPrimitive operations)
{
return Task.Factory.StartNew(s => ((IPrimitive)s).GetDurationAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with duration properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DurationWrapper> GetDurationAsync(this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetDurationWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with duration properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='field'>
/// </param>
public static void PutDuration(this IPrimitive operations, System.TimeSpan? field = default(System.TimeSpan?))
{
Task.Factory.StartNew(s => ((IPrimitive)s).PutDurationAsync(field), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with duration properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='field'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutDurationAsync(this IPrimitive operations, System.TimeSpan? field = default(System.TimeSpan?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutDurationWithHttpMessagesAsync(field, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get complex types with byte properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static ByteWrapper GetByte(this IPrimitive operations)
{
return Task.Factory.StartNew(s => ((IPrimitive)s).GetByteAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with byte properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ByteWrapper> GetByteAsync(this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetByteWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with byte properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='field'>
/// </param>
public static void PutByte(this IPrimitive operations, byte[] field = default(byte[]))
{
Task.Factory.StartNew(s => ((IPrimitive)s).PutByteAsync(field), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with byte properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='field'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutByteAsync(this IPrimitive operations, byte[] field = default(byte[]), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutByteWithHttpMessagesAsync(field, null, cancellationToken).ConfigureAwait(false);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Monitoring;
using OpenSim.Framework.Servers;
using OpenSim.Region.CoreModules.Framework.Monitoring.Alerts;
using OpenSim.Region.CoreModules.Framework.Monitoring.Monitors;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
namespace OpenSim.Region.CoreModules.Framework.Monitoring
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MonitorModule")]
public class MonitorModule : INonSharedRegionModule
{
/// <summary>
/// Is this module enabled?
/// </summary>
public bool Enabled { get; private set; }
private Scene m_scene;
/// <summary>
/// These are monitors where we know the static details in advance.
/// </summary>
/// <remarks>
/// Dynamic monitors also exist (we don't know any of the details of what stats we get back here)
/// but these are currently hardcoded.
/// </remarks>
private readonly List<IMonitor> m_staticMonitors = new List<IMonitor>();
private readonly List<IAlert> m_alerts = new List<IAlert>();
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public MonitorModule()
{
Enabled = true;
}
#region Implementation of INonSharedRegionModule
public void Initialise(IConfigSource source)
{
IConfig cnfg = source.Configs["Monitoring"];
if (cnfg != null)
Enabled = cnfg.GetBoolean("Enabled", true);
if (!Enabled)
return;
}
public void AddRegion(Scene scene)
{
if (!Enabled)
return;
m_scene = scene;
m_scene.AddCommand("General", this, "monitor report",
"monitor report",
"Returns a variety of statistics about the current region and/or simulator",
DebugMonitors);
MainServer.Instance.AddHTTPHandler("/monitorstats/" + m_scene.RegionInfo.RegionID, StatsPage);
MainServer.Instance.AddHTTPHandler(
"/monitorstats/" + Uri.EscapeDataString(m_scene.RegionInfo.RegionName), StatsPage);
AddMonitors();
RegisterStatsManagerRegionStatistics();
}
public void RemoveRegion(Scene scene)
{
if (!Enabled)
return;
MainServer.Instance.RemoveHTTPHandler("GET", "/monitorstats/" + m_scene.RegionInfo.RegionID);
MainServer.Instance.RemoveHTTPHandler("GET", "/monitorstats/" + Uri.EscapeDataString(m_scene.RegionInfo.RegionName));
UnRegisterStatsManagerRegionStatistics();
m_scene = null;
}
public void Close()
{
}
public string Name
{
get { return "Region Health Monitoring Module"; }
}
public void RegionLoaded(Scene scene)
{
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
public void AddMonitors()
{
m_staticMonitors.Add(new AgentCountMonitor(m_scene));
m_staticMonitors.Add(new ChildAgentCountMonitor(m_scene));
m_staticMonitors.Add(new GCMemoryMonitor());
m_staticMonitors.Add(new ObjectCountMonitor(m_scene));
m_staticMonitors.Add(new PhysicsFrameMonitor(m_scene));
m_staticMonitors.Add(new PhysicsUpdateFrameMonitor(m_scene));
m_staticMonitors.Add(new PWSMemoryMonitor());
m_staticMonitors.Add(new ThreadCountMonitor());
m_staticMonitors.Add(new TotalFrameMonitor(m_scene));
m_staticMonitors.Add(new EventFrameMonitor(m_scene));
m_staticMonitors.Add(new LandFrameMonitor(m_scene));
m_staticMonitors.Add(new LastFrameTimeMonitor(m_scene));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"TimeDilationMonitor",
"Time Dilation",
m => m.Scene.StatsReporter.LastReportedSimStats[0],
m => m.GetValue().ToString()));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"SimFPSMonitor",
"Sim FPS",
m => m.Scene.StatsReporter.LastReportedSimStats[1],
m => string.Format("{0}", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"PhysicsFPSMonitor",
"Physics FPS",
m => m.Scene.StatsReporter.LastReportedSimStats[2],
m => string.Format("{0}", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"AgentUpdatesPerSecondMonitor",
"Agent Updates",
m => m.Scene.StatsReporter.LastReportedSimStats[3],
m => string.Format("{0} per second", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"ActiveObjectCountMonitor",
"Active Objects",
m => m.Scene.StatsReporter.LastReportedSimStats[7],
m => string.Format("{0}", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"ActiveScriptsMonitor",
"Active Scripts",
m => m.Scene.StatsReporter.LastReportedSimStats[19],
m => string.Format("{0}", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"ScriptEventsPerSecondMonitor",
"Script Events",
m => m.Scene.StatsReporter.LastReportedSimStats[20],
m => string.Format("{0} per second", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"InPacketsPerSecondMonitor",
"In Packets",
m => m.Scene.StatsReporter.LastReportedSimStats[13],
m => string.Format("{0} per second", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"OutPacketsPerSecondMonitor",
"Out Packets",
m => m.Scene.StatsReporter.LastReportedSimStats[14],
m => string.Format("{0} per second", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"UnackedBytesMonitor",
"Unacked Bytes",
m => m.Scene.StatsReporter.LastReportedSimStats[15],
m => string.Format("{0}", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"PendingDownloadsMonitor",
"Pending Downloads",
m => m.Scene.StatsReporter.LastReportedSimStats[17],
m => string.Format("{0}", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"PendingUploadsMonitor",
"Pending Uploads",
m => m.Scene.StatsReporter.LastReportedSimStats[18],
m => string.Format("{0}", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"TotalFrameTimeMonitor",
"Total Frame Time",
m => m.Scene.StatsReporter.LastReportedSimStats[8],
m => string.Format("{0} ms", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"NetFrameTimeMonitor",
"Net Frame Time",
m => m.Scene.StatsReporter.LastReportedSimStats[9],
m => string.Format("{0} ms", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"PhysicsFrameTimeMonitor",
"Physics Frame Time",
m => m.Scene.StatsReporter.LastReportedSimStats[10],
m => string.Format("{0} ms", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"SimulationFrameTimeMonitor",
"Simulation Frame Time",
m => m.Scene.StatsReporter.LastReportedSimStats[12],
m => string.Format("{0} ms", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"AgentFrameTimeMonitor",
"Agent Frame Time",
m => m.Scene.StatsReporter.LastReportedSimStats[16],
m => string.Format("{0} ms", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"ImagesFrameTimeMonitor",
"Images Frame Time",
m => m.Scene.StatsReporter.LastReportedSimStats[11],
m => string.Format("{0} ms", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"SpareFrameTimeMonitor",
"Spare Frame Time",
m => m.Scene.StatsReporter.LastReportedSimStats[21],
m => string.Format("{0} ms", m.GetValue())));
m_alerts.Add(new DeadlockAlert(m_staticMonitors.Find(x => x is LastFrameTimeMonitor) as LastFrameTimeMonitor));
foreach (IAlert alert in m_alerts)
{
alert.OnTriggerAlert += OnTriggerAlert;
}
}
public void DebugMonitors(string module, string[] args)
{
foreach (IMonitor monitor in m_staticMonitors)
{
MainConsole.Instance.OutputFormat(
"[MONITOR MODULE]: {0} reports {1} = {2}",
m_scene.RegionInfo.RegionName, monitor.GetFriendlyName(), monitor.GetFriendlyValue());
}
foreach (KeyValuePair<string, float> tuple in m_scene.StatsReporter.GetExtraSimStats())
{
MainConsole.Instance.OutputFormat(
"[MONITOR MODULE]: {0} reports {1} = {2}",
m_scene.RegionInfo.RegionName, tuple.Key, tuple.Value);
}
}
public void TestAlerts()
{
foreach (IAlert alert in m_alerts)
{
alert.Test();
}
}
public Hashtable StatsPage(Hashtable request)
{
// If request was for a specific monitor
// eg url/?monitor=Monitor.Name
if (request.ContainsKey("monitor"))
{
string monID = (string) request["monitor"];
foreach (IMonitor monitor in m_staticMonitors)
{
string elemName = monitor.ToString();
if (elemName.StartsWith(monitor.GetType().Namespace))
elemName = elemName.Substring(monitor.GetType().Namespace.Length + 1);
if (elemName == monID || monitor.ToString() == monID)
{
Hashtable ereply3 = new Hashtable();
ereply3["int_response_code"] = 404; // 200 OK
ereply3["str_response_string"] = monitor.GetValue().ToString();
ereply3["content_type"] = "text/plain";
return ereply3;
}
}
// FIXME: Arguably this should also be done with dynamic monitors but I'm not sure what the above code
// is even doing. Why are we inspecting the type of the monitor???
// No monitor with that name
Hashtable ereply2 = new Hashtable();
ereply2["int_response_code"] = 404; // 200 OK
ereply2["str_response_string"] = "No such monitor";
ereply2["content_type"] = "text/plain";
return ereply2;
}
string xml = "<data>";
foreach (IMonitor monitor in m_staticMonitors)
{
string elemName = monitor.GetName();
xml += "<" + elemName + ">" + monitor.GetValue().ToString() + "</" + elemName + ">";
// m_log.DebugFormat("[MONITOR MODULE]: {0} = {1}", elemName, monitor.GetValue());
}
foreach (KeyValuePair<string, float> tuple in m_scene.StatsReporter.GetExtraSimStats())
{
xml += "<" + tuple.Key + ">" + tuple.Value + "</" + tuple.Key + ">";
}
xml += "</data>";
Hashtable ereply = new Hashtable();
ereply["int_response_code"] = 200; // 200 OK
ereply["str_response_string"] = xml;
ereply["content_type"] = "text/xml";
return ereply;
}
void OnTriggerAlert(System.Type reporter, string reason, bool fatal)
{
m_log.Error("[Monitor] " + reporter.Name + " for " + m_scene.RegionInfo.RegionName + " reports " + reason + " (Fatal: " + fatal + ")");
}
private List<Stat> registeredStats = new List<Stat>();
private void MakeStat(string pName, string pUnitName, Action<Stat> act)
{
Stat tempStat = new Stat(pName, pName, pName, pUnitName, "scene", m_scene.RegionInfo.RegionName, StatType.Pull, act, StatVerbosity.Info);
StatsManager.RegisterStat(tempStat);
registeredStats.Add(tempStat);
}
private void RegisterStatsManagerRegionStatistics()
{
MakeStat("RootAgents", "avatars", (s) => { s.Value = m_scene.SceneGraph.GetRootAgentCount(); });
MakeStat("ChildAgents", "avatars", (s) => { s.Value = m_scene.SceneGraph.GetChildAgentCount(); });
MakeStat("TotalPrims", "objects", (s) => { s.Value = m_scene.SceneGraph.GetTotalObjectsCount(); });
MakeStat("ActivePrims", "objects", (s) => { s.Value = m_scene.SceneGraph.GetActiveObjectsCount(); });
MakeStat("ActiveScripts", "scripts", (s) => { s.Value = m_scene.SceneGraph.GetActiveScriptsCount(); });
MakeStat("TimeDilation", "sec/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[0]; });
MakeStat("SimFPS", "fps", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[1]; });
MakeStat("PhysicsFPS", "fps", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[2]; });
MakeStat("AgentUpdates", "updates/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[3]; });
MakeStat("FrameTime", "ms/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[8]; });
MakeStat("NetTime", "ms/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[9]; });
MakeStat("OtherTime", "ms/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[12]; });
MakeStat("PhysicsTime", "ms/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[10]; });
MakeStat("AgentTime", "ms/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[16]; });
MakeStat("ImageTime", "ms/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[11]; });
MakeStat("ScriptLines", "lines/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[20]; });
MakeStat("SimSpareMS", "ms/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[21]; });
}
private void UnRegisterStatsManagerRegionStatistics()
{
foreach (Stat stat in registeredStats)
{
StatsManager.DeregisterStat(stat);
stat.Dispose();
}
registeredStats.Clear();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Messaging.EventHubs.Core;
using Azure.Messaging.EventHubs.Diagnostics;
namespace Azure.Messaging.EventHubs.Primitives
{
/// <summary>
/// Handles all load balancing concerns for an event processor including claiming, stealing, and relinquishing ownership.
/// </summary>
///
internal class PartitionLoadBalancer
{
/// <summary>The random number generator to use for a specific thread.</summary>
private static readonly ThreadLocal<Random> RandomNumberGenerator = new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref s_randomSeed)), false);
/// <summary>The seed to use for initializing random number generated for a given thread-specific instance.</summary>
private static int s_randomSeed = Environment.TickCount;
/// <summary>
/// Responsible for creation of checkpoints and for ownership claim.
/// </summary>
///
private readonly StorageManager StorageManager;
/// <summary>
/// A partition distribution dictionary, mapping an owner's identifier to the amount of partitions it owns and its list of partitions.
/// </summary>
///
private readonly Dictionary<string, List<EventProcessorPartitionOwnership>> ActiveOwnershipWithDistribution = new Dictionary<string, List<EventProcessorPartitionOwnership>>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// The fully qualified Event Hubs namespace that the processor is associated with. This is likely
/// to be similar to <c>{yournamespace}.servicebus.windows.net</c>.
/// </summary>
///
public string FullyQualifiedNamespace { get; }
/// <summary>
/// The name of the Event Hub that the processor is connected to, specific to the
/// Event Hubs namespace that contains it.
/// </summary>
///
public string EventHubName { get; }
/// <summary>
/// The name of the consumer group this load balancer is associated with. Events will be
/// read only in the context of this group.
/// </summary>
///
public string ConsumerGroup { get; }
/// <summary>
/// The identifier of the EventProcessorClient that owns this load balancer.
/// </summary>
///
public string OwnerIdentifier { get; }
/// <summary>
/// The minimum amount of time for an ownership to be considered expired without further updates.
/// </summary>
///
public TimeSpan OwnershipExpirationInterval { get; }
/// <summary>
/// The minimum amount of time to be elapsed between two load balancing verifications.
/// </summary>
///
public TimeSpan LoadBalanceInterval { get; internal set; }
/// <summary>
/// Indicates whether the load balancer believes itself to be in a balanced state
/// when considering its fair share of partitions and whether any partitions
/// remain unclaimed.
/// </summary>
///
public virtual bool IsBalanced { get; private set; }
/// <summary>
/// The partitionIds currently owned by the associated event processor.
/// </summary>
///
public virtual IEnumerable<string> OwnedPartitionIds => InstanceOwnership.Keys;
/// <summary>
/// The instance of <see cref="PartitionLoadBalancerEventSource" /> which can be mocked for testing.
/// </summary>
///
internal PartitionLoadBalancerEventSource Logger { get; set; } = PartitionLoadBalancerEventSource.Log;
/// <summary>
/// The set of partition ownership the associated event processor owns. Partition ids are used as keys.
/// </summary>
///
private Dictionary<string, EventProcessorPartitionOwnership> InstanceOwnership { get; set; } = new Dictionary<string, EventProcessorPartitionOwnership>();
/// <summary>
/// Initializes a new instance of the <see cref="PartitionLoadBalancer" /> class.
/// </summary>
///
/// <param name="storageManager">Responsible for creation of checkpoints and for ownership claim.</param>
/// <param name="identifier">The identifier of the EventProcessorClient that owns this load balancer.</param>
/// <param name="consumerGroup">The name of the consumer group this load balancer is associated with.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace that the processor is associated with.</param>
/// <param name="eventHubName">The name of the Event Hub that the processor is associated with.</param>
/// <param name="ownershipExpirationInterval">The minimum amount of time for an ownership to be considered expired without further updates.</param>
/// <param name="loadBalancingInterval">The minimum amount of time to be elapsed between two load balancing verifications.</param>
///
public PartitionLoadBalancer(StorageManager storageManager,
string identifier,
string consumerGroup,
string fullyQualifiedNamespace,
string eventHubName,
TimeSpan ownershipExpirationInterval,
TimeSpan loadBalancingInterval)
{
Argument.AssertNotNull(storageManager, nameof(storageManager));
Argument.AssertNotNullOrEmpty(identifier, nameof(identifier));
Argument.AssertNotNullOrEmpty(consumerGroup, nameof(consumerGroup));
Argument.AssertNotNullOrEmpty(fullyQualifiedNamespace, nameof(fullyQualifiedNamespace));
Argument.AssertNotNullOrEmpty(eventHubName, nameof(eventHubName));
StorageManager = storageManager;
OwnerIdentifier = identifier;
FullyQualifiedNamespace = fullyQualifiedNamespace;
EventHubName = eventHubName;
ConsumerGroup = consumerGroup;
OwnershipExpirationInterval = ownershipExpirationInterval;
LoadBalanceInterval = loadBalancingInterval;
}
/// <summary>
/// Initializes a new instance of the <see cref="PartitionLoadBalancer" /> class.
/// </summary>
///
protected PartitionLoadBalancer()
{
// Because this constructor is used heavily in testing, initialize the
// critical timing properties to their default option values.
var options = new EventProcessorOptions();
LoadBalanceInterval = options.LoadBalancingUpdateInterval;
OwnershipExpirationInterval = options.PartitionOwnershipExpirationInterval;
}
/// <summary>
/// Performs load balancing between multiple EventProcessorClient instances, claiming others' partitions to enforce
/// a more equal distribution when necessary. It also manages its own partition processing tasks and ownership.
/// </summary>
///
/// <param name="partitionIds">The set of partitionIds available for ownership balancing.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>The claimed ownership. <c>null</c> if this instance is not eligible, if no claimable ownership was found or if the claim attempt failed.</returns>
///
public virtual async ValueTask<EventProcessorPartitionOwnership> RunLoadBalancingAsync(string[] partitionIds,
CancellationToken cancellationToken)
{
// Renew this instance's ownership so they don't expire.
await RenewOwnershipAsync(cancellationToken).ConfigureAwait(false);
// From the storage service, obtain a complete list of ownership, including expired ones. We may still need
// their eTags to claim orphan partitions.
IEnumerable<EventProcessorPartitionOwnership> completeOwnershipList;
try
{
completeOwnershipList = (await StorageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup, cancellationToken)
.ConfigureAwait(false))
.ToList();
}
catch (TaskCanceledException)
{
throw;
}
catch (OperationCanceledException)
{
throw new TaskCanceledException();
}
catch (Exception ex)
{
// If ownership list retrieval fails, give up on the current cycle. There's nothing more we can do
// without an updated ownership list. Set the EventHubName to null so it doesn't modify the exception
// message. This exception message is used so the processor can retrieve the raw Operation string, and
// adding the EventHubName would append unwanted info to it.
throw new EventHubsException(true, null, Resources.OperationListOwnership, ex);
}
// There's no point in continuing the current cycle if we failed to fetch the completeOwnershipList.
if (completeOwnershipList == default)
{
return default;
}
// Create a partition distribution dictionary from the complete ownership list we have, mapping an owner's identifier to the list of
// partitions it owns. When an event processor goes down and it has only expired ownership, it will not be taken into consideration
// by others. The expiration time defaults to 30 seconds, but it may be overridden by a derived class.
var unclaimedPartitions = new HashSet<string>(partitionIds);
var utcNow = GetDateTimeOffsetNow();
var activeOwnership = default(EventProcessorPartitionOwnership);
ActiveOwnershipWithDistribution.Clear();
ActiveOwnershipWithDistribution[OwnerIdentifier] = new List<EventProcessorPartitionOwnership>();
foreach (EventProcessorPartitionOwnership ownership in completeOwnershipList)
{
if (utcNow.Subtract(ownership.LastModifiedTime) < OwnershipExpirationInterval && !string.IsNullOrEmpty(ownership.OwnerIdentifier))
{
activeOwnership = ownership;
// If a processor crashes and restarts, then it is possible for it to own partitions that it is not currently
// tracking as owned. Test for this case and ensure that ownership is tracked and extended.
if ((string.Equals(ownership.OwnerIdentifier, OwnerIdentifier, StringComparison.OrdinalIgnoreCase)) && (!InstanceOwnership.ContainsKey(ownership.PartitionId)))
{
(_, activeOwnership) = await ClaimOwnershipAsync(ownership.PartitionId, new[] { ownership }, cancellationToken).ConfigureAwait(false);
// If the claim failed, then the ownership period was not extended. Since the original ownership had not
// yet expired prior to the claim attempt, consider the original to be the active ownership for this cycle.
if (activeOwnership == default)
{
activeOwnership = ownership;
}
InstanceOwnership[activeOwnership.PartitionId] = activeOwnership;
}
// Update active ownership and trim the unclaimed partitions.
if (ActiveOwnershipWithDistribution.ContainsKey(activeOwnership.OwnerIdentifier))
{
ActiveOwnershipWithDistribution[activeOwnership.OwnerIdentifier].Add(activeOwnership);
}
else
{
ActiveOwnershipWithDistribution[activeOwnership.OwnerIdentifier] = new List<EventProcessorPartitionOwnership> { activeOwnership };
}
unclaimedPartitions.Remove(activeOwnership.PartitionId);
}
}
// Find an ownership to claim and try to claim it. The method will return null if this instance was not eligible to
// increase its ownership list, if no claimable ownership could be found or if a claim attempt has failed.
var (claimAttempted, claimedOwnership) = await FindAndClaimOwnershipAsync(completeOwnershipList, unclaimedPartitions, partitionIds.Length, cancellationToken).ConfigureAwait(false);
if (claimedOwnership != null)
{
InstanceOwnership[claimedOwnership.PartitionId] = claimedOwnership;
}
// Update the balanced state. Consider the load balanced if this processor has its minimum share of partitions and did not
// attempt to claim a partition.
var minimumDesiredPartitions = partitionIds.Length / ActiveOwnershipWithDistribution.Keys.Count;
IsBalanced = ((InstanceOwnership.Count >= minimumDesiredPartitions) && (!claimAttempted));
return claimedOwnership;
}
/// <summary>
/// Relinquishes this instance's ownership so they can be claimed by other processors and clears the OwnedPartitionIds.
/// </summary>
///
/// <param name="cancellationToken">A <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
public virtual async Task RelinquishOwnershipAsync(CancellationToken cancellationToken)
{
IEnumerable<EventProcessorPartitionOwnership> ownershipToRelinquish = InstanceOwnership.Values
.Select(ownership => new EventProcessorPartitionOwnership
{
FullyQualifiedNamespace = ownership.FullyQualifiedNamespace,
EventHubName = ownership.EventHubName,
ConsumerGroup = ownership.ConsumerGroup,
OwnerIdentifier = string.Empty, //set ownership to Empty so that it is treated as available to claim
PartitionId = ownership.PartitionId,
LastModifiedTime = ownership.LastModifiedTime,
Version = ownership.Version
});
await StorageManager.ClaimOwnershipAsync(ownershipToRelinquish, cancellationToken).ConfigureAwait(false);
InstanceOwnership.Clear();
}
/// <summary>
/// Finds and tries to claim an ownership if this processor instance is eligible to increase its ownership list.
/// </summary>
///
/// <param name="completeOwnershipEnumerable">A complete enumerable of ownership obtained from the storage service.</param>
/// <param name="unclaimedPartitions">The set of partitionIds that are currently unclaimed.</param>
/// <param name="partitionCount">The count of partitions.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>A tuple indicating whether a claim was attempted and any ownership that was claimed. The claimed ownership will be <c>null</c> if no claim was attempted or if the claim attempt failed.</returns>
///
private ValueTask<(bool wasClaimAttempted, EventProcessorPartitionOwnership claimedPartition)> FindAndClaimOwnershipAsync(IEnumerable<EventProcessorPartitionOwnership> completeOwnershipEnumerable,
HashSet<string> unclaimedPartitions,
int partitionCount,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
// The minimum owned partitions count is the minimum amount of partitions every event processor needs to own when the distribution
// is balanced. If n = minimumOwnedPartitionsCount, a balanced distribution will only have processors that own n or n + 1 partitions
// each. We can guarantee the partition distribution has at least one key, which corresponds to this event processor instance, even
// if it owns no partitions.
var minimumOwnedPartitionsCount = partitionCount / ActiveOwnershipWithDistribution.Keys.Count;
Logger.MinimumPartitionsPerEventProcessor(minimumOwnedPartitionsCount);
var ownedPartitionsCount = ActiveOwnershipWithDistribution[OwnerIdentifier].Count;
Logger.CurrentOwnershipCount(ownedPartitionsCount, OwnerIdentifier);
// There are two possible situations in which we may need to claim a partition ownership:
//
// - The first one is when we are below the minimum amount of owned partitions. There's nothing more to check, as we need to claim more
// partitions to enforce balancing.
//
// - The second case is a bit tricky. Sometimes the claim must be performed by an event processor that already has reached the minimum
// amount of ownership. This may happen, for instance, when we have 13 partitions and 3 processors, each of them owning 4 partitions.
// The minimum amount of partitions per processor is, in fact, 4, but in this example we still have 1 orphan partition to claim. To
// avoid overlooking this kind of situation, we may want to claim an ownership when we have exactly the minimum amount of ownership,
// but we are making sure there are no better candidates among the other event processors.
if (ownedPartitionsCount < minimumOwnedPartitionsCount
|| (ownedPartitionsCount == minimumOwnedPartitionsCount && !ActiveOwnershipWithDistribution.Values.Any(partitions => partitions.Count < minimumOwnedPartitionsCount)))
{
// Look for unclaimed partitions. If any, randomly pick one of them to claim.
Logger.UnclaimedPartitions(unclaimedPartitions);
if (unclaimedPartitions.Count > 0)
{
var index = RandomNumberGenerator.Value.Next(unclaimedPartitions.Count);
var returnTask = ClaimOwnershipAsync(unclaimedPartitions.ElementAt(index), completeOwnershipEnumerable, cancellationToken);
return new ValueTask<(bool, EventProcessorPartitionOwnership)>(returnTask);
}
// Only try to steal partitions if there are no unclaimed partitions left. At first, only processors that have exceeded the
// maximum owned partition count should be targeted.
Logger.ShouldStealPartition(OwnerIdentifier);
var maximumOwnedPartitionsCount = minimumOwnedPartitionsCount + 1;
var partitionsOwnedByProcessorWithGreaterThanMaximumOwnedPartitionsCount = new List<string>();
var partitionsOwnedByProcessorWithExactlyMaximumOwnedPartitionsCount = new List<string>();
// Build a list of partitions owned by processors owning exactly maximumOwnedPartitionsCount partitions
// and a list of partitions owned by processors owning more than maximumOwnedPartitionsCount partitions.
// Ignore the partitions already owned by this processor even though the current processor should never meet either criteria.
foreach (var key in ActiveOwnershipWithDistribution.Keys)
{
var ownedPartitions = ActiveOwnershipWithDistribution[key];
if (ownedPartitions.Count < maximumOwnedPartitionsCount || string.Equals(key, OwnerIdentifier, StringComparison.OrdinalIgnoreCase))
{
// Skip if the common case is true.
continue;
}
if (ownedPartitions.Count == maximumOwnedPartitionsCount)
{
ownedPartitions
.ForEach(ownership => partitionsOwnedByProcessorWithExactlyMaximumOwnedPartitionsCount.Add(ownership.PartitionId));
}
else
{
ownedPartitions
.ForEach(ownership => partitionsOwnedByProcessorWithGreaterThanMaximumOwnedPartitionsCount.Add(ownership.PartitionId));
}
}
// Here's the important part. If there are no processors that have exceeded the maximum owned partition count allowed, we may
// need to steal from the processors that have exactly the maximum amount. If this instance is below the minimum count, then
// we have no choice as we need to enforce balancing. Otherwise, leave it as it is because the distribution wouldn't change.
if (partitionsOwnedByProcessorWithGreaterThanMaximumOwnedPartitionsCount.Count > 0)
{
// If any stealable partitions were found, randomly pick one of them to claim.
Logger.StealPartition(OwnerIdentifier);
var index = RandomNumberGenerator.Value.Next(partitionsOwnedByProcessorWithGreaterThanMaximumOwnedPartitionsCount.Count);
var returnTask = ClaimOwnershipAsync(
partitionsOwnedByProcessorWithGreaterThanMaximumOwnedPartitionsCount[index],
completeOwnershipEnumerable,
cancellationToken);
return new ValueTask<(bool, EventProcessorPartitionOwnership)>(returnTask);
}
else if (ownedPartitionsCount < minimumOwnedPartitionsCount)
{
// If any stealable partitions were found, randomly pick one of them to claim.
Logger.StealPartition(OwnerIdentifier);
var index = RandomNumberGenerator.Value.Next(partitionsOwnedByProcessorWithExactlyMaximumOwnedPartitionsCount.Count);
var returnTask = ClaimOwnershipAsync(
partitionsOwnedByProcessorWithExactlyMaximumOwnedPartitionsCount[index],
completeOwnershipEnumerable,
cancellationToken);
return new ValueTask<(bool, EventProcessorPartitionOwnership)>(returnTask);
}
}
// No ownership has been claimed.
return new ValueTask<(bool, EventProcessorPartitionOwnership)>((false, default));
}
/// <summary>
/// Renews this instance's ownership so they don't expire.
/// </summary>
///
/// <param name="cancellationToken">A <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
private async Task RenewOwnershipAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
Logger.RenewOwnershipStart(OwnerIdentifier);
var utcNow = GetDateTimeOffsetNow();
List<EventProcessorPartitionOwnership> ownershipToRenew = InstanceOwnership.Values
.Where(ownership => (utcNow - ownership.LastModifiedTime) > LoadBalanceInterval)
.Select(ownership => new EventProcessorPartitionOwnership
{
FullyQualifiedNamespace = ownership.FullyQualifiedNamespace,
EventHubName = ownership.EventHubName,
ConsumerGroup = ownership.ConsumerGroup,
OwnerIdentifier = ownership.OwnerIdentifier,
PartitionId = ownership.PartitionId,
LastModifiedTime = utcNow,
Version = ownership.Version
})
.ToList();
try
{
// Update ownerships we renewed and remove the ones we didn't
var newOwnerships = await StorageManager.ClaimOwnershipAsync(ownershipToRenew, cancellationToken)
.ConfigureAwait(false);
foreach (var oldOwnership in ownershipToRenew)
{
InstanceOwnership.Remove(oldOwnership.PartitionId);
}
foreach (var newOwnership in newOwnerships)
{
InstanceOwnership[newOwnership.PartitionId] = newOwnership;
}
}
catch (Exception ex)
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
// If ownership renewal fails just give up and try again in the next cycle. The processor may
// end up losing some of its ownership.
Logger.RenewOwnershipError(OwnerIdentifier, ex.Message);
// Set the EventHubName to null so it doesn't modify the exception message. This exception message is
// used so the processor can retrieve the raw Operation string, and adding the EventHubName would append
// unwanted info to it.
throw new EventHubsException(true, null, Resources.OperationRenewOwnership, ex);
}
finally
{
Logger.RenewOwnershipComplete(OwnerIdentifier);
}
}
/// <summary>
/// Tries to claim ownership of the specified partition.
/// </summary>
///
/// <param name="partitionId">The identifier of the Event Hub partition the ownership is associated with.</param>
/// <param name="completeOwnershipEnumerable">A complete enumerable of ownership obtained from the stored service provided by the user.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>A tuple indicating whether a claim was attempted and the claimed ownership. The claimed ownership will be <c>null</c> if the claim attempt failed.</returns>
///
private async Task<(bool wasClaimAttempted, EventProcessorPartitionOwnership claimedPartition)> ClaimOwnershipAsync(string partitionId,
IEnumerable<EventProcessorPartitionOwnership> completeOwnershipEnumerable,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
Logger.ClaimOwnershipStart(partitionId);
// We need the eTag from the most recent ownership of this partition, even if it's expired. We want to keep the offset and
// the sequence number as well.
var oldOwnership = completeOwnershipEnumerable.FirstOrDefault(ownership => ownership.PartitionId == partitionId);
var newOwnership = new EventProcessorPartitionOwnership
{
FullyQualifiedNamespace = FullyQualifiedNamespace,
EventHubName = EventHubName,
ConsumerGroup = ConsumerGroup,
OwnerIdentifier = OwnerIdentifier,
PartitionId = partitionId,
LastModifiedTime = DateTimeOffset.UtcNow,
Version = oldOwnership?.Version
};
var claimedOwnership = default(IEnumerable<EventProcessorPartitionOwnership>);
try
{
claimedOwnership = await StorageManager.ClaimOwnershipAsync(new List<EventProcessorPartitionOwnership> { newOwnership }, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
// If ownership claim fails, just treat it as a usual ownership claim failure.
Logger.ClaimOwnershipError(partitionId, ex.Message);
// Set the EventHubName to null so it doesn't modify the exception message. This exception message is
// used so the processor can retrieve the raw Operation string, and adding the EventHubName would append
// unwanted info to it. This exception also communicates the PartitionId to the caller.
var exception = new EventHubsException(true, null, Resources.OperationClaimOwnership, ex);
exception.SetFailureOperation(exception.Message);
exception.SetFailureData(partitionId);
throw exception;
}
// We are expecting an enumerable with a single element if the claim attempt succeeds.
return (true, claimedOwnership.FirstOrDefault());
}
/// <summary>
/// Queries the value to use for the current date/time. This is abstracted to allow for deterministic
/// values to be used for testing.
/// </summary>
///
/// <returns>The current date and time, in UTC.</returns>
internal virtual DateTimeOffset GetDateTimeOffsetNow()
{
return DateTimeOffset.UtcNow;
}
}
}
| |
// 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.SafeHandles;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Authentication.ExtendedProtection;
namespace System.Net.Security
{
//
// Used when working with SSPI APIs, like SafeSspiAuthDataHandle(). Holds the pointer to the auth data blob.
//
#if DEBUG
internal sealed class SafeSspiAuthDataHandle : DebugSafeHandle
{
#else
internal sealed class SafeSspiAuthDataHandle : SafeHandleZeroOrMinusOneIsInvalid
{
#endif
public SafeSspiAuthDataHandle() : base(true)
{
}
protected override bool ReleaseHandle()
{
return Interop.SspiCli.SspiFreeAuthIdentity(handle) == Interop.SECURITY_STATUS.OK;
}
}
//
// A set of Safe Handles that depend on native FreeContextBuffer finalizer.
//
#if DEBUG
internal abstract class SafeFreeContextBuffer : DebugSafeHandle
{
#else
internal abstract class SafeFreeContextBuffer : SafeHandleZeroOrMinusOneIsInvalid
{
#endif
protected SafeFreeContextBuffer() : base(true) { }
// This must be ONLY called from this file.
internal void Set(IntPtr value)
{
this.handle = value;
}
internal static int EnumeratePackages(out int pkgnum, out SafeFreeContextBuffer pkgArray)
{
int res = -1;
SafeFreeContextBuffer_SECURITY pkgArray_SECURITY = null;
res = Interop.SspiCli.EnumerateSecurityPackagesW(out pkgnum, out pkgArray_SECURITY);
pkgArray = pkgArray_SECURITY;
if (res != 0 && pkgArray != null)
{
pkgArray.SetHandleAsInvalid();
}
return res;
}
internal static SafeFreeContextBuffer CreateEmptyHandle()
{
return new SafeFreeContextBuffer_SECURITY();
}
//
// After PInvoke call the method will fix the refHandle.handle with the returned value.
// The caller is responsible for creating a correct SafeHandle template or null can be passed if no handle is returned.
//
// This method switches between three non-interruptible helper methods. (This method can't be both non-interruptible and
// reference imports from all three DLLs - doing so would cause all three DLLs to try to be bound to.)
//
public static unsafe int QueryContextAttributes(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, byte* buffer, SafeHandle refHandle)
{
return QueryContextAttributes_SECURITY(phContext, contextAttribute, buffer, refHandle);
}
private static unsafe int QueryContextAttributes_SECURITY(
SafeDeleteContext phContext,
Interop.SspiCli.ContextAttribute contextAttribute,
byte* buffer,
SafeHandle refHandle)
{
int status = (int)Interop.SECURITY_STATUS.InvalidHandle;
try
{
bool ignore = false;
phContext.DangerousAddRef(ref ignore);
status = Interop.SspiCli.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer);
}
finally
{
phContext.DangerousRelease();
}
if (status == 0 && refHandle != null)
{
if (refHandle is SafeFreeContextBuffer)
{
((SafeFreeContextBuffer)refHandle).Set(*(IntPtr*)buffer);
}
else
{
((SafeFreeCertContext)refHandle).Set(*(IntPtr*)buffer);
}
}
if (status != 0 && refHandle != null)
{
refHandle.SetHandleAsInvalid();
}
return status;
}
public static int SetContextAttributes(
SafeDeleteContext phContext,
Interop.SspiCli.ContextAttribute contextAttribute, byte[] buffer)
{
return SetContextAttributes_SECURITY(phContext, contextAttribute, buffer);
}
private static int SetContextAttributes_SECURITY(
SafeDeleteContext phContext,
Interop.SspiCli.ContextAttribute contextAttribute,
byte[] buffer)
{
try
{
bool ignore = false;
phContext.DangerousAddRef(ref ignore);
return Interop.SspiCli.SetContextAttributesW(ref phContext._handle, contextAttribute, buffer, buffer.Length);
}
finally
{
phContext.DangerousRelease();
}
}
}
internal sealed class SafeFreeContextBuffer_SECURITY : SafeFreeContextBuffer
{
internal SafeFreeContextBuffer_SECURITY() : base() { }
protected override bool ReleaseHandle()
{
return Interop.SspiCli.FreeContextBuffer(handle) == 0;
}
}
//
// Implementation of handles required CertFreeCertificateContext
//
#if DEBUG
internal sealed class SafeFreeCertContext : DebugSafeHandle
{
#else
internal sealed class SafeFreeCertContext : SafeHandleZeroOrMinusOneIsInvalid
{
#endif
internal SafeFreeCertContext() : base(true) { }
// This must be ONLY called from this file.
internal void Set(IntPtr value)
{
this.handle = value;
}
private const uint CRYPT_ACQUIRE_SILENT_FLAG = 0x00000040;
protected override bool ReleaseHandle()
{
Interop.Crypt32.CertFreeCertificateContext(handle);
return true;
}
}
//
// Implementation of handles dependable on FreeCredentialsHandle
//
#if DEBUG
internal abstract class SafeFreeCredentials : DebugSafeHandle
{
#else
internal abstract class SafeFreeCredentials : SafeHandle
{
#endif
internal Interop.SspiCli.CredHandle _handle; //should be always used as by ref in PInvokes parameters
protected SafeFreeCredentials() : base(IntPtr.Zero, true)
{
_handle = new Interop.SspiCli.CredHandle();
}
#if TRACE_VERBOSE
public override string ToString()
{
return "0x" + _handle.ToString();
}
#endif
public override bool IsInvalid
{
get { return IsClosed || _handle.IsZero; }
}
#if DEBUG
public new IntPtr DangerousGetHandle()
{
Debug.Fail("This method should never be called for this type");
throw NotImplemented.ByDesign;
}
#endif
public static unsafe int AcquireCredentialsHandle(
string package,
Interop.SspiCli.CredentialUse intent,
ref Interop.SspiCli.SEC_WINNT_AUTH_IDENTITY_W authdata,
out SafeFreeCredentials outCredential)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, package, intent, authdata);
int errorCode = -1;
long timeStamp;
outCredential = new SafeFreeCredential_SECURITY();
errorCode = Interop.SspiCli.AcquireCredentialsHandleW(
null,
package,
(int)intent,
null,
ref authdata,
null,
null,
ref outCredential._handle,
out timeStamp);
#if TRACE_VERBOSE
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle:{outCredential}");
#endif
if (errorCode != 0)
{
outCredential.SetHandleAsInvalid();
}
return errorCode;
}
public static unsafe int AcquireDefaultCredential(
string package,
Interop.SspiCli.CredentialUse intent,
out SafeFreeCredentials outCredential)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, package, intent);
int errorCode = -1;
long timeStamp;
outCredential = new SafeFreeCredential_SECURITY();
errorCode = Interop.SspiCli.AcquireCredentialsHandleW(
null,
package,
(int)intent,
null,
IntPtr.Zero,
null,
null,
ref outCredential._handle,
out timeStamp);
#if TRACE_VERBOSE
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle = {outCredential}");
#endif
if (errorCode != 0)
{
outCredential.SetHandleAsInvalid();
}
return errorCode;
}
public static unsafe int AcquireCredentialsHandle(
string package,
Interop.SspiCli.CredentialUse intent,
ref SafeSspiAuthDataHandle authdata,
out SafeFreeCredentials outCredential)
{
int errorCode = -1;
long timeStamp;
outCredential = new SafeFreeCredential_SECURITY();
errorCode = Interop.SspiCli.AcquireCredentialsHandleW(
null,
package,
(int)intent,
null,
authdata,
null,
null,
ref outCredential._handle,
out timeStamp);
if (errorCode != 0)
{
outCredential.SetHandleAsInvalid();
}
return errorCode;
}
public static unsafe int AcquireCredentialsHandle(
string package,
Interop.SspiCli.CredentialUse intent,
ref Interop.SspiCli.SCHANNEL_CRED authdata,
out SafeFreeCredentials outCredential)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, package, intent, authdata);
int errorCode = -1;
long timeStamp;
// If there is a certificate, wrap it into an array.
// Not threadsafe.
IntPtr copiedPtr = authdata.paCred;
try
{
IntPtr certArrayPtr = new IntPtr(&copiedPtr);
if (copiedPtr != IntPtr.Zero)
{
authdata.paCred = certArrayPtr;
}
outCredential = new SafeFreeCredential_SECURITY();
errorCode = Interop.SspiCli.AcquireCredentialsHandleW(
null,
package,
(int)intent,
null,
ref authdata,
null,
null,
ref outCredential._handle,
out timeStamp);
}
finally
{
authdata.paCred = copiedPtr;
}
#if TRACE_VERBOSE
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle = {outCredential}");
#endif
if (errorCode != 0)
{
outCredential.SetHandleAsInvalid();
}
return errorCode;
}
}
//
// This is a class holding a Credential handle reference, used for static handles cache
//
#if DEBUG
internal sealed class SafeCredentialReference : DebugCriticalHandleMinusOneIsInvalid
{
#else
internal sealed class SafeCredentialReference : CriticalHandleMinusOneIsInvalid
{
#endif
//
// Static cache will return the target handle if found the reference in the table.
//
internal SafeFreeCredentials Target;
internal static SafeCredentialReference CreateReference(SafeFreeCredentials target)
{
SafeCredentialReference result = new SafeCredentialReference(target);
if (result.IsInvalid)
{
return null;
}
return result;
}
private SafeCredentialReference(SafeFreeCredentials target) : base()
{
// Bumps up the refcount on Target to signify that target handle is statically cached so
// its dispose should be postponed
bool ignore = false;
target.DangerousAddRef(ref ignore);
Target = target;
SetHandle(new IntPtr(0)); // make this handle valid
}
protected override bool ReleaseHandle()
{
SafeFreeCredentials target = Target;
if (target != null)
{
target.DangerousRelease();
}
Target = null;
return true;
}
}
internal sealed class SafeFreeCredential_SECURITY : SafeFreeCredentials
{
public SafeFreeCredential_SECURITY() : base() { }
protected override bool ReleaseHandle()
{
return Interop.SspiCli.FreeCredentialsHandle(ref _handle) == 0;
}
}
//
// Implementation of handles that are dependent on DeleteSecurityContext
//
#if DEBUG
internal abstract partial class SafeDeleteContext : DebugSafeHandle
{
#else
internal abstract partial class SafeDeleteContext : SafeHandle
{
#endif
private const string dummyStr = " ";
private static readonly byte[] s_dummyBytes = new byte[] { 0 };
protected SafeFreeCredentials _EffectiveCredential;
//-------------------------------------------------------------------
internal static unsafe int InitializeSecurityContext(
ref SafeFreeCredentials inCredentials,
ref SafeDeleteContext refContext,
string targetName,
Interop.SspiCli.ContextFlags inFlags,
Interop.SspiCli.Endianness endianness,
SecurityBuffer inSecBuffer,
SecurityBuffer[] inSecBuffers,
SecurityBuffer outSecBuffer,
ref Interop.SspiCli.ContextFlags outFlags)
{
#if TRACE_VERBOSE
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(null, $"credential:{inCredentials}, crefContext:{refContext}, targetName:{targetName}, inFlags:{inFlags}, endianness:{endianness}");
if (inSecBuffers == null)
{
NetEventSource.Info(null, $"inSecBuffers = (null)");
}
else
{
NetEventSource.Info(null, $"inSecBuffers = {inSecBuffers}");
}
}
#endif
if (outSecBuffer == null)
{
NetEventSource.Fail(null, "outSecBuffer != null");
}
if (inSecBuffer != null && inSecBuffers != null)
{
NetEventSource.Fail(null, "inSecBuffer == null || inSecBuffers == null");
}
if (inCredentials == null)
{
throw new ArgumentNullException(nameof(inCredentials));
}
Interop.SspiCli.SecBufferDesc inSecurityBufferDescriptor = default(Interop.SspiCli.SecBufferDesc);
bool haveInSecurityBufferDescriptor = false;
if (inSecBuffer != null)
{
inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1);
haveInSecurityBufferDescriptor = true;
}
else if (inSecBuffers != null)
{
inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(inSecBuffers.Length);
haveInSecurityBufferDescriptor = true;
}
Interop.SspiCli.SecBufferDesc outSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1);
// Actually, this is returned in outFlags.
bool isSspiAllocated = (inFlags & Interop.SspiCli.ContextFlags.AllocateMemory) != 0 ? true : false;
int errorCode = -1;
Interop.SspiCli.CredHandle contextHandle = new Interop.SspiCli.CredHandle();
if (refContext != null)
{
contextHandle = refContext._handle;
}
// These are pinned user byte arrays passed along with SecurityBuffers.
GCHandle[] pinnedInBytes = null;
GCHandle pinnedOutBytes = new GCHandle();
// Optional output buffer that may need to be freed.
SafeFreeContextBuffer outFreeContextBuffer = null;
try
{
pinnedOutBytes = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned);
Interop.SspiCli.SecBuffer[] inUnmanagedBuffer = new Interop.SspiCli.SecBuffer[haveInSecurityBufferDescriptor ? inSecurityBufferDescriptor.cBuffers : 1];
fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer)
{
if (haveInSecurityBufferDescriptor)
{
// Fix Descriptor pointer that points to unmanaged SecurityBuffers.
inSecurityBufferDescriptor.pBuffers = inUnmanagedBufferPtr;
pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.cBuffers];
SecurityBuffer securityBuffer;
for (int index = 0; index < inSecurityBufferDescriptor.cBuffers; ++index)
{
securityBuffer = inSecBuffer != null ? inSecBuffer : inSecBuffers[index];
if (securityBuffer != null)
{
// Copy the SecurityBuffer content into unmanaged place holder.
inUnmanagedBuffer[index].cbBuffer = securityBuffer.size;
inUnmanagedBuffer[index].BufferType = securityBuffer.type;
// Use the unmanaged token if it's not null; otherwise use the managed buffer.
if (securityBuffer.unmanagedToken != null)
{
inUnmanagedBuffer[index].pvBuffer = securityBuffer.unmanagedToken.DangerousGetHandle();
}
else if (securityBuffer.token == null || securityBuffer.token.Length == 0)
{
inUnmanagedBuffer[index].pvBuffer = IntPtr.Zero;
}
else
{
pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned);
inUnmanagedBuffer[index].pvBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset);
}
#if TRACE_VERBOSE
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"SecBuffer: cbBuffer:{securityBuffer.size} BufferType:{securityBuffer.type}");
#endif
}
}
}
Interop.SspiCli.SecBuffer[] outUnmanagedBuffer = new Interop.SspiCli.SecBuffer[1];
fixed (void* outUnmanagedBufferPtr = &outUnmanagedBuffer[0])
{
// Fix Descriptor pointer that points to unmanaged SecurityBuffers.
outSecurityBufferDescriptor.pBuffers = outUnmanagedBufferPtr;
outUnmanagedBuffer[0].cbBuffer = outSecBuffer.size;
outUnmanagedBuffer[0].BufferType = outSecBuffer.type;
if (outSecBuffer.token == null || outSecBuffer.token.Length == 0)
{
outUnmanagedBuffer[0].pvBuffer = IntPtr.Zero;
}
else
{
outUnmanagedBuffer[0].pvBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset);
}
if (isSspiAllocated)
{
outFreeContextBuffer = SafeFreeContextBuffer.CreateEmptyHandle();
}
if (refContext == null || refContext.IsInvalid)
{
refContext = new SafeDeleteContext_SECURITY();
}
if (targetName == null || targetName.Length == 0)
{
targetName = dummyStr;
}
fixed (char* namePtr = targetName)
{
errorCode = MustRunInitializeSecurityContext_SECURITY(
ref inCredentials,
contextHandle.IsZero ? null : &contextHandle,
(byte*)(((object)targetName == (object)dummyStr) ? null : namePtr),
inFlags,
endianness,
haveInSecurityBufferDescriptor ? &inSecurityBufferDescriptor : null,
refContext,
ref outSecurityBufferDescriptor,
ref outFlags,
outFreeContextBuffer);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(null, "Marshalling OUT buffer");
// Get unmanaged buffer with index 0 as the only one passed into PInvoke.
outSecBuffer.size = outUnmanagedBuffer[0].cbBuffer;
outSecBuffer.type = outUnmanagedBuffer[0].BufferType;
if (outSecBuffer.size > 0)
{
outSecBuffer.token = new byte[outSecBuffer.size];
Marshal.Copy(outUnmanagedBuffer[0].pvBuffer, outSecBuffer.token, 0, outSecBuffer.size);
}
else
{
outSecBuffer.token = null;
}
}
}
}
finally
{
if (pinnedInBytes != null)
{
for (int index = 0; index < pinnedInBytes.Length; index++)
{
if (pinnedInBytes[index].IsAllocated)
{
pinnedInBytes[index].Free();
}
}
}
if (pinnedOutBytes.IsAllocated)
{
pinnedOutBytes.Free();
}
if (outFreeContextBuffer != null)
{
outFreeContextBuffer.Dispose();
}
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"errorCode:0x{errorCode:x8}, refContext:{refContext}");
return errorCode;
}
//
// After PInvoke call the method will fix the handleTemplate.handle with the returned value.
// The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavor or null can be passed if no handle is returned.
//
private static unsafe int MustRunInitializeSecurityContext_SECURITY(
ref SafeFreeCredentials inCredentials,
void* inContextPtr,
byte* targetName,
Interop.SspiCli.ContextFlags inFlags,
Interop.SspiCli.Endianness endianness,
Interop.SspiCli.SecBufferDesc* inputBuffer,
SafeDeleteContext outContext,
ref Interop.SspiCli.SecBufferDesc outputBuffer,
ref Interop.SspiCli.ContextFlags attributes,
SafeFreeContextBuffer handleTemplate)
{
int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle;
try
{
bool ignore = false;
inCredentials.DangerousAddRef(ref ignore);
outContext.DangerousAddRef(ref ignore);
Interop.SspiCli.CredHandle credentialHandle = inCredentials._handle;
long timeStamp;
errorCode = Interop.SspiCli.InitializeSecurityContextW(
ref credentialHandle,
inContextPtr,
targetName,
inFlags,
0,
endianness,
inputBuffer,
0,
ref outContext._handle,
ref outputBuffer,
ref attributes,
out timeStamp);
}
finally
{
//
// When a credential handle is first associated with the context we keep credential
// ref count bumped up to ensure ordered finalization.
// If the credential handle has been changed we de-ref the old one and associate the
// context with the new cred handle but only if the call was successful.
if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0)
{
// Disassociate the previous credential handle
if (outContext._EffectiveCredential != null)
{
outContext._EffectiveCredential.DangerousRelease();
}
outContext._EffectiveCredential = inCredentials;
}
else
{
inCredentials.DangerousRelease();
}
outContext.DangerousRelease();
}
// The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer.
if (handleTemplate != null)
{
//ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes
handleTemplate.Set(((Interop.SspiCli.SecBuffer*)outputBuffer.pBuffers)->pvBuffer);
if (handleTemplate.IsInvalid)
{
handleTemplate.SetHandleAsInvalid();
}
}
if (inContextPtr == null && (errorCode & 0x80000000) != 0)
{
// an error on the first call, need to set the out handle to invalid value
outContext._handle.SetToInvalid();
}
return errorCode;
}
//-------------------------------------------------------------------
internal static unsafe int AcceptSecurityContext(
ref SafeFreeCredentials inCredentials,
ref SafeDeleteContext refContext,
Interop.SspiCli.ContextFlags inFlags,
Interop.SspiCli.Endianness endianness,
SecurityBuffer inSecBuffer,
SecurityBuffer[] inSecBuffers,
SecurityBuffer outSecBuffer,
ref Interop.SspiCli.ContextFlags outFlags)
{
#if TRACE_VERBOSE
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(null, $"credential={inCredentials}, refContext={refContext}, inFlags={inFlags}");
if (inSecBuffers == null)
{
NetEventSource.Info(null, "inSecBuffers = (null)");
}
else
{
NetEventSource.Info(null, $"inSecBuffers[] = (inSecBuffers)");
}
}
#endif
if (outSecBuffer == null)
{
NetEventSource.Fail(null, "outSecBuffer != null");
}
if (inSecBuffer != null && inSecBuffers != null)
{
NetEventSource.Fail(null, "inSecBuffer == null || inSecBuffers == null");
}
if (inCredentials == null)
{
throw new ArgumentNullException(nameof(inCredentials));
}
Interop.SspiCli.SecBufferDesc inSecurityBufferDescriptor = default(Interop.SspiCli.SecBufferDesc);
bool haveInSecurityBufferDescriptor = false;
if (inSecBuffer != null)
{
inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1);
haveInSecurityBufferDescriptor = true;
}
else if (inSecBuffers != null)
{
inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(inSecBuffers.Length);
haveInSecurityBufferDescriptor = true;
}
Interop.SspiCli.SecBufferDesc outSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1);
// Actually, this is returned in outFlags.
bool isSspiAllocated = (inFlags & Interop.SspiCli.ContextFlags.AllocateMemory) != 0 ? true : false;
int errorCode = -1;
Interop.SspiCli.CredHandle contextHandle = new Interop.SspiCli.CredHandle();
if (refContext != null)
{
contextHandle = refContext._handle;
}
// These are pinned user byte arrays passed along with SecurityBuffers.
GCHandle[] pinnedInBytes = null;
GCHandle pinnedOutBytes = new GCHandle();
// Optional output buffer that may need to be freed.
SafeFreeContextBuffer outFreeContextBuffer = null;
try
{
pinnedOutBytes = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned);
var inUnmanagedBuffer = new Interop.SspiCli.SecBuffer[haveInSecurityBufferDescriptor ? inSecurityBufferDescriptor.cBuffers : 1];
fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer)
{
if (haveInSecurityBufferDescriptor)
{
// Fix Descriptor pointer that points to unmanaged SecurityBuffers.
inSecurityBufferDescriptor.pBuffers = inUnmanagedBufferPtr;
pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.cBuffers];
SecurityBuffer securityBuffer;
for (int index = 0; index < inSecurityBufferDescriptor.cBuffers; ++index)
{
securityBuffer = inSecBuffer != null ? inSecBuffer : inSecBuffers[index];
if (securityBuffer != null)
{
// Copy the SecurityBuffer content into unmanaged place holder.
inUnmanagedBuffer[index].cbBuffer = securityBuffer.size;
inUnmanagedBuffer[index].BufferType = securityBuffer.type;
// Use the unmanaged token if it's not null; otherwise use the managed buffer.
if (securityBuffer.unmanagedToken != null)
{
inUnmanagedBuffer[index].pvBuffer = securityBuffer.unmanagedToken.DangerousGetHandle();
}
else if (securityBuffer.token == null || securityBuffer.token.Length == 0)
{
inUnmanagedBuffer[index].pvBuffer = IntPtr.Zero;
}
else
{
pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned);
inUnmanagedBuffer[index].pvBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset);
}
#if TRACE_VERBOSE
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"SecBuffer: cbBuffer:{securityBuffer.size} BufferType:{securityBuffer.type}");
#endif
}
}
}
var outUnmanagedBuffer = new Interop.SspiCli.SecBuffer[1];
fixed (void* outUnmanagedBufferPtr = &outUnmanagedBuffer[0])
{
// Fix Descriptor pointer that points to unmanaged SecurityBuffers.
outSecurityBufferDescriptor.pBuffers = outUnmanagedBufferPtr;
// Copy the SecurityBuffer content into unmanaged place holder.
outUnmanagedBuffer[0].cbBuffer = outSecBuffer.size;
outUnmanagedBuffer[0].BufferType = outSecBuffer.type;
if (outSecBuffer.token == null || outSecBuffer.token.Length == 0)
{
outUnmanagedBuffer[0].pvBuffer = IntPtr.Zero;
}
else
{
outUnmanagedBuffer[0].pvBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset);
}
if (isSspiAllocated)
{
outFreeContextBuffer = SafeFreeContextBuffer.CreateEmptyHandle();
}
if (refContext == null || refContext.IsInvalid)
{
refContext = new SafeDeleteContext_SECURITY();
}
errorCode = MustRunAcceptSecurityContext_SECURITY(
ref inCredentials,
contextHandle.IsZero ? null : &contextHandle,
haveInSecurityBufferDescriptor ? &inSecurityBufferDescriptor : null,
inFlags,
endianness,
refContext,
ref outSecurityBufferDescriptor,
ref outFlags,
outFreeContextBuffer);
if (NetEventSource.IsEnabled) NetEventSource.Info(null, "Marshaling OUT buffer");
// Get unmanaged buffer with index 0 as the only one passed into PInvoke.
outSecBuffer.size = outUnmanagedBuffer[0].cbBuffer;
outSecBuffer.type = outUnmanagedBuffer[0].BufferType;
if (outSecBuffer.size > 0)
{
outSecBuffer.token = new byte[outSecBuffer.size];
Marshal.Copy(outUnmanagedBuffer[0].pvBuffer, outSecBuffer.token, 0, outSecBuffer.size);
}
else
{
outSecBuffer.token = null;
}
}
}
}
finally
{
if (pinnedInBytes != null)
{
for (int index = 0; index < pinnedInBytes.Length; index++)
{
if (pinnedInBytes[index].IsAllocated)
{
pinnedInBytes[index].Free();
}
}
}
if (pinnedOutBytes.IsAllocated)
{
pinnedOutBytes.Free();
}
if (outFreeContextBuffer != null)
{
outFreeContextBuffer.Dispose();
}
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"errorCode:0x{errorCode:x8}, refContext:{refContext}");
return errorCode;
}
//
// After PInvoke call the method will fix the handleTemplate.handle with the returned value.
// The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavor or null can be passed if no handle is returned.
//
private static unsafe int MustRunAcceptSecurityContext_SECURITY(
ref SafeFreeCredentials inCredentials,
void* inContextPtr,
Interop.SspiCli.SecBufferDesc* inputBuffer,
Interop.SspiCli.ContextFlags inFlags,
Interop.SspiCli.Endianness endianness,
SafeDeleteContext outContext,
ref Interop.SspiCli.SecBufferDesc outputBuffer,
ref Interop.SspiCli.ContextFlags outFlags,
SafeFreeContextBuffer handleTemplate)
{
int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle;
// Run the body of this method as a non-interruptible block.
try
{
bool ignore = false;
inCredentials.DangerousAddRef(ref ignore);
outContext.DangerousAddRef(ref ignore);
Interop.SspiCli.CredHandle credentialHandle = inCredentials._handle;
long timeStamp;
errorCode = Interop.SspiCli.AcceptSecurityContext(
ref credentialHandle,
inContextPtr,
inputBuffer,
inFlags,
endianness,
ref outContext._handle,
ref outputBuffer,
ref outFlags,
out timeStamp);
}
finally
{
//
// When a credential handle is first associated with the context we keep credential
// ref count bumped up to ensure ordered finalization.
// If the credential handle has been changed we de-ref the old one and associate the
// context with the new cred handle but only if the call was successful.
if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0)
{
// Disassociate the previous credential handle.
if (outContext._EffectiveCredential != null)
{
outContext._EffectiveCredential.DangerousRelease();
}
outContext._EffectiveCredential = inCredentials;
}
else
{
inCredentials.DangerousRelease();
}
outContext.DangerousRelease();
}
// The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer.
if (handleTemplate != null)
{
//ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes.
handleTemplate.Set(((Interop.SspiCli.SecBuffer*)outputBuffer.pBuffers)->pvBuffer);
if (handleTemplate.IsInvalid)
{
handleTemplate.SetHandleAsInvalid();
}
}
if (inContextPtr == null && (errorCode & 0x80000000) != 0)
{
// An error on the first call, need to set the out handle to invalid value.
outContext._handle.SetToInvalid();
}
return errorCode;
}
internal static unsafe int CompleteAuthToken(
ref SafeDeleteContext refContext,
SecurityBuffer[] inSecBuffers)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(null, "SafeDeleteContext::CompleteAuthToken");
NetEventSource.Info(null, $" refContext = {refContext}");
NetEventSource.Info(null, $" inSecBuffers[] = {inSecBuffers}");
}
if (inSecBuffers == null)
{
NetEventSource.Fail(null, "inSecBuffers == null");
}
var inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(inSecBuffers.Length);
int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle;
// These are pinned user byte arrays passed along with SecurityBuffers.
GCHandle[] pinnedInBytes = null;
var inUnmanagedBuffer = new Interop.SspiCli.SecBuffer[inSecurityBufferDescriptor.cBuffers];
fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer)
{
// Fix Descriptor pointer that points to unmanaged SecurityBuffers.
inSecurityBufferDescriptor.pBuffers = inUnmanagedBufferPtr;
pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.cBuffers];
SecurityBuffer securityBuffer;
for (int index = 0; index < inSecurityBufferDescriptor.cBuffers; ++index)
{
securityBuffer = inSecBuffers[index];
if (securityBuffer != null)
{
inUnmanagedBuffer[index].cbBuffer = securityBuffer.size;
inUnmanagedBuffer[index].BufferType = securityBuffer.type;
// Use the unmanaged token if it's not null; otherwise use the managed buffer.
if (securityBuffer.unmanagedToken != null)
{
inUnmanagedBuffer[index].pvBuffer = securityBuffer.unmanagedToken.DangerousGetHandle();
}
else if (securityBuffer.token == null || securityBuffer.token.Length == 0)
{
inUnmanagedBuffer[index].pvBuffer = IntPtr.Zero;
}
else
{
pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned);
inUnmanagedBuffer[index].pvBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset);
}
#if TRACE_VERBOSE
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"SecBuffer: cbBuffer:{securityBuffer.size} BufferType: {securityBuffer.type}");
#endif
}
}
Interop.SspiCli.CredHandle contextHandle = new Interop.SspiCli.CredHandle();
if (refContext != null)
{
contextHandle = refContext._handle;
}
try
{
if (refContext == null || refContext.IsInvalid)
{
refContext = new SafeDeleteContext_SECURITY();
}
try
{
bool ignore = false;
refContext.DangerousAddRef(ref ignore);
errorCode = Interop.SspiCli.CompleteAuthToken(contextHandle.IsZero ? null : &contextHandle, ref inSecurityBufferDescriptor);
}
finally
{
refContext.DangerousRelease();
}
}
finally
{
if (pinnedInBytes != null)
{
for (int index = 0; index < pinnedInBytes.Length; index++)
{
if (pinnedInBytes[index].IsAllocated)
{
pinnedInBytes[index].Free();
}
}
}
}
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"unmanaged CompleteAuthToken() errorCode:0x{errorCode:x8} refContext:{refContext}");
return errorCode;
}
internal static unsafe int ApplyControlToken(
ref SafeDeleteContext refContext,
SecurityBuffer[] inSecBuffers)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(null);
NetEventSource.Info(null, $" refContext = {refContext}");
NetEventSource.Info(null, $" inSecBuffers[] = length:{inSecBuffers.Length}");
}
if (inSecBuffers == null)
{
NetEventSource.Fail(null, "inSecBuffers == null");
}
var inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(inSecBuffers.Length);
int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle;
// These are pinned user byte arrays passed along with SecurityBuffers.
GCHandle[] pinnedInBytes = null;
var inUnmanagedBuffer = new Interop.SspiCli.SecBuffer[inSecurityBufferDescriptor.cBuffers];
fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer)
{
// Fix Descriptor pointer that points to unmanaged SecurityBuffers.
inSecurityBufferDescriptor.pBuffers = inUnmanagedBufferPtr;
pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.cBuffers];
SecurityBuffer securityBuffer;
for (int index = 0; index < inSecurityBufferDescriptor.cBuffers; ++index)
{
securityBuffer = inSecBuffers[index];
if (securityBuffer != null)
{
inUnmanagedBuffer[index].cbBuffer = securityBuffer.size;
inUnmanagedBuffer[index].BufferType = securityBuffer.type;
// Use the unmanaged token if it's not null; otherwise use the managed buffer.
if (securityBuffer.unmanagedToken != null)
{
inUnmanagedBuffer[index].pvBuffer = securityBuffer.unmanagedToken.DangerousGetHandle();
}
else if (securityBuffer.token == null || securityBuffer.token.Length == 0)
{
inUnmanagedBuffer[index].pvBuffer = IntPtr.Zero;
}
else
{
pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned);
inUnmanagedBuffer[index].pvBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset);
}
#if TRACE_VERBOSE
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"SecBuffer: cbBuffer:{securityBuffer.size} BufferType:{securityBuffer.type}");
#endif
}
}
// TODO: (#3114): Optimizations to remove the unnecesary allocation of a CredHandle, remove the AddRef
// if refContext was previously null, refactor the code to unify CompleteAuthToken and ApplyControlToken.
Interop.SspiCli.CredHandle contextHandle = new Interop.SspiCli.CredHandle();
if (refContext != null)
{
contextHandle = refContext._handle;
}
try
{
if (refContext == null || refContext.IsInvalid)
{
refContext = new SafeDeleteContext_SECURITY();
}
try
{
bool ignore = false;
refContext.DangerousAddRef(ref ignore);
errorCode = Interop.SspiCli.ApplyControlToken(contextHandle.IsZero ? null : &contextHandle, ref inSecurityBufferDescriptor);
}
finally
{
refContext.DangerousRelease();
}
}
finally
{
if (pinnedInBytes != null)
{
for (int index = 0; index < pinnedInBytes.Length; index++)
{
if (pinnedInBytes[index].IsAllocated)
{
pinnedInBytes[index].Free();
}
}
}
}
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"unmanaged ApplyControlToken() errorCode:0x{errorCode:x8} refContext: {refContext}");
return errorCode;
}
}
internal sealed class SafeDeleteContext_SECURITY : SafeDeleteContext
{
internal SafeDeleteContext_SECURITY() : base() { }
protected override bool ReleaseHandle()
{
if (this._EffectiveCredential != null)
{
this._EffectiveCredential.DangerousRelease();
}
return Interop.SspiCli.DeleteSecurityContext(ref _handle) == 0;
}
}
// Based on SafeFreeContextBuffer.
internal abstract class SafeFreeContextBufferChannelBinding : ChannelBinding
{
private int _size;
public override int Size
{
get { return _size; }
}
public override bool IsInvalid
{
get { return handle == new IntPtr(0) || handle == new IntPtr(-1); }
}
internal unsafe void Set(IntPtr value)
{
this.handle = value;
}
internal static SafeFreeContextBufferChannelBinding CreateEmptyHandle()
{
return new SafeFreeContextBufferChannelBinding_SECURITY();
}
public static unsafe int QueryContextChannelBinding(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, SecPkgContext_Bindings* buffer, SafeFreeContextBufferChannelBinding refHandle)
{
return QueryContextChannelBinding_SECURITY(phContext, contextAttribute, buffer, refHandle);
}
private static unsafe int QueryContextChannelBinding_SECURITY(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, SecPkgContext_Bindings* buffer, SafeFreeContextBufferChannelBinding refHandle)
{
int status = (int)Interop.SECURITY_STATUS.InvalidHandle;
// SCHANNEL only supports SECPKG_ATTR_ENDPOINT_BINDINGS and SECPKG_ATTR_UNIQUE_BINDINGS which
// map to our enum ChannelBindingKind.Endpoint and ChannelBindingKind.Unique.
if (contextAttribute != Interop.SspiCli.ContextAttribute.SECPKG_ATTR_ENDPOINT_BINDINGS &&
contextAttribute != Interop.SspiCli.ContextAttribute.SECPKG_ATTR_UNIQUE_BINDINGS)
{
return status;
}
try
{
bool ignore = false;
phContext.DangerousAddRef(ref ignore);
status = Interop.SspiCli.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer);
}
finally
{
phContext.DangerousRelease();
}
if (status == 0 && refHandle != null)
{
refHandle.Set((*buffer).Bindings);
refHandle._size = (*buffer).BindingsLength;
}
if (status != 0 && refHandle != null)
{
refHandle.SetHandleAsInvalid();
}
return status;
}
public override string ToString()
{
if (IsInvalid)
{
return null;
}
var bytes = new byte[_size];
Marshal.Copy(handle, bytes, 0, bytes.Length);
return BitConverter.ToString(bytes).Replace('-', ' ');
}
}
internal sealed class SafeFreeContextBufferChannelBinding_SECURITY : SafeFreeContextBufferChannelBinding
{
protected override bool ReleaseHandle()
{
return Interop.SspiCli.FreeContextBuffer(handle) == 0;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// HashJoinQueryOperatorEnumerator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// This enumerator implements the hash-join algorithm as noted earlier.
///
/// Assumptions:
/// This enumerator type won't work properly at all if the analysis engine didn't
/// ensure a proper hash-partition. We expect inner and outer elements with equal
/// keys are ALWAYS in the same partition. If they aren't (e.g. if the analysis is
/// busted) we'll silently drop items on the floor. :(
///
///
/// This is the enumerator class for two operators:
/// - Join
/// - GroupJoin
/// </summary>
/// <typeparam name="TLeftInput"></typeparam>
/// <typeparam name="TLeftKey"></typeparam>
/// <typeparam name="TRightInput"></typeparam>
/// <typeparam name="THashKey"></typeparam>
/// <typeparam name="TOutput"></typeparam>
internal class HashJoinQueryOperatorEnumerator<TLeftInput, TLeftKey, TRightInput, THashKey, TOutput>
: QueryOperatorEnumerator<TOutput, TLeftKey>
{
private readonly QueryOperatorEnumerator<Pair<TLeftInput,THashKey>, TLeftKey> _leftSource; // Left (outer) data source. For probing.
private readonly QueryOperatorEnumerator<Pair<TRightInput,THashKey>, int> _rightSource; // Right (inner) data source. For building.
private readonly Func<TLeftInput, TRightInput, TOutput> _singleResultSelector; // Single result selector.
private readonly Func<TLeftInput, IEnumerable<TRightInput>, TOutput> _groupResultSelector; // Group result selector.
private readonly IEqualityComparer<THashKey> _keyComparer; // An optional key comparison object.
private readonly CancellationToken _cancellationToken;
private Mutables _mutables;
private class Mutables
{
internal TLeftInput _currentLeft; // The current matching left element.
internal TLeftKey _currentLeftKey; // The current index of the matching left element.
internal HashLookup<THashKey, Pair<TRightInput, ListChunk<TRightInput>>> _rightHashLookup; // The hash lookup.
internal ListChunk<TRightInput> _currentRightMatches; // Current right matches (if any).
internal int _currentRightMatchesIndex; // Current index in the set of right matches.
internal int _outputLoopCount;
}
//---------------------------------------------------------------------------------------
// Instantiates a new hash-join enumerator.
//
internal HashJoinQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair<TLeftInput,THashKey>, TLeftKey> leftSource,
QueryOperatorEnumerator<Pair<TRightInput,THashKey>, int> rightSource,
Func<TLeftInput, TRightInput, TOutput> singleResultSelector,
Func<TLeftInput, IEnumerable<TRightInput>, TOutput> groupResultSelector,
IEqualityComparer<THashKey> keyComparer,
CancellationToken cancellationToken)
{
Debug.Assert(leftSource != null);
Debug.Assert(rightSource != null);
Debug.Assert(singleResultSelector != null || groupResultSelector != null);
_leftSource = leftSource;
_rightSource = rightSource;
_singleResultSelector = singleResultSelector;
_groupResultSelector = groupResultSelector;
_keyComparer = keyComparer;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// MoveNext implements all the hash-join logic noted earlier. When it is called first, it
// will execute the entire inner query tree, and build a hash-table lookup. This is the
// Building phase. Then for the first call and all subsequent calls to MoveNext, we will
// incrementally perform the Probing phase. We'll keep getting elements from the outer
// data source, looking into the hash-table we built, and enumerating the full results.
//
// This routine supports both inner and outer (group) joins. An outer join will yield a
// (possibly empty) list of matching elements from the inner instead of one-at-a-time,
// as we do for inner joins.
//
internal override bool MoveNext(ref TOutput currentElement, ref TLeftKey currentKey)
{
Debug.Assert(_singleResultSelector != null || _groupResultSelector != null, "expected a compiled result selector");
Debug.Assert(_leftSource != null);
Debug.Assert(_rightSource != null);
// BUILD phase: If we haven't built the hash-table yet, create that first.
Mutables mutables = _mutables;
if (mutables == null)
{
mutables = _mutables = new Mutables();
#if DEBUG
int hashLookupCount = 0;
int hashKeyCollisions = 0;
#endif
mutables._rightHashLookup = new HashLookup<THashKey, Pair<TRightInput, ListChunk<TRightInput>>>(_keyComparer);
Pair<TRightInput, THashKey> rightPair = default(Pair<TRightInput, THashKey>);
int rightKeyUnused = default(int);
int i = 0;
while (_rightSource.MoveNext(ref rightPair, ref rightKeyUnused))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
TRightInput rightElement = rightPair.First;
THashKey rightHashKey = rightPair.Second;
// We ignore null keys.
if (rightHashKey != null)
{
#if DEBUG
hashLookupCount++;
#endif
// See if we've already stored an element under the current key. If not, we
// lazily allocate a pair to hold the elements mapping to the same key.
const int INITIAL_CHUNK_SIZE = 2;
Pair<TRightInput, ListChunk<TRightInput>> currentValue = default(Pair<TRightInput, ListChunk<TRightInput>>);
if (!mutables._rightHashLookup.TryGetValue(rightHashKey, ref currentValue))
{
currentValue = new Pair<TRightInput, ListChunk<TRightInput>>(rightElement, null);
if (_groupResultSelector != null)
{
// For group joins, we also add the element to the list. This makes
// it easier later to yield the list as-is.
currentValue.Second = new ListChunk<TRightInput>(INITIAL_CHUNK_SIZE);
currentValue.Second.Add(rightElement);
}
mutables._rightHashLookup.Add(rightHashKey, currentValue);
}
else
{
if (currentValue.Second == null)
{
// Lazily allocate a list to hold all but the 1st value. We need to
// re-store this element because the pair is a value type.
currentValue.Second = new ListChunk<TRightInput>(INITIAL_CHUNK_SIZE);
mutables._rightHashLookup[rightHashKey] = currentValue;
}
currentValue.Second.Add(rightElement);
#if DEBUG
hashKeyCollisions++;
#endif
}
}
}
#if DEBUG
TraceHelpers.TraceInfo("ParallelJoinQueryOperator::MoveNext - built hash table [count = {0}, collisions = {1}]",
hashLookupCount, hashKeyCollisions);
#endif
}
// PROBE phase: So long as the source has a next element, return the match.
ListChunk<TRightInput> currentRightChunk = mutables._currentRightMatches;
if (currentRightChunk != null && mutables._currentRightMatchesIndex == currentRightChunk.Count)
{
currentRightChunk = mutables._currentRightMatches = currentRightChunk.Next;
mutables._currentRightMatchesIndex = 0;
}
if (mutables._currentRightMatches == null)
{
// We have to look up the next list of matches in the hash-table.
Pair<TLeftInput, THashKey> leftPair = default(Pair<TLeftInput, THashKey>);
TLeftKey leftKey = default(TLeftKey);
while (_leftSource.MoveNext(ref leftPair, ref leftKey))
{
if ((mutables._outputLoopCount++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// Find the match in the hash table.
Pair<TRightInput, ListChunk<TRightInput>> matchValue = default(Pair<TRightInput, ListChunk<TRightInput>>);
TLeftInput leftElement = leftPair.First;
THashKey leftHashKey = leftPair.Second;
// Ignore null keys.
if (leftHashKey != null)
{
if (mutables._rightHashLookup.TryGetValue(leftHashKey, ref matchValue))
{
// We found a new match. For inner joins, we remember the list in case
// there are multiple value under this same key -- the next iteration will pick
// them up. For outer joins, we will use the list momentarily.
if (_singleResultSelector != null)
{
mutables._currentRightMatches = matchValue.Second;
Debug.Assert(mutables._currentRightMatches == null || mutables._currentRightMatches.Count > 0,
"we were expecting that the list would be either null or empty");
mutables._currentRightMatchesIndex = 0;
// Yield the value.
currentElement = _singleResultSelector(leftElement, matchValue.First);
currentKey = leftKey;
// If there is a list of matches, remember the left values for next time.
if (matchValue.Second != null)
{
mutables._currentLeft = leftElement;
mutables._currentLeftKey = leftKey;
}
return true;
}
}
}
// For outer joins, we always yield a result.
if (_groupResultSelector != null)
{
// Grab the matches, or create an empty list if there are none.
IEnumerable<TRightInput> matches = matchValue.Second;
if (matches == null)
{
matches = ParallelEnumerable.Empty<TRightInput>();
}
// Generate the current value.
currentElement = _groupResultSelector(leftElement, matches);
currentKey = leftKey;
return true;
}
}
// If we've reached the end of the data source, we're done.
return false;
}
// Produce the next element and increment our index within the matches.
Debug.Assert(_singleResultSelector != null);
Debug.Assert(mutables._currentRightMatches != null);
Debug.Assert(0 <= mutables._currentRightMatchesIndex && mutables._currentRightMatchesIndex < mutables._currentRightMatches.Count);
currentElement = _singleResultSelector(
mutables._currentLeft, mutables._currentRightMatches._chunk[mutables._currentRightMatchesIndex]);
currentKey = mutables._currentLeftKey;
mutables._currentRightMatchesIndex++;
return true;
}
protected override void Dispose(bool disposing)
{
Debug.Assert(_leftSource != null && _rightSource != null);
_leftSource.Dispose();
_rightSource.Dispose();
}
}
}
| |
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
Licensed under the Oculus SDK License Version 3.4.1 (the "License");
you may not use the Oculus SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/sdk-3.4.1
Unless required by applicable law or agreed to in writing, the Oculus SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
using UnityEngine;
using System;
using System.Collections;
using System.Runtime.InteropServices;
/// <summary>
/// Add OVROverlay script to an object with an optional mesh primitive
/// rendered as a TimeWarp overlay instead by drawing it into the eye buffer.
/// This will take full advantage of the display resolution and avoid double
/// resampling of the texture.
///
/// We support 3 types of Overlay shapes right now
/// 1. Quad : This is most common overlay type , you render a quad in Timewarp space.
/// 2. Cylinder: [Mobile Only][Experimental], Display overlay as partial surface of a cylinder
/// * The cylinder's center will be your game object's center
/// * We encoded the cylinder's parameters in transform.scale,
/// **[scale.z] is the radius of the cylinder
/// **[scale.y] is the height of the cylinder
/// **[scale.x] is the length of the arc of cylinder
/// * Limitations
/// **Only the half of the cylinder can be displayed, which means the arc angle has to be smaller than 180 degree, [scale.x] / [scale.z] <= PI
/// **Your camera has to be inside of the inscribed sphere of the cylinder, the overlay will be faded out automatically when the camera is close to the inscribed sphere's surface.
/// **Translation only works correctly with vrDriver 1.04 or above
/// 3. Cubemap: Display overlay as a cube map
/// 4. OffcenterCubemap: [Mobile Only] Display overlay as a cube map with a texture coordinate offset
/// * The actually sampling will looks like [color = texture(cubeLayerSampler, normalize(direction) + offset)] instead of [color = texture( cubeLayerSampler, direction )]
/// * The extra center offset can be feed from transform.position
/// * Note: if transform.position's magnitude is greater than 1, which will cause some cube map pixel always invisible
/// Which is usually not what people wanted, we don't kill the ability for developer to do so here, but will warn out.
/// 5. Equirect: Display overlay as a 360-degree equirectangular skybox.
/// </summary>
public class OVROverlay : MonoBehaviour
{
#region Interface
/// <summary>
/// Determines the on-screen appearance of a layer.
/// </summary>
public enum OverlayShape
{
Quad = OVRPlugin.OverlayShape.Quad,
Cylinder = OVRPlugin.OverlayShape.Cylinder,
Cubemap = OVRPlugin.OverlayShape.Cubemap,
OffcenterCubemap = OVRPlugin.OverlayShape.OffcenterCubemap,
Equirect = OVRPlugin.OverlayShape.Equirect,
}
/// <summary>
/// Whether the layer appears behind or infront of other content in the scene.
/// </summary>
public enum OverlayType
{
None,
Underlay,
Overlay,
};
/// <summary>
/// Specify overlay's type
/// </summary>
[Tooltip("Specify overlay's type")]
public OverlayType currentOverlayType = OverlayType.Overlay;
/// <summary>
/// If true, the texture's content is copied to the compositor each frame.
/// </summary>
[Tooltip("If true, the texture's content is copied to the compositor each frame.")]
public bool isDynamic = false;
/// <summary>
/// If true, the layer would be used to present protected content (e.g. HDCP). The flag is effective only on PC.
/// </summary>
[Tooltip("If true, the layer would be used to present protected content (e.g. HDCP). The flag is effective only on PC.")]
public bool isProtectedContent = false;
/// <summary>
/// If true, the layer will be created as an external surface. externalSurfaceObject contains the Surface object. It's effective only on Android.
/// </summary>
[Tooltip("If true, the layer will be created as an external surface. externalSurfaceObject contains the Surface object. It's effective only on Android.")]
public bool isExternalSurface = false;
/// <summary>
/// The width which will be used to create the external surface. It's effective only on Android.
/// </summary>
[Tooltip("The width which will be used to create the external surface. It's effective only on Android.")]
public int externalSurfaceWidth = 0;
/// <summary>
/// The height which will be used to create the external surface. It's effective only on Android.
/// </summary>
[Tooltip("The height which will be used to create the external surface. It's effective only on Android.")]
public int externalSurfaceHeight = 0;
/// <summary>
/// The compositionDepth defines the order of the OVROverlays in composition. The overlay/underlay with smaller compositionDepth would be composited in the front of the overlay/underlay with larger compositionDepth.
/// </summary>
[Tooltip("The compositionDepth defines the order of the OVROverlays in composition. The overlay/underlay with smaller compositionDepth would be composited in the front of the overlay/underlay with larger compositionDepth.")]
public int compositionDepth = 0;
/// <summary>
/// The noDepthBufferTesting will stop layer's depth buffer compositing even if the engine has "Depth buffer sharing" enabled on Rift.
/// </summary>
[Tooltip("The noDepthBufferTesting will stop layer's depth buffer compositing even if the engine has \"Shared Depth Buffer\" enabled")]
public bool noDepthBufferTesting = false;
/// <summary>
/// Specify overlay's shape
/// </summary>
[Tooltip("Specify overlay's shape")]
public OverlayShape currentOverlayShape = OverlayShape.Quad;
private OverlayShape prevOverlayShape = OverlayShape.Quad;
/// <summary>
/// The left- and right-eye Textures to show in the layer.
/// \note If you need to change the texture on a per-frame basis, please use OverrideOverlayTextureInfo(..) to avoid caching issues.
/// </summary>
[Tooltip("The left- and right-eye Textures to show in the layer.")]
public Texture[] textures = new Texture[] { null, null };
protected IntPtr[] texturePtrs = new IntPtr[] { IntPtr.Zero, IntPtr.Zero };
/// <summary>
/// The Surface object (Android only).
/// </summary>
public System.IntPtr externalSurfaceObject;
public delegate void ExternalSurfaceObjectCreated();
/// <summary>
/// Will be triggered after externalSurfaceTextueObject get created.
/// </summary>
public ExternalSurfaceObjectCreated externalSurfaceObjectCreated;
/// <summary>
/// Use this function to set texture and texNativePtr when app is running
/// GetNativeTexturePtr is a slow behavior, the value should be pre-cached
/// </summary>
#if UNITY_2017_2_OR_NEWER
public void OverrideOverlayTextureInfo(Texture srcTexture, IntPtr nativePtr, UnityEngine.XR.XRNode node)
#else
public void OverrideOverlayTextureInfo(Texture srcTexture, IntPtr nativePtr, UnityEngine.VR.VRNode node)
#endif
{
#if UNITY_2017_2_OR_NEWER
int index = (node == UnityEngine.XR.XRNode.RightEye) ? 1 : 0;
#else
int index = (node == UnityEngine.VR.VRNode.RightEye) ? 1 : 0;
#endif
if (textures.Length <= index)
return;
textures[index] = srcTexture;
texturePtrs[index] = nativePtr;
isOverridePending = true;
}
protected bool isOverridePending;
internal const int maxInstances = 15;
internal static OVROverlay[] instances = new OVROverlay[maxInstances];
#endregion
private static Material tex2DMaterial;
private static Material cubeMaterial;
private OVRPlugin.LayerLayout layout {
get {
#if UNITY_ANDROID && !UNITY_EDITOR
if (textures.Length == 2 && textures[1] != null)
return OVRPlugin.LayerLayout.Stereo;
#endif
return OVRPlugin.LayerLayout.Mono;
}
}
private struct LayerTexture {
public Texture appTexture;
public IntPtr appTexturePtr;
public Texture[] swapChain;
public IntPtr[] swapChainPtr;
};
private LayerTexture[] layerTextures;
private OVRPlugin.LayerDesc layerDesc;
private int stageCount = -1;
private int layerIndex = -1; // Controls the composition order based on wake-up time.
private int layerId = 0; // The layer's internal handle in the compositor.
private GCHandle layerIdHandle;
private IntPtr layerIdPtr = IntPtr.Zero;
private int frameIndex = 0;
private int prevFrameIndex = -1;
private Renderer rend;
private int texturesPerStage { get { return (layout == OVRPlugin.LayerLayout.Stereo) ? 2 : 1; } }
private bool CreateLayer(int mipLevels, int sampleCount, OVRPlugin.EyeTextureFormat etFormat, int flags, OVRPlugin.Sizei size, OVRPlugin.OverlayShape shape)
{
if (!layerIdHandle.IsAllocated || layerIdPtr == IntPtr.Zero)
{
layerIdHandle = GCHandle.Alloc(layerId, GCHandleType.Pinned);
layerIdPtr = layerIdHandle.AddrOfPinnedObject();
}
if (layerIndex == -1)
{
for (int i = 0; i < maxInstances; ++i)
{
if (instances[i] == null || instances[i] == this)
{
layerIndex = i;
instances[i] = this;
break;
}
}
}
bool needsSetup = (
isOverridePending ||
layerDesc.MipLevels != mipLevels ||
layerDesc.SampleCount != sampleCount ||
layerDesc.Format != etFormat ||
layerDesc.Layout != layout ||
layerDesc.LayerFlags != flags ||
!layerDesc.TextureSize.Equals(size) ||
layerDesc.Shape != shape);
if (!needsSetup)
return false;
OVRPlugin.LayerDesc desc = OVRPlugin.CalculateLayerDesc(shape, layout, size, mipLevels, sampleCount, etFormat, flags);
OVRPlugin.EnqueueSetupLayer(desc, compositionDepth, layerIdPtr);
layerId = (int)layerIdHandle.Target;
if (layerId > 0)
{
layerDesc = desc;
if (isExternalSurface)
{
stageCount = 1;
}
else
{
stageCount = OVRPlugin.GetLayerTextureStageCount(layerId);
}
}
isOverridePending = false;
return true;
}
private bool CreateLayerTextures(bool useMipmaps, OVRPlugin.Sizei size, bool isHdr)
{
if (isExternalSurface)
{
if (externalSurfaceObject == System.IntPtr.Zero)
{
externalSurfaceObject = OVRPlugin.GetLayerAndroidSurfaceObject(layerId);
if (externalSurfaceObject != System.IntPtr.Zero)
{
Debug.LogFormat("GetLayerAndroidSurfaceObject returns {0}", externalSurfaceObject);
if (externalSurfaceObjectCreated != null)
{
externalSurfaceObjectCreated();
}
}
}
return false;
}
bool needsCopy = false;
if (stageCount <= 0)
return false;
// For newer SDKs, blit directly to the surface that will be used in compositing.
if (layerTextures == null)
layerTextures = new LayerTexture[texturesPerStage];
for (int eyeId = 0; eyeId < texturesPerStage; ++eyeId)
{
if (layerTextures[eyeId].swapChain == null)
layerTextures[eyeId].swapChain = new Texture[stageCount];
if (layerTextures[eyeId].swapChainPtr == null)
layerTextures[eyeId].swapChainPtr = new IntPtr[stageCount];
for (int stage = 0; stage < stageCount; ++stage)
{
Texture sc = layerTextures[eyeId].swapChain[stage];
IntPtr scPtr = layerTextures[eyeId].swapChainPtr[stage];
if (sc != null && scPtr != IntPtr.Zero)
continue;
if (scPtr == IntPtr.Zero)
scPtr = OVRPlugin.GetLayerTexture(layerId, stage, (OVRPlugin.Eye)eyeId);
if (scPtr == IntPtr.Zero)
continue;
var txFormat = (isHdr) ? TextureFormat.RGBAHalf : TextureFormat.RGBA32;
if (currentOverlayShape != OverlayShape.Cubemap && currentOverlayShape != OverlayShape.OffcenterCubemap)
sc = Texture2D.CreateExternalTexture(size.w, size.h, txFormat, useMipmaps, true, scPtr);
#if UNITY_2017_1_OR_NEWER
else
sc = Cubemap.CreateExternalTexture(size.w, txFormat, useMipmaps, scPtr);
#endif
layerTextures[eyeId].swapChain[stage] = sc;
layerTextures[eyeId].swapChainPtr[stage] = scPtr;
needsCopy = true;
}
}
return needsCopy;
}
private void DestroyLayerTextures()
{
if (isExternalSurface)
{
return;
}
for (int eyeId = 0; layerTextures != null && eyeId < texturesPerStage; ++eyeId)
{
if (layerTextures[eyeId].swapChain != null)
{
for (int stage = 0; stage < stageCount; ++stage)
DestroyImmediate(layerTextures[eyeId].swapChain[stage]);
}
}
layerTextures = null;
}
private void DestroyLayer()
{
if (layerIndex != -1)
{
// Turn off the overlay if it was on.
OVRPlugin.EnqueueSubmitLayer(true, false, false, IntPtr.Zero, IntPtr.Zero, -1, 0, OVRPose.identity.ToPosef(), Vector3.one.ToVector3f(), layerIndex, (OVRPlugin.OverlayShape)prevOverlayShape);
instances[layerIndex] = null;
layerIndex = -1;
}
if (layerIdPtr != IntPtr.Zero)
{
OVRPlugin.EnqueueDestroyLayer(layerIdPtr);
layerIdPtr = IntPtr.Zero;
layerIdHandle.Free();
layerId = 0;
}
layerDesc = new OVRPlugin.LayerDesc();
frameIndex = 0;
prevFrameIndex = -1;
}
private bool LatchLayerTextures()
{
if (isExternalSurface)
{
return true;
}
for (int i = 0; i < texturesPerStage; ++i)
{
if (textures[i] != layerTextures[i].appTexture || layerTextures[i].appTexturePtr == IntPtr.Zero)
{
if (textures[i] != null)
{
#if UNITY_EDITOR
var assetPath = UnityEditor.AssetDatabase.GetAssetPath(textures[i]);
var importer = (UnityEditor.TextureImporter)UnityEditor.TextureImporter.GetAtPath(assetPath);
if (importer && importer.textureType != UnityEditor.TextureImporterType.Default)
{
Debug.LogError("Need Default Texture Type for overlay");
return false;
}
#endif
var rt = textures[i] as RenderTexture;
if (rt && !rt.IsCreated())
rt.Create();
layerTextures[i].appTexturePtr = (texturePtrs[i] != IntPtr.Zero) ? texturePtrs[i] : textures[i].GetNativeTexturePtr();
if (layerTextures[i].appTexturePtr != IntPtr.Zero)
layerTextures[i].appTexture = textures[i];
}
}
if (currentOverlayShape == OverlayShape.Cubemap)
{
if (textures[i] as Cubemap == null)
{
Debug.LogError("Need Cubemap texture for cube map overlay");
return false;
}
}
}
#if !UNITY_ANDROID || UNITY_EDITOR
if (currentOverlayShape == OverlayShape.OffcenterCubemap)
{
Debug.LogWarning("Overlay shape " + currentOverlayShape + " is not supported on current platform");
return false;
}
#endif
if (layerTextures[0].appTexture == null || layerTextures[0].appTexturePtr == IntPtr.Zero)
return false;
return true;
}
private OVRPlugin.LayerDesc GetCurrentLayerDesc()
{
OVRPlugin.Sizei textureSize = new OVRPlugin.Sizei() { w = 0, h = 0 };
if (isExternalSurface)
{
textureSize.w = externalSurfaceWidth;
textureSize.h = externalSurfaceHeight;
}
else
{
if (textures[0] == null)
{
Debug.LogWarning("textures[0] hasn't been set");
}
textureSize.w = textures[0] ? textures[0].width : 0;
textureSize.h = textures[0] ? textures[0].height : 0;
}
OVRPlugin.LayerDesc newDesc = new OVRPlugin.LayerDesc() {
Format = OVRPlugin.EyeTextureFormat.R8G8B8A8_sRGB,
LayerFlags = isExternalSurface ? 0 : (int)OVRPlugin.LayerFlags.TextureOriginAtBottomLeft,
Layout = layout,
MipLevels = 1,
SampleCount = 1,
Shape = (OVRPlugin.OverlayShape)currentOverlayShape,
TextureSize = textureSize
};
var tex2D = textures[0] as Texture2D;
if (tex2D != null)
{
if (tex2D.format == TextureFormat.RGBAHalf || tex2D.format == TextureFormat.RGBAFloat)
newDesc.Format = OVRPlugin.EyeTextureFormat.R16G16B16A16_FP;
newDesc.MipLevels = tex2D.mipmapCount;
}
var texCube = textures[0] as Cubemap;
if (texCube != null)
{
if (texCube.format == TextureFormat.RGBAHalf || texCube.format == TextureFormat.RGBAFloat)
newDesc.Format = OVRPlugin.EyeTextureFormat.R16G16B16A16_FP;
newDesc.MipLevels = texCube.mipmapCount;
}
var rt = textures[0] as RenderTexture;
if (rt != null)
{
newDesc.SampleCount = rt.antiAliasing;
if (rt.format == RenderTextureFormat.ARGBHalf || rt.format == RenderTextureFormat.ARGBFloat || rt.format == RenderTextureFormat.RGB111110Float)
newDesc.Format = OVRPlugin.EyeTextureFormat.R16G16B16A16_FP;
}
if (isProtectedContent)
{
newDesc.LayerFlags |= (int)OVRPlugin.LayerFlags.ProtectedContent;
}
if (isExternalSurface)
{
newDesc.LayerFlags |= (int)OVRPlugin.LayerFlags.AndroidSurfaceSwapChain;
}
return newDesc;
}
private bool PopulateLayer(int mipLevels, bool isHdr, OVRPlugin.Sizei size, int sampleCount, int stage)
{
if (isExternalSurface)
{
return true;
}
bool ret = false;
RenderTextureFormat rtFormat = (isHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32;
for (int eyeId = 0; eyeId < texturesPerStage; ++eyeId)
{
Texture et = layerTextures[eyeId].swapChain[stage];
if (et == null)
continue;
for (int mip = 0; mip < mipLevels; ++mip)
{
int width = size.w >> mip;
if (width < 1) width = 1;
int height = size.h >> mip;
if (height < 1) height = 1;
#if UNITY_2017_1_1 || UNITY_2017_2_OR_NEWER
RenderTextureDescriptor descriptor = new RenderTextureDescriptor(width, height, rtFormat, 0);
descriptor.msaaSamples = sampleCount;
descriptor.useMipMap = true;
descriptor.autoGenerateMips = false;
descriptor.sRGB = false;
var tempRTDst = RenderTexture.GetTemporary(descriptor);
#else
var tempRTDst = RenderTexture.GetTemporary(width, height, 0, rtFormat, RenderTextureReadWrite.Linear, sampleCount);
#endif
if (!tempRTDst.IsCreated())
tempRTDst.Create();
tempRTDst.DiscardContents();
bool dataIsLinear = isHdr || (QualitySettings.activeColorSpace == ColorSpace.Linear);
#if !UNITY_2017_1_OR_NEWER
var rt = textures[eyeId] as RenderTexture;
dataIsLinear |= rt != null && rt.sRGB; //HACK: Unity 5.6 and earlier convert to linear on read from sRGB RenderTexture.
#endif
#if UNITY_ANDROID && !UNITY_EDITOR
dataIsLinear = true; //HACK: Graphics.CopyTexture causes linear->srgb conversion on target write with D3D but not GLES.
#endif
if (currentOverlayShape != OverlayShape.Cubemap && currentOverlayShape != OverlayShape.OffcenterCubemap)
{
tex2DMaterial.SetInt("_linearToSrgb", (!isHdr && dataIsLinear) ? 1 : 0);
//Resolve, decompress, swizzle, etc not handled by simple CopyTexture.
#if !UNITY_ANDROID || UNITY_EDITOR
// The PC compositor uses premultiplied alpha, so multiply it here.
tex2DMaterial.SetInt("_premultiply", 1);
#endif
Graphics.Blit(textures[eyeId], tempRTDst, tex2DMaterial);
Graphics.CopyTexture(tempRTDst, 0, 0, et, 0, mip);
}
#if UNITY_2017_1_OR_NEWER
else // Cubemap
{
for (int face = 0; face < 6; ++face)
{
cubeMaterial.SetInt("_linearToSrgb", (!isHdr && dataIsLinear) ? 1 : 0);
#if !UNITY_ANDROID || UNITY_EDITOR
// The PC compositor uses premultiplied alpha, so multiply it here.
cubeMaterial.SetInt("_premultiply", 1);
#endif
cubeMaterial.SetInt("_face", face);
//Resolve, decompress, swizzle, etc not handled by simple CopyTexture.
Graphics.Blit(textures[eyeId], tempRTDst, cubeMaterial);
Graphics.CopyTexture(tempRTDst, 0, 0, et, face, mip);
}
}
#endif
RenderTexture.ReleaseTemporary(tempRTDst);
ret = true;
}
}
return ret;
}
private bool SubmitLayer(bool overlay, bool headLocked, bool noDepthBufferTesting, OVRPose pose, Vector3 scale, int frameIndex)
{
int rightEyeIndex = (texturesPerStage >= 2) ? 1 : 0;
bool isOverlayVisible = OVRPlugin.EnqueueSubmitLayer(overlay, headLocked, noDepthBufferTesting,
isExternalSurface ? System.IntPtr.Zero : layerTextures[0].appTexturePtr,
isExternalSurface ? System.IntPtr.Zero : layerTextures[rightEyeIndex].appTexturePtr,
layerId, frameIndex, pose.flipZ().ToPosef(), scale.ToVector3f(), layerIndex, (OVRPlugin.OverlayShape)currentOverlayShape);
prevOverlayShape = currentOverlayShape;
return isOverlayVisible;
}
#region Unity Messages
void Awake()
{
Debug.Log("Overlay Awake");
if (tex2DMaterial == null)
tex2DMaterial = new Material(Shader.Find("Oculus/Texture2D Blit"));
if (cubeMaterial == null)
cubeMaterial = new Material(Shader.Find("Oculus/Cubemap Blit"));
rend = GetComponent<Renderer>();
if (textures.Length == 0)
textures = new Texture[] { null };
// Backward compatibility
if (rend != null && textures[0] == null)
textures[0] = rend.material.mainTexture;
}
void OnEnable()
{
if (!OVRManager.isHmdPresent)
{
enabled = false;
return;
}
}
void OnDisable()
{
if ((gameObject.hideFlags & HideFlags.DontSaveInBuild) != 0)
return;
DestroyLayerTextures();
DestroyLayer();
}
void OnDestroy()
{
DestroyLayerTextures();
DestroyLayer();
}
bool ComputeSubmit(ref OVRPose pose, ref Vector3 scale, ref bool overlay, ref bool headLocked)
{
Camera headCamera = Camera.main;
overlay = (currentOverlayType == OverlayType.Overlay);
headLocked = false;
for (var t = transform; t != null && !headLocked; t = t.parent)
headLocked |= (t == headCamera.transform);
pose = (headLocked) ? transform.ToHeadSpacePose(headCamera) : transform.ToTrackingSpacePose(headCamera);
scale = transform.lossyScale;
for (int i = 0; i < 3; ++i)
scale[i] /= headCamera.transform.lossyScale[i];
if (currentOverlayShape == OverlayShape.Cubemap)
{
#if UNITY_ANDROID && !UNITY_EDITOR
//HACK: VRAPI cubemaps assume are yawed 180 degrees relative to LibOVR.
pose.orientation = pose.orientation * Quaternion.AngleAxis(180, Vector3.up);
#endif
pose.position = headCamera.transform.position;
}
// Pack the offsetCenter directly into pose.position for offcenterCubemap
if (currentOverlayShape == OverlayShape.OffcenterCubemap)
{
pose.position = transform.position;
if (pose.position.magnitude > 1.0f)
{
Debug.LogWarning("Your cube map center offset's magnitude is greater than 1, which will cause some cube map pixel always invisible .");
return false;
}
}
// Cylinder overlay sanity checking
if (currentOverlayShape == OverlayShape.Cylinder)
{
float arcAngle = scale.x / scale.z / (float)Math.PI * 180.0f;
if (arcAngle > 180.0f)
{
Debug.LogWarning("Cylinder overlay's arc angle has to be below 180 degree, current arc angle is " + arcAngle + " degree." );
return false;
}
}
return true;
}
void LateUpdate()
{
// The overlay must be specified every eye frame, because it is positioned relative to the
// current head location. If frames are dropped, it will be time warped appropriately,
// just like the eye buffers.
if (currentOverlayType == OverlayType.None || ((textures.Length < texturesPerStage || textures[0] == null) && !isExternalSurface))
return;
OVRPose pose = OVRPose.identity;
Vector3 scale = Vector3.one;
bool overlay = false;
bool headLocked = false;
if (!ComputeSubmit(ref pose, ref scale, ref overlay, ref headLocked))
return;
OVRPlugin.LayerDesc newDesc = GetCurrentLayerDesc();
bool isHdr = (newDesc.Format == OVRPlugin.EyeTextureFormat.R16G16B16A16_FP);
bool createdLayer = CreateLayer(newDesc.MipLevels, newDesc.SampleCount, newDesc.Format, newDesc.LayerFlags, newDesc.TextureSize, newDesc.Shape);
if (layerIndex == -1 || layerId <= 0)
return;
bool useMipmaps = (newDesc.MipLevels > 1);
createdLayer |= CreateLayerTextures(useMipmaps, newDesc.TextureSize, isHdr);
if (!isExternalSurface && (layerTextures[0].appTexture as RenderTexture != null))
isDynamic = true;
if (!LatchLayerTextures())
return;
// Don't populate the same frame image twice.
if (frameIndex > prevFrameIndex)
{
int stage = frameIndex % stageCount;
if (!PopulateLayer (newDesc.MipLevels, isHdr, newDesc.TextureSize, newDesc.SampleCount, stage))
return;
}
bool isOverlayVisible = SubmitLayer(overlay, headLocked, noDepthBufferTesting, pose, scale, frameIndex);
prevFrameIndex = frameIndex;
if (isDynamic)
++frameIndex;
// Backward compatibility: show regular renderer if overlay isn't visible.
if (rend)
rend.enabled = !isOverlayVisible;
}
#endregion
}
| |
/*
Matali Physics Demo
Copyright (c) 2013 KOMIRES Sp. z o. o.
*/
using System;
using System.Collections.Generic;
using OpenTK;
using OpenTK.Graphics.OpenGL;
using Komires.MataliPhysics;
namespace MataliPhysicsDemo
{
/// <summary>
/// This is the main type for your game
/// </summary>
public sealed class BridgesScene : IDemoScene
{
Demo demo;
PhysicsScene scene;
string name;
string instanceIndexName;
string info;
public PhysicsScene PhysicsScene { get { return scene; } }
public string SceneName { get { return name; } }
public string SceneInfo { get { return info; } }
// Declare objects in the scene
Sky skyInstance1;
Quad quadInstance1;
Cursor cursorInstance;
Shot shotInstance;
Car1 car1Instance1;
Bridge1 bridge1Instance1;
Bridge1 bridge1Instance2;
Ragdoll1 ragdoll1Instance1;
Camera1 camera1Instance1;
Lights lightInstance;
// Declare controllers in the scene
SkyDraw1 skyDraw1Instance1;
CursorDraw1 cursorDraw1Instance;
Car1Animation1 car1Animation1Instance1;
Camera1Animation1 camera1Animation1Instance1;
Camera1Draw1 camera1Draw1Instance1;
public BridgesScene(Demo demo, string name, int instanceIndex, string info)
{
this.demo = demo;
this.name = name;
this.instanceIndexName = " " + instanceIndex.ToString();
this.info = info;
// Create a new objects in the scene
skyInstance1 = new Sky(demo, 1);
quadInstance1 = new Quad(demo, 1);
cursorInstance = new Cursor(demo);
shotInstance = new Shot(demo);
car1Instance1 = new Car1(demo, 1);
bridge1Instance1 = new Bridge1(demo, 1);
bridge1Instance2 = new Bridge1(demo, 2);
ragdoll1Instance1 = new Ragdoll1(demo, 1);
camera1Instance1 = new Camera1(demo, 1);
lightInstance = new Lights(demo);
// Create a new controllers in the scene
skyDraw1Instance1 = new SkyDraw1(demo, 1);
cursorDraw1Instance = new CursorDraw1(demo);
car1Animation1Instance1 = new Car1Animation1(demo, 1);
camera1Animation1Instance1 = new Camera1Animation1(demo, 1);
camera1Draw1Instance1 = new Camera1Draw1(demo, 1);
}
public void Create()
{
string sceneInstanceIndexName = name + instanceIndexName;
if (demo.Engine.Factory.PhysicsSceneManager.Find(sceneInstanceIndexName) != null) return;
scene = demo.Engine.Factory.PhysicsSceneManager.Create(sceneInstanceIndexName);
// Initialize maximum number of solver iterations for the scene
scene.MaxIterationCount = 10;
// Initialize time of simulation for the scene
scene.TimeOfSimulation = 1.0f / 15.0f;
Initialize();
// Initialize objects in the scene
skyInstance1.Initialize(scene);
quadInstance1.Initialize(scene);
cursorInstance.Initialize(scene);
shotInstance.Initialize(scene);
car1Instance1.Initialize(scene);
bridge1Instance1.Initialize(scene);
bridge1Instance2.Initialize(scene);
ragdoll1Instance1.Initialize(scene);
camera1Instance1.Initialize(scene);
lightInstance.Initialize(scene);
// Initialize controllers in the scene
skyDraw1Instance1.Initialize(scene);
cursorDraw1Instance.Initialize(scene);
car1Animation1Instance1.Initialize(scene);
camera1Animation1Instance1.Initialize(scene);
camera1Draw1Instance1.Initialize(scene);
// Create shapes shared for all physics objects in the scene
// These shapes are used by all objects in the scene
Demo.CreateSharedShapes(demo, scene);
// Create shapes for objects in the scene
Sky.CreateShapes(demo, scene);
Quad.CreateShapes(demo, scene);
Cursor.CreateShapes(demo, scene);
Shot.CreateShapes(demo, scene);
Car1.CreateShapes(demo, scene);
Bridge1.CreateShapes(demo, scene);
Ragdoll1.CreateShapes(demo, scene);
Camera1.CreateShapes(demo, scene);
Lights.CreateShapes(demo, scene);
// Create physics objects for objects in the scene
skyInstance1.Create(new Vector3(0.0f, 0.0f, 0.0f));
quadInstance1.Create(new Vector3(0.0f, -40.0f, 20.0f), new Vector3(1000.0f, 31.0f, 1000.0f), Quaternion.Identity);
cursorInstance.Create();
shotInstance.Create();
car1Instance1.Create(new Vector3(20.0f, 60.0f, 20.0f), Vector3.One, Quaternion.FromAxisAngle(Vector3.UnitY, MathHelper.DegreesToRadians(90.0f)));
bridge1Instance1.Create(new Vector3(0.0f, 10.0f, 0.0f), Vector3.One, Quaternion.FromAxisAngle(Vector3.UnitY, MathHelper.DegreesToRadians(-5.0f)), 50, new Vector3(5.0f, 0.4f, 15.0f));
bridge1Instance2.Create(new Vector3(0.0f, 10.0f, 100.0f), Vector3.One, Quaternion.FromAxisAngle(Vector3.UnitY, MathHelper.DegreesToRadians(5.0f)), 50, new Vector3(5.0f, 0.4f, 15.0f));
ragdoll1Instance1.Create(new Vector3(0.0f, 30.0f, 100.0f), Vector3.One, Quaternion.FromAxisAngle(Vector3.UnitX, MathHelper.DegreesToRadians(0.0f)), false, false, 1.0f);
camera1Instance1.Create(new Vector3(0.0f, 65.0f, -22.0f), Quaternion.FromAxisAngle(Vector3.UnitX, MathHelper.DegreesToRadians(-30.0f)), Quaternion.Identity, Quaternion.Identity, true);
lightInstance.CreateLightPoint(0, "Glass", new Vector3(-50.0f, 15.0f, 100.0f), new Vector3(0.2f, 1.0f, 1.0f), 40.0f, 1.0f);
lightInstance.CreateLightPoint(1, "Glass", new Vector3(0.0f, 15.0f, 100.0f), new Vector3(1.0f, 0.5f, 0.1f), 40.0f, 1.0f);
lightInstance.CreateLightPoint(2, "Glass", new Vector3(50.0f, 15.0f, 105.0f), new Vector3(1.0f, 0.7f, 0.0f), 40.0f, 1.0f);
lightInstance.CreateLightPoint(3, "Glass", new Vector3(-50.0f, 15.0f, 45.0f), new Vector3(1.0f, 0.7f, 0.5f), 40.0f, 1.0f);
lightInstance.CreateLightPoint(4, "Glass", new Vector3(0.0f, 15.0f, 40.0f), new Vector3(1.0f, 1.0f, 0.5f), 40.0f, 1.0f);
lightInstance.CreateLightPoint(5, "Glass", new Vector3(50.0f, 15.0f, 35.0f), new Vector3(0.3f, 0.7f, 0.5f), 40.0f, 1.0f);
lightInstance.CreateLightSpot(0, "Glass", new Vector3(-60.0f, 50.0f, 45.0f), new Vector3(0.1f, 0.7f, 1.0f), 40.0f, 1.0f);
lightInstance.CreateLightSpot(1, "Glass", new Vector3(10.0f, 50.0f, 105.0f), new Vector3(1.0f, 0.5f, 0.2f), 40.0f, 1.0f);
lightInstance.CreateLightSpot(2, "Glass", new Vector3(60.0f, 50.0f, 35.0f), new Vector3(0.5f, 1.0f, 0.2f), 40.0f, 1.0f);
// Set controllers for objects in the scene
SetControllers();
}
public void Initialize()
{
scene.UserControllers.PostDrawMethods += demo.DrawInfo;
if (scene.Light == null)
{
scene.CreateLight(true);
scene.Light.Type = PhysicsLightType.Directional;
scene.Light.SetDirection(-0.4f, -0.8f, 0.4f, 0.0f);
}
}
public void SetControllers()
{
skyDraw1Instance1.SetControllers();
cursorDraw1Instance.SetControllers();
car1Animation1Instance1.SetControllers(true);
camera1Animation1Instance1.SetControllers();
camera1Draw1Instance1.SetControllers(false, false, false, false, false, false);
}
public void Refresh(double time)
{
camera1Animation1Instance1.RefreshControllers();
camera1Draw1Instance1.RefreshControllers();
GL.Clear(ClearBufferMask.DepthBufferBit);
scene.Simulate(time);
scene.Draw(time);
if (demo.EnableMenu)
{
GL.Clear(ClearBufferMask.DepthBufferBit);
demo.MenuScene.PhysicsScene.Draw(time);
}
demo.SwapBuffers();
}
public void Remove()
{
string sceneInstanceIndexName = name + instanceIndexName;
if (demo.Engine.Factory.PhysicsSceneManager.Find(sceneInstanceIndexName) != null)
demo.Engine.Factory.PhysicsSceneManager.Remove(sceneInstanceIndexName);
}
public void CreateResources()
{
}
public void DisposeResources()
{
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Text;
using Xunit;
namespace System.Text.EncodingTests
{
// GetChars(System.Byte[],System.Int32,System.Int32,System.Char[],System.Int32)
public class DecoderGetChars3
{
#region Private Fields
private const int c_SIZE_OF_ARRAY = 127;
#endregion
#region Positive Test Cases
// PosTest1: Call GetChars with ASCII decoder to convert a ASCII byte array
[Fact]
public void PosTest1()
{
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
char[] chars = new char[bytes.Length];
char[] expectedChars = new char[bytes.Length];
Decoder decoder = Encoding.UTF8.GetDecoder();
for (int i = 0; i < bytes.Length; ++i)
{
bytes[i] = (byte)i;
}
for (int i = 0; i < expectedChars.Length; ++i)
{
expectedChars[i] = (char)('\0' + i);
}
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, bytes.Length, expectedChars, "001.1");
}
// PosTest2: Call GetChars with Unicode decoder to convert a ASCII byte array
[Fact]
public void PosTest2()
{
byte[] bytes = new byte[c_SIZE_OF_ARRAY * 2];
char[] chars = new char[c_SIZE_OF_ARRAY];
char[] expectedChars = new char[c_SIZE_OF_ARRAY];
Decoder decoder = Encoding.Unicode.GetDecoder();
byte c = 0;
for (int i = 0; i < bytes.Length; i += 2)
{
bytes[i] = c++;
bytes[i + 1] = 0;
}
for (int i = 0; i < expectedChars.Length; ++i)
{
expectedChars[i] = (char)('\0' + i);
}
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, expectedChars.Length, expectedChars, "002.1");
}
// PosTest3: Call GetChars with Unicode decoder to convert a Unicode byte array
[Fact]
public void PosTest3()
{
byte[] bytes = new byte[] {
217,
143,
42,
78,
0,
78,
42,
78,
75,
109,
213,
139
};
char[] expected = "\u8FD9\u4E2A\u4E00\u4E2A\u6D4B\u8BD5".ToCharArray();
char[] chars = new char[expected.Length];
Decoder decoder = Encoding.Unicode.GetDecoder();
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, expected.Length, expected, "003.1");
}
// PosTest4: Call GetChars with ASCII decoder to convert partial of ASCII byte array
[Fact]
public void PosTest4()
{
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
char[] chars = new char[bytes.Length];
Decoder decoder = Encoding.UTF8.GetDecoder();
for (int i = 0; i < bytes.Length; ++i)
{
bytes[i] = (byte)i;
}
VerificationHelper(decoder, bytes, 0, bytes.Length / 2, chars, 0, bytes.Length / 2, "004.1");
VerificationHelper(decoder, bytes, bytes.Length / 2, bytes.Length / 2, chars, chars.Length / 2, bytes.Length / 2, "004.2");
}
// PosTest5: Call GetChars with Unicode decoder to convert partial of an Unicode byte array
[Fact]
public void PosTest5()
{
byte[] bytes = new byte[] {
217,
143,
42,
78,
0,
78,
42,
78,
75,
109,
213,
139
};
char[] expected = "\u8FD9\u4E2A\u4E00\u4E2A\u6D4B\u8BD5".ToCharArray();
char[] chars = new char[expected.Length];
Decoder decoder = Encoding.Unicode.GetDecoder();
VerificationHelper(decoder, bytes, 0, bytes.Length / 2, chars, 0, chars.Length / 2, "005.1");
VerificationHelper(decoder, bytes, bytes.Length / 2, bytes.Length / 2, chars, 1, chars.Length / 2, "005.2");
}
// PosTest6: Call GetChars with ASCII decoder to convert arbitrary byte array
[Fact]
public void PosTest6()
{
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
char[] chars = new char[bytes.Length];
Decoder decoder = Encoding.UTF8.GetDecoder();
TestLibrary.Generator.GetBytes(-55, bytes);
decoder.GetChars(bytes, 0, bytes.Length, chars, 0);
}
// PosTest7: Call GetChars with Unicode decoder to convert arbitrary byte array
[Fact]
public void PosTest7()
{
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
char[] chars = new char[bytes.Length];
Decoder decoder = Encoding.Unicode.GetDecoder();
TestLibrary.Generator.GetBytes(-55, bytes);
decoder.GetChars(bytes, 0, bytes.Length, chars, 0);
}
// PosTest8: Call GetChars but convert nothing
[Fact]
public void PosTest8()
{
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
char[] chars = new char[bytes.Length];
Decoder decoder = Encoding.UTF8.GetDecoder();
TestLibrary.Generator.GetBytes(-55, bytes);
VerificationHelper(decoder, bytes, 0, 0, chars, 0, 0, "008.1");
decoder = Encoding.Unicode.GetDecoder();
VerificationHelper(decoder, bytes, 0, 0, chars, 0, 0, "008.2");
}
#endregion
#region Negative Test Cases
// NegTest1: ArgumentNullException should be throw when bytes is a null reference or chars is a null reference
[Fact]
public void NegTest1()
{
Decoder decoder = Encoding.UTF8.GetDecoder();
char[] chars = new char[c_SIZE_OF_ARRAY];
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
VerificationHelper<ArgumentNullException>(decoder, null, 0, 0, chars, 0, typeof(ArgumentNullException), "101.1");
VerificationHelper<ArgumentNullException>(decoder, bytes, 0, 0, null, 0, typeof(ArgumentNullException), "101.2");
}
// NegTest2: ArgumentOutOfRangeException should be throw when byteIndex or byteCount or charIndex is less than zero.
[Fact]
public void NegTest2()
{
Decoder decoder = Encoding.UTF8.GetDecoder();
char[] chars = new char[c_SIZE_OF_ARRAY];
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
VerificationHelper<ArgumentOutOfRangeException>(decoder, bytes, 0, -1, chars, 0, typeof(ArgumentOutOfRangeException), "102.1");
VerificationHelper<ArgumentOutOfRangeException>(decoder, bytes, 0, 0, chars, -1, typeof(ArgumentOutOfRangeException), "102.2");
VerificationHelper<ArgumentOutOfRangeException>(decoder, bytes, -1, 0, chars, 0, typeof(ArgumentOutOfRangeException), "102.3");
}
// NegTest3: ArgumentException should be throw when charCount is less than the resulting number of characters
[Fact]
public void NegTest3()
{
Decoder decoder = Encoding.UTF8.GetDecoder();
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
char[] chars = new char[1];
TestLibrary.Generator.GetBytes(-55, bytes);
VerificationHelper<ArgumentException>(decoder, bytes, 0, bytes.Length, chars, 0, typeof(ArgumentException), "103.1");
}
// NegTest4: ArgumentOutOfRangeException should be throw when byteindex and byteCount do not denote a valid range in bytes.
[Fact]
public void NegTest4()
{
Decoder decoder = Encoding.UTF8.GetDecoder();
char[] chars = new char[c_SIZE_OF_ARRAY];
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
VerificationHelper<ArgumentOutOfRangeException>(decoder, bytes, 1, bytes.Length, chars, 0, typeof(ArgumentOutOfRangeException), "104.1");
VerificationHelper<ArgumentOutOfRangeException>(decoder, bytes, bytes.Length, 1, chars, 0, typeof(ArgumentOutOfRangeException), "104.2");
}
// NegTest5: ArgumentOutOfRangeException should be throw when charIndex is not a valid index in chars.
[Fact]
public void NegTest5()
{
Decoder decoder = Encoding.UTF8.GetDecoder();
char[] chars = new char[c_SIZE_OF_ARRAY];
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
VerificationHelper<ArgumentOutOfRangeException>(decoder, bytes, 1, 0, chars, chars.Length + 1, typeof(ArgumentOutOfRangeException), "105.1");
}
#endregion
private void VerificationHelper<T>(Decoder decoder, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, Type expected, string errorno) where T : Exception
{
Assert.Throws<T>(() =>
{
decoder.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
});
}
private void VerificationHelper(Decoder decoder, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int expected, string errorno)
{
int actual = decoder.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
Assert.Equal(expected, actual);
}
private void VerificationHelper(Decoder decoder, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int expected, char[] expectedChars, string errorno)
{
VerificationHelper(decoder, bytes, byteIndex, byteCount, chars, charIndex, expected, errorno + ".1");
Assert.Equal(expectedChars.Length, chars.Length);
Assert.Equal(expectedChars, chars);
}
}
}
| |
#region Apache License
//
// 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.
//
#endregion
using System;
using Ctrip.Core;
namespace Ctrip.Util
{
/// <summary>
/// A fixed size rolling buffer of logging events.
/// </summary>
/// <remarks>
/// <para>
/// An array backed fixed size leaky bucket.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public class CyclicBuffer
{
#region Public Instance Constructors
/// <summary>
/// Constructor
/// </summary>
/// <param name="maxSize">The maximum number of logging events in the buffer.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="CyclicBuffer" /> class with
/// the specified maximum number of buffered logging events.
/// </para>
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">The <paramref name="maxSize"/> argument is not a positive integer.</exception>
public CyclicBuffer(int maxSize)
{
if (maxSize < 1)
{
throw SystemInfo.CreateArgumentOutOfRangeException("maxSize", (object)maxSize, "Parameter: maxSize, Value: [" + maxSize + "] out of range. Non zero positive integer required");
}
m_maxSize = maxSize;
m_events = new LoggingEvent[maxSize];
m_first = 0;
m_last = 0;
m_numElems = 0;
}
#endregion Public Instance Constructors
#region Public Instance Methods
/// <summary>
/// Appends a <paramref name="loggingEvent"/> to the buffer.
/// </summary>
/// <param name="loggingEvent">The event to append to the buffer.</param>
/// <returns>The event discarded from the buffer, if the buffer is full, otherwise <c>null</c>.</returns>
/// <remarks>
/// <para>
/// Append an event to the buffer. If the buffer still contains free space then
/// <c>null</c> is returned. If the buffer is full then an event will be dropped
/// to make space for the new event, the event dropped is returned.
/// </para>
/// </remarks>
public LoggingEvent Append(LoggingEvent loggingEvent)
{
if (loggingEvent == null)
{
throw new ArgumentNullException("loggingEvent");
}
lock(this)
{
// save the discarded event
LoggingEvent discardedLoggingEvent = m_events[m_last];
// overwrite the last event position
m_events[m_last] = loggingEvent;
if (++m_last == m_maxSize)
{
m_last = 0;
}
if (m_numElems < m_maxSize)
{
m_numElems++;
}
else if (++m_first == m_maxSize)
{
m_first = 0;
}
if (m_numElems < m_maxSize)
{
// Space remaining
return null;
}
else
{
// Buffer is full and discarding an event
return discardedLoggingEvent;
}
}
}
/// <summary>
/// Get and remove the oldest event in the buffer.
/// </summary>
/// <returns>The oldest logging event in the buffer</returns>
/// <remarks>
/// <para>
/// Gets the oldest (first) logging event in the buffer and removes it
/// from the buffer.
/// </para>
/// </remarks>
public LoggingEvent PopOldest()
{
lock(this)
{
LoggingEvent ret = null;
if (m_numElems > 0)
{
m_numElems--;
ret = m_events[m_first];
m_events[m_first] = null;
if (++m_first == m_maxSize)
{
m_first = 0;
}
}
return ret;
}
}
/// <summary>
/// Pops all the logging events from the buffer into an array.
/// </summary>
/// <returns>An array of all the logging events in the buffer.</returns>
/// <remarks>
/// <para>
/// Get all the events in the buffer and clear the buffer.
/// </para>
/// </remarks>
public LoggingEvent[] PopAll()
{
lock(this)
{
LoggingEvent[] ret = new LoggingEvent[m_numElems];
if (m_numElems > 0)
{
if (m_first < m_last)
{
Array.Copy(m_events, m_first, ret, 0, m_numElems);
}
else
{
Array.Copy(m_events, m_first, ret, 0, m_maxSize - m_first);
Array.Copy(m_events, 0, ret, m_maxSize - m_first, m_last);
}
}
Clear();
return ret;
}
}
/// <summary>
/// Clear the buffer
/// </summary>
/// <remarks>
/// <para>
/// Clear the buffer of all events. The events in the buffer are lost.
/// </para>
/// </remarks>
public void Clear()
{
lock(this)
{
// Set all the elements to null
Array.Clear(m_events, 0, m_events.Length);
m_first = 0;
m_last = 0;
m_numElems = 0;
}
}
#if RESIZABLE_CYCLIC_BUFFER
/// <summary>
/// Resizes the cyclic buffer to <paramref name="newSize"/>.
/// </summary>
/// <param name="newSize">The new size of the buffer.</param>
/// <remarks>
/// <para>
/// Resize the cyclic buffer. Events in the buffer are copied into
/// the newly sized buffer. If the buffer is shrunk and there are
/// more events currently in the buffer than the new size of the
/// buffer then the newest events will be dropped from the buffer.
/// </para>
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">The <paramref name="newSize"/> argument is not a positive integer.</exception>
public void Resize(int newSize)
{
lock(this)
{
if (newSize < 0)
{
throw Ctrip.Util.SystemInfo.CreateArgumentOutOfRangeException("newSize", (object)newSize, "Parameter: newSize, Value: [" + newSize + "] out of range. Non zero positive integer required");
}
if (newSize == m_numElems)
{
return; // nothing to do
}
LoggingEvent[] temp = new LoggingEvent[newSize];
int loopLen = (newSize < m_numElems) ? newSize : m_numElems;
for(int i = 0; i < loopLen; i++)
{
temp[i] = m_events[m_first];
m_events[m_first] = null;
if (++m_first == m_numElems)
{
m_first = 0;
}
}
m_events = temp;
m_first = 0;
m_numElems = loopLen;
m_maxSize = newSize;
if (loopLen == newSize)
{
m_last = 0;
}
else
{
m_last = loopLen;
}
}
}
#endif
#endregion Public Instance Methods
#region Public Instance Properties
/// <summary>
/// Gets the <paramref name="i"/>th oldest event currently in the buffer.
/// </summary>
/// <value>The <paramref name="i"/>th oldest event currently in the buffer.</value>
/// <remarks>
/// <para>
/// If <paramref name="i"/> is outside the range 0 to the number of events
/// currently in the buffer, then <c>null</c> is returned.
/// </para>
/// </remarks>
public LoggingEvent this[int i]
{
get
{
lock(this)
{
if (i < 0 || i >= m_numElems)
{
return null;
}
return m_events[(m_first + i) % m_maxSize];
}
}
}
/// <summary>
/// Gets the maximum size of the buffer.
/// </summary>
/// <value>The maximum size of the buffer.</value>
/// <remarks>
/// <para>
/// Gets the maximum size of the buffer
/// </para>
/// </remarks>
public int MaxSize
{
get
{
lock(this)
{
return m_maxSize;
}
}
#if RESIZABLE_CYCLIC_BUFFER
set
{
/// Setting the MaxSize will cause the buffer to resize.
Resize(value);
}
#endif
}
/// <summary>
/// Gets the number of logging events in the buffer.
/// </summary>
/// <value>The number of logging events in the buffer.</value>
/// <remarks>
/// <para>
/// This number is guaranteed to be in the range 0 to <see cref="MaxSize"/>
/// (inclusive).
/// </para>
/// </remarks>
public int Length
{
get
{
lock(this)
{
return m_numElems;
}
}
}
#endregion Public Instance Properties
#region Private Instance Fields
private LoggingEvent[] m_events;
private int m_first;
private int m_last;
private int m_numElems;
private int m_maxSize;
#endregion Private Instance 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 System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace System.ComponentModel.DataAnnotations
{
/// <summary>
/// Helper class to validate objects, properties and other values using their associated
/// <see cref="ValidationAttribute" />
/// custom attributes.
/// </summary>
public static class Validator
{
private static readonly ValidationAttributeStore _store = ValidationAttributeStore.Instance;
/// <summary>
/// Tests whether the given property value is valid.
/// </summary>
/// <remarks>
/// This method will test each <see cref="ValidationAttribute" /> associated with the property
/// identified by <paramref name="validationContext" />. If <paramref name="validationResults" /> is non-null,
/// this method will add a <see cref="ValidationResult" /> to it for each validation failure.
/// <para>
/// If there is a <see cref="RequiredAttribute" /> found on the property, it will be evaluated before all other
/// validation attributes. If the required validator fails then validation will abort, adding that single
/// failure into the <paramref name="validationResults" /> when applicable, returning a value of <c>false</c>.
/// </para>
/// <para>
/// If <paramref name="validationResults" /> is null and there isn't a <see cref="RequiredAttribute" /> failure,
/// then all validators will be evaluated.
/// </para>
/// </remarks>
/// <param name="value">The value to test.</param>
/// <param name="validationContext">
/// Describes the property member to validate and provides services and context for the
/// validators.
/// </param>
/// <param name="validationResults">Optional collection to receive <see cref="ValidationResult" />s for the failures.</param>
/// <returns><c>true</c> if the value is valid, <c>false</c> if any validation errors are encountered.</returns>
/// <exception cref="ArgumentException">
/// When the <see cref="ValidationContext.MemberName" /> of <paramref name="validationContext" /> is not a valid
/// property.
/// </exception>
public static bool TryValidateProperty(object value, ValidationContext validationContext,
ICollection<ValidationResult> validationResults)
{
// Throw if value cannot be assigned to this property. That is not a validation exception.
var propertyType = _store.GetPropertyType(validationContext);
var propertyName = validationContext.MemberName;
EnsureValidPropertyType(propertyName, propertyType, value);
var result = true;
var breakOnFirstError = (validationResults == null);
var attributes = _store.GetPropertyValidationAttributes(validationContext);
foreach (var err in GetValidationErrors(value, validationContext, attributes, breakOnFirstError))
{
result = false;
validationResults?.Add(err.ValidationResult);
}
return result;
}
/// <summary>
/// Tests whether the given object instance is valid.
/// </summary>
/// <remarks>
/// This method evaluates all <see cref="ValidationAttribute" />s attached to the object instance's type. It also
/// checks to ensure all properties marked with <see cref="RequiredAttribute" /> are set. It does not validate the
/// property values of the object.
/// <para>
/// If <paramref name="validationResults" /> is null, then execution will abort upon the first validation
/// failure. If <paramref name="validationResults" /> is non-null, then all validation attributes will be
/// evaluated.
/// </para>
/// </remarks>
/// <param name="instance">The object instance to test. It cannot be <c>null</c>.</param>
/// <param name="validationContext">Describes the object to validate and provides services and context for the validators.</param>
/// <param name="validationResults">Optional collection to receive <see cref="ValidationResult" />s for the failures.</param>
/// <returns><c>true</c> if the object is valid, <c>false</c> if any validation errors are encountered.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="instance" /> is null.</exception>
/// <exception cref="ArgumentException">
/// When <paramref name="instance" /> doesn't match the
/// <see cref="ValidationContext.ObjectInstance" />on <paramref name="validationContext" />.
/// </exception>
public static bool TryValidateObject(
object instance, ValidationContext validationContext, ICollection<ValidationResult> validationResults) =>
TryValidateObject(instance, validationContext, validationResults, false /*validateAllProperties*/);
/// <summary>
/// Tests whether the given object instance is valid.
/// </summary>
/// <remarks>
/// This method evaluates all <see cref="ValidationAttribute" />s attached to the object instance's type. It also
/// checks to ensure all properties marked with <see cref="RequiredAttribute" /> are set. If
/// <paramref name="validateAllProperties" />
/// is <c>true</c>, this method will also evaluate the <see cref="ValidationAttribute" />s for all the immediate
/// properties
/// of this object. This process is not recursive.
/// <para>
/// If <paramref name="validationResults" /> is null, then execution will abort upon the first validation
/// failure. If <paramref name="validationResults" /> is non-null, then all validation attributes will be
/// evaluated.
/// </para>
/// <para>
/// For any given property, if it has a <see cref="RequiredAttribute" /> that fails validation, no other validators
/// will be evaluated for that property.
/// </para>
/// </remarks>
/// <param name="instance">The object instance to test. It cannot be null.</param>
/// <param name="validationContext">Describes the object to validate and provides services and context for the validators.</param>
/// <param name="validationResults">Optional collection to receive <see cref="ValidationResult" />s for the failures.</param>
/// <param name="validateAllProperties">
/// If <c>true</c>, also evaluates all properties of the object (this process is not
/// recursive over properties of the properties).
/// </param>
/// <returns><c>true</c> if the object is valid, <c>false</c> if any validation errors are encountered.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="instance" /> is null.</exception>
/// <exception cref="ArgumentException">
/// When <paramref name="instance" /> doesn't match the
/// <see cref="ValidationContext.ObjectInstance" />on <paramref name="validationContext" />.
/// </exception>
public static bool TryValidateObject(object instance, ValidationContext validationContext,
ICollection<ValidationResult> validationResults, bool validateAllProperties)
{
if (instance == null)
{
throw new ArgumentNullException(nameof(instance));
}
if (validationContext != null && instance != validationContext.ObjectInstance)
{
throw new ArgumentException(
SR.Validator_InstanceMustMatchValidationContextInstance, nameof(instance));
}
var result = true;
var breakOnFirstError = (validationResults == null);
foreach (
var err in
GetObjectValidationErrors(instance, validationContext, validateAllProperties, breakOnFirstError))
{
result = false;
validationResults?.Add(err.ValidationResult);
}
return result;
}
/// <summary>
/// Tests whether the given value is valid against a specified list of <see cref="ValidationAttribute" />s.
/// </summary>
/// <remarks>
/// This method will test each <see cref="ValidationAttribute" />s specified. If
/// <paramref name="validationResults" /> is non-null, this method will add a <see cref="ValidationResult" />
/// to it for each validation failure.
/// <para>
/// If there is a <see cref="RequiredAttribute" /> within the <paramref name="validationAttributes" />, it will
/// be evaluated before all other validation attributes. If the required validator fails then validation will
/// abort, adding that single failure into the <paramref name="validationResults" /> when applicable, returning a
/// value of <c>false</c>.
/// </para>
/// <para>
/// If <paramref name="validationResults" /> is null and there isn't a <see cref="RequiredAttribute" /> failure,
/// then all validators will be evaluated.
/// </para>
/// </remarks>
/// <param name="value">The value to test. It cannot be null.</param>
/// <param name="validationContext">
/// Describes the object being validated and provides services and context for the
/// validators.
/// </param>
/// <param name="validationResults">Optional collection to receive <see cref="ValidationResult" />s for the failures.</param>
/// <param name="validationAttributes">
/// The list of <see cref="ValidationAttribute" />s to validate this
/// <paramref name="value" /> against.
/// </param>
/// <returns><c>true</c> if the object is valid, <c>false</c> if any validation errors are encountered.</returns>
public static bool TryValidateValue(object value, ValidationContext validationContext,
ICollection<ValidationResult> validationResults, IEnumerable<ValidationAttribute> validationAttributes)
{
var result = true;
var breakOnFirstError = validationResults == null;
foreach (
var err in
GetValidationErrors(value, validationContext, validationAttributes, breakOnFirstError))
{
result = false;
validationResults?.Add(err.ValidationResult);
}
return result;
}
/// <summary>
/// Throws a <see cref="ValidationException" /> if the given property <paramref name="value" /> is not valid.
/// </summary>
/// <param name="value">The value to test.</param>
/// <param name="validationContext">
/// Describes the object being validated and provides services and context for the
/// validators. It cannot be <c>null</c>.
/// </param>
/// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception>
/// <exception cref="ValidationException">When <paramref name="value" /> is invalid for this property.</exception>
public static void ValidateProperty(object value, ValidationContext validationContext)
{
// Throw if value cannot be assigned to this property. That is not a validation exception.
var propertyType = _store.GetPropertyType(validationContext);
EnsureValidPropertyType(validationContext.MemberName, propertyType, value);
var attributes = _store.GetPropertyValidationAttributes(validationContext);
GetValidationErrors(value, validationContext, attributes, false).FirstOrDefault()
?.ThrowValidationException();
}
/// <summary>
/// Throws a <see cref="ValidationException" /> if the given <paramref name="instance" /> is not valid.
/// </summary>
/// <remarks>
/// This method evaluates all <see cref="ValidationAttribute" />s attached to the object's type.
/// </remarks>
/// <param name="instance">The object instance to test. It cannot be null.</param>
/// <param name="validationContext">
/// Describes the object being validated and provides services and context for the
/// validators. It cannot be <c>null</c>.
/// </param>
/// <exception cref="ArgumentNullException">When <paramref name="instance" /> is null.</exception>
/// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception>
/// <exception cref="ArgumentException">
/// When <paramref name="instance" /> doesn't match the
/// <see cref="ValidationContext.ObjectInstance" /> on <paramref name="validationContext" />.
/// </exception>
/// <exception cref="ValidationException">When <paramref name="instance" /> is found to be invalid.</exception>
public static void ValidateObject(object instance, ValidationContext validationContext)
{
ValidateObject(instance, validationContext, false /*validateAllProperties*/);
}
/// <summary>
/// Throws a <see cref="ValidationException" /> if the given object instance is not valid.
/// </summary>
/// <remarks>
/// This method evaluates all <see cref="ValidationAttribute" />s attached to the object's type.
/// If <paramref name="validateAllProperties" /> is <c>true</c> it also validates all the object's properties.
/// </remarks>
/// <param name="instance">The object instance to test. It cannot be null.</param>
/// <param name="validationContext">
/// Describes the object being validated and provides services and context for the
/// validators. It cannot be <c>null</c>.
/// </param>
/// <param name="validateAllProperties">If <c>true</c>, also validates all the <paramref name="instance" />'s properties.</param>
/// <exception cref="ArgumentNullException">When <paramref name="instance" /> is null.</exception>
/// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception>
/// <exception cref="ArgumentException">
/// When <paramref name="instance" /> doesn't match the
/// <see cref="ValidationContext.ObjectInstance" /> on <paramref name="validationContext" />.
/// </exception>
/// <exception cref="ValidationException">When <paramref name="instance" /> is found to be invalid.</exception>
public static void ValidateObject(object instance, ValidationContext validationContext,
bool validateAllProperties)
{
if (instance == null)
{
throw new ArgumentNullException(nameof(instance));
}
if (validationContext == null)
{
throw new ArgumentNullException(nameof(validationContext));
}
if (instance != validationContext.ObjectInstance)
{
throw new ArgumentException(
SR.Validator_InstanceMustMatchValidationContextInstance, nameof(instance));
}
GetObjectValidationErrors(instance, validationContext, validateAllProperties, false).FirstOrDefault()?.ThrowValidationException();
}
/// <summary>
/// Throw a <see cref="ValidationException" /> if the given value is not valid for the
/// <see cref="ValidationAttribute" />s.
/// </summary>
/// <remarks>
/// This method evaluates the <see cref="ValidationAttribute" />s supplied until a validation error occurs,
/// at which time a <see cref="ValidationException" /> is thrown.
/// <para>
/// A <see cref="RequiredAttribute" /> within the <paramref name="validationAttributes" /> will always be evaluated
/// first.
/// </para>
/// </remarks>
/// <param name="value">The value to test. It cannot be null.</param>
/// <param name="validationContext">Describes the object being tested.</param>
/// <param name="validationAttributes">The list of <see cref="ValidationAttribute" />s to validate against this instance.</param>
/// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception>
/// <exception cref="ValidationException">When <paramref name="value" /> is found to be invalid.</exception>
public static void ValidateValue(object value, ValidationContext validationContext,
IEnumerable<ValidationAttribute> validationAttributes)
{
if (validationContext == null)
{
throw new ArgumentNullException(nameof(validationContext));
}
GetValidationErrors(value, validationContext, validationAttributes, false).FirstOrDefault()?.ThrowValidationException();
}
/// <summary>
/// Creates a new <see cref="ValidationContext" /> to use to validate the type or a member of
/// the given object instance.
/// </summary>
/// <param name="instance">The object instance to use for the context.</param>
/// <param name="validationContext">
/// An parent validation context that supplies an <see cref="IServiceProvider" />
/// and <see cref="ValidationContext.Items" />.
/// </param>
/// <returns>A new <see cref="ValidationContext" /> for the <paramref name="instance" /> provided.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception>
private static ValidationContext CreateValidationContext(object instance, ValidationContext validationContext)
{
Debug.Assert(validationContext != null);
// Create a new context using the existing ValidationContext that acts as an IServiceProvider and contains our existing items.
var context = new ValidationContext(instance, validationContext, validationContext.Items);
return context;
}
/// <summary>
/// Determine whether the given value can legally be assigned into the specified type.
/// </summary>
/// <param name="destinationType">The destination <see cref="Type" /> for the value.</param>
/// <param name="value">
/// The value to test to see if it can be assigned as the Type indicated by
/// <paramref name="destinationType" />.
/// </param>
/// <returns><c>true</c> if the assignment is legal.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="destinationType" /> is null.</exception>
private static bool CanBeAssigned(Type destinationType, object value)
{
if (value == null)
{
// Null can be assigned only to reference types or Nullable or Nullable<>
return !destinationType.IsValueType ||
(destinationType.IsGenericType &&
destinationType.GetGenericTypeDefinition() == typeof(Nullable<>));
}
// Not null -- be sure it can be cast to the right type
return destinationType.IsInstanceOfType(value);
}
/// <summary>
/// Determines whether the given value can legally be assigned to the given property.
/// </summary>
/// <param name="propertyName">The name of the property.</param>
/// <param name="propertyType">The type of the property.</param>
/// <param name="value">The value. Null is permitted only if the property will accept it.</param>
/// <exception cref="ArgumentException"> is thrown if <paramref name="value" /> is the wrong type for this property.</exception>
private static void EnsureValidPropertyType(string propertyName, Type propertyType, object value)
{
if (!CanBeAssigned(propertyType, value))
{
throw new ArgumentException(
string.Format(CultureInfo.CurrentCulture,
SR.Validator_Property_Value_Wrong_Type, propertyName, propertyType),
nameof(value));
}
}
/// <summary>
/// Internal iterator to enumerate all validation errors for the given object instance.
/// </summary>
/// <param name="instance">Object instance to test.</param>
/// <param name="validationContext">Describes the object type.</param>
/// <param name="validateAllProperties">if <c>true</c> also validates all properties.</param>
/// <param name="breakOnFirstError">Whether to break on the first error or validate everything.</param>
/// <returns>
/// A collection of validation errors that result from validating the <paramref name="instance" /> with
/// the given <paramref name="validationContext" />.
/// </returns>
/// <exception cref="ArgumentNullException">When <paramref name="instance" /> is null.</exception>
/// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception>
/// <exception cref="ArgumentException">
/// When <paramref name="instance" /> doesn't match the
/// <see cref="ValidationContext.ObjectInstance" /> on <paramref name="validationContext" />.
/// </exception>
private static IEnumerable<ValidationError> GetObjectValidationErrors(object instance,
ValidationContext validationContext, bool validateAllProperties, bool breakOnFirstError)
{
Debug.Assert(instance != null);
if (validationContext == null)
{
throw new ArgumentNullException(nameof(validationContext));
}
// Step 1: Validate the object properties' validation attributes
var errors = new List<ValidationError>();
errors.AddRange(GetObjectPropertyValidationErrors(instance, validationContext, validateAllProperties,
breakOnFirstError));
// We only proceed to Step 2 if there are no errors
if (errors.Any())
{
return errors;
}
// Step 2: Validate the object's validation attributes
var attributes = _store.GetTypeValidationAttributes(validationContext);
errors.AddRange(GetValidationErrors(instance, validationContext, attributes, breakOnFirstError));
// We only proceed to Step 3 if there are no errors
if (errors.Any())
{
return errors;
}
// Step 3: Test for IValidatableObject implementation
if (instance is IValidatableObject validatable)
{
var results = validatable.Validate(validationContext);
if (results != null)
{
foreach (var result in results.Where(r => r != ValidationResult.Success))
{
errors.Add(new ValidationError(null, instance, result));
}
}
}
return errors;
}
/// <summary>
/// Internal iterator to enumerate all the validation errors for all properties of the given object instance.
/// </summary>
/// <param name="instance">Object instance to test.</param>
/// <param name="validationContext">Describes the object type.</param>
/// <param name="validateAllProperties">
/// If <c>true</c>, evaluates all the properties, otherwise just checks that
/// ones marked with <see cref="RequiredAttribute" /> are not null.
/// </param>
/// <param name="breakOnFirstError">Whether to break on the first error or validate everything.</param>
/// <returns>A list of <see cref="ValidationError" /> instances.</returns>
private static IEnumerable<ValidationError> GetObjectPropertyValidationErrors(object instance,
ValidationContext validationContext, bool validateAllProperties, bool breakOnFirstError)
{
var properties = GetPropertyValues(instance, validationContext);
var errors = new List<ValidationError>();
foreach (var property in properties)
{
// get list of all validation attributes for this property
var attributes = _store.GetPropertyValidationAttributes(property.Key);
if (validateAllProperties)
{
// validate all validation attributes on this property
errors.AddRange(GetValidationErrors(property.Value, property.Key, attributes, breakOnFirstError));
}
else
{
// only validate the Required attributes
var reqAttr = attributes.OfType<RequiredAttribute>().FirstOrDefault();
if (reqAttr != null)
{
// Note: we let the [Required] attribute do its own null testing,
// since the user may have subclassed it and have a deeper meaning to what 'required' means
var validationResult = reqAttr.GetValidationResult(property.Value, property.Key);
if (validationResult != ValidationResult.Success)
{
errors.Add(new ValidationError(reqAttr, property.Value, validationResult));
}
}
}
if (breakOnFirstError && errors.Any())
{
break;
}
}
return errors;
}
/// <summary>
/// Retrieves the property values for the given instance.
/// </summary>
/// <param name="instance">Instance from which to fetch the properties.</param>
/// <param name="validationContext">Describes the entity being validated.</param>
/// <returns>
/// A set of key value pairs, where the key is a validation context for the property and the value is its current
/// value.
/// </returns>
/// <remarks>Ignores indexed properties.</remarks>
private static ICollection<KeyValuePair<ValidationContext, object>> GetPropertyValues(object instance,
ValidationContext validationContext)
{
var properties = instance.GetType().GetRuntimeProperties()
.Where(p => ValidationAttributeStore.IsPublic(p) && !p.GetIndexParameters().Any());
var items = new List<KeyValuePair<ValidationContext, object>>(properties.Count());
foreach (var property in properties)
{
var context = CreateValidationContext(instance, validationContext);
context.MemberName = property.Name;
if (_store.GetPropertyValidationAttributes(context).Any())
{
items.Add(new KeyValuePair<ValidationContext, object>(context, property.GetValue(instance, null)));
}
}
return items;
}
/// <summary>
/// Internal iterator to enumerate all validation errors for an value.
/// </summary>
/// <remarks>
/// If a <see cref="RequiredAttribute" /> is found, it will be evaluated first, and if that fails,
/// validation will abort, regardless of the <paramref name="breakOnFirstError" /> parameter value.
/// </remarks>
/// <param name="value">The value to pass to the validation attributes.</param>
/// <param name="validationContext">Describes the type/member being evaluated.</param>
/// <param name="attributes">The validation attributes to evaluate.</param>
/// <param name="breakOnFirstError">
/// Whether or not to break on the first validation failure. A
/// <see cref="RequiredAttribute" /> failure will always abort with that sole failure.
/// </param>
/// <returns>The collection of validation errors.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception>
private static IEnumerable<ValidationError> GetValidationErrors(object value,
ValidationContext validationContext, IEnumerable<ValidationAttribute> attributes, bool breakOnFirstError)
{
if (validationContext == null)
{
throw new ArgumentNullException(nameof(validationContext));
}
var errors = new List<ValidationError>();
ValidationError validationError;
// Get the required validator if there is one and test it first, aborting on failure
var required = attributes.OfType<RequiredAttribute>().FirstOrDefault();
if (required != null)
{
if (!TryValidate(value, validationContext, required, out validationError))
{
errors.Add(validationError);
return errors;
}
}
// Iterate through the rest of the validators, skipping the required validator
foreach (var attr in attributes)
{
if (attr != required)
{
if (!TryValidate(value, validationContext, attr, out validationError))
{
errors.Add(validationError);
if (breakOnFirstError)
{
break;
}
}
}
}
return errors;
}
/// <summary>
/// Tests whether a value is valid against a single <see cref="ValidationAttribute" /> using the
/// <see cref="ValidationContext" />.
/// </summary>
/// <param name="value">The value to be tested for validity.</param>
/// <param name="validationContext">Describes the property member to validate.</param>
/// <param name="attribute">The validation attribute to test.</param>
/// <param name="validationError">
/// The validation error that occurs during validation. Will be <c>null</c> when the return
/// value is <c>true</c>.
/// </param>
/// <returns><c>true</c> if the value is valid.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception>
private static bool TryValidate(object value, ValidationContext validationContext, ValidationAttribute attribute,
out ValidationError validationError)
{
Debug.Assert(validationContext != null);
var validationResult = attribute.GetValidationResult(value, validationContext);
if (validationResult != ValidationResult.Success)
{
validationError = new ValidationError(attribute, value, validationResult);
return false;
}
validationError = null;
return true;
}
/// <summary>
/// Private helper class to encapsulate a ValidationAttribute with the failed value and the user-visible
/// target name against which it was validated.
/// </summary>
private class ValidationError
{
private readonly object _value;
private readonly ValidationAttribute _validationAttribute;
internal ValidationError(ValidationAttribute validationAttribute, object value,
ValidationResult validationResult)
{
_validationAttribute = validationAttribute;
ValidationResult = validationResult;
_value = value;
}
internal ValidationResult ValidationResult { get; }
internal void ThrowValidationException() => throw new ValidationException(ValidationResult, _validationAttribute, _value);
}
}
}
| |
/*
*** do not modify the line below, it is updated by the build scripts ***
goedle.io SDK for Unity version v1.0.0
*/
/*
#if !UNITY_PRO_LICENSE && (UNITY_2_6||UNITY_2_6_1||UNITY_3_0||UNITY_3_0_0||UNITY_3_1||UNITY_3_2||UNITY_3_3||UNITY_3_4||UNITY_3_5||UNITY_4_0||UNITY_4_0_1||UNITY_4_1||UNITY_4_2||UNITY_4_3||UNITY_4_5||UNITY_4_6)
#define DISABLE_GOEDLE
#warning "Your Unity version does not support native plugins - goedle.io disabled"
#endif
*/
using UnityEngine;
using System;
using SimpleJSON;
using UnityEngine.Networking;
namespace goedle_sdk
{
/// <summary>
/// Core class for interacting with %goedle.io .
/// </summary>
/// <description>
/// <p>Create a GameObject and attach this %goedle.io component. Then, set the properties in the unity inspector (app_key, api_key)</p>
/// <p>Use the GoedleAnalytics class to set up your project and track events with %goedle.io . Once you have
/// a component, you can track events in %goedle.io Engagement using <c>GoedleAnalytics.track(string eventName)</c>.
/// </description>
public class GoedleAnalytics : MonoBehaviour
{
public static GoedleAnalytics instance = null;
/*! \cond PRIVATE */
#region settings
[Header("Project")]
[Tooltip("Enable (True) / Disable(False) stageing_enviroment, highly recommeded for testing")]
public bool staging = false;
[Tooltip("The APP Key of the goedle.io project.")]
public string app_key = "";
[Tooltip("The API Key of the goedle.io project.")]
public string api_key = "";
[Tooltip("You can specify an app version here.")]
public string APP_VERSION = "";
[Tooltip("You should specify an app name here.")]
public string APP_NAME = "";
[Tooltip("Google Analytics Tracking Id")]
public string GA_TRACKIND_ID = null;
[Tooltip("Google Analytics Custom Dimension Event Listener. This is for group call support.")]
public string GA_CD_EVENT = null;
[Tooltip("Google Analytics Number of Custom Dimension for Group type. (To set this you need a configured custom dimension in Google Analytics)")]
public int GA_CD_1 = 0;
[Tooltip("Google Analytics Number of Custom Dimension for Group member. (To set this you need a configured custom dimension in Google Analytics)")]
public int GA_CD_2 = 0;
[Tooltip("Enable (True) / Disable(False) only content adaptation")]
public bool adaptation_only = false;
#endregion
/*! \endcond */
/// <summary>
/// Tracks an event.
/// </summary>
/// <param name="event">the name of the event to send</param>
public void track(string eventName)
{
goedle_analytics.track(eventName, new detail.GoedleUploadHandler());
}
/// <summary>
/// Tracks an event.
/// </summary>
/// <param name="event">the name of the event to send</param>
/// <param name="event_id">the name of the event to send</param>
public void track(string eventName, string eventId)
{
goedle_analytics.track(eventName,eventId, new detail.GoedleUploadHandler());
}
/// <summary>
/// Tracks an event.
/// </summary>
/// <param name="event">the name of the event to send</param>
/// <param name="event_id">the id of the event to send</param>
/// <param name="event_value">the value of the event to send</param>
public void track(string eventName, string eventId, string event_value)
{
goedle_analytics.track(eventName,eventId,event_value, new detail.GoedleUploadHandler());
}
/// <summary>
/// Identify function for a user.
/// </summary>
/// <param name="trait_key">for now only last_name and first_name is supported</param>
/// <param name="trait_value">the value of the key</param>
public void trackTraits(string traitKey, string traitValue)
{
goedle_analytics.trackTraits(traitKey, traitValue, new detail.GoedleUploadHandler());
}
/// <summary>
/// Group tracking function for a user.
/// </summary>
/// <param name="group_type">The entity type, like school or company</param>
/// <param name="group_member">The name or identifier for the entity, like department number, class number</param>
public void trackGroup(string group_type, string group_member)
{
goedle_analytics.trackGroup(group_type, group_member, new detail.GoedleUploadHandler());
}
/// <summary>
/// set user id function for a user.
/// </summary>
/// <param name="user_id">a custom user id</param>
public void setUserId(string user_id)
{
goedle_analytics.set_user_id(user_id, new detail.GoedleUploadHandler());
}
/// <summary>
/// request strategy from GIO API
/// </summary>s
public void requestStrategy()
{
if (!staging)
{
detail.IGoedleDownloadBuffer goedleDownloadBuffer = new detail.GoedleDownloadBuffer();
goedle_analytics.requestStrategy(goedleDownloadBuffer);
}
}
/// <summary>
/// Reset user id
/// </summary>
public void resetUserId()
{
Guid new_user_id = Guid.NewGuid();
goedle_analytics.reset_user_id(new_user_id.ToString("D"));
}
#region internal
public detail.GoedleAnalytics gio_interface;
public detail.GoedleAnalytics goedle_analytics
{
get
{
return gio_interface;
}
}
void Awake()
{
//Check if instance already exists
if (instance == null)
{
//if not, set instance to this
instance = this;
InitGoedle();
}
//If instance already exists and it's not this:
else if (instance != this)
{
//Then destroy this. This enforces our singleton pattern, meaning there can only ever be one instance of a GameManager.
Destroy(gameObject);
}
//Sets this to not be destroyed when reloading scene
DontDestroyOnLoad(gameObject);
}
private void InitGoedle()
{
Guid user_id = Guid.NewGuid();
string app_version = APP_VERSION;
string app_name = APP_NAME;
if (String.IsNullOrEmpty(app_version))
app_version = Application.version;
if (String.IsNullOrEmpty(app_name))
if (String.IsNullOrEmpty(app_name))
app_name = Application.productName;
else
app_name = app_version;
// string locale = Application.systemLanguage.ToString();
// Build HTTP CLient
detail.IGoedleWebRequest goedleWebRequest = new detail.GoedleWebRequest();
detail.IGoedleUploadHandler goedleUploadHandler = new detail.GoedleUploadHandler();
if (gio_interface == null && (!string.IsNullOrEmpty(instance.api_key) || !string.IsNullOrEmpty(instance.app_key)))
{
gio_interface = new detail.GoedleAnalytics(api_key, app_key, user_id.ToString("D"), app_version, GA_TRACKIND_ID, app_name, GA_CD_1, GA_CD_2, GA_CD_EVENT, detail.GoedleHttpClient.instance, goedleWebRequest, goedleUploadHandler, staging, adaptation_only);
Debug.Log("goedle.io SDK is initialzied");
}
}
void OnDestroy()
{
// Future Usage
}
#endregion
}
}
| |
#if TEST
using System;
using NUnit.Framework;
using SharpVectors.Dom.Css;
using System.Diagnostics;
using System.Drawing;
namespace SharpVectors.Dom.Css
{
[TestFixture]
public class CssTests
{
private CssXmlDocument doc;
private CssStyleSheet cssStyleSheet;
private CssStyleRule rule;
private CssStyleDeclaration colorRules;
private bool initDone = false;
#region Setup
[SetUp]
public void Init()
{
if(!initDone)
{
doc = new CssXmlDocument();
doc.AddStyleElement("http://www.w3.org/2000/svg", "style");
doc.Load("http://www.sharpvectors.org/tests/css_unittest_01.svg");
cssStyleSheet = (CssStyleSheet)doc.StyleSheets[0];
colorRules = (CssStyleDeclaration)((CssStyleRule)cssStyleSheet.CssRules[4]).Style;
initDone = true;
}
}
#endregion
#region Basic structure tests
[Test]
public void TestStylesheets()
{
Assert.AreEqual(2, doc.StyleSheets.Length, "Number of stylesheets");
}
[Test]
public void TestCssStyleSheet()
{
Assert.IsTrue(doc.StyleSheets[0] is CssStyleSheet);
cssStyleSheet = (CssStyleSheet)doc.StyleSheets[0];
Assert.IsTrue(cssStyleSheet.AbsoluteHref.AbsolutePath.EndsWith("css_unittest_01.css"), "AbsoluteHref");
Assert.AreEqual(cssStyleSheet.Title, "Test title", "Title");
Assert.AreEqual("text/css", cssStyleSheet.Type);
Assert.AreEqual(false, cssStyleSheet.Disabled);
}
[Test]
public void TestCssRules()
{
Assert.AreEqual(16, cssStyleSheet.CssRules.Length, "CssRules.Length");
Assert.IsTrue(cssStyleSheet.CssRules[0] is CssStyleRule);
}
[Test]
public void TestCssStyleRule()
{
rule = (CssStyleRule)cssStyleSheet.CssRules[0];
Assert.IsNull(rule.ParentRule);
Assert.AreEqual("g", rule.SelectorText);
Assert.AreEqual("g{fill:#123456 !important;opacity:0.5;}", rule.CssText);
Assert.AreEqual(CssRuleType.StyleRule, rule.Type);
Assert.AreSame(cssStyleSheet, rule.ParentStyleSheet);
Assert.IsTrue(rule.Style is CssStyleDeclaration);
}
[Test]
public void TestCssStyleDeclaration()
{
rule = (CssStyleRule)cssStyleSheet.CssRules[0];
CssStyleDeclaration csd = (CssStyleDeclaration)rule.Style;
Assert.AreEqual("fill:#123456 !important;opacity:0.5;", csd.CssText);
Assert.AreEqual(2, csd.Length);
Assert.AreSame(rule, csd.ParentRule);
Assert.AreEqual("important", csd.GetPropertyPriority("fill"));
Assert.AreEqual("0.5", csd.GetPropertyValue("opacity"));
Assert.AreEqual("", csd.GetPropertyPriority("opacity"));
Assert.AreEqual("#123456", csd.GetPropertyValue("fill"));
csd.SetProperty("opacity", "0.8", "");
Assert.AreEqual("0.8", csd.GetPropertyValue("opacity"));
Assert.AreEqual("", csd.GetPropertyPriority("opacity"));
csd.SetProperty("opacity", "0.2", "important");
Assert.AreEqual("0.2", csd.GetPropertyValue("opacity"));
Assert.AreEqual("important", csd.GetPropertyPriority("opacity"));
Assert.AreEqual("0.2", csd.RemoveProperty("opacity"));
Assert.AreEqual(1, csd.Length);
csd.SetProperty("foo", "bar", "");
Assert.AreEqual("bar", csd.GetPropertyValue("foo"));
Assert.AreEqual(2, csd.Length);
// reset values
csd.RemoveProperty("foo");
csd.SetProperty("opacity", "0.5", "");
}
#endregion
#region Color tests
[Test]
public void TestColorLongHexValue()
{
CssValue val = (CssValue)colorRules.GetPropertyCssValue("longhex");
Assert.IsTrue(val is CssPrimitiveValue, "1");
CssPrimitiveValue primValue = (CssPrimitiveValue)colorRules.GetPropertyCssValue("longhex");
Assert.AreEqual("rgb(101,67,33)", primValue.CssText, "2");
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType, "3");
Assert.AreEqual(CssPrimitiveType.RgbColor, primValue.PrimitiveType, "4");
RgbColor color = (RgbColor)primValue.GetRgbColorValue();
Assert.AreEqual(101, color.Red.GetFloatValue(CssPrimitiveType.Number), "5");
Assert.AreEqual(67, color.Green.GetFloatValue(CssPrimitiveType.Number), "6");
Assert.AreEqual(33, color.Blue.GetFloatValue(CssPrimitiveType.Number), "7");
Assert.AreEqual(ColorTranslator.FromHtml("#654321"), color.GdiColor, "8");
}
[Test]
public void TestColorShortHexValue()
{
CssPrimitiveValue primValue = (CssPrimitiveValue)colorRules.GetPropertyCssValue("shorthex");
Assert.AreEqual("rgb(17,34,51)", primValue.CssText);
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType);
Assert.AreEqual(CssPrimitiveType.RgbColor, primValue.PrimitiveType);
RgbColor color = (RgbColor)primValue.GetRgbColorValue();
Assert.AreEqual(17, color.Red.GetFloatValue(CssPrimitiveType.Number));
Assert.AreEqual(34, color.Green.GetFloatValue(CssPrimitiveType.Number));
Assert.AreEqual(51, color.Blue.GetFloatValue(CssPrimitiveType.Number));
}
[Test]
public void TestColorNameValue()
{
CssPrimitiveValue primValue = (CssPrimitiveValue)colorRules.GetPropertyCssValue("name");
Assert.AreEqual("rgb(60,179,113)", primValue.CssText);
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType);
Assert.AreEqual(CssPrimitiveType.RgbColor, primValue.PrimitiveType);
RgbColor color = (RgbColor)primValue.GetRgbColorValue();
Assert.AreEqual(60, color.Red.GetFloatValue(CssPrimitiveType.Number));
Assert.AreEqual(179, color.Green.GetFloatValue(CssPrimitiveType.Number));
Assert.AreEqual(113, color.Blue.GetFloatValue(CssPrimitiveType.Number));
primValue = (CssPrimitiveValue)colorRules.GetPropertyCssValue("grey-name");
color = (RgbColor)primValue.GetRgbColorValue();
Assert.AreEqual(119, color.Red.GetFloatValue(CssPrimitiveType.Number));
Assert.AreEqual(136, color.Green.GetFloatValue(CssPrimitiveType.Number));
Assert.AreEqual(153, color.Blue.GetFloatValue(CssPrimitiveType.Number));
}
[Test]
public void TestColorRgbAbsValue()
{
CssPrimitiveValue primValue = (CssPrimitiveValue)colorRules.GetPropertyCssValue("rgbabs");
Assert.AreEqual("rgb(45,78,98)", primValue.CssText);
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType);
Assert.AreEqual(CssPrimitiveType.RgbColor, primValue.PrimitiveType);
RgbColor color = (RgbColor)primValue.GetRgbColorValue();
Assert.AreEqual(45, color.Red.GetFloatValue(CssPrimitiveType.Number));
Assert.AreEqual(78, color.Green.GetFloatValue(CssPrimitiveType.Number));
Assert.AreEqual(98, color.Blue.GetFloatValue(CssPrimitiveType.Number));
}
[Test]
public void TestColorRgbPercValue()
{
CssPrimitiveValue primValue = (CssPrimitiveValue)colorRules.GetPropertyCssValue("rgbperc");
Assert.AreEqual("rgb(59,115,171)", primValue.CssText);
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType);
Assert.AreEqual(CssPrimitiveType.RgbColor, primValue.PrimitiveType);
RgbColor color = (RgbColor)primValue.GetRgbColorValue();
Assert.AreEqual(0.23*255, color.Red.GetFloatValue(CssPrimitiveType.Number));
Assert.AreEqual(0.45*255, color.Green.GetFloatValue(CssPrimitiveType.Number));
Assert.AreEqual(0.67*255, color.Blue.GetFloatValue(CssPrimitiveType.Number));
}
#endregion
#region String tests
[Test]
public void TestStringValue()
{
CssStyleDeclaration csd = (CssStyleDeclaration)((CssStyleRule)cssStyleSheet.CssRules[1]).Style;
CssValue val = (CssValue)csd.GetPropertyCssValue("string");
Assert.IsTrue(val is CssPrimitiveValue);
CssPrimitiveValue primValue = (CssPrimitiveValue)csd.GetPropertyCssValue("string");
Assert.AreEqual("\"a string\"", primValue.CssText);
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType);
Assert.AreEqual(CssPrimitiveType.String, primValue.PrimitiveType);
string str = primValue.GetStringValue();
Assert.AreEqual("a string", str);
}
#endregion
#region rect tests
[Test]
public void TestRectValue()
{
CssStyleDeclaration csd = (CssStyleDeclaration)((CssStyleRule)cssStyleSheet.CssRules[1]).Style;
CssValue val = (CssValue)csd.GetPropertyCssValue("rect");
Assert.IsTrue(val is CssPrimitiveValue);
CssPrimitiveValue primValue = (CssPrimitiveValue)csd.GetPropertyCssValue("rect");
Assert.AreEqual("rect(10cm 23px 45px 89px)", primValue.CssText);
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType);
Assert.AreEqual(CssPrimitiveType.Rect, primValue.PrimitiveType);
IRect rect = primValue.GetRectValue();
ICssPrimitiveValue rectValue = rect.Top;
Assert.AreEqual(100, rectValue.GetFloatValue(CssPrimitiveType.Mm));
Assert.AreEqual(CssPrimitiveType.Cm, rectValue.PrimitiveType);
rectValue = rect.Right;
Assert.AreEqual(23, rectValue.GetFloatValue(CssPrimitiveType.Px));
Assert.AreEqual(CssPrimitiveType.Px, rectValue.PrimitiveType);
rectValue = rect.Bottom;
Assert.AreEqual(45, rectValue.GetFloatValue(CssPrimitiveType.Px));
Assert.AreEqual(CssPrimitiveType.Px, rectValue.PrimitiveType);
rectValue = rect.Left;
Assert.AreEqual(89, rectValue.GetFloatValue(CssPrimitiveType.Px));
Assert.AreEqual(CssPrimitiveType.Px, rectValue.PrimitiveType);
}
#endregion
#region Float tests
[Test]
public void TestFloatPxValue()
{
CssStyleDeclaration csd = (CssStyleDeclaration)((CssStyleRule)cssStyleSheet.CssRules[5]).Style;
CssValue val = (CssValue)csd.GetPropertyCssValue("float-px");
Assert.IsTrue(val is CssPrimitiveValue);
CssPrimitiveValue primValue = (CssPrimitiveValue)csd.GetPropertyCssValue("float-px");
Assert.AreEqual("12px", primValue.CssText);
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType);
Assert.AreEqual(CssPrimitiveType.Px, primValue.PrimitiveType);
double res = primValue.GetFloatValue(CssPrimitiveType.Px);
Assert.AreEqual(12, res);
}
[Test]
public void TestFloatUnitlessValue()
{
CssStyleDeclaration csd = (CssStyleDeclaration)((CssStyleRule)cssStyleSheet.CssRules[5]).Style;
CssValue val = (CssValue)csd.GetPropertyCssValue("float-unitless");
Assert.IsTrue(val is CssPrimitiveValue);
CssPrimitiveValue primValue = (CssPrimitiveValue)csd.GetPropertyCssValue("float-unitless");
Assert.AreEqual("67", primValue.CssText);
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType);
Assert.AreEqual(CssPrimitiveType.Number, primValue.PrimitiveType);
double res = primValue.GetFloatValue(CssPrimitiveType.Number);
Assert.AreEqual(67, res);
}
[Test]
public void TestFloatCmValue()
{
CssStyleDeclaration csd = (CssStyleDeclaration)((CssStyleRule)cssStyleSheet.CssRules[5]).Style;
CssValue val = (CssValue)csd.GetPropertyCssValue("float-cm");
Assert.IsTrue(val is CssPrimitiveValue);
CssPrimitiveValue primValue = (CssPrimitiveValue)csd.GetPropertyCssValue("float-cm");
Assert.AreEqual("10cm", primValue.CssText);
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType);
Assert.AreEqual(CssPrimitiveType.Cm, primValue.PrimitiveType);
Assert.AreEqual(10, primValue.GetFloatValue(CssPrimitiveType.Cm));
}
[Test]
public void TestFloatMmValue()
{
CssStyleDeclaration csd = (CssStyleDeclaration)((CssStyleRule)cssStyleSheet.CssRules[5]).Style;
CssValue val = (CssValue)csd.GetPropertyCssValue("float-mm");
Assert.IsTrue(val is CssPrimitiveValue);
CssPrimitiveValue primValue = (CssPrimitiveValue)csd.GetPropertyCssValue("float-mm");
Assert.AreEqual("10mm", primValue.CssText);
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType);
Assert.AreEqual(CssPrimitiveType.Mm, primValue.PrimitiveType);
Assert.AreEqual(10, primValue.GetFloatValue(CssPrimitiveType.Mm));
}
[Test]
public void TestFloatInValue()
{
CssStyleDeclaration csd = (CssStyleDeclaration)((CssStyleRule)cssStyleSheet.CssRules[5]).Style;
CssValue val = (CssValue)csd.GetPropertyCssValue("float-in");
Assert.IsTrue(val is CssPrimitiveValue);
CssPrimitiveValue primValue = (CssPrimitiveValue)csd.GetPropertyCssValue("float-in");
Assert.AreEqual("10in", primValue.CssText);
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType);
Assert.AreEqual(CssPrimitiveType.In, primValue.PrimitiveType);
Assert.AreEqual(10, primValue.GetFloatValue(CssPrimitiveType.In));
}
[Test]
public void TestFloatPcValue()
{
CssStyleDeclaration csd = (CssStyleDeclaration)((CssStyleRule)cssStyleSheet.CssRules[5]).Style;
CssValue val = (CssValue)csd.GetPropertyCssValue("float-pc");
Assert.IsTrue(val is CssPrimitiveValue);
CssPrimitiveValue primValue = (CssPrimitiveValue)csd.GetPropertyCssValue("float-pc");
Assert.AreEqual("10pc", primValue.CssText, "CssText");
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType, "CssValueType");
Assert.AreEqual(CssPrimitiveType.Pc, primValue.PrimitiveType, "PrimitiveType");
Assert.AreEqual(10, primValue.GetFloatValue(CssPrimitiveType.Pc), "To PC");
}
[Test]
public void TestFloatPtValue()
{
CssStyleDeclaration csd = (CssStyleDeclaration)((CssStyleRule)cssStyleSheet.CssRules[5]).Style;
CssValue val = (CssValue)csd.GetPropertyCssValue("float-pt");
Assert.IsTrue(val is CssPrimitiveValue);
CssPrimitiveValue primValue = (CssPrimitiveValue)csd.GetPropertyCssValue("float-pt");
Assert.AreEqual("10pt", primValue.CssText, "CssText");
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType, "CssValueType");
Assert.AreEqual(CssPrimitiveType.Pt, primValue.PrimitiveType, "PrimitiveType");
Assert.AreEqual(10, primValue.GetFloatValue(CssPrimitiveType.Pt), "To PC");
Assert.AreEqual(10/72D*2.54D, primValue.GetFloatValue(CssPrimitiveType.Cm), "To CM");
Assert.AreEqual(100/72D*2.54D, primValue.GetFloatValue(CssPrimitiveType.Mm), "To MM");
Assert.AreEqual(10/72D, primValue.GetFloatValue(CssPrimitiveType.In), "To IN");
Assert.AreEqual(10/12D, primValue.GetFloatValue(CssPrimitiveType.Pc), "To PT");
}
#endregion
}
}
#endif
| |
using System;
using System.IO;
using Platform.IO;
using Platform.Text;
using Platform.Utilities;
using Platform.VirtualFileSystem.Network.Text.Protocol;
namespace Platform.VirtualFileSystem.Network.Text
{
public partial class TextNetworkFileSystemClient
{
internal class TextRandomAccessNetworkFileSystemStream
: Stream, IStreamWithEvents
{
private readonly bool canSeek;
private readonly FileShare fileShare;
private readonly FileAccess fileAccess;
private readonly TextNetworkFileSystemClient client;
public TextRandomAccessNetworkFileSystemStream(TextNetworkFileSystemClient client, FileAccess fileAccess, FileShare fileShare, bool canSeek, long length)
{
this.client = client;
this.canSeek = canSeek;
this.fileShare = fileShare;
this.fileAccess = fileAccess;
this.length = length;
this.writeResponsesQueue = new InvocationQueue();
}
public override bool CanRead
{
get
{
return (this.fileAccess & FileAccess.Read) == FileAccess.Read;
}
}
public override bool CanSeek
{
get
{
return this.canSeek;
}
}
public override bool CanWrite
{
get
{
return (this.fileAccess & FileAccess.Write) == FileAccess.Write;
}
}
public override long Length
{
get
{
if (!CanSeek)
{
throw new NotSupportedException();
}
if (((this.fileShare & FileShare.Write) == FileShare.Write && (this.readBytesLeft == 0) && (this.writeResponsesQueue.TaskState != TaskState.Running))
|| this.length == -1)
{
this.length = LoadLength();
}
return this.length;
}
}
private long length = -1;
protected virtual long LoadLength()
{
StabilizeClientState();
var response = this.client.SendCommand(1, "getlength").ProcessError();
var localLength = Int64.Parse(response.ResponseTuples["length"]);
this.client.ReadReady();
return localLength;
}
private bool closed = false;
public override void Close()
{
lock (this)
{
if (!this.closed)
{
StabilizeClientState();
Flush();
OnBeforeClose(EventArgs.Empty);
if (ActionUtils.IgnoreExceptions(delegate
{
this.client.SendCommand(1, "exit");
this.client.ReadReady();
this.closed = true;
}) != null)
{
ActionUtils.IgnoreExceptions(() => this.client.Disconnect());
}
OnAfterClose(EventArgs.Empty);
}
}
}
public override long Position
{
get
{
if (!CanSeek)
{
throw new NotSupportedException();
}
return this.position;
}
set
{
if (!CanSeek)
{
throw new NotSupportedException();
}
Seek(value, SeekOrigin.Begin);
}
}
private long position = 0;
private int readBytesLeft = 0;
[ThreadStatic]
private byte[] tempBuffer;
private void StabilizeClientState(bool forWrite = false)
{
lock (this.client.SyncLock)
{
if (this.readBytesLeft > 0)
{
this.client.WriteStream.Flush();
if (this.tempBuffer == null)
{
this.tempBuffer = new byte[64 * 1024];
}
while (this.readBytesLeft > 0)
{
this.readBytesLeft -= this.client.ReadStream.Read(this.tempBuffer, 0, Math.Min(this.readBytesLeft, this.tempBuffer.Length));
}
this.client.ReadReady();
}
}
if (!forWrite)
{
bool wait = false;
if (this.writeResponsesQueue.TaskState == TaskState.Running)
{
this.writeResponsesQueue.Enqueue(delegate
{
this.writeResponsesQueue.Stop();
});
this.client.WriteStream.Flush();
wait = true;
}
if (wait)
{
this.writeResponsesQueue.WaitForAnyTaskState(PredicateUtils.ObjectNotEquals(TaskState.Running));
this.writeResponsesQueue.Reset();
}
}
if (this.errorResponse != null)
{
var localErrorResponse = this.errorResponse;
this.errorResponse = null;
localErrorResponse.ProcessError();
}
}
private CommandResponse errorResponse;
private readonly InvocationQueue writeResponsesQueue;
public override void Write(byte[] buffer, int offset, int count)
{
StabilizeClientState(true);
lock (this.client.SyncLock)
{
this.client.SendCommandWithoutResponse("write {0}", count);
this.client.WriteStream.Write(buffer, offset, count);
//client.WriteStream.Flush();
}
var dateTime = DateTime.Now;
this.writeResponsesQueue.Enqueue(delegate
{
//lock (writeResponsesQueue.SyncLock)
{
var response = this.client.ReadResponse();
this.client.ReadReady();
if (response.ResponseType != ResponseCodes.OK)
{
if (this.errorResponse != null)
{
this.errorResponse = response;
}
}
else if (this.writeResponsesQueue.Count == 0)
{
var now = DateTime.Now;
if (now < dateTime || (now - dateTime > TimeSpan.FromSeconds(60)))
{
this.writeResponsesQueue.Stop();
}
}
}
});
if (this.writeResponsesQueue.TaskState != TaskState.Running
&& this.writeResponsesQueue.Count > 0)
{
this.writeResponsesQueue.TaskAsynchronisity = TaskAsynchronisity.AsyncWithSystemPoolThread;
this.writeResponsesQueue.Start();
}
this.position += count;
if (this.position > this.length)
{
this.length = this.position;
}
}
public override void Flush()
{
this.client.writeStream.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
int localLength;
int readLength;
if (this.readBytesLeft == 0)
{
StabilizeClientState();
var response = this.client.SendCommand(1, "read {0}", count).ProcessError();
localLength = Convert.ToInt32(response.ResponseTuples["length"]);
this.readBytesLeft = localLength;
}
else
{
localLength = this.readBytesLeft;
}
using (this.client.AquireBinaryReadContext())
{
readLength = this.client.ReadStream.Read(buffer, offset, Math.Min(localLength, count));
}
this.readBytesLeft -= readLength;
if (this.readBytesLeft == 0)
{
this.client.ReadReady();
}
this.position += readLength;
if (this.position > this.length)
{
this.length = this.position;
}
return readLength;
}
public override long Seek(long offset, SeekOrigin origin)
{
if ((this.fileShare & FileShare.Write) != FileShare.Write)
{
switch (origin)
{
case SeekOrigin.Begin:
if (this.position == offset)
{
return this.position;
}
break;
case SeekOrigin.Current:
if (offset == 0)
{
return this.position;
}
break;
}
}
StabilizeClientState();
var response = this.client.SendCommand(1, "seek -o={0} \"{1}\"", origin.ToString().ToLower(), offset).ProcessError();
this.position = Convert.ToInt64(response.ResponseTuples["position"]);
this.length = Convert.ToInt64(response.ResponseTuples["length"]);
this.client.ReadReady();
return this.position;
}
public virtual HashValue ComputeHash(string algorithm, long offset, long length)
{
StabilizeClientState();
var response = this.client.SendCommand(DefaultTryCount, @"computehash -o=""{0}"" -l=""{1}"" -a=""{2}""", offset, length, algorithm).ProcessError();
length = Convert.ToInt64(response.ResponseTuples["length"]);
var hash = TextConversion.FromBase64String(response.ResponseTuples["hash"]);
this.position = Convert.ToInt64(response.ResponseTuples["stream-position"]);
this.client.ReadReady();
return new HashValue(hash, algorithm, offset, length);
}
public override void SetLength(long value)
{
if (!CanSeek)
{
throw new NotSupportedException();
}
StabilizeClientState();
var response = this.client.SendCommand(1, "setlength {0}", value).ProcessError();
this.position = Convert.ToInt64(response.ResponseTuples["position"]);
this.length = Convert.ToInt64(response.ResponseTuples["length"]);
this.client.ReadReady();
}
public virtual event EventHandler BeforeClose;
public virtual void OnBeforeClose(EventArgs eventArgs)
{
if (BeforeClose != null)
{
BeforeClose(this, eventArgs);
}
}
public virtual event EventHandler AfterClose;
public virtual void OnAfterClose(EventArgs eventArgs)
{
if (AfterClose != null)
{
AfterClose(this, eventArgs);
}
}
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
// ERROR: Not supported in C#: OptionDeclaration
using Microsoft.VisualBasic.PowerPacks;
namespace _4PosBackOffice.NET
{
internal partial class frmPricingGroup : System.Windows.Forms.Form
{
private ADODB.Recordset withEventsField_adoPrimaryRS;
public ADODB.Recordset adoPrimaryRS {
get { return withEventsField_adoPrimaryRS; }
set {
if (withEventsField_adoPrimaryRS != null) {
withEventsField_adoPrimaryRS.MoveComplete -= adoPrimaryRS_MoveComplete;
withEventsField_adoPrimaryRS.WillChangeRecord -= adoPrimaryRS_WillChangeRecord;
}
withEventsField_adoPrimaryRS = value;
if (withEventsField_adoPrimaryRS != null) {
withEventsField_adoPrimaryRS.MoveComplete += adoPrimaryRS_MoveComplete;
withEventsField_adoPrimaryRS.WillChangeRecord += adoPrimaryRS_WillChangeRecord;
}
}
}
bool mbChangedByCode;
int mvBookMark;
bool mbEditFlag;
bool mbAddNewFlag;
bool mbDataChanged;
short pRid;
int gID;
//Dim WithEvents lblLabels As New List(Of Label)
List<TextBox> txtFields = new List<TextBox>();
List<TextBox> txtFloat = new List<TextBox>();
List<TextBox> txtInteger = new List<TextBox>();
List<TextBox> txtFloatNegative = new List<TextBox>();
List<Label> lblCG = new List<Label>();
private void loadLanguage()
{
//frmPricingGroup = No Code [Edit Pricing Group Details]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then frmPricingGroup.Caption = rsLang("LanguageLayoutLnk_Description"): frmPricingGroup.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1074;
//Undo|Checked
if (modRecordSet.rsLang.RecordCount){cmdCancel.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdCancel.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//cmdMatrix = No Code [Pricing Matrix]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then cmdMatrix.Caption = rsLang("LanguageLayoutLnk_Description"): cmdMatrix.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//DB Entry needs "&" for accelerator key
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1085;
//Print|Checked
if (modRecordSet.rsLang.RecordCount){cmdPrint.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdPrint.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
//Exit|Checked
if (modRecordSet.rsLang.RecordCount){cmdClose.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdClose.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1010;
//General|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_5.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_5.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1066;
//Pricing Group Name|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_38.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_38.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1067;
//Pricing Rules|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_0.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//lbl(10) = No Code [When a Stock Item value is over]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then lbl(10).Caption = rsLang("LanguageLayoutLnk_Description"): lbl(10).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//lbl(18) = No Code [round all amounts below]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then lbl(18).Caption = rsLang("LanguageLayoutLnk_Description"): lbl(18).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//========================================================================================
//NOTE: For multi-currency support the word "RAND" must be removed from the labels below!!
//Recommend generating the sentence from two DB entries, and use a fixed variable to
//stores the currency of choice inserted in the middle before applying it to the component.
//
// E.g. firstPart = rsLang.filter = & 1234;
// lastPart = rsLang.Filter = & 1235;
// _lbl_3.Caption = firstPart + ' ' + currency + ' ' + lastPart;
//========================================================================================
//_lbl_3 = No Code [cents to the lower <Rand> value]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _lbl_3.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_3.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//_lbl_2 = No Code [value, then remove]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _lbl_2.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_2.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//NOTE: Same problem as _lbl_3 applies here!!!
//_lbl_4 = No Code [cents from the rounded stock item <Rand> value]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _lbl_4.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_4.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1068;
//Default Pricing Markup Percentage|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//lblLabels(34) = No Code (Closest match 2105, but grammar wrong for use)
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then lblLabels(34).Caption = rsLang("LanguageLayoutLnk_Description"): lblLabels(34).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//lblLabels(33) = No Code [Case/Carton]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then lblLabels(33).Caption = rsLang("LanguageLayoutLnk_Description"): lblLabels(33).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//lblCG(0) = Dynamic
//lblCG(1) = Dynamic
//lblCG(2) = Dynamic
//lblCG(3) = Dynamic
//lblCG(4) = Dynamic
//lblCG(5) = Dynamic
//lblCG(6) = Dynamic
//lblCG(7) = Dynamic
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1069;
//Disabled Pricing Group|Checked
if (modRecordSet.rsLang.RecordCount){Label1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Label1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1070;
//Disable this Pricing Group|Checked
if (modRecordSet.rsLang.RecordCount){chkPricing.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;chkPricing.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmPricingGroup.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
private void buildDataControls()
{
// doDataControl Me.cmbChannel, "SELECT ChannelID, Channel_Name FROM Channel ORDER BY ChannelID", "Customer_ChannelID", "ChannelID", "Channel_Name"
}
private void doDataControl(ref myDataGridView dataControl, ref string sql, ref string DataField, ref string boundColumn, ref string listField)
{
//Dim rs As ADODB.Recordset
//rs = getRS(sql)
//UPGRADE_WARNING: Couldn't resolve default property of object dataControl.DataSource. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
//dataControl.DataBindings.Add(rs)
//UPGRADE_ISSUE: Control method dataControl.DataSource was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
//dataControl.DataSource = adoPrimaryRS
//UPGRADE_ISSUE: Control method dataControl.DataField was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
//dataControl.DataField = DataField
//UPGRADE_WARNING: Couldn't resolve default property of object dataControl.boundColumn. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
//dataControl.boundColumn = boundColumn
//UPGRADE_WARNING: Couldn't resolve default property of object dataControl.listField. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
//dataControl.listField = listField
}
public void loadItem(ref int id)
{
System.Windows.Forms.TextBox oText = null;
System.Windows.Forms.CheckBox oCheck = null;
// ERROR: Not supported in C#: OnErrorStatement
if (id) {
pRid = id;
adoPrimaryRS = modRecordSet.getRS(ref "select PricingGroupID,PricingGroup_Name,PricingGroup_RemoveCents,PricingGroup_RoundAfter,PricingGroup_RoundDown,PricingGroup_Unit1,PricingGroup_Case1,PricingGroup_Unit2,PricingGroup_Case2,PricingGroup_Unit3,PricingGroup_Case3,PricingGroup_Unit4,PricingGroup_Case4,PricingGroup_Unit5,PricingGroup_Case5,PricingGroup_Unit6,PricingGroup_Case6,PricingGroup_Unit7,PricingGroup_Case7,PricingGroup_Unit8,PricingGroup_Case8,PricingGroup_Disabled from PricingGroup WHERE PricingGroupID = " + id);
} else {
adoPrimaryRS = modRecordSet.getRS(ref "select * from PricingGroup");
adoPrimaryRS.AddNew();
this.Text = this.Text + " [New record]";
mbAddNewFlag = true;
}
setup();
foreach (TextBox oText_loopVariable in this.txtFields) {
oText = oText_loopVariable;
oText.DataBindings.Add(adoPrimaryRS);
oText.MaxLength = adoPrimaryRS.Fields(oText.DataBindings).DefinedSize;
}
foreach (TextBox oText_loopVariable in this.txtInteger) {
oText = oText_loopVariable;
oText.DataBindings.Add(adoPrimaryRS);
oText.Leave += txtInteger_Leave;
}
foreach (TextBox oText_loopVariable in this.txtFloat) {
oText = oText_loopVariable;
oText.DataBindings.Add(adoPrimaryRS);
if (string.IsNullOrEmpty(oText.Text))
oText.Text = "0";
oText.Text = Convert.ToString(Convert.ToDouble(oText.Text) * 100);
oText.Leave += txtFloat_Leave;
}
foreach (TextBox oText_loopVariable in this.txtFloatNegative) {
oText = oText_loopVariable;
oText.DataBindings.Add(adoPrimaryRS);
if (string.IsNullOrEmpty(oText.Text))
oText.Text = "0";
oText.Text = Convert.ToString(Convert.ToDouble(oText.Text) * 100);
oText.Leave += txtFloatNegative_Leave;
}
if (Convert.ToInt16(adoPrimaryRS.Fields("PricingGroup_Disabled").Value)) {
this.chkPricing.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkPricing.Tag = 1;
} else {
this.chkPricing.Tag = 0;
}
buildDataControls();
mbDataChanged = false;
loadLanguage();
ShowDialog();
}
private void setup()
{
ADODB.Recordset rs = default(ADODB.Recordset);
short x = 0;
rs = modRecordSet.getRS(ref "SELECT Channel_Code FROM Channel ORDER BY ChannelID");
rs.MoveFirst();
for (x = 0; x <= 7; x++) {
this.lblCG[x].Text = rs.Fields("Channel_Code").Value;
rs.moveNext();
}
}
private void Command1_Click()
{
}
private void cmdMatrix_Click(System.Object eventSender, System.EventArgs eventArgs)
{
cmdMatrix.Focus();
System.Windows.Forms.Application.DoEvents();
update_Renamed();
Cursor = System.Windows.Forms.Cursors.WaitCursor;
My.MyProject.Forms.frmPricingMatrix.loadMatrix(ref adoPrimaryRS.Fields("PricingGroupID").Value);
Cursor = System.Windows.Forms.Cursors.Default;
frmPricingMatrix form = null;
form.Show();
}
private void cmdPrint_Click(System.Object eventSender, System.EventArgs eventArgs)
{
modApplication.report_PricingGroup();
}
private void frmPricingGroup_Load(object sender, System.EventArgs e)
{
txtFields.AddRange(new TextBox[] { _txtFields_28 });
txtFloat.AddRange(new TextBox[] { _txtFloat_1 });
txtInteger.AddRange(new TextBox[] {
_txtInteger_0,
_txtInteger_2
});
txtFloatNegative.AddRange(new TextBox[] {
_txtFloatNegative_0,
_txtFloatNegative_1,
_txtFloatNegative_2,
_txtFloatNegative_3,
_txtFloatNegative_4,
_txtFloatNegative_5,
_txtFloatNegative_6,
_txtFloatNegative_7,
_txtFloatNegative_8,
_txtFloatNegative_9,
_txtFloatNegative_10,
_txtFloatNegative_11,
_txtFloatNegative_12,
_txtFloatNegative_13,
_txtFloatNegative_14,
_txtFloatNegative_15
});
lblCG.AddRange(new Label[] {
_lblCG_0,
_lblCG_1,
_lblCG_2,
_lblCG_3,
_lblCG_4,
_lblCG_5,
_lblCG_6,
_lblCG_7
});
_txtFields_28.Enter += txtFields_Enter;
_txtFloat_1.Enter += txtFloat_Enter;
_txtFloat_1.KeyPress += txtFloat_KeyPress;
TextBox tb = new TextBox();
foreach (TextBox tb_loopVariable in txtInteger) {
tb = tb_loopVariable;
tb.Enter += txtInteger_Enter;
tb.KeyPress += txtInteger_KeyPress;
}
foreach (TextBox tb_loopVariable in txtFloatNegative) {
tb = tb_loopVariable;
tb.Enter += txtFloatNegative_Enter;
tb.KeyPress += txtFloatNegative_KeyPress;
}
}
//UPGRADE_WARNING: Event frmPricingGroup.Resize may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"'
private void frmPricingGroup_Resize(System.Object eventSender, System.EventArgs eventArgs)
{
Button cmdLast = null;
Button cmdnext = null;
Label lblStatus = null;
// ERROR: Not supported in C#: OnErrorStatement
//UPGRADE_WARNING: Couldn't resolve default property of object lblStatus.Width. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
lblStatus.Width = sizeConvertors.pixelToTwips(this.Width, true) - 1500;
//UPGRADE_WARNING: Couldn't resolve default property of object cmdnext.Left. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
//UPGRADE_WARNING: Couldn't resolve default property of object lblStatus.Width. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
cmdnext.Left = lblStatus.Width + 700;
//UPGRADE_WARNING: Couldn't resolve default property of object cmdLast.Left. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
//UPGRADE_WARNING: Couldn't resolve default property of object cmdnext.Left. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
cmdLast.Left = cmdnext.Left + 340;
}
private void frmPricingGroup_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
switch (KeyAscii) {
case System.Windows.Forms.Keys.Escape:
KeyAscii = 0;
cmdClose.Focus();
System.Windows.Forms.Application.DoEvents();
adoPrimaryRS.Move(0);
cmdClose_Click(cmdClose, new System.EventArgs());
break;
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void frmPricingGroup_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs)
{
//UPGRADE_WARNING: Screen property Screen.MousePointer has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6BA9B8D2-2A32-4B6E-8D36-44949974A5B4"'
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
}
private void adoPrimaryRS_MoveComplete(ADODB.EventReasonEnum adReason, ADODB.Error pError, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset)
{
//This will display the current record position for this recordset
}
private void adoPrimaryRS_WillChangeRecord(ADODB.EventReasonEnum adReason, int cRecords, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset)
{
//This is where you put validation code
//This event gets called when the following actions occur
bool bCancel = false;
switch (adReason) {
case ADODB.EventReasonEnum.adRsnAddNew:
break;
case ADODB.EventReasonEnum.adRsnClose:
break;
case ADODB.EventReasonEnum.adRsnDelete:
break;
case ADODB.EventReasonEnum.adRsnFirstChange:
break;
case ADODB.EventReasonEnum.adRsnMove:
break;
case ADODB.EventReasonEnum.adRsnRequery:
break;
case ADODB.EventReasonEnum.adRsnResynch:
break;
case ADODB.EventReasonEnum.adRsnUndoAddNew:
break;
case ADODB.EventReasonEnum.adRsnUndoDelete:
break;
case ADODB.EventReasonEnum.adRsnUndoUpdate:
break;
case ADODB.EventReasonEnum.adRsnUpdate:
break;
}
if (bCancel)
adStatus = ADODB.EventStatusEnum.adStatusCancel;
}
private void cmdCancel_Click(System.Object eventSender, System.EventArgs eventArgs)
{
TextBox oText = new TextBox();
// ERROR: Not supported in C#: OnErrorStatement
if (mbAddNewFlag) {
this.Close();
} else {
mbEditFlag = false;
mbAddNewFlag = false;
adoPrimaryRS.CancelUpdate();
//UPGRADE_WARNING: Couldn't resolve default property of object mvBookMark. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
if (mvBookMark > 0) {
//UPGRADE_WARNING: Couldn't resolve default property of object mvBookMark. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
adoPrimaryRS.Bookmark = mvBookMark;
} else {
adoPrimaryRS.MoveFirst();
}
foreach (TextBox oText_loopVariable in this.txtInteger) {
oText = oText_loopVariable;
//UPGRADE_WARNING: Couldn't resolve default property of object oText.Index. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
//txtInteger_Leave(txtInteger.Item(oText.Index), New System.EventArgs())
}
foreach (TextBox oText_loopVariable in this.txtFloat) {
oText = oText_loopVariable;
//UPGRADE_WARNING: Couldn't resolve default property of object oText.Text. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
if (string.IsNullOrEmpty(oText.Text))
oText.Text = "0";
//UPGRADE_WARNING: Couldn't resolve default property of object oText.Text. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
oText.Text = oText.Text * 100;
//UPGRADE_WARNING: Couldn't resolve default property of object oText.Index. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
//txtFloat_Leave(txtFloat.Item(oText.Index), New System.EventArgs())
}
foreach (TextBox oText_loopVariable in this.txtFloatNegative) {
oText = oText_loopVariable;
//UPGRADE_WARNING: Couldn't resolve default property of object oText.Text. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
if (string.IsNullOrEmpty(oText.Text))
oText.Text = "0";
//UPGRADE_WARNING: Couldn't resolve default property of object oText.Text. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
oText.Text = oText.Text * 100;
//UPGRADE_WARNING: Couldn't resolve default property of object oText.Index. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
//txtFloatNegative_Leave(txtFloatNegative.Item(oText.Index), New System.EventArgs())
}
mbDataChanged = false;
}
}
//UPGRADE_NOTE: update was upgraded to update_Renamed. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A9E4979A-37FA-4718-9994-97DD76ED70A7"'
private bool update_Renamed()
{
bool functionReturnValue = false;
// ERROR: Not supported in C#: OnErrorStatement
bool lDirty = false;
short x = 0;
lDirty = false;
functionReturnValue = true;
if (mbAddNewFlag) {
adoPrimaryRS.UpdateBatch(ADODB.AffectEnum.adAffectAll);
adoPrimaryRS.MoveLast();
//move to the new record
} else {
for (x = 1; x <= 8; x++) {
if (adoPrimaryRS.Fields("PricingGroup_Unit" + x).Value != adoPrimaryRS.Fields("PricingGroup_Unit" + x).OriginalValue)
lDirty = true;
if (adoPrimaryRS.Fields("PricingGroup_Case" + x).Value != adoPrimaryRS.Fields("PricingGroup_Case" + x).OriginalValue)
lDirty = true;
}
if (adoPrimaryRS.Fields("PricingGroup_RemoveCents").Value != adoPrimaryRS.Fields("PricingGroup_RemoveCents").OriginalValue)
lDirty = true;
if (adoPrimaryRS.Fields("PricingGroup_RoundAfter").Value != adoPrimaryRS.Fields("PricingGroup_RoundAfter").OriginalValue)
lDirty = true;
if (adoPrimaryRS.Fields("PricingGroup_RoundDown").Value != adoPrimaryRS.Fields("PricingGroup_RoundDown").OriginalValue)
lDirty = true;
if (lDirty) {
modRecordSet.cnnDB.Execute("INSERT INTO tempStockItem ( tempStockItemID ) SELECT StockItem.StockItemID FROM StockItem LEFT JOIN tempStockItem ON StockItem.StockItemID = tempStockItem.tempStockItemID WHERE (((StockItem.StockItem_PricingGroupID)=" + adoPrimaryRS.Fields("PricingGroupID").Value + ") AND ((tempStockItem.tempStockItemID) Is Null));");
}
adoPrimaryRS.UpdateBatch(ADODB.AffectEnum.adAffectAll);
}
mbEditFlag = false;
mbAddNewFlag = false;
mbDataChanged = false;
return functionReturnValue;
UpdateErr:
Interaction.MsgBox(Err().Description);
functionReturnValue = false;
return functionReturnValue;
}
private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs)
{
cmdClose.Focus();
System.Windows.Forms.Application.DoEvents();
if (Convert.ToDouble(this.chkPricing.Tag) != this.chkPricing.CheckState) {
modRecordSet.cnnDB.Execute("UPDATE PricingGroup SET PricingGroup_Disabled = " + Conversion.Val(Convert.ToString(this.chkPricing.CheckState)) + " WHERE PricingGroupID = " + pRid);
}
if (update_Renamed()) {
this.Close();
}
}
private void txtFields_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
int Index = 0;
TextBox txBox = new TextBox();
txBox = (TextBox)eventSender;
Index = GetIndex.GetIndexer(ref txBox, ref txtFields);
modUtilities.MyGotFocus(ref txtFields[Index]);
}
private void txtInteger_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
int Index = 0;
TextBox txtBox = new TextBox();
txtBox = (TextBox)eventSender;
Index = GetIndex.GetIndexer(ref txtBox, ref txtInteger);
modUtilities.MyGotFocusNumeric(ref txtInteger[Index]);
}
private void txtInteger_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
//Dim Index As Short = txtInteger.GetIndex(eventSender)
modUtilities.MyKeyPress(ref KeyAscii);
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void txtInteger_Leave(System.Object eventSender, EventArgs eventArgs)
{
int Index = 0;
TextBox txtBox = new TextBox();
txtBox = (TextBox)eventSender;
Index = GetIndex.GetIndexer(ref txtBox, ref txtInteger);
modUtilities.MyLostFocus(ref txtInteger[Index], ref 0);
}
private void txtFloat_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
int Index = 0;
TextBox textBox = new TextBox();
textBox = (TextBox)eventSender;
Index = GetIndex.GetIndexer(ref textBox, ref txtFloat);
modUtilities.MyGotFocusNumeric(ref txtFloat[Index]);
}
private void txtFloat_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
//Dim Index As Short = txtFloat.GetIndex(eventSender)
modUtilities.MyKeyPress(ref KeyAscii);
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void txtFloat_Leave(System.Object eventSender, System.EventArgs eventArgs)
{
int Index = 0;
TextBox txtBox = new TextBox();
txtBox = (TextBox)eventSender;
Index = GetIndex.GetIndexer(ref txtBox, ref txtFloat);
modUtilities.MyLostFocus(ref txtFloat[Index], ref 2);
}
private void txtFloatNegative_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
int Index = 0;
TextBox txtBox = new TextBox();
txtBox = (TextBox)eventSender;
Index = GetIndex.GetIndexer(ref txtBox, ref txtFloatNegative);
modUtilities.MyGotFocusNumeric(ref txtFloatNegative[Index]);
}
private void txtFloatNegative_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
int Index = 0;
TextBox txtBox = new TextBox();
txtBox = (TextBox)eventSender;
Index = GetIndex.GetIndexer(ref txtBox, ref txtFloatNegative);
modUtilities.MyKeyPressNegative(ref txtFloatNegative[Index], ref KeyAscii);
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void txtFloatNegative_Leave(System.Object eventSender, System.EventArgs eventArgs)
{
int Index = 0;
TextBox txtBox = new TextBox();
txtBox = (TextBox)eventSender;
Index = GetIndex.GetIndexer(ref txtBox, ref txtFloatNegative);
modUtilities.MyLostFocus(ref txtFloatNegative[Index], ref 2);
}
}
}
| |
// 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.Linq;
using Microsoft.Test.ModuleCore;
using Xunit;
namespace System.Xml.Linq.Tests
{
public class Annotations
{
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddStringAnnotation(XObject xo)
{
const string expected = "test string";
xo.AddAnnotation(expected);
ValidateAnnotations(xo, new string[] { expected });
Assert.Equal(expected, xo.Annotation<string>());
Assert.Equal(expected, (string)xo.Annotation(typeof(string)));
Assert.Equal(expected, xo.Annotation(typeof(object)));
Assert.Equal(expected, xo.Annotation<object>());
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddIntAnnotation(XObject xo)
{
const int expected = 123456;
xo.AddAnnotation(expected);
ValidateAnnotations(xo, new object[] { expected });
Assert.Equal(expected, xo.Annotation<object>());
Assert.Equal(expected, (int)xo.Annotation(typeof(int)));
Assert.Equal(expected, xo.Annotation(typeof(object)));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddIntAndStringAnnotation(XObject xo)
{
const string expectedStr = "<!@@63784sgdh111>";
const int expectedNum = 123456;
xo.AddAnnotation(expectedStr);
xo.AddAnnotation(expectedNum);
ValidateAnnotations(xo, new object[] { expectedStr, expectedNum });
ValidateAnnotations(xo, new string[] { expectedStr });
Assert.Equal(expectedNum, (int)xo.Annotation(typeof(int)));
Assert.Equal(expectedStr, xo.Annotation<string>());
Assert.Equal(expectedStr, (string)xo.Annotation(typeof(string)));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddRemoveGetAnnotation(XObject xo)
{
string str1 = "<!@@63784sgdh111>";
string str2 = "<!@@63784sgdh222>";
int num = 123456;
xo.AddAnnotation(str1);
xo.AddAnnotation(str2);
xo.AddAnnotation(num);
ValidateAnnotations(xo, new object[] { str1, str2, num });
ValidateAnnotations(xo, new string[] { str1, str2 });
xo.RemoveAnnotations<string>();
ValidateAnnotations(xo, new object[] { num });
xo.RemoveAnnotations(typeof(int));
Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void RemoveAnnotationWithoutAdding(XObject xo)
{
xo.RemoveAnnotations<string>();
Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo));
xo.RemoveAnnotations(typeof(int));
Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddIntRemoveStringGetIntAnnotation(XObject xo)
{
const int num = 123456;
xo.AddAnnotation(num);
xo.RemoveAnnotations<string>();
ValidateAnnotations(xo, new object[] { num });
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddMultipleStringAnnotations(XObject xo)
{
const string str1 = "<!@@63784sgdh111>";
const string str2 = "sdjverqjbe4 kjvweh342$$% ";
xo.AddAnnotation(str1);
xo.AddAnnotation(str2);
ValidateAnnotations(xo, new string[] { str1, str2 });
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void RemoveAnnotationTwice(XObject xo)
{
xo.RemoveAnnotations<object>();
xo.RemoveAnnotations<object>();
Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddGenericAnnotation(XObject xo)
{
Dictionary<string, string> d = new Dictionary<string, string>();
xo.AddAnnotation(d);
ValidateAnnotations(xo, new Dictionary<string, string>[] { d });
Assert.Equal(d, xo.Annotation<Dictionary<string, string>>());
Assert.Equal(d, (Dictionary<string, string>)xo.Annotation(typeof(Dictionary<string, string>)));
Assert.Equal(d, xo.Annotation<object>());
Assert.Equal(d, xo.Annotation(typeof(object)));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void RemoveGenericAnnotation(XObject xo)
{
Dictionary<string, string> d = new Dictionary<string, string>();
xo.AddAnnotation(d);
xo.RemoveAnnotations<Dictionary<string, string>>();
Assert.Equal(expected: 0, actual: CountAnnotations<Dictionary<string, string>>(xo));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddInheritedAnnotation(XObject xo)
{
A a = new A();
B b = new B();
xo.AddAnnotation(a);
xo.AddAnnotation(b);
ValidateAnnotations(xo, new A[] { a, b });
ValidateAnnotations(xo, new B[] { b });
Assert.Equal(b, xo.Annotation<B>());
Assert.Equal(b, (B)xo.Annotation(typeof(B)));
Assert.Equal(a, xo.Annotation<A>());
Assert.Equal(a, (A)xo.Annotation(typeof(A)));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void RemoveInheritedAnnotation(XObject xo)
{
A a = new A();
B b = new B();
xo.AddAnnotation(a);
xo.AddAnnotation(b);
xo.RemoveAnnotations<B>();
ValidateAnnotations(xo, new A[] { a });
Assert.Equal(a, xo.Annotation<A>());
Assert.Equal(a, (A)xo.Annotation(typeof(A)));
Assert.Equal(a, xo.Annotation<object>());
Assert.Equal(a, xo.Annotation(typeof(object)));
Assert.Equal(0, CountAnnotations<B>(xo));
xo.RemoveAnnotations(typeof(A));
Assert.Equal(0, CountAnnotations<A>(xo));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddNull(XObject xo)
{
Assert.Throws<ArgumentNullException>("annotation", () => xo.AddAnnotation(null));
Assert.Null(xo.Annotation<object>());
Assert.Throws<ArgumentNullException>("annotation", () => xo.AddAnnotation(null));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void RemoveNull(XObject xo)
{
Assert.Throws<ArgumentNullException>("type", () => xo.RemoveAnnotations(null));
Assert.Throws<ArgumentNullException>("type", () => xo.RemoveAnnotations(null));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void GetAllNull(XObject xo)
{
Assert.Throws<ArgumentNullException>("type", () => xo.Annotations(null));
Assert.Throws<ArgumentNullException>("type", () => xo.Annotations(null));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void GetOneNull(XObject xo)
{
Assert.Throws<ArgumentNullException>("type", () => xo.Annotation(null));
Assert.Throws<ArgumentNullException>("type", () => xo.Annotation(null));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddNullString(XObject xo)
{
Assert.Throws<ArgumentNullException>("annotation", () => xo.AddAnnotation((string)null));
Assert.Null(xo.Annotation<object>());
Assert.Throws<ArgumentNullException>("annotation", () => xo.AddAnnotation((string)null));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddAnnotationWithSameClassNameButDifferentNamespace(XObject xo)
{
DifferentNamespace.A a1 = new DifferentNamespace.A();
A a2 = new A();
xo.AddAnnotation(a1);
xo.AddAnnotation(a2);
ValidateAnnotations(xo, new DifferentNamespace.A[] { a1 });
ValidateAnnotations(xo, new A[] { a2 });
Assert.Equal(a1, xo.Annotation<DifferentNamespace.A>());
Assert.Equal(a1, (DifferentNamespace.A)xo.Annotation(typeof(DifferentNamespace.A)));
Assert.Equal(a2, xo.Annotation<A>());
Assert.Equal(a2, (A)xo.Annotation(typeof(A)));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void RemoveAnnotationWithSameClassNameButDifferentNamespace(XObject xo)
{
DifferentNamespace.A a1 = new DifferentNamespace.A();
A a2 = new A();
xo.AddAnnotation(a1);
xo.AddAnnotation(a2);
xo.RemoveAnnotations<DifferentNamespace.A>();
Assert.Equal(expected: 0, actual: CountAnnotations<DifferentNamespace.A>(xo));
ValidateAnnotations<A>(xo, new A[] { a2 });
Assert.Equal(a2, xo.Annotation<A>());
Assert.Equal(a2, (A)xo.Annotation(typeof(A)));
xo.RemoveAnnotations(typeof(A));
Assert.Equal(expected: 0, actual: CountAnnotations<A>(xo));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void RemoveAnnotationsOfDifferentTypesAndDifferentXObjects(XObject xo)
{
AddAnnotation(xo);
foreach (Type type in GetTypes())
{
RemoveAnnotations(xo, type);
}
Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void RemoveTwiceAnnotationsOfDifferentTypesAndDifferentXObjects(XObject xo)
{
foreach (Type type in GetTypes())
{
RemoveAnnotations(xo, type);
}
foreach (Type type in GetTypes())
{
RemoveAnnotations(xo, type);
}
Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddTwiceRemoveOnceAnnotationsOfDifferentTypesAndDifferentXObjects(XObject xo)
{
AddAnnotation(xo);
int count = CountAnnotations<object>(xo) * 2;
AddAnnotation(xo);
Assert.Equal(expected: count, actual: CountAnnotations<object>(xo));
foreach (Type type in GetTypes())
{
RemoveAnnotations(xo, type);
}
Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo));
}
[Fact]
public void AddAnnotationAndClone()
{
// Add annotation to XElement, and clone this element to another subtree, get null annotation
const string expected = "element1111";
XElement element1 = new XElement("e", new XAttribute("a", "value"));
element1.AddAnnotation(expected);
XElement element2 = new XElement(element1);
ValidateAnnotations(element1, new string[] { expected });
Assert.Equal(expected, element1.Annotation<string>());
Assert.Equal(expected, element1.Annotation(typeof(string)));
Assert.Equal(0, CountAnnotations<string>(element2));
}
[Fact]
public void AddAnnotationXElementRemoveAndGet()
{
// Add annotation to XElement, and remove this element, get annotation
const string expected = "element1111";
XElement root = new XElement("root");
XElement element = new XElement("elem1");
root.Add(element);
element.AddAnnotation(expected);
element.Remove();
ValidateAnnotations(element, new string[] { expected });
Assert.Equal(expected, element.Annotation<string>());
Assert.Equal(expected, element.Annotation(typeof(string)));
}
[Fact]
public void AddAnnotationToParentAndChildAndValIdate()
{
// Add annotation to parent and child, valIdate annotations for each XObjects
string str1 = "root 1111";
string str2 = "element 1111";
XElement root = new XElement("root");
XElement element = new XElement("elem1");
root.Add(element);
root.AddAnnotation(str1);
element.AddAnnotation(str2);
ValidateAnnotations(root, new string[] { str1 });
Assert.Equal(str1, root.Annotation<string>());
Assert.Equal(str1, root.Annotation(typeof(string)));
ValidateAnnotations(element, new string[] { str2 });
Assert.Equal(str2, element.Annotation<string>());
Assert.Equal(str2, element.Annotation(typeof(string)));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddAnnotationsAndRemoveOfTypeObject(XObject xo)
{
AddAnnotation(xo);
RemoveAnnotations(xo, typeof(object));
Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void EnumerateAnnotationsWithoutAdding(XObject xo)
{
Assert.Null(xo.Annotation(typeof(object)));
Assert.Null(xo.Annotation<object>());
Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo));
Assert.Equal(expected: 0, actual: CountAnnotations<string>(xo));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void RemoveAnnotationsUsingTypeObject(XObject xo)
{
AddAnnotation(xo);
RemoveAnnotations<object>(xo);
Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void RemoveTwiceAnnotationsWithoutAddingUsingTypeObject(XObject xo)
{
RemoveAnnotations<object>(xo);
RemoveAnnotations<object>(xo);
Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo));
}
//
// helpers
//
public static IEnumerable<object[]> GetXObjects()
{
yield return new object[] { new XDocument() };
yield return new object[] { new XAttribute("attr", "val") };
yield return new object[] { new XElement("elem1") };
yield return new object[] { new XText("text1") };
yield return new object[] { new XComment("comment1") };
yield return new object[] { new XProcessingInstruction("pi1", "pi1pi1pi1pi1pi1") };
yield return new object[] { new XCData("cdata cdata") };
yield return new object[] { new XDocumentType("dtd1", "dtd1dtd1dtd1", "dtd1dtd1", "dtd1dtd1dtd1dtd1") };
}
public static object[] GetObjects()
{
object[] aObject = new object[]
{
new A(), new B(), new DifferentNamespace.A(), new DifferentNamespace.B(), "stringstring", 12345,
new Dictionary<string, string>(), new XDocument(), new XAttribute("attr", "val"), new XElement("elem1"),
new XText("text1 text1"), new XComment("comment1 comment1"),
new XProcessingInstruction("pi1", "pi1pi1pi1pi1pi1"), new XCData("cdata cdata"),
new XDeclaration("234", "UTF-8", "yes"), XNamespace.Xmlns,
//new XStreamingElement("elementSequence"),
new XDocumentType("dtd1", "dtd1dtd1dtd1", "dtd1 dtd1", "dtd1 dtd1 dtd1 ")
};
return aObject;
}
private static void ValidateAnnotations<T>(XObject xo, T[] values) where T : class
{
//
// use inefficient n^2 algorithm, which is OK for our testing purposes
// assumes that all items are unique
//
int count = CountAnnotations<T>(xo);
TestLog.Compare(count, values.Length, "unexpected number of annotations");
foreach (T value in values)
{
//
// use non-generics enum first
//
bool found = false;
foreach (T annotation in xo.Annotations(typeof(T)))
{
if (annotation.Equals(value))
{
found = true;
break;
}
}
TestLog.Compare(found, "didn't find value using non-generic enumeration");
//
// now double check with generics one
//
found = false;
foreach (T annotation in xo.Annotations<T>())
{
if (annotation.Equals(value))
{
found = true;
break;
}
}
TestLog.Compare(found, "didn't find value using generic enumeration");
}
}
private static int CountAnnotations<T>(XObject xo) where T : class
{
int count = xo.Annotations(typeof(T)).Count();
Assert.Equal(count, xo.Annotations<T>().Count());
// Generics and non-generics annotations enumerations returned different number of objects
return count;
}
private static void AddAnnotation(XObject xo)
{
foreach (object o in GetObjects())
{
xo.AddAnnotation(o);
}
}
private static void RemoveAnnotations(XObject xo, Type type)
{
xo.RemoveAnnotations(type);
}
private static void RemoveAnnotations<T>(XObject xo) where T : class
{
xo.RemoveAnnotations<T>();
}
private static Type[] GetTypes()
{
Type[] types = new Type[]
{
typeof(string), typeof(int), typeof(Dictionary<string, string>), typeof(A), typeof(B),
typeof(DifferentNamespace.A), typeof(DifferentNamespace.B), typeof(XAttribute), typeof(XElement),
typeof(Extensions), typeof(XDocument), typeof(XText), typeof(XName), typeof(XComment),
typeof(XProcessingInstruction), typeof(XCData), typeof(XDeclaration), typeof(XNamespace),
//typeof(XStreamingElement),
typeof(XDocumentType)
};
return types;
}
public class A
{
}
public class B : A
{
}
}
namespace DifferentNamespace
{
public class A { }
public class B : A { }
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using NUnit.Framework;
using ServiceStack.Text.Tests.DynamicModels.DataModel;
namespace ServiceStack.Text.Tests
{
[TestFixture]
public class DictionaryTests
: TestBase
{
[TestFixtureSetUp]
public void SetUp()
{
#if MONOTOUCH
JsConfig.RegisterTypeForAot<Dictionary<string, int>> ();
JsConfig.RegisterTypeForAot<KeyValuePair<int, string>> ();
JsConfig.RegisterTypeForAot<KeyValuePair<string, int>> ();
JsConfig.RegisterTypeForAot<Dictionary<string, int>> ();
JsConfig.RegisterTypeForAot<KeyValuePair<string, Dictionary<string, int>>> ();
JsConfig.RegisterTypeForAot<Dictionary<string, Dictionary<string, int>>> ();
JsConfig.RegisterTypeForAot<KeyValuePair<int, Dictionary<string, int>>> ();
JsConfig.RegisterTypeForAot<Dictionary<int, Dictionary<string, int>>> ();
#endif
}
[TearDown]
public void TearDown()
{
JsConfig.Reset();
}
[Test]
public void Can_serialize_one_level_dictionary()
{
var map = new Dictionary<string, int>
{
{"One", 1}, {"Two", 2}, {"Three", 3},
};
Serialize(map);
}
[Test]
public void Can_serialize_empty_map()
{
var emptyMap = new Dictionary<string, int>();
Serialize(emptyMap);
}
[Test]
public void Can_serialize_empty_string_map()
{
var emptyMap = new Dictionary<string, string>();
Serialize(emptyMap);
}
[Test]
public void Can_serialize_two_level_dictionary()
{
var map = new Dictionary<string, Dictionary<string, int>>
{
{"map1", new Dictionary<string, int>
{
{"One", 1}, {"Two", 2}, {"Three", 3},
}
},
{"map2", new Dictionary<string, int>
{
{"Four", 4}, {"Five", 5}, {"Six", 6},
}
},
};
Serialize(map);
}
[Test]
public void Can_serialize_two_level_dictionary_with_int_key()
{
var map = new Dictionary<int, Dictionary<string, int>>
{
{1, new Dictionary<string, int>
{
{"One", 1}, {"Two", 2}, {"Three", 3},
}
},
{2, new Dictionary<string, int>
{
{"Four", 4}, {"Five", 5}, {"Six", 6},
}
},
};
Serialize(map);
}
[Test]
public void Can_deserialize_two_level_dictionary_with_array()
{
JsConfig.TryToParsePrimitiveTypeValues = true;
JsConfig.ConvertObjectTypesIntoStringDictionary = true;
var original = new Dictionary<string, StrictType[]>
{
{"array",
new [] {
new StrictType { Name = "First" },
new StrictType { Name = "Second" },
new StrictType { Name = "Third" },
}
},
};
var json = JsonSerializer.SerializeToString(original);
var deserialized = JsonSerializer.DeserializeFromString<Dictionary<string, object>>(json);
Console.WriteLine(json);
Assert.That(deserialized, Is.Not.Null);
Assert.That(deserialized["array"], Is.Not.Null);
Assert.That(((List<object>)deserialized["array"]).Count, Is.EqualTo(3));
Assert.That(((List<object>)deserialized["array"])[0].ToJson(), Is.EqualTo("{\"Name\":\"First\"}"));
Assert.That(((List<object>)deserialized["array"])[1].ToJson(), Is.EqualTo("{\"Name\":\"Second\"}"));
Assert.That(((List<object>)deserialized["array"])[2].ToJson(), Is.EqualTo("{\"Name\":\"Third\"}"));
}
[Test]
public void Can_deserialize_dictionary_with_special_characters_in_strings()
{
JsConfig.TryToParsePrimitiveTypeValues = true;
JsConfig.ConvertObjectTypesIntoStringDictionary = true;
var original = new Dictionary<string, string>
{
{"embeddedtypecharacters", "{{body}}"},
{"embeddedlistcharacters", "[stuff]"},
{"ShortDateTimeFormat", "yyyy-MM-dd"},
{"DefaultDateTimeFormat", "dd/MM/yyyy HH:mm:ss"},
{"DefaultDateTimeFormatWithFraction", "dd/MM/yyyy HH:mm:ss.fff"},
{"XsdDateTimeFormat", "yyyy-MM-ddTHH:mm:ss.fffffffZ"},
{"XsdDateTimeFormat3F", "yyyy-MM-ddTHH:mm:ss.fffZ"},
{"XsdDateTimeFormatSeconds", "yyyy-MM-ddTHH:mm:ssZ"},
{"ShouldBeAZeroInAString", "0"},
{"ShouldBeAPositiveIntegerInAString", "12345"},
{"ShouldBeANegativeIntegerInAString", "-12345"},
};
var json = JsonSerializer.SerializeToString(original);
var deserialized = JsonSerializer.DeserializeFromString<Dictionary<string, object>>(json);
Console.WriteLine(json);
Assert.That(deserialized, Is.Not.Null);
Assert.That(deserialized["embeddedtypecharacters"], Is.Not.Null);
Assert.That(deserialized["embeddedtypecharacters"], Is.EqualTo("{{body}}"));
Assert.That(deserialized["embeddedlistcharacters"], Is.EqualTo("[stuff]"));
Assert.That(deserialized["ShortDateTimeFormat"], Is.EqualTo("yyyy-MM-dd"));
Assert.That(deserialized["DefaultDateTimeFormat"], Is.EqualTo("dd/MM/yyyy HH:mm:ss"));
Assert.That(deserialized["DefaultDateTimeFormatWithFraction"], Is.EqualTo("dd/MM/yyyy HH:mm:ss.fff"));
Assert.That(deserialized["XsdDateTimeFormat"], Is.EqualTo("yyyy-MM-ddTHH:mm:ss.fffffffZ"));
Assert.That(deserialized["XsdDateTimeFormat3F"], Is.EqualTo("yyyy-MM-ddTHH:mm:ss.fffZ"));
Assert.That(deserialized["XsdDateTimeFormatSeconds"], Is.EqualTo("yyyy-MM-ddTHH:mm:ssZ"));
Assert.That(deserialized["ShouldBeAZeroInAString"], Is.EqualTo("0"));
Assert.That(deserialized["ShouldBeAZeroInAString"], Is.InstanceOf<string>());
Assert.That(deserialized["ShouldBeAPositiveIntegerInAString"], Is.EqualTo("12345"));
Assert.That(deserialized["ShouldBeAPositiveIntegerInAString"], Is.InstanceOf<string>());
Assert.That(deserialized["ShouldBeANegativeIntegerInAString"], Is.EqualTo("-12345"));
}
private static Dictionary<string, object> SetupDict()
{
return new Dictionary<string, object> {
{ "a", "text" },
{ "b", 32 },
{ "c", false },
{ "d", new[] {1, 2, 3} }
};
}
public class MixType
{
public string a { get; set; }
public int b { get; set; }
public bool c { get; set; }
public int[] d { get; set; }
}
private static void AssertDict(Dictionary<string, object> dict)
{
Assert.AreEqual("text", dict["a"]);
Assert.AreEqual(32, dict["b"]);
Assert.AreEqual(false, dict["c"]);
}
//[Test]
//public void Test_JsonNet()
//{
// var dict = SetupDict();
// var json = JsonConvert.SerializeObject(dict);
// var deserializedDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
// AssertDict(deserializedDict);
//}
[Test]
public void Test_ServiceStack_Text_TypeSerializer()
{
JsConfig.TryToParsePrimitiveTypeValues = true;
JsConfig.ConvertObjectTypesIntoStringDictionary = true;
var dict = SetupDict();
var json = TypeSerializer.SerializeToString(dict);
var deserializedDict = TypeSerializer.DeserializeFromString<Dictionary<string, object>>(json);
AssertDict(deserializedDict);
}
[Test]
public void Test_ServiceStack_Text_JsonSerializer()
{
JsConfig.TryToParsePrimitiveTypeValues = true;
JsConfig.ConvertObjectTypesIntoStringDictionary = true;
var dict = SetupDict();
var json = JsonSerializer.SerializeToString(dict);
var deserializedDict = JsonSerializer.DeserializeFromString<Dictionary<string, object>>(json);
AssertDict(deserializedDict);
}
[Test]
public void Test_ServiceStack_Text_JsonSerializer_Array_Value_Deserializes_Correctly()
{
JsConfig.TryToParsePrimitiveTypeValues = true;
JsConfig.ConvertObjectTypesIntoStringDictionary = true;
var dict = SetupDict();
var json = JsonSerializer.SerializeToString(dict);
var deserializedDict = JsonSerializer.DeserializeFromString<Dictionary<string, object>>(json);
Assert.AreEqual("text", deserializedDict["a"]);
Assert.AreEqual(new List<int> {1, 2, 3}, deserializedDict["d"]);
}
[Test]
public void Can_deserialize_mixed_dictionary_into_strongtyped_map()
{
var mixedMap = SetupDict();
var json = JsonSerializer.SerializeToString(mixedMap);
Console.WriteLine("JSON:\n" + json);
var mixedType = json.FromJson<MixType>();
Assert.AreEqual("text", mixedType.a);
Assert.AreEqual(32, mixedType.b);
Assert.AreEqual(false, mixedType.c);
Assert.AreEqual(new[] {1, 2, 3}, mixedType.d);
}
[Test]
public void Can_serialise_null_values_from_dictionary_correctly()
{
JsConfig.IncludeNullValues = true;
var dictionary = new Dictionary<string, object> { { "value", null } };
Serialize(dictionary, includeXml: false);
var json = JsonSerializer.SerializeToString(dictionary);
Log(json);
Assert.That(json, Is.EqualTo("{\"value\":null}"));
JsConfig.Reset();
}
[Test]
public void Will_ignore_null_values_from_dictionary_correctly()
{
JsConfig.IncludeNullValues = false;
var dictionary = new Dictionary<string, string> { { "value", null } };
Serialize(dictionary, includeXml: false);
var json = JsonSerializer.SerializeToString(dictionary);
Log(json);
Assert.That(json, Is.EqualTo("{}"));
JsConfig.Reset();
}
public class FooSlash
{
public Dictionary<string, string> Nested { get; set; }
public string Bar { get; set; }
}
[Test]
public void Can_serialize_Dictionary_with_end_slash()
{
var foo = new FooSlash {
Nested = new Dictionary<string, string> { { "key", "value\"" } },
Bar = "BarValue"
};
Serialize(foo);
}
[Test]
public void Can_serialise_null_values_from_nested_dictionary_correctly()
{
JsConfig.IncludeNullValues = true;
var foo = new FooSlash();
var json = JsonSerializer.SerializeToString(foo);
Assert.That(json, Is.EqualTo("{\"Nested\":null,\"Bar\":null}"));
JsConfig.Reset();
}
[Test]
public void Can_serialize_Dictionary_with_quotes()
{
var dto = new Dictionary<string, string> { { "title", "\"test\"" } };
var to = Serialize(dto);
Assert.That(to["title"], Is.EqualTo(dto["title"]));
}
[Test]
public void Can_Deserialize_Object_To_Dictionary()
{
const string json = "{\"Id\":1}";
var d = json.To<Dictionary<string, string>>();
Assert.That(d.ContainsKey("Id"));
Assert.That(d["Id"], Is.EqualTo("1"));
}
#if NET40
[Test]
public void Nongeneric_implementors_of_IDictionary_K_V_Should_serialize_like_Dictionary_K_V()
{
dynamic expando = new System.Dynamic.ExpandoObject();
expando.Property = "Value";
IDictionary<string, object> dict = expando;
Assert.AreEqual(dict.Dump(), new Dictionary<string, object>(dict).Dump());
}
#endif
}
}
| |
/*
* 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 Document = Lucene.Net.Documents.Document;
using CorruptIndexException = Lucene.Net.Index.CorruptIndexException;
using Term = Lucene.Net.Index.Term;
namespace Lucene.Net.Search
{
/// <summary> An abstract base class for search implementations. Implements the main search
/// methods.
///
/// <p/>
/// Note that you can only access hits from a Searcher as long as it is not yet
/// closed, otherwise an IOException will be thrown.
/// </summary>
public abstract class Searcher : System.MarshalByRefObject, Searchable, System.IDisposable
{
public Searcher()
{
InitBlock();
}
private void InitBlock()
{
similarity = Similarity.GetDefault();
}
/// <summary>Returns the documents matching <code>query</code>. </summary>
/// <throws> BooleanQuery.TooManyClauses </throws>
/// <deprecated> Hits will be removed in Lucene 3.0. Use
/// {@link #Search(Query, Filter, int)} instead.
/// </deprecated>
[Obsolete("Hits will be removed in Lucene 3.0. Use Search(Query, Filter, int) instead")]
public Hits Search(Query query)
{
return Search(query, (Filter) null);
}
/// <summary>Returns the documents matching <code>query</code> and
/// <code>filter</code>.
/// </summary>
/// <throws> BooleanQuery.TooManyClauses </throws>
/// <deprecated> Hits will be removed in Lucene 3.0. Use
/// {@link #Search(Query, Filter, int)} instead.
/// </deprecated>
[Obsolete("Hits will be removed in Lucene 3.0. Use Search(Query, Filter, int) instead")]
public virtual Hits Search(Query query, Filter filter)
{
return new Hits(this, query, filter);
}
/// <summary>Returns documents matching <code>query</code> sorted by
/// <code>sort</code>.
/// </summary>
/// <throws> BooleanQuery.TooManyClauses </throws>
/// <deprecated> Hits will be removed in Lucene 3.0. Use
/// {@link #Search(Query, Filter, int, Sort)} instead.
/// </deprecated>
[Obsolete("Hits will be removed in Lucene 3.0. Use Search(Query, Filter, int, Sort) instead")]
public virtual Hits Search(Query query, Sort sort)
{
return new Hits(this, query, null, sort);
}
/// <summary>Returns documents matching <code>query</code> and <code>filter</code>,
/// sorted by <code>sort</code>.
/// </summary>
/// <throws> BooleanQuery.TooManyClauses </throws>
/// <deprecated> Hits will be removed in Lucene 3.0. Use
/// {@link #Search(Query, Filter, int, Sort)} instead.
/// </deprecated>
[Obsolete("Hits will be removed in Lucene 3.0. Use Search(Query, Filter, int, Sort) instead")]
public virtual Hits Search(Query query, Filter filter, Sort sort)
{
return new Hits(this, query, filter, sort);
}
/// <summary>Search implementation with arbitrary sorting. Finds
/// the top <code>n</code> hits for <code>query</code>, applying
/// <code>filter</code> if non-null, and sorting the hits by the criteria in
/// <code>sort</code>.
///
/// <p/>NOTE: this does not compute scores by default; use
/// {@link IndexSearcher#setDefaultFieldSortScoring} to enable scoring.
///
/// </summary>
/// <throws> BooleanQuery.TooManyClauses </throws>
public virtual TopFieldDocs Search(Query query, Filter filter, int n, Sort sort)
{
return Search(CreateWeight(query), filter, n, sort);
}
/// <summary>Lower-level search API.
///
/// <p/>{@link HitCollector#Collect(int,float)} is called for every matching
/// document.
///
/// <p/>Applications should only use this if they need <i>all</i> of the
/// matching documents. The high-level search API ({@link
/// Searcher#Search(Query)}) is usually more efficient, as it skips
/// non-high-scoring hits.
/// <p/>Note: The <code>score</code> passed to this method is a raw score.
/// In other words, the score will not necessarily be a float whose value is
/// between 0 and 1.
/// </summary>
/// <throws> BooleanQuery.TooManyClauses </throws>
/// <deprecated> use {@link #Search(Query, Collector)} instead.
/// </deprecated>
[Obsolete("use Search(Query, Collector) instead.")]
public virtual void Search(Query query, HitCollector results)
{
Search(CreateWeight(query), null, new HitCollectorWrapper(results));
}
/// <summary>Lower-level search API.
///
/// <p/>{@link Collector#Collect(int)} is called for every matching document.
///
/// <p/>Applications should only use this if they need <i>all</i> of the matching
/// documents. The high-level search API ({@link Searcher#Search(Query, int)}
/// ) is usually more efficient, as it skips non-high-scoring hits.
/// <p/>Note: The <code>score</code> passed to this method is a raw score.
/// In other words, the score will not necessarily be a float whose value is
/// between 0 and 1.
/// </summary>
/// <throws> BooleanQuery.TooManyClauses </throws>
public virtual void Search(Query query, Collector results)
{
Search(CreateWeight(query), null, results);
}
/// <summary>Lower-level search API.
///
/// <p/>{@link HitCollector#Collect(int,float)} is called for every matching
/// document.
/// <br/>HitCollector-based access to remote indexes is discouraged.
///
/// <p/>Applications should only use this if they need <i>all</i> of the
/// matching documents. The high-level search API ({@link
/// Searcher#Search(Query, Filter, int)}) is usually more efficient, as it skips
/// non-high-scoring hits.
///
/// </summary>
/// <param name="query">to match documents
/// </param>
/// <param name="filter">if non-null, used to permit documents to be collected.
/// </param>
/// <param name="results">to receive hits
/// </param>
/// <throws> BooleanQuery.TooManyClauses </throws>
/// <deprecated> use {@link #Search(Query, Filter, Collector)} instead.
/// </deprecated>
[Obsolete("use Search(Query, Filter, Collector) instead.")]
public virtual void Search(Query query, Filter filter, HitCollector results)
{
Search(CreateWeight(query), filter, new HitCollectorWrapper(results));
}
/// <summary>Lower-level search API.
///
/// <p/>{@link Collector#Collect(int)} is called for every matching
/// document.
/// <br/>Collector-based access to remote indexes is discouraged.
///
/// <p/>Applications should only use this if they need <i>all</i> of the
/// matching documents. The high-level search API ({@link
/// Searcher#Search(Query, Filter, int)}) is usually more efficient, as it skips
/// non-high-scoring hits.
///
/// </summary>
/// <param name="query">to match documents
/// </param>
/// <param name="filter">if non-null, used to permit documents to be collected.
/// </param>
/// <param name="results">to receive hits
/// </param>
/// <throws> BooleanQuery.TooManyClauses </throws>
public virtual void Search(Query query, Filter filter, Collector results)
{
Search(CreateWeight(query), filter, results);
}
/// <summary>Finds the top <code>n</code>
/// hits for <code>query</code>, applying <code>filter</code> if non-null.
///
/// </summary>
/// <throws> BooleanQuery.TooManyClauses </throws>
public virtual TopDocs Search(Query query, Filter filter, int n)
{
return Search(CreateWeight(query), filter, n);
}
/// <summary>Finds the top <code>n</code>
/// hits for <code>query</code>.
///
/// </summary>
/// <throws> BooleanQuery.TooManyClauses </throws>
public virtual TopDocs Search(Query query, int n)
{
return Search(query, null, n);
}
/// <summary>Returns an Explanation that describes how <code>doc</code> scored against
/// <code>query</code>.
///
/// <p/>This is intended to be used in developing Similarity implementations,
/// and, for good performance, should not be displayed with every hit.
/// Computing an explanation is as expensive as executing the query over the
/// entire index.
/// </summary>
public virtual Explanation Explain(Query query, int doc)
{
return Explain(CreateWeight(query), doc);
}
/// <summary>The Similarity implementation used by this searcher. </summary>
private Similarity similarity;
/// <summary>Expert: Set the Similarity implementation used by this Searcher.
///
/// </summary>
/// <seealso cref="Similarity.SetDefault(Similarity)">
/// </seealso>
public virtual void SetSimilarity(Similarity similarity)
{
this.similarity = similarity;
}
/// <summary>Expert: Return the Similarity implementation used by this Searcher.
///
/// <p/>This defaults to the current value of {@link Similarity#GetDefault()}.
/// </summary>
public virtual Similarity GetSimilarity()
{
return this.similarity;
}
/// <summary> creates a weight for <code>query</code></summary>
/// <returns> new weight
/// </returns>
public /*protected internal*/ virtual Weight CreateWeight(Query query)
{
return query.Weight(this);
}
// inherit javadoc
public virtual int[] DocFreqs(Term[] terms)
{
int[] result = new int[terms.Length];
for (int i = 0; i < terms.Length; i++)
{
result[i] = DocFreq(terms[i]);
}
return result;
}
/* The following abstract methods were added as a workaround for GCJ bug #15411.
* http://gcc.gnu.org/bugzilla/show_bug.cgi?id=15411
*/
/// <deprecated> use {@link #Search(Weight, Filter, Collector)} instead.
/// </deprecated>
[Obsolete("use Search(Weight, Filter, Collector) instead.")]
public virtual void Search(Weight weight, Filter filter, HitCollector results)
{
Search(weight, filter, new HitCollectorWrapper(results));
}
abstract public void Search(Weight weight, Filter filter, Collector results);
abstract public void Close();
abstract public void Dispose();
abstract public int DocFreq(Term term);
abstract public int MaxDoc();
abstract public TopDocs Search(Weight weight, Filter filter, int n);
abstract public Document Doc(int i);
abstract public Query Rewrite(Query query);
abstract public Explanation Explain(Weight weight, int doc);
abstract public TopFieldDocs Search(Weight weight, Filter filter, int n, Sort sort);
/* End patch for GCJ bug #15411. */
public abstract Lucene.Net.Documents.Document Doc(int param1, Lucene.Net.Documents.FieldSelector param2);
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Bond.Expressions
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
public class TaggedParser<R> : IParser
{
delegate Expression TypeHandlerCompiletime(BondDataType type);
delegate Expression TypeHandlerRuntime(Expression type);
readonly TaggedReader<R> reader = new TaggedReader<R>();
readonly PayloadBondedFactory bondedFactory;
readonly TaggedParser<R> baseParser;
readonly TaggedParser<R> fieldParser;
readonly bool isBase;
public TaggedParser(RuntimeSchema schema)
: this(schema, null)
{ }
public TaggedParser(RuntimeSchema schema, PayloadBondedFactory bondedFactory)
: this(bondedFactory)
{ }
public TaggedParser(Type type)
: this(type, null)
{ }
public TaggedParser(Type type, PayloadBondedFactory bondedFactory)
: this(bondedFactory)
{ }
private TaggedParser(PayloadBondedFactory bondedFactory)
{
isBase = false;
this.bondedFactory = bondedFactory ?? NewBonded;
baseParser = new TaggedParser<R>(this, isBase: true);
fieldParser = this;
}
TaggedParser(TaggedParser<R> that, bool isBase)
{
this.isBase = isBase;
bondedFactory = that.bondedFactory;
reader = that.reader;
baseParser = this;
fieldParser = that;
}
public ParameterExpression ReaderParam { get { return reader.Param; } }
public Expression ReaderValue { get { return reader.Param; } }
public int HierarchyDepth { get { return 0; } }
public bool IsBonded { get { return false; } }
public Expression Apply(ITransform transform)
{
var fieldId = Expression.Variable(typeof(UInt16), "fieldId");
var fieldType = Expression.Variable(typeof(BondDataType), "fieldType");
var endLabel = Expression.Label("end");
var breakLoop = Expression.Break(endLabel);
// (int)fieldType > (int)BT_STOP_BASE
var notEndOrEndBase = Expression.GreaterThan(
Expression.Convert(fieldType, typeof(int)),
Expression.Constant((int)BondDataType.BT_STOP_BASE));
var notEnd = isBase ? notEndOrEndBase : Expression.NotEqual(fieldType, Expression.Constant(BondDataType.BT_STOP));
var isEndBase = Expression.Equal(fieldType, Expression.Constant(BondDataType.BT_STOP_BASE));
var body = new List<Expression>
{
isBase ? reader.ReadBaseBegin() : reader.ReadStructBegin(),
transform.Begin,
transform.Base(baseParser),
reader.ReadFieldBegin(fieldType, fieldId)
};
// known fields
body.AddRange(
from f in transform.Fields select
Expression.Loop(
Expression.IfThenElse(notEndOrEndBase,
Expression.Block(
Expression.IfThenElse(
Expression.Equal(fieldId, Expression.Constant(f.Id)),
Expression.Block(
f.Value(fieldParser, fieldType),
reader.ReadFieldEnd(),
reader.ReadFieldBegin(fieldType, fieldId),
breakLoop),
Expression.IfThenElse(
Expression.GreaterThan(fieldId, Expression.Constant(f.Id)),
Expression.Block(
f.Omitted,
breakLoop),
transform.UnknownField(fieldParser, fieldType, fieldId) ?? Skip(fieldType))),
reader.ReadFieldEnd(),
reader.ReadFieldBegin(fieldType, fieldId),
Expression.IfThen(
Expression.GreaterThan(fieldId, Expression.Constant(f.Id)),
breakLoop)),
Expression.Block(
f.Omitted,
breakLoop)),
endLabel));
// unknown fields
body.Add(
ControlExpression.While(notEnd,
Expression.Block(
Expression.IfThenElse(
isEndBase,
transform.UnknownEnd,
Expression.Block(
transform.UnknownField(fieldParser, fieldType, fieldId) ?? Skip(fieldType),
reader.ReadFieldEnd())),
reader.ReadFieldBegin(fieldType, fieldId))));
body.Add(isBase ? reader.ReadBaseEnd() : reader.ReadStructEnd());
body.Add(transform.End);
return Expression.Block(
new[] { fieldType, fieldId },
body);
}
public Expression Container(BondDataType? expectedType, ContainerHandler handler)
{
var count = Expression.Variable(typeof(int), "count");
var elementType = Expression.Variable(typeof(BondDataType), "elementType");
var next = Expression.GreaterThan(Expression.PostDecrementAssign(count), Expression.Constant(0));
var loops = MatchOrCompatible(
elementType,
expectedType,
type => handler(this, type, next, count));
return Expression.Block(
new[] { count, elementType },
reader.ReadContainerBegin(count, elementType),
loops,
reader.ReadContainerEnd());
}
public Expression Map(BondDataType? expectedKeyType, BondDataType? expectedValueType, MapHandler handler)
{
var count = Expression.Variable(typeof(int), "count");
var keyType = Expression.Variable(typeof(BondDataType), "keyType");
var valueType = Expression.Variable(typeof(BondDataType), "valueType");
var next = Expression.GreaterThan(Expression.PostDecrementAssign(count), Expression.Constant(0));
var loops = MatchOrCompatible(keyType, expectedKeyType, constantKeyType =>
MatchOrCompatible(valueType, expectedValueType, constantValueType =>
handler(this, this, constantKeyType, constantValueType, next, Expression.Empty(), count)));
return Expression.Block(
new[] { count, keyType, valueType },
reader.ReadContainerBegin(count, keyType, valueType),
loops,
reader.ReadContainerEnd());
}
public Expression Blob(Expression count)
{
return reader.ReadBytes(count);
}
public Expression Scalar(Expression valueType, BondDataType expectedType, ValueHandler handler)
{
return MatchOrCompatible(valueType, expectedType,
type => handler(reader.Read(type)));
}
public Expression Bonded(ValueHandler handler)
{
var newBonded = bondedFactory(reader.Param, Expression.Constant(RuntimeSchema.Empty));
return Expression.Block(
handler(newBonded),
reader.Skip(Expression.Constant(BondDataType.BT_STRUCT)));
}
public Expression Skip(Expression type)
{
return reader.Skip(type);
}
static Expression NewBonded(Expression reader, Expression schema)
{
var ctor = typeof(BondedVoid<>).MakeGenericType(reader.Type).GetConstructor(reader.Type);
return Expression.New(ctor, reader);
}
static Expression MatchOrCompatible(Expression valueType, BondDataType? expectedType, TypeHandlerRuntime handler)
{
return (expectedType == null) ?
handler(valueType) :
MatchOrCompatible(valueType, expectedType.Value, type => handler(Expression.Constant(type)));
}
// Generate expression to handle exact match or compatible type
static Expression MatchOrCompatible(Expression valueType, BondDataType expectedType, TypeHandlerCompiletime handler)
{
return MatchOrElse(valueType, expectedType, handler,
TryCompatible(valueType, expectedType, handler));
}
// valueType maybe a ConstantExpression and then Prune optimizes unreachable branches out
static Expression MatchOrElse(Expression valueType, BondDataType expectedType, TypeHandlerCompiletime handler, Expression orElse)
{
return PrunedExpression.IfThenElse(
Expression.Equal(valueType, Expression.Constant(expectedType)),
handler(expectedType),
orElse);
}
// Generates expression to handle value of type that is different but compatible with expected type
static Expression TryCompatible(Expression valueType, BondDataType expectedType, TypeHandlerCompiletime handler)
{
if (expectedType == BondDataType.BT_DOUBLE)
{
return MatchOrElse(valueType, BondDataType.BT_FLOAT, handler,
InvalidType(expectedType, valueType));
}
if (expectedType == BondDataType.BT_UINT64)
{
return MatchOrElse(valueType, BondDataType.BT_UINT32, handler,
MatchOrElse(valueType, BondDataType.BT_UINT16, handler,
MatchOrElse(valueType, BondDataType.BT_UINT8, handler,
InvalidType(expectedType, valueType))));
}
if (expectedType == BondDataType.BT_UINT32)
{
return MatchOrElse(valueType, BondDataType.BT_UINT16, handler,
MatchOrElse(valueType, BondDataType.BT_UINT8, handler,
InvalidType(expectedType, valueType)));
}
if (expectedType == BondDataType.BT_UINT16)
{
return MatchOrElse(valueType, BondDataType.BT_UINT8, handler,
InvalidType(expectedType, valueType));
}
if (expectedType == BondDataType.BT_INT64)
{
return MatchOrElse(valueType, BondDataType.BT_INT32, handler,
MatchOrElse(valueType, BondDataType.BT_INT16, handler,
MatchOrElse(valueType, BondDataType.BT_INT8, handler,
InvalidType(expectedType, valueType))));
}
if (expectedType == BondDataType.BT_INT32)
{
return MatchOrElse(valueType, BondDataType.BT_INT16, handler,
MatchOrElse(valueType, BondDataType.BT_INT8, handler,
InvalidType(expectedType, valueType)));
}
if (expectedType == BondDataType.BT_INT16)
{
return MatchOrElse(valueType, BondDataType.BT_INT8, handler,
InvalidType(expectedType, valueType));
}
return InvalidType(expectedType, valueType);
}
static Expression InvalidType(BondDataType expectedType, Expression valueType)
{
return ThrowExpression.InvalidTypeException(Expression.Constant(expectedType), valueType);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
namespace System.IO.Pipes
{
public abstract partial class PipeStream : Stream
{
internal const bool CheckOperationsRequiresSetHandle = true;
internal ThreadPoolBoundHandle _threadPoolBinding;
internal static string GetPipePath(string serverName, string pipeName)
{
string normalizedPipePath = Path.GetFullPath(@"\\" + serverName + @"\pipe\" + pipeName);
if (String.Equals(normalizedPipePath, @"\\.\pipe\anonymous", StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentOutOfRangeException("pipeName", SR.ArgumentOutOfRange_AnonymousReserved);
}
return normalizedPipePath;
}
/// <summary>Throws an exception if the supplied handle does not represent a valid pipe.</summary>
/// <param name="safePipeHandle">The handle to validate.</param>
internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle)
{
// Check that this handle is infact a handle to a pipe.
if (Interop.mincore.GetFileType(safePipeHandle) != Interop.mincore.FileTypes.FILE_TYPE_PIPE)
{
throw new IOException(SR.IO_InvalidPipeHandle);
}
}
/// <summary>Initializes the handle to be used asynchronously.</summary>
/// <param name="handle">The handle.</param>
private void InitializeAsyncHandle(SafePipeHandle handle)
{
// If the handle is of async type, bind the handle to the ThreadPool so that we can use
// the async operations (it's needed so that our native callbacks get called).
_threadPoolBinding = ThreadPoolBoundHandle.BindHandle(handle);
}
private void UninitializeAsyncHandle()
{
if (_threadPoolBinding != null)
_threadPoolBinding.Dispose();
}
[SecurityCritical]
private unsafe int ReadCore(byte[] buffer, int offset, int count)
{
int errorCode = 0;
int r = ReadFileNative(_handle, buffer, offset, count, null, out errorCode);
if (r == -1)
{
// If the other side has broken the connection, set state to Broken and return 0
if (errorCode == Interop.mincore.Errors.ERROR_BROKEN_PIPE ||
errorCode == Interop.mincore.Errors.ERROR_PIPE_NOT_CONNECTED)
{
State = PipeState.Broken;
r = 0;
}
else
{
throw Win32Marshal.GetExceptionForWin32Error(errorCode, String.Empty);
}
}
_isMessageComplete = (errorCode != Interop.mincore.Errors.ERROR_MORE_DATA);
Debug.Assert(r >= 0, "PipeStream's ReadCore is likely broken.");
return r;
}
[SecuritySafeCritical]
private Task<int> ReadAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
var completionSource = new ReadWriteCompletionSource(this, buffer, cancellationToken, isWrite: false);
// Queue an async ReadFile operation and pass in a packed overlapped
int errorCode = 0;
int r;
unsafe
{
r = ReadFileNative(_handle, buffer, offset, count, completionSource.Overlapped, out errorCode);
}
// ReadFile, the OS version, will return 0 on failure, but this ReadFileNative wrapper
// returns -1. This will return the following:
// - On error, r==-1.
// - On async requests that are still pending, r==-1 w/ hr==ERROR_IO_PENDING
// - On async requests that completed sequentially, r==0
//
// You will NEVER RELIABLY be able to get the number of buffer read back from this call
// when using overlapped structures! You must not pass in a non-null lpNumBytesRead to
// ReadFile when using overlapped structures! This is by design NT behavior.
if (r == -1)
{
switch (errorCode)
{
// One side has closed its handle or server disconnected.
// Set the state to Broken and do some cleanup work
case Interop.mincore.Errors.ERROR_BROKEN_PIPE:
case Interop.mincore.Errors.ERROR_PIPE_NOT_CONNECTED:
State = PipeState.Broken;
unsafe
{
// Clear the overlapped status bit for this special case. Failure to do so looks
// like we are freeing a pending overlapped.
completionSource.Overlapped->InternalLow = IntPtr.Zero;
}
completionSource.ReleaseResources();
UpdateMessageCompletion(true);
return s_zeroTask;
case Interop.mincore.Errors.ERROR_IO_PENDING:
break;
default:
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
completionSource.RegisterForCancellation();
return completionSource.Task;
}
[SecurityCritical]
private unsafe void WriteCore(byte[] buffer, int offset, int count)
{
int errorCode = 0;
int r = WriteFileNative(_handle, buffer, offset, count, null, out errorCode);
if (r == -1)
{
throw WinIOError(errorCode);
}
Debug.Assert(r >= 0, "PipeStream's WriteCore is likely broken.");
}
[SecuritySafeCritical]
private Task WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
var completionSource = new ReadWriteCompletionSource(this, buffer, cancellationToken, isWrite: true);
int errorCode = 0;
// Queue an async WriteFile operation and pass in a packed overlapped
int r;
unsafe
{
r = WriteFileNative(_handle, buffer, offset, count, completionSource.Overlapped, out errorCode);
}
// WriteFile, the OS version, will return 0 on failure, but this WriteFileNative
// wrapper returns -1. This will return the following:
// - On error, r==-1.
// - On async requests that are still pending, r==-1 w/ hr==ERROR_IO_PENDING
// - On async requests that completed sequentially, r==0
//
// You will NEVER RELIABLY be able to get the number of buffer written back from this
// call when using overlapped structures! You must not pass in a non-null
// lpNumBytesWritten to WriteFile when using overlapped structures! This is by design
// NT behavior.
if (r == -1 && errorCode != Interop.mincore.Errors.ERROR_IO_PENDING)
{
completionSource.ReleaseResources();
throw WinIOError(errorCode);
}
completionSource.RegisterForCancellation();
return completionSource.Task;
}
// Blocks until the other end of the pipe has read in all written buffer.
[SecurityCritical]
public void WaitForPipeDrain()
{
CheckWriteOperations();
if (!CanWrite)
{
throw __Error.GetWriteNotSupported();
}
// Block until other end of the pipe has read everything.
if (!Interop.mincore.FlushFileBuffers(_handle))
{
throw WinIOError(Marshal.GetLastWin32Error());
}
}
// Gets the transmission mode for the pipe. This is virtual so that subclassing types can
// override this in cases where only one mode is legal (such as anonymous pipes)
public virtual PipeTransmissionMode TransmissionMode
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
if (_isFromExistingHandle)
{
int pipeFlags;
if (!Interop.mincore.GetNamedPipeInfo(_handle, out pipeFlags, IntPtr.Zero, IntPtr.Zero,
IntPtr.Zero))
{
throw WinIOError(Marshal.GetLastWin32Error());
}
if ((pipeFlags & Interop.mincore.PipeOptions.PIPE_TYPE_MESSAGE) != 0)
{
return PipeTransmissionMode.Message;
}
else
{
return PipeTransmissionMode.Byte;
}
}
else
{
return _transmissionMode;
}
}
}
// Gets the buffer size in the inbound direction for the pipe. This checks if pipe has read
// access. If that passes, call to GetNamedPipeInfo will succeed.
public virtual int InBufferSize
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
get
{
CheckPipePropertyOperations();
if (!CanRead)
{
throw new NotSupportedException(SR.NotSupported_UnreadableStream);
}
int inBufferSize;
if (!Interop.mincore.GetNamedPipeInfo(_handle, IntPtr.Zero, IntPtr.Zero, out inBufferSize, IntPtr.Zero))
{
throw WinIOError(Marshal.GetLastWin32Error());
}
return inBufferSize;
}
}
// Gets the buffer size in the outbound direction for the pipe. This uses cached version
// if it's an outbound only pipe because GetNamedPipeInfo requires read access to the pipe.
// However, returning cached is good fallback, especially if user specified a value in
// the ctor.
public virtual int OutBufferSize
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
if (!CanWrite)
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
int outBufferSize;
// Use cached value if direction is out; otherwise get fresh version
if (_pipeDirection == PipeDirection.Out)
{
outBufferSize = _outBufferSize;
}
else if (!Interop.mincore.GetNamedPipeInfo(_handle, IntPtr.Zero, out outBufferSize,
IntPtr.Zero, IntPtr.Zero))
{
throw WinIOError(Marshal.GetLastWin32Error());
}
return outBufferSize;
}
}
public virtual PipeTransmissionMode ReadMode
{
[SecurityCritical]
get
{
CheckPipePropertyOperations();
// get fresh value if it could be stale
if (_isFromExistingHandle || IsHandleExposed)
{
UpdateReadMode();
}
return _readMode;
}
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
set
{
// Nothing fancy here. This is just a wrapper around the Win32 API. Note, that NamedPipeServerStream
// and the AnonymousPipeStreams override this.
CheckPipePropertyOperations();
if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message)
{
throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
}
unsafe
{
int pipeReadType = (int)value << 1;
if (!Interop.mincore.SetNamedPipeHandleState(_handle, &pipeReadType, IntPtr.Zero, IntPtr.Zero))
{
throw WinIOError(Marshal.GetLastWin32Error());
}
else
{
_readMode = value;
}
}
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
[SecurityCritical]
private unsafe int ReadFileNative(SafePipeHandle handle, byte[] buffer, int offset, int count,
NativeOverlapped* overlapped, out int errorCode)
{
DebugAssertReadWriteArgs(buffer, offset, count, handle);
Debug.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter screwup in call to ReadFileNative.");
// You can't use the fixed statement on an array of length 0. Note that async callers
// check to avoid calling this first, so they can call user's callback
if (buffer.Length == 0)
{
errorCode = 0;
return 0;
}
int r = 0;
int numBytesRead = 0;
fixed (byte* p = buffer)
{
if (_isAsync)
{
r = Interop.mincore.ReadFile(handle, p + offset, count, IntPtr.Zero, overlapped);
}
else
{
r = Interop.mincore.ReadFile(handle, p + offset, count, out numBytesRead, IntPtr.Zero);
}
}
if (r == 0)
{
errorCode = Marshal.GetLastWin32Error();
// In message mode, the ReadFile can inform us that there is more data to come.
if (errorCode == Interop.mincore.Errors.ERROR_MORE_DATA)
{
return numBytesRead;
}
return -1;
}
else
{
errorCode = 0;
}
return numBytesRead;
}
[SecurityCritical]
private unsafe int WriteFileNative(SafePipeHandle handle, byte[] buffer, int offset, int count,
NativeOverlapped* overlapped, out int errorCode)
{
DebugAssertReadWriteArgs(buffer, offset, count, handle);
Debug.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter screwup in call to WriteFileNative.");
// You can't use the fixed statement on an array of length 0. Note that async callers
// check to avoid calling this first, so they can call user's callback
if (buffer.Length == 0)
{
errorCode = 0;
return 0;
}
int numBytesWritten = 0;
int r = 0;
fixed (byte* p = buffer)
{
if (_isAsync)
{
r = Interop.mincore.WriteFile(handle, p + offset, count, IntPtr.Zero, overlapped);
}
else
{
r = Interop.mincore.WriteFile(handle, p + offset, count, out numBytesWritten, IntPtr.Zero);
}
}
if (r == 0)
{
errorCode = Marshal.GetLastWin32Error();
return -1;
}
else
{
errorCode = 0;
}
return numBytesWritten;
}
[SecurityCritical]
internal static Interop.mincore.SECURITY_ATTRIBUTES GetSecAttrs(HandleInheritability inheritability)
{
Interop.mincore.SECURITY_ATTRIBUTES secAttrs = default(Interop.mincore.SECURITY_ATTRIBUTES);
if ((inheritability & HandleInheritability.Inheritable) != 0)
{
secAttrs = new Interop.mincore.SECURITY_ATTRIBUTES();
secAttrs.nLength = (uint)Marshal.SizeOf(secAttrs);
secAttrs.bInheritHandle = true;
}
return secAttrs;
}
/// <summary>
/// Determine pipe read mode from Win32
/// </summary>
[SecurityCritical]
private void UpdateReadMode()
{
int flags;
if (!Interop.mincore.GetNamedPipeHandleState(SafePipeHandle, out flags, IntPtr.Zero, IntPtr.Zero,
IntPtr.Zero, IntPtr.Zero, 0))
{
throw WinIOError(Marshal.GetLastWin32Error());
}
if ((flags & Interop.mincore.PipeOptions.PIPE_READMODE_MESSAGE) != 0)
{
_readMode = PipeTransmissionMode.Message;
}
else
{
_readMode = PipeTransmissionMode.Byte;
}
}
/// <summary>
/// Filter out all pipe related errors and do some cleanup before calling __Error.WinIOError.
/// </summary>
/// <param name="errorCode"></param>
[SecurityCritical]
internal Exception WinIOError(int errorCode)
{
switch (errorCode)
{
case Interop.mincore.Errors.ERROR_BROKEN_PIPE:
case Interop.mincore.Errors.ERROR_PIPE_NOT_CONNECTED:
case Interop.mincore.Errors.ERROR_NO_DATA:
// Other side has broken the connection
_state = PipeState.Broken;
return new IOException(SR.IO_PipeBroken, Win32Marshal.MakeHRFromErrorCode(errorCode));
case Interop.mincore.Errors.ERROR_HANDLE_EOF:
return __Error.GetEndOfFile();
case Interop.mincore.Errors.ERROR_INVALID_HANDLE:
// For invalid handles, detect the error and mark our handle
// as invalid to give slightly better error messages. Also
// help ensure we avoid handle recycling bugs.
_handle.SetHandleAsInvalid();
_state = PipeState.Broken;
break;
}
return Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace HTLib3
{
using DEBUG = System.Diagnostics.Debug;
public partial class Debug
{
public static Random rand = new Random();
public static readonly Debug debug = new Debug();
[System.Diagnostics.Conditional("DEBUG")]
// [System.Diagnostics.DebuggerHiddenAttribute()]
public static void InitValues<T>(IList<T> values, T initvalue)
{
for(int i=0; i<values.Count; i++)
values[i] = initvalue;
}
[System.Diagnostics.Conditional("DEBUG")]
// [System.Diagnostics.DebuggerHiddenAttribute()]
public static void InitValues<T>(T[,] values, T initvalue)
{
for(int i0=0; i0<values.GetLength(0); i0++)
for(int i1=0; i1<values.GetLength(1); i1++)
values[i0, i1] = initvalue;
}
[System.Diagnostics.Conditional("DEBUG")]
[System.Diagnostics.DebuggerHiddenAttribute()]
public static void Assert(params bool[] conditions)
{
AssertAnd(conditions);
}
[System.Diagnostics.Conditional("DEBUG")]
[System.Diagnostics.DebuggerHiddenAttribute()]
public static void AssertTolerant(double tolerance, params double[] values)
{
for(int i=0; i<values.Length; i++)
if(Math.Abs(values[i]) > tolerance)
{
System.Diagnostics.Debug.Assert(false);
return;
}
}
[System.Diagnostics.Conditional("DEBUG")]
[System.Diagnostics.DebuggerHiddenAttribute()]
public static void AssertTolerantIf(bool condition, double tolerance, params double[] values)
{
if(condition)
AssertTolerant(tolerance, values);
}
[System.Diagnostics.Conditional("DEBUG")]
[System.Diagnostics.DebuggerHiddenAttribute()]
public static void AssertTolerant(double tolerance, params double[][] values)
{
for(int i=0; i<values.Length; i++)
for(int j=0; j<values[i].Length; j++)
if(Math.Abs(values[i][j]) > tolerance)
{
System.Diagnostics.Debug.Assert(false);
return;
}
}
[System.Diagnostics.Conditional("DEBUG")]
[System.Diagnostics.DebuggerHiddenAttribute()]
public static void AssertTolerant(double tolerance, double[,] values)
{
for(int c=0; c<values.GetLength(0); c++)
for(int r=0; r<values.GetLength(1); r++)
if(Math.Abs(values[c, r]) > tolerance)
{
System.Diagnostics.Debug.Assert(false);
return;
}
}
//////////////////////////////////////////////
[System.Diagnostics.DebuggerHiddenAttribute()]
public static void Verify(bool condition)
{
System.Diagnostics.Debug.Assert(condition);
}
[System.Diagnostics.Conditional("DEBUG")]
[System.Diagnostics.DebuggerHiddenAttribute()]
public static void AssertOr(params bool[] conditions)
{
foreach(bool condition in conditions)
{
if(condition == true)
{
return;
}
}
System.Diagnostics.Debug.Assert(false);
}
[System.Diagnostics.Conditional("DEBUG")]
[System.Diagnostics.DebuggerHiddenAttribute()]
public static void AssertAnd(params bool[] conditions)
{
bool success = true;
foreach(bool condition in conditions)
{
if(condition == false)
{
success = false;
}
}
System.Diagnostics.Debug.Assert(success);
}
[System.Diagnostics.Conditional("DEBUG")]
[System.Diagnostics.DebuggerHiddenAttribute()]
public static void AssertXor(params bool[] conditions)
{
int numsuccess = 0;
foreach(bool condition in conditions)
{
if(condition == true)
{
numsuccess++;
}
}
System.Diagnostics.Debug.Assert(numsuccess == 1);
}
[System.Diagnostics.Conditional("DEBUG")]
[System.Diagnostics.DebuggerHiddenAttribute()]
public static void AssertIf(bool condition, params bool[] asserts)
{
if(condition)
{
bool assert = true;
for(int i=0; i<asserts.Length; i++)
assert = assert && asserts[i];
Assert(assert);
}
}
static public bool IsDebuggerAttached
{
get
{
return System.Diagnostics.Debugger.IsAttached;
}
}
static public bool IsDebuggerAttachedWithProb(double prob)
{
if(System.Diagnostics.Debugger.IsAttached)
{
Debug.Assert(0<=prob, prob<=1);
double nrand = rand.NextDouble();
return (nrand < prob);
}
return false;
}
[System.Diagnostics.Conditional("DEBUG")]
[System.Diagnostics.DebuggerHiddenAttribute()]
static public void Break()
{
System.Diagnostics.Debugger.Break();
}
[System.Diagnostics.Conditional("DEBUG")]
[System.Diagnostics.DebuggerHiddenAttribute()]
static public void Break(params bool[] conditions)
{
BreakOr(conditions);
}
[System.Diagnostics.Conditional("DEBUG")]
[System.Diagnostics.DebuggerHiddenAttribute()]
static public void BreakAnd(params bool[] conditions)
{
if(conditions.Length >= 1)
{
bool dobreak = true;
foreach(bool condition in conditions)
dobreak = dobreak && condition;
if(dobreak)
System.Diagnostics.Debugger.Break();
}
}
[System.Diagnostics.Conditional("DEBUG")]
[System.Diagnostics.DebuggerHiddenAttribute()]
static public void BreakOr(params bool[] conditions)
{
if(conditions.Length >= 1)
{
bool dobreak = false;
foreach(bool condition in conditions)
dobreak = dobreak || condition;
if(dobreak)
System.Diagnostics.Debugger.Break();
}
}
[System.Diagnostics.Conditional("DEBUG")]
[System.Diagnostics.DebuggerHiddenAttribute()]
static public void ToDo(params string[] todos)
{
foreach(string todo in todos)
System.Console.Error.WriteLine("TODO: " + todo);
Break();
}
public static class Trace
{
public static bool AutoFlush { set{ System.Diagnostics.Trace.AutoFlush = value; } get{ return System.Diagnostics.Trace.AutoFlush ; } }
public static int IndentLevel { set{ System.Diagnostics.Trace.IndentLevel = value; } get{ return System.Diagnostics.Trace.IndentLevel; } }
public static int IndentSize { set{ System.Diagnostics.Trace.IndentSize = value; } get{ return System.Diagnostics.Trace.IndentSize ; } }
public static System.Diagnostics.CorrelationManager CorrelationManager { get{ return System.Diagnostics.Trace.CorrelationManager; } }
public static System.Diagnostics.TraceListenerCollection Listeners { get{ return System.Diagnostics.Trace.Listeners ; } }
[System.Diagnostics.Conditional("TRACE")] public static void Flush() { System.Diagnostics.Trace.Flush(); }
[System.Diagnostics.Conditional("TRACE")] public static void Indent() { System.Diagnostics.Trace.Indent(); }
[System.Diagnostics.Conditional("TRACE")] public static void Unindent() { System.Diagnostics.Trace.Unindent(); }
public static void Refresh() { System.Diagnostics.Trace.Refresh(); }
[System.Diagnostics.Conditional("TRACE")] public static void Write(object value) { System.Diagnostics.Trace.Write(value); }
[System.Diagnostics.Conditional("TRACE")] public static void Write(string message) { System.Diagnostics.Trace.Write(message); }
[System.Diagnostics.Conditional("TRACE")] public static void Write(object value, string category) { System.Diagnostics.Trace.Write(value, category); }
[System.Diagnostics.Conditional("TRACE")] public static void Write(string message, string category) { System.Diagnostics.Trace.Write(message, category); }
[System.Diagnostics.Conditional("TRACE")] public static void WriteIf(bool condition, object value) { System.Diagnostics.Trace.WriteIf(condition, value); }
[System.Diagnostics.Conditional("TRACE")] public static void WriteIf(bool condition, string message) { System.Diagnostics.Trace.WriteIf(condition, message); }
[System.Diagnostics.Conditional("TRACE")] public static void WriteIf(bool condition, object value, string category) { System.Diagnostics.Trace.WriteIf(condition, value, category); }
[System.Diagnostics.Conditional("TRACE")] public static void WriteIf(bool condition, string message, string category) { System.Diagnostics.Trace.WriteIf(condition, message, category); }
[System.Diagnostics.Conditional("TRACE")] public static void WriteLine(object value) { System.Diagnostics.Trace.WriteLine(value); }
[System.Diagnostics.Conditional("TRACE")] public static void WriteLine(string message) { System.Diagnostics.Trace.WriteLine(message); }
[System.Diagnostics.Conditional("TRACE")] public static void WriteLine(object value, string category) { System.Diagnostics.Trace.WriteLine(value, category); }
[System.Diagnostics.Conditional("TRACE")] public static void WriteLine(string message, string category) { System.Diagnostics.Trace.WriteLine(message, category); }
[System.Diagnostics.Conditional("TRACE")] public static void WriteLineIf(bool condition, object value) { System.Diagnostics.Trace.WriteLineIf(condition, value); }
[System.Diagnostics.Conditional("TRACE")] public static void WriteLineIf(bool condition, string message) { System.Diagnostics.Trace.WriteLineIf(condition, message); }
[System.Diagnostics.Conditional("TRACE")] public static void WriteLineIf(bool condition, object value, string category) { System.Diagnostics.Trace.WriteLineIf(condition, value, category); }
[System.Diagnostics.Conditional("TRACE")] public static void WriteLineIf(bool condition, string message, string category) { System.Diagnostics.Trace.WriteLineIf(condition, message, category); }
}
public static class TraceFile
{
static System.IO.StreamWriter writer = System.IO.File.CreateText("TRACE.TXT");
//[System.Diagnostics.Conditional("TRACE")] public static void Write(object value) { writer.Write(value); writer.Flush(); }
[System.Diagnostics.Conditional("TRACE")] public static void Write(string message) { writer.Write(message); writer.Flush(); }
//[System.Diagnostics.Conditional("TRACE")] public static void Write(object value, string category) { writer.Write(value, category); writer.Flush(); }
[System.Diagnostics.Conditional("TRACE")] public static void Write(string message, string category) { writer.Write(message, category); writer.Flush(); }
//[System.Diagnostics.Conditional("TRACE")] public static void WriteIf(bool condition, object value) { writer.WriteIf(condition, value); writer.Flush(); }
//[System.Diagnostics.Conditional("TRACE")] public static void WriteIf(bool condition, string message) { writer.WriteIf(condition, message); writer.Flush(); }
//[System.Diagnostics.Conditional("TRACE")] public static void WriteIf(bool condition, object value, string category) { writer.WriteIf(condition, value, category); writer.Flush(); }
//[System.Diagnostics.Conditional("TRACE")] public static void WriteIf(bool condition, string message, string category) { writer.WriteIf(condition, message, category); writer.Flush(); }
//[System.Diagnostics.Conditional("TRACE")] public static void WriteLine(object value) { writer.WriteLine(value); writer.Flush(); }
[System.Diagnostics.Conditional("TRACE")] public static void WriteLine(string message) { writer.WriteLine(message); writer.Flush(); }
//[System.Diagnostics.Conditional("TRACE")] public static void WriteLine(object value, string category) { writer.WriteLine(value, category); writer.Flush(); }
[System.Diagnostics.Conditional("TRACE")] public static void WriteLine(string message, string category) { writer.WriteLine(message, category); writer.Flush(); }
//[System.Diagnostics.Conditional("TRACE")] public static void WriteLineIf(bool condition, object value) { writer.WriteLineIf(condition, value); writer.Flush(); }
//[System.Diagnostics.Conditional("TRACE")] public static void WriteLineIf(bool condition, string message) { writer.WriteLineIf(condition, message); writer.Flush(); }
//[System.Diagnostics.Conditional("TRACE")] public static void WriteLineIf(bool condition, object value, string category) { writer.WriteLineIf(condition, value, category); writer.Flush(); }
//[System.Diagnostics.Conditional("TRACE")] public static void WriteLineIf(bool condition, string message, string category) { writer.WriteLineIf(condition, message, category); writer.Flush(); }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Diagnostics;
namespace CheckComboBoxTest {
public class CheckedComboBox : ComboBox {
protected override void OnMouseDown( MouseEventArgs e )
{
base.OnMouseDown( e );
this.DroppedDown = false;
}
/// <summary>
/// Internal class to represent the dropdown list of the CheckedComboBox
/// </summary>
internal class Dropdown : Form {
// ---------------------------------- internal class CCBoxEventArgs --------------------------------------------
/// <summary>
/// Custom EventArgs encapsulating value as to whether the combo box value(s) should be assignd to or not.
/// </summary>
internal class CCBoxEventArgs : EventArgs {
private bool assignValues;
public bool AssignValues {
get { return assignValues; }
set { assignValues = value; }
}
private EventArgs e;
public EventArgs EventArgs {
get { return e; }
set { e = value; }
}
public CCBoxEventArgs(EventArgs e, bool assignValues) : base() {
this.e = e;
this.assignValues = assignValues;
}
}
// ---------------------------------- internal class CustomCheckedListBox --------------------------------------------
/// <summary>
/// A custom CheckedListBox being shown within the dropdown form representing the dropdown list of the CheckedComboBox.
/// </summary>
internal class CustomCheckedListBox : CheckedListBox {
private int curSelIndex = -1;
public CustomCheckedListBox() : base() {
this.SelectionMode = SelectionMode.One;
this.HorizontalScrollbar = true;
}
/// <summary>
/// Intercepts the keyboard input, [Enter] confirms a selection and [Esc] cancels it.
/// </summary>
/// <param name="e">The Key event arguments</param>
protected override void OnKeyDown(KeyEventArgs e) {
if (e.KeyCode == Keys.Enter) {
// Enact selection.
((CheckedComboBox.Dropdown) Parent).OnDeactivate(new CCBoxEventArgs(null, true));
e.Handled = true;
} else if (e.KeyCode == Keys.Escape) {
// Cancel selection.
((CheckedComboBox.Dropdown) Parent).OnDeactivate(new CCBoxEventArgs(null, false));
e.Handled = true;
} else if (e.KeyCode == Keys.Delete) {
// Delete unckecks all, [Shift + Delete] checks all.
for (int i = 0; i < Items.Count; i++) {
SetItemChecked(i, e.Shift);
}
e.Handled = true;
}
// If no Enter or Esc keys presses, let the base class handle it.
base.OnKeyDown(e);
}
protected override void OnMouseMove(MouseEventArgs e) {
base.OnMouseMove(e);
int index = IndexFromPoint(e.Location);
Debug.WriteLine("Mouse over item: " + (index >= 0 ? GetItemText(Items[index]) : "None"));
if ((index >= 0) && (index != curSelIndex)) {
curSelIndex = index;
SetSelected(index, true);
}
}
} // end internal class CustomCheckedListBox
// --------------------------------------------------------------------------------------------------------
// ********************************************* Data *********************************************
private CheckedComboBox ccbParent;
// Keeps track of whether checked item(s) changed, hence the value of the CheckedComboBox as a whole changed.
// This is simply done via maintaining the old string-representation of the value(s) and the new one and comparing them!
private string oldStrValue = "";
public bool ValueChanged {
get {
string newStrValue = ccbParent.Text;
if ((oldStrValue.Length > 0) && (newStrValue.Length > 0)) {
return (oldStrValue.CompareTo(newStrValue) != 0);
} else {
return (oldStrValue.Length != newStrValue.Length);
}
}
}
// Array holding the checked states of the items. This will be used to reverse any changes if user cancels selection.
bool[] checkedStateArr;
// Whether the dropdown is closed.
private bool dropdownClosed = true;
private CustomCheckedListBox cclb;
public CustomCheckedListBox List {
get { return cclb; }
set { cclb = value; }
}
// ********************************************* Construction *********************************************
public Dropdown(CheckedComboBox ccbParent) {
this.ccbParent = ccbParent;
InitializeComponent();
this.ShowInTaskbar = false;
// Add a handler to notify our parent of ItemCheck events.
this.cclb.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.cclb_ItemCheck);
}
// ********************************************* Methods *********************************************
// Create a CustomCheckedListBox which fills up the entire form area.
private void InitializeComponent() {
this.cclb = new CustomCheckedListBox();
this.SuspendLayout();
//
// cclb
//
this.cclb.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.cclb.Dock = System.Windows.Forms.DockStyle.Fill;
this.cclb.FormattingEnabled = true;
this.cclb.Location = new System.Drawing.Point(0, 0);
this.cclb.Name = "cclb";
this.cclb.Size = new System.Drawing.Size(47, 15);
this.cclb.TabIndex = 0;
//
// Dropdown
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Menu;
this.ClientSize = new System.Drawing.Size(47, 16);
this.ControlBox = false;
this.Controls.Add(this.cclb);
this.ForeColor = System.Drawing.SystemColors.ControlText;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.MinimizeBox = false;
this.Name = "ccbParent";
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.ResumeLayout(false);
}
public string GetCheckedItemsStringValue() {
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < cclb.CheckedItems.Count; i++) {
sb.Append(cclb.GetItemText(cclb.CheckedItems[i])).Append(ccbParent.ValueSeparator);
}
if (sb.Length > 0) {
sb.Remove(sb.Length - ccbParent.ValueSeparator.Length, ccbParent.ValueSeparator.Length);
}
return sb.ToString();
}
/// <summary>
/// Closes the dropdown portion and enacts any changes according to the specified boolean parameter.
/// NOTE: even though the caller might ask for changes to be enacted, this doesn't necessarily mean
/// that any changes have occurred as such. Caller should check the ValueChanged property of the
/// CheckedComboBox (after the dropdown has closed) to determine any actual value changes.
/// </summary>
/// <param name="enactChanges"></param>
public void CloseDropdown(bool enactChanges) {
if (dropdownClosed) {
return;
}
Debug.WriteLine("CloseDropdown");
// Perform the actual selection and display of checked items.
if (enactChanges) {
ccbParent.SelectedIndex = -1;
// Set the text portion equal to the string comprising all checked items (if any, otherwise empty!).
ccbParent.Text = GetCheckedItemsStringValue();
} else {
// Caller cancelled selection - need to restore the checked items to their original state.
for (int i = 0; i < cclb.Items.Count; i++) {
cclb.SetItemChecked(i, checkedStateArr[i]);
}
}
// From now on the dropdown is considered closed. We set the flag here to prevent OnDeactivate() calling
// this method once again after hiding this window.
dropdownClosed = true;
// Set the focus to our parent CheckedComboBox and hide the dropdown check list.
ccbParent.Focus();
this.Hide();
// Notify CheckedComboBox that its dropdown is closed. (NOTE: it does not matter which parameters we pass to
// OnDropDownClosed() as long as the argument is CCBoxEventArgs so that the method knows the notification has
// come from our code and not from the framework).
ccbParent.OnDropDownClosed(new CCBoxEventArgs(null, false));
}
protected override void OnActivated(EventArgs e) {
Debug.WriteLine("OnActivated");
base.OnActivated(e);
dropdownClosed = false;
// Assign the old string value to compare with the new value for any changes.
oldStrValue = ccbParent.Text;
// Make a copy of the checked state of each item, in cace caller cancels selection.
checkedStateArr = new bool[cclb.Items.Count];
for (int i = 0; i < cclb.Items.Count; i++) {
checkedStateArr[i] = cclb.GetItemChecked(i);
}
}
protected override void OnDeactivate(EventArgs e) {
Debug.WriteLine("OnDeactivate");
base.OnDeactivate(e);
CCBoxEventArgs ce = e as CCBoxEventArgs;
if (ce != null) {
CloseDropdown(ce.AssignValues);
} else {
// If not custom event arguments passed, means that this method was called from the
// framework. We assume that the checked values should be registered regardless.
CloseDropdown(true);
}
}
private void cclb_ItemCheck(object sender, ItemCheckEventArgs e) {
if (ccbParent.ItemCheck != null) {
ccbParent.ItemCheck(sender, e);
}
}
} // end internal class Dropdown
// ******************************** Data ********************************
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
// A form-derived object representing the drop-down list of the checked combo box.
private Dropdown dropdown;
// The valueSeparator character(s) between the ticked elements as they appear in the
// text portion of the CheckedComboBox.
private string valueSeparator;
public string ValueSeparator {
get { return valueSeparator; }
set { valueSeparator = value; }
}
public bool CheckOnClick {
get { return dropdown.List.CheckOnClick; }
set { dropdown.List.CheckOnClick = value; }
}
public new string DisplayMember {
get { return dropdown.List.DisplayMember; }
set { dropdown.List.DisplayMember = value; }
}
public new CheckedListBox.ObjectCollection Items {
get { return dropdown.List.Items; }
}
public CheckedListBox.CheckedItemCollection CheckedItems {
get { return dropdown.List.CheckedItems; }
}
public CheckedListBox.CheckedIndexCollection CheckedIndices {
get { return dropdown.List.CheckedIndices; }
}
public bool ValueChanged {
get { return dropdown.ValueChanged; }
}
// Event handler for when an item check state changes.
public event ItemCheckEventHandler ItemCheck;
// ******************************** Construction ********************************
public CheckedComboBox() : base() {
// We want to do the drawing of the dropdown.
this.DrawMode = DrawMode.OwnerDrawVariable;
// Default value separator.
this.valueSeparator = ", ";
// This prevents the actual ComboBox dropdown to show, although it's not strickly-speaking necessary.
// But including this remove a slight flickering just before our dropdown appears (which is caused by
// the empty-dropdown list of the ComboBox which is displayed for fractions of a second).
this.DropDownHeight = 1;
// This is the default setting - text portion is editable and user must click the arrow button
// to see the list portion. Although we don't want to allow the user to edit the text portion
// the DropDownList style is not being used because for some reason it wouldn't allow the text
// portion to be programmatically set. Hence we set it as editable but disable keyboard input (see below).
this.DropDownStyle = ComboBoxStyle.DropDown;
this.dropdown = new Dropdown(this);
// CheckOnClick style for the dropdown (NOTE: must be set after dropdown is created).
this.CheckOnClick = true;
}
// ******************************** Operations ********************************
/// <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);
}
protected override void OnDropDown(EventArgs e) {
base.OnDropDown(e);
DoDropDown();
}
private void DoDropDown() {
if (!dropdown.Visible) {
Rectangle rect = RectangleToScreen(this.ClientRectangle);
dropdown.Location = new Point(rect.X, rect.Y + this.Size.Height);
int count = dropdown.List.Items.Count;
if (count > this.MaxDropDownItems) {
count = this.MaxDropDownItems;
} else if (count == 0) {
count = 1;
}
dropdown.Size = new Size(this.Size.Width, (dropdown.List.ItemHeight) * count + 2);
dropdown.Show(this);
}
}
protected override void OnDropDownClosed(EventArgs e) {
// Call the handlers for this event only if the call comes from our code - NOT the framework's!
// NOTE: that is because the events were being fired in a wrong order, due to the actual dropdown list
// of the ComboBox which lies underneath our dropdown and gets involved every time.
if (e is Dropdown.CCBoxEventArgs) {
base.OnDropDownClosed(e);
}
}
protected override void OnKeyDown(KeyEventArgs e) {
if (e.KeyCode == Keys.Down) {
// Signal that the dropdown is "down". This is required so that the behaviour of the dropdown is the same
// when it is a result of user pressing the Down_Arrow (which we handle and the framework wouldn't know that
// the list portion is down unless we tell it so).
// NOTE: all that so the DropDownClosed event fires correctly!
OnDropDown(null);
}
// Make sure that certain keys or combinations are not blocked.
e.Handled = !e.Alt && !(e.KeyCode == Keys.Tab) &&
!((e.KeyCode == Keys.Left) || (e.KeyCode == Keys.Right) || (e.KeyCode == Keys.Home) || (e.KeyCode == Keys.End));
base.OnKeyDown(e);
}
protected override void OnKeyPress(KeyPressEventArgs e) {
e.Handled = true;
base.OnKeyPress(e);
}
public bool GetItemChecked(int index) {
if (index < 0 || index > Items.Count) {
throw new ArgumentOutOfRangeException("index", "value out of range");
} else {
return dropdown.List.GetItemChecked(index);
}
}
public void SetItemChecked(int index, bool isChecked) {
if (index < 0 || index > Items.Count) {
throw new ArgumentOutOfRangeException("index", "value out of range");
} else {
dropdown.List.SetItemChecked(index, isChecked);
// Need to update the Text.
this.Text = dropdown.GetCheckedItemsStringValue();
}
}
public CheckState GetItemCheckState(int index) {
if (index < 0 || index > Items.Count) {
throw new ArgumentOutOfRangeException("index", "value out of range");
} else {
return dropdown.List.GetItemCheckState(index);
}
}
public void SetItemCheckState(int index, CheckState state) {
if (index < 0 || index > Items.Count) {
throw new ArgumentOutOfRangeException("index", "value out of range");
} else {
dropdown.List.SetItemCheckState(index, state);
// Need to update the Text.
this.Text = dropdown.GetCheckedItemsStringValue();
}
}
} // end public class CheckedComboBox
}
| |
using EpisodeInformer.Data;
using EpisodeInformer.Data.Basics;
using EpisodeInformer.LocalClasses;
using EpisodeInformer.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace EpisodeInformer
{
public partial class frmGhostForm : Form
{
private IContainer components = (IContainer)null;
private ContextMenuStrip cmsConMenuStrip;
private ToolStripMenuItem cmiMenuItemExit;
private ToolStripSeparator cmiMenuItemSep1;
private ToolStripMenuItem tlsMenuItemMessage;
private ToolStripMenuItem tlsMenuItemDailyDLMsg;
private ToolStripMenuItem cmiMenuItemBrowse;
private ToolStripMenuItem tlsMenuItemBrowser;
private ToolStripSeparator cmiMenuItemSep3;
private ToolStripMenuItem tlsMenuItemSRIBrowse;
private ToolStripMenuItem tlsMenuItemEPIBrowser;
private ToolStripSeparator tlsSeperator1;
private ToolStripMenuItem tlsMenuItemDLSettings;
private ToolStripMenuItem cmiMenuItemFeeds;
private ToolStripMenuItem tlsMenuItemFeedBrowser;
private ToolStripSeparator tlsSeparator1;
private ToolStripMenuItem tlsMenuItemADDFeed;
private ToolStripSeparator cmiMenuItemSep2;
private ToolStripMenuItem tlsMenuItemFeedManager;
private ToolStripMenuItem cmiMenuItemAbout;
private ToolStripMenuItem tlsMenuItemSeriesLstEmpty;
private ToolStripSeparator tlsSeparator2;
private ToolStripMenuItem tlsMenuItemTodaysDL;
private ToolStripMenuItem tlsMenuItemDLByDay;
private ToolStripMenuItem tlsMenuItemMissedEpisodes;
private ToolStripMenuItem tlsMenuItemMissedEpisodesMsg;
private ToolStripMenuItem cmiMenuItemSettings;
private ToolStripMenuItem tlsmiNotificationEmail;
protected override void Dispose(bool disposing)
{
if (disposing && this.components != null)
this.components.Dispose();
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.components = (IContainer)new Container();
ComponentResourceManager resources = new ComponentResourceManager(typeof(frmGhostForm));
this.cmsConMenuStrip = new ContextMenuStrip(this.components);
this.cmiMenuItemBrowse = new ToolStripMenuItem();
this.tlsMenuItemBrowser = new ToolStripMenuItem();
this.tlsSeperator1 = new ToolStripSeparator();
this.tlsMenuItemSRIBrowse = new ToolStripMenuItem();
this.tlsMenuItemEPIBrowser = new ToolStripMenuItem();
this.tlsMenuItemDLSettings = new ToolStripMenuItem();
this.tlsSeparator2 = new ToolStripSeparator();
this.tlsMenuItemTodaysDL = new ToolStripMenuItem();
this.tlsMenuItemDLByDay = new ToolStripMenuItem();
this.tlsMenuItemMissedEpisodes = new ToolStripMenuItem();
this.cmiMenuItemSep3 = new ToolStripSeparator();
this.cmiMenuItemFeeds = new ToolStripMenuItem();
this.tlsMenuItemFeedBrowser = new ToolStripMenuItem();
this.tlsMenuItemFeedManager = new ToolStripMenuItem();
this.tlsSeparator1 = new ToolStripSeparator();
this.tlsMenuItemADDFeed = new ToolStripMenuItem();
this.cmiMenuItemSep2 = new ToolStripSeparator();
this.tlsMenuItemMessage = new ToolStripMenuItem();
this.tlsMenuItemDailyDLMsg = new ToolStripMenuItem();
this.tlsMenuItemSeriesLstEmpty = new ToolStripMenuItem();
this.tlsMenuItemMissedEpisodesMsg = new ToolStripMenuItem();
this.cmiMenuItemSep1 = new ToolStripSeparator();
this.cmiMenuItemSettings = new ToolStripMenuItem();
this.cmiMenuItemAbout = new ToolStripMenuItem();
this.cmiMenuItemExit = new ToolStripMenuItem();
this.tlsmiNotificationEmail = new ToolStripMenuItem();
this.cmsConMenuStrip.SuspendLayout();
this.SuspendLayout();
this.cmsConMenuStrip.Items.AddRange(new ToolStripItem[9]
{
(ToolStripItem) this.cmiMenuItemBrowse,
(ToolStripItem) this.cmiMenuItemSep3,
(ToolStripItem) this.cmiMenuItemFeeds,
(ToolStripItem) this.cmiMenuItemSep2,
(ToolStripItem) this.tlsMenuItemMessage,
(ToolStripItem) this.cmiMenuItemSep1,
(ToolStripItem) this.cmiMenuItemSettings,
(ToolStripItem) this.cmiMenuItemAbout,
(ToolStripItem) this.cmiMenuItemExit
});
this.cmsConMenuStrip.Name = "cmsConMenuStrip";
this.cmsConMenuStrip.ShowCheckMargin = true;
this.cmsConMenuStrip.ShowImageMargin = false;
this.cmsConMenuStrip.Size = new Size(153, 176);
this.cmiMenuItemBrowse.DropDownItems.AddRange(new ToolStripItem[9]
{
(ToolStripItem) this.tlsMenuItemBrowser,
(ToolStripItem) this.tlsSeperator1,
(ToolStripItem) this.tlsMenuItemSRIBrowse,
(ToolStripItem) this.tlsMenuItemEPIBrowser,
(ToolStripItem) this.tlsMenuItemDLSettings,
(ToolStripItem) this.tlsSeparator2,
(ToolStripItem) this.tlsMenuItemTodaysDL,
(ToolStripItem) this.tlsMenuItemDLByDay,
(ToolStripItem) this.tlsMenuItemMissedEpisodes
});
this.cmiMenuItemBrowse.Name = "cmiMenuItemBrowse";
this.cmiMenuItemBrowse.Size = new Size(152, 22);
this.cmiMenuItemBrowse.Text = "Browse";
this.tlsMenuItemBrowser.Name = "tlsMenuItemBrowser";
this.tlsMenuItemBrowser.Size = new Size(189, 22);
this.tlsMenuItemBrowser.Text = "TvDB.com Browser";
this.tlsMenuItemBrowser.Click += new EventHandler(this.cmiMenuItemBrowser_Click);
this.tlsSeperator1.Name = "tlsSeperator1";
this.tlsSeperator1.Size = new Size(186, 6);
this.tlsMenuItemSRIBrowse.Name = "tlsMenuItemSRIBrowse";
this.tlsMenuItemSRIBrowse.Size = new Size(189, 22);
this.tlsMenuItemSRIBrowse.Text = "Series Browser";
this.tlsMenuItemSRIBrowse.Click += new EventHandler(this.tlsMenuItemSRIBrowse_Click);
this.tlsMenuItemEPIBrowser.Name = "tlsMenuItemEPIBrowser";
this.tlsMenuItemEPIBrowser.Size = new Size(189, 22);
this.tlsMenuItemEPIBrowser.Text = "Episode Browser";
this.tlsMenuItemEPIBrowser.Click += new EventHandler(this.tlsMenuItemEPIBrowser_Click);
this.tlsMenuItemDLSettings.Name = "tlsMenuItemDLSettings";
this.tlsMenuItemDLSettings.Size = new Size(189, 22);
this.tlsMenuItemDLSettings.Text = "Download Settings";
this.tlsMenuItemDLSettings.Click += new EventHandler(this.tlsMenuItemDLSettings_Click);
this.tlsSeparator2.Name = "tlsSeparator2";
this.tlsSeparator2.Size = new Size(186, 6);
this.tlsMenuItemTodaysDL.Name = "tlsMenuItemTodaysDL";
this.tlsMenuItemTodaysDL.Size = new Size(189, 22);
this.tlsMenuItemTodaysDL.Text = "Downloads For Today";
this.tlsMenuItemTodaysDL.Click += new EventHandler(this.tlsMenuItemTodaysDL_Click);
this.tlsMenuItemDLByDay.Name = "tlsMenuItemDLByDay";
this.tlsMenuItemDLByDay.Size = new Size(189, 22);
this.tlsMenuItemDLByDay.Text = "Look For Downloads";
this.tlsMenuItemDLByDay.Click += new EventHandler(this.tlsMenuItemDLByDay_Click);
this.tlsMenuItemMissedEpisodes.Name = "tlsMenuItemMissedEpisodes";
this.tlsMenuItemMissedEpisodes.Size = new Size(189, 22);
this.tlsMenuItemMissedEpisodes.Text = "Missed Episodes";
this.tlsMenuItemMissedEpisodes.Click += new EventHandler(this.tlsMenuItemMissedEpisodes_Click);
this.cmiMenuItemSep3.Name = "cmiMenuItemSep3";
this.cmiMenuItemSep3.Size = new Size(149, 6);
this.cmiMenuItemFeeds.DropDownItems.AddRange(new ToolStripItem[4]
{
(ToolStripItem) this.tlsMenuItemFeedBrowser,
(ToolStripItem) this.tlsMenuItemFeedManager,
(ToolStripItem) this.tlsSeparator1,
(ToolStripItem) this.tlsMenuItemADDFeed
});
this.cmiMenuItemFeeds.Name = "cmiMenuItemFeeds";
this.cmiMenuItemFeeds.Size = new Size(152, 22);
this.cmiMenuItemFeeds.Text = "Feeds";
this.tlsMenuItemFeedBrowser.Name = "tlsMenuItemFeedBrowser";
this.tlsMenuItemFeedBrowser.Size = new Size(154, 22);
this.tlsMenuItemFeedBrowser.Text = "Feed Browser";
this.tlsMenuItemFeedBrowser.Click += new EventHandler(this.tlsMenuItemFeedBrowser_Click);
this.tlsMenuItemFeedManager.Name = "tlsMenuItemFeedManager";
this.tlsMenuItemFeedManager.Size = new Size(154, 22);
this.tlsMenuItemFeedManager.Text = "Feeds Manager";
this.tlsMenuItemFeedManager.Click += new EventHandler(this.tlsMenuItemFeedManager_Click);
this.tlsSeparator1.Name = "tlsSeparator1";
this.tlsSeparator1.Size = new Size(151, 6);
this.tlsMenuItemADDFeed.Name = "tlsMenuItemADDFeed";
this.tlsMenuItemADDFeed.Size = new Size(154, 22);
this.tlsMenuItemADDFeed.Text = "Add Feed";
this.tlsMenuItemADDFeed.Click += new EventHandler(this.tlsMenuItemADDFeed_Click);
this.cmiMenuItemSep2.Name = "cmiMenuItemSep2";
this.cmiMenuItemSep2.Size = new Size(149, 6);
this.tlsMenuItemMessage.DropDownItems.AddRange(new ToolStripItem[3]
{
(ToolStripItem) this.tlsMenuItemDailyDLMsg,
(ToolStripItem) this.tlsMenuItemSeriesLstEmpty,
(ToolStripItem) this.tlsMenuItemMissedEpisodesMsg
});
this.tlsMenuItemMessage.Name = "tlsMenuItemMessage";
this.tlsMenuItemMessage.Size = new Size(152, 22);
this.tlsMenuItemMessage.Text = "Messages";
this.tlsMenuItemDailyDLMsg.Checked = true;
this.tlsMenuItemDailyDLMsg.CheckOnClick = true;
this.tlsMenuItemDailyDLMsg.CheckState = CheckState.Checked;
this.tlsMenuItemDailyDLMsg.Name = "tlsMenuItemDailyDLMsg";
this.tlsMenuItemDailyDLMsg.Size = new Size(211, 22);
this.tlsMenuItemDailyDLMsg.Text = "Daily Download Message";
this.tlsMenuItemDailyDLMsg.Click += new EventHandler(this.tlsMenuItemDailyDLMsg_Click);
this.tlsMenuItemSeriesLstEmpty.Checked = true;
this.tlsMenuItemSeriesLstEmpty.CheckOnClick = true;
this.tlsMenuItemSeriesLstEmpty.CheckState = CheckState.Checked;
this.tlsMenuItemSeriesLstEmpty.Name = "tlsMenuItemSeriesLstEmpty";
this.tlsMenuItemSeriesLstEmpty.Size = new Size(211, 22);
this.tlsMenuItemSeriesLstEmpty.Text = "Series List Empty Message";
this.tlsMenuItemSeriesLstEmpty.Click += new EventHandler(this.tlsMenuItemSeriesLstEmpty_Click);
this.tlsMenuItemMissedEpisodesMsg.Checked = true;
this.tlsMenuItemMissedEpisodesMsg.CheckOnClick = true;
this.tlsMenuItemMissedEpisodesMsg.CheckState = CheckState.Checked;
this.tlsMenuItemMissedEpisodesMsg.Name = "tlsMenuItemMissedEpisodesMsg";
this.tlsMenuItemMissedEpisodesMsg.Size = new Size(211, 22);
this.tlsMenuItemMissedEpisodesMsg.Text = "Missed Episodes Message";
this.tlsMenuItemMissedEpisodesMsg.Click += new EventHandler(this.tlsMenuItemMissedEpisodesMsg_Click);
this.cmiMenuItemSep1.Name = "cmiMenuItemSep1";
this.cmiMenuItemSep1.Size = new Size(149, 6);
this.cmiMenuItemSettings.DropDownItems.AddRange(new ToolStripItem[1]
{
(ToolStripItem) this.tlsmiNotificationEmail
});
this.cmiMenuItemSettings.Name = "cmiMenuItemSettings";
this.cmiMenuItemSettings.Size = new Size(152, 22);
this.cmiMenuItemSettings.Text = "&Settings";
this.cmiMenuItemAbout.Name = "cmiMenuItemAbout";
this.cmiMenuItemAbout.Size = new Size(152, 22);
this.cmiMenuItemAbout.Text = "A&bout";
this.cmiMenuItemAbout.Click += new EventHandler(this.cmiMenuItemAbout_Click);
this.cmiMenuItemExit.Name = "cmiMenuItemExit";
this.cmiMenuItemExit.Size = new Size(152, 22);
this.cmiMenuItemExit.Text = "E&xit";
this.cmiMenuItemExit.Click += new EventHandler(this.cmiMenuItemExit_Click);
this.tlsmiNotificationEmail.Name = "tlsmiNotificationEmail";
this.tlsmiNotificationEmail.Size = new Size(169, 22);
this.tlsmiNotificationEmail.Text = "Notifiaction Email";
this.tlsmiNotificationEmail.Click += new EventHandler(this.tlsmiNotificationEmail_Click);
this.AutoScaleDimensions = new SizeF(6f, 13f);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new Size(293, 187);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = (Icon)resources.GetObject("$this.Icon");
this.MaximizeBox = false;
this.Name = "frmGhostForm";
this.Opacity = 0.0;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "GHOST";
this.FormClosing += new FormClosingEventHandler(this.frmGhostForm_FormClosing);
this.Load += new EventHandler(this.frmGhostForm_Load);
this.Shown += new EventHandler(this.frmGhostForm_Shown);
this.cmsConMenuStrip.ResumeLayout(false);
this.ResumeLayout(false);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.