context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace pony.unity3d.scene.ucore
{
public class PercentPosUCore : global::UnityEngine.MonoBehaviour, global::haxe.lang.IHxObject, global::pony.IPercent
{
public PercentPosUCore(global::haxe.lang.EmptyObject empty) : base()
{
unchecked
{
}
#line default
}
public PercentPosUCore() : base()
{
unchecked
{
#line 16 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
this.percent = ((double) (1) );
}
#line default
}
public static object __hx_createEmpty()
{
unchecked
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return new global::pony.unity3d.scene.ucore.PercentPosUCore(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ));
}
#line default
}
public static object __hx_create(global::Array arr)
{
unchecked
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return new global::pony.unity3d.scene.ucore.PercentPosUCore();
}
#line default
}
public double percent;
public double nullPos;
public double initPos;
public double size;
public virtual void Start()
{
unchecked
{
#line 24 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
this.initPos = ((double) (this.transform.localPosition.y) );
this.size = global::System.Math.Abs(((double) (( (( this.nullPos > this.initPos )) ? (( this.nullPos - this.initPos )) : (( this.initPos - this.nullPos )) )) ));
}
#line default
}
public virtual double _set_percent(double v)
{
unchecked
{
#line 29 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
if (( this.size == 0 ))
{
if (( this.renderer != default(global::UnityEngine.Renderer) ))
{
#line 30 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
this.renderer.enabled = false;
}
return v;
}
#line 33 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
if (( ( v > 0 ) || ( this.renderer == default(global::UnityEngine.Renderer) ) ))
{
this.transform.localPosition = new global::UnityEngine.Vector3(((float) (this.transform.localPosition.x) ), ((float) (( this.nullPos + ( this.size * v ) )) ), ((float) (this.transform.localPosition.z) ));
if (( this.renderer != default(global::UnityEngine.Renderer) ))
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
this.renderer.enabled = true;
}
}
else
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
this.renderer.enabled = false;
}
#line 39 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.percent = v;
}
#line default
}
public virtual bool __hx_deleteField(string field, int hash)
{
unchecked
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return false;
}
#line default
}
public virtual object __hx_lookupField(string field, int hash, bool throwErrors, bool isCheck)
{
unchecked
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
if (isCheck)
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return global::haxe.lang.Runtime.undefined;
}
else
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
if (throwErrors)
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
throw global::haxe.lang.HaxeException.wrap("Field not found.");
}
else
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return default(object);
}
}
}
#line default
}
public virtual double __hx_lookupField_f(string field, int hash, bool throwErrors)
{
unchecked
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
if (throwErrors)
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
throw global::haxe.lang.HaxeException.wrap("Field not found or incompatible field type.");
}
else
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return default(double);
}
}
#line default
}
public virtual object __hx_lookupSetField(string field, int hash, object @value)
{
unchecked
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
throw global::haxe.lang.HaxeException.wrap("Cannot access field for writing.");
}
#line default
}
public virtual double __hx_lookupSetField_f(string field, int hash, double @value)
{
unchecked
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
throw global::haxe.lang.HaxeException.wrap("Cannot access field for writing or incompatible type.");
}
#line default
}
public virtual double __hx_setField_f(string field, int hash, double @value, bool handleProperties)
{
unchecked
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
switch (hash)
{
case 1280549057:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
this.size = ((double) (@value) );
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return @value;
}
case 1267475556:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
this.initPos = ((double) (@value) );
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return @value;
}
case 484509005:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
this.nullPos = ((double) (@value) );
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return @value;
}
case 2027596485:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
if (handleProperties)
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
this._set_percent(@value);
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return @value;
}
else
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
this.percent = ((double) (@value) );
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return @value;
}
}
default:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.__hx_lookupSetField_f(field, hash, @value);
}
}
}
#line default
}
public virtual object __hx_setField(string field, int hash, object @value, bool handleProperties)
{
unchecked
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
switch (hash)
{
case 1575675685:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
this.hideFlags = ((global::UnityEngine.HideFlags) (@value) );
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return @value;
}
case 1224700491:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
this.name = global::haxe.lang.Runtime.toString(@value);
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return @value;
}
case 5790298:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
this.tag = global::haxe.lang.Runtime.toString(@value);
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return @value;
}
case 373703110:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
this.active = ((bool) (@value) );
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return @value;
}
case 2117141633:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
this.enabled = ((bool) (@value) );
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return @value;
}
case 896046654:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
this.useGUILayout = ((bool) (@value) );
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return @value;
}
case 1280549057:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
this.size = ((double) (global::haxe.lang.Runtime.toDouble(@value)) );
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return @value;
}
case 1267475556:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
this.initPos = ((double) (global::haxe.lang.Runtime.toDouble(@value)) );
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return @value;
}
case 484509005:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
this.nullPos = ((double) (global::haxe.lang.Runtime.toDouble(@value)) );
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return @value;
}
case 2027596485:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
if (handleProperties)
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
this._set_percent(((double) (global::haxe.lang.Runtime.toDouble(@value)) ));
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return @value;
}
else
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
this.percent = ((double) (global::haxe.lang.Runtime.toDouble(@value)) );
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return @value;
}
}
default:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.__hx_lookupSetField(field, hash, @value);
}
}
}
#line default
}
public virtual object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties)
{
unchecked
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
switch (hash)
{
case 1826409040:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetType"), ((int) (1826409040) ))) );
}
case 304123084:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("ToString"), ((int) (304123084) ))) );
}
case 276486854:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetInstanceID"), ((int) (276486854) ))) );
}
case 295397041:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetHashCode"), ((int) (295397041) ))) );
}
case 1955029599:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Equals"), ((int) (1955029599) ))) );
}
case 1575675685:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.hideFlags;
}
case 1224700491:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.name;
}
case 294420221:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("SendMessageUpwards"), ((int) (294420221) ))) );
}
case 139469119:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("SendMessage"), ((int) (139469119) ))) );
}
case 967979664:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponentsInChildren"), ((int) (967979664) ))) );
}
case 2122408236:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponents"), ((int) (2122408236) ))) );
}
case 1328964235:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponentInChildren"), ((int) (1328964235) ))) );
}
case 1723652455:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponent"), ((int) (1723652455) ))) );
}
case 89600725:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("CompareTag"), ((int) (89600725) ))) );
}
case 2134927590:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("BroadcastMessage"), ((int) (2134927590) ))) );
}
case 5790298:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.tag;
}
case 373703110:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.active;
}
case 1471506513:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.gameObject;
}
case 1751728597:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.particleSystem;
}
case 524620744:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.particleEmitter;
}
case 964013983:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.hingeJoint;
}
case 1238753076:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.collider;
}
case 674101152:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.guiTexture;
}
case 262266241:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.guiElement;
}
case 1515196979:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.networkView;
}
case 801759432:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.guiText;
}
case 662730966:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.audio;
}
case 853263683:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.renderer;
}
case 1431885287:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.constantForce;
}
case 1261760260:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.animation;
}
case 1962709206:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.light;
}
case 931940005:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.camera;
}
case 1895479501:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.rigidbody;
}
case 1167273324:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.transform;
}
case 2117141633:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.enabled;
}
case 2084823382:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StopCoroutine"), ((int) (2084823382) ))) );
}
case 1856815770:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StopAllCoroutines"), ((int) (1856815770) ))) );
}
case 832859768:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StartCoroutine_Auto"), ((int) (832859768) ))) );
}
case 987108662:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StartCoroutine"), ((int) (987108662) ))) );
}
case 602588383:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("IsInvoking"), ((int) (602588383) ))) );
}
case 1641152943:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("InvokeRepeating"), ((int) (1641152943) ))) );
}
case 1416948632:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Invoke"), ((int) (1416948632) ))) );
}
case 757431474:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("CancelInvoke"), ((int) (757431474) ))) );
}
case 896046654:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.useGUILayout;
}
case 155324904:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("set_percent"), ((int) (155324904) ))) );
}
case 389604418:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Start"), ((int) (389604418) ))) );
}
case 1280549057:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.size;
}
case 1267475556:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.initPos;
}
case 484509005:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.nullPos;
}
case 2027596485:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.percent;
}
default:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.__hx_lookupField(field, hash, throwErrors, isCheck);
}
}
}
#line default
}
public virtual double __hx_getField_f(string field, int hash, bool throwErrors, bool handleProperties)
{
unchecked
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
switch (hash)
{
case 1280549057:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.size;
}
case 1267475556:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.initPos;
}
case 484509005:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.nullPos;
}
case 2027596485:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.percent;
}
default:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this.__hx_lookupField_f(field, hash, throwErrors);
}
}
}
#line default
}
public virtual object __hx_invokeField(string field, int hash, global::Array dynargs)
{
unchecked
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
switch (hash)
{
case 757431474:case 1416948632:case 1641152943:case 602588383:case 987108662:case 832859768:case 1856815770:case 2084823382:case 2134927590:case 89600725:case 1723652455:case 1328964235:case 2122408236:case 967979664:case 139469119:case 294420221:case 1955029599:case 295397041:case 276486854:case 304123084:case 1826409040:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return global::haxe.lang.Runtime.slowCallField(this, field, dynargs);
}
case 155324904:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return this._set_percent(((double) (global::haxe.lang.Runtime.toDouble(dynargs[0])) ));
}
case 389604418:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
this.Start();
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
break;
}
default:
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return ((global::haxe.lang.Function) (this.__hx_getField(field, hash, true, false, false)) ).__hx_invokeDynamic(dynargs);
}
}
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
return default(object);
}
#line default
}
public virtual void __hx_getFields(global::Array<object> baseArr)
{
unchecked
{
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("hideFlags");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("name");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("tag");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("active");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("gameObject");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("particleSystem");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("particleEmitter");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("hingeJoint");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("collider");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("guiTexture");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("guiElement");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("networkView");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("guiText");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("audio");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("renderer");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("constantForce");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("animation");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("light");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("camera");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("rigidbody");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("transform");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("enabled");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("useGUILayout");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("size");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("initPos");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("nullPos");
#line 14 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/PercentPosUCore.hx"
baseArr.push("percent");
}
#line default
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Globalization {
using System;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using Microsoft.Win32;
using PermissionSet = System.Security.PermissionSet;
using System.Security.Permissions;
/*=================================JapaneseCalendar==========================
**
** JapaneseCalendar is based on Gregorian calendar. The month and day values are the same as
** Gregorian calendar. However, the year value is an offset to the Gregorian
** year based on the era.
**
** This system is adopted by Emperor Meiji in 1868. The year value is counted based on the reign of an emperor,
** and the era begins on the day an emperor ascends the throne and continues until his death.
** The era changes at 12:00AM.
**
** For example, the current era is Heisei. It started on 1989/1/8 A.D. Therefore, Gregorian year 1989 is also Heisei 1st.
** 1989/1/8 A.D. is also Heisei 1st 1/8.
**
** Any date in the year during which era is changed can be reckoned in either era. For example,
** 1989/1/1 can be 1/1 Heisei 1st year or 1/1 Showa 64th year.
**
** Note:
** The DateTime can be represented by the JapaneseCalendar are limited to two factors:
** 1. The min value and max value of DateTime class.
** 2. The available era information.
**
** Calendar support range:
** Calendar Minimum Maximum
** ========== ========== ==========
** Gregorian 1868/09/08 9999/12/31
** Japanese Meiji 01/01 Heisei 8011/12/31
============================================================================*/
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class JapaneseCalendar : Calendar
{
internal static readonly DateTime calendarMinValue = new DateTime(1868, 9, 8);
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MinSupportedDateTime
{
get
{
return (calendarMinValue);
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
// Return the type of the Japanese calendar.
//
[System.Runtime.InteropServices.ComVisible(false)]
public override CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.SolarCalendar;
}
}
//
// Using a field initializer rather than a static constructor so that the whole class can be lazy
// init.
static internal volatile EraInfo[] japaneseEraInfo;
//
// Read our era info
//
// m_EraInfo must be listed in reverse chronological order. The most recent era
// should be the first element.
// That is, m_EraInfo[0] contains the most recent era.
//
// We know about 4 built-in eras, however users may add additional era(s) from the
// registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras
//
// Registry values look like:
// yyyy.mm.dd=era_abbrev_english_englishabbrev
//
// Where yyyy.mm.dd is the registry value name, and also the date of the era start.
// yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
// era is the Japanese Era name
// abbrev is the Abbreviated Japanese Era Name
// english is the English name for the Era (unused)
// englishabbrev is the Abbreviated English name for the era.
// . is a delimiter, but the value of . doesn't matter.
// '_' marks the space between the japanese era name, japanese abbreviated era name
// english name, and abbreviated english names.
//
internal static EraInfo[] GetEraInfo()
{
// See if we need to build it
if (japaneseEraInfo == null)
{
// See if we have any eras from the registry
japaneseEraInfo = GetErasFromRegistry();
// See if we have to use the built-in eras
if (japaneseEraInfo == null)
{
// We know about some built-in ranges
EraInfo[] defaultEraRanges = new EraInfo[4];
defaultEraRanges[0] = new EraInfo( 4, 1989, 1, 8, 1988, 1, GregorianCalendar.MaxYear - 1988,
"\x5e73\x6210", "\x5e73", "H"); // era #4 start year/month/day, yearOffset, minEraYear
defaultEraRanges[1] = new EraInfo( 3, 1926, 12, 25, 1925, 1, 1989-1925,
"\x662d\x548c", "\x662d", "S"); // era #3,start year/month/day, yearOffset, minEraYear
defaultEraRanges[2] = new EraInfo( 2, 1912, 7, 30, 1911, 1, 1926-1911,
"\x5927\x6b63", "\x5927", "T"); // era #2,start year/month/day, yearOffset, minEraYear
defaultEraRanges[3] = new EraInfo( 1, 1868, 1, 1, 1867, 1, 1912-1867,
"\x660e\x6cbb", "\x660e", "M"); // era #1,start year/month/day, yearOffset, minEraYear
// Remember the ranges we built
japaneseEraInfo = defaultEraRanges;
}
}
// return the era we found/made
return japaneseEraInfo;
}
#if FEATURE_WIN32_REGISTRY
private const string c_japaneseErasHive = @"System\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras";
private const string c_japaneseErasHivePermissionList = @"HKEY_LOCAL_MACHINE\" + c_japaneseErasHive;
//
// GetErasFromRegistry()
//
// We know about 4 built-in eras, however users may add additional era(s) from the
// registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras
//
// Registry values look like:
// yyyy.mm.dd=era_abbrev_english_englishabbrev
//
// Where yyyy.mm.dd is the registry value name, and also the date of the era start.
// yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
// era is the Japanese Era name
// abbrev is the Abbreviated Japanese Era Name
// english is the English name for the Era (unused)
// englishabbrev is the Abbreviated English name for the era.
// . is a delimiter, but the value of . doesn't matter.
// '_' marks the space between the japanese era name, japanese abbreviated era name
// english name, and abbreviated english names.
[System.Security.SecuritySafeCritical] // auto-generated
private static EraInfo[] GetErasFromRegistry()
{
// Look in the registry key and see if we can find any ranges
int iFoundEras = 0;
EraInfo[] registryEraRanges = null;
try
{
// Need to access registry
PermissionSet permSet = new PermissionSet(PermissionState.None);
permSet.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, c_japaneseErasHivePermissionList));
permSet.Assert();
RegistryKey key = RegistryKey.GetBaseKey(RegistryKey.HKEY_LOCAL_MACHINE).OpenSubKey(c_japaneseErasHive, false);
// Abort if we didn't find anything
if (key == null) return null;
// Look up the values in our reg key
String[] valueNames = key.GetValueNames();
if (valueNames != null && valueNames.Length > 0)
{
registryEraRanges = new EraInfo[valueNames.Length];
// Loop through the registry and read in all the values
for (int i = 0; i < valueNames.Length; i++)
{
// See if the era is a valid date
EraInfo era = GetEraFromValue(valueNames[i], key.GetValue(valueNames[i]).ToString());
// continue if not valid
if (era == null) continue;
// Remember we found one.
registryEraRanges[iFoundEras] = era;
iFoundEras++;
}
}
}
catch (System.Security.SecurityException)
{
// If we weren't allowed to read, then just ignore the error
return null;
}
catch (System.IO.IOException)
{
// If key is being deleted just ignore the error
return null;
}
catch (System.UnauthorizedAccessException)
{
// Registry access rights permissions, just ignore the error
return null;
}
//
// If we didn't have valid eras, then fail
// should have at least 4 eras
//
if (iFoundEras < 4) return null;
//
// Now we have eras, clean them up.
//
// Clean up array length
Array.Resize(ref registryEraRanges, iFoundEras);
// Sort them
Array.Sort(registryEraRanges, CompareEraRanges);
// Clean up era information
for (int i = 0; i < registryEraRanges.Length; i++)
{
// eras count backwards from length to 1 (and are 1 based indexes into string arrays)
registryEraRanges[i].era = registryEraRanges.Length - i;
// update max era year
if (i == 0)
{
// First range is 'til the end of the calendar
registryEraRanges[0].maxEraYear = GregorianCalendar.MaxYear - registryEraRanges[0].yearOffset;
}
else
{
// Rest are until the next era (remember most recent era is first in array)
registryEraRanges[i].maxEraYear = registryEraRanges[i-1].yearOffset + 1 - registryEraRanges[i].yearOffset;
}
}
// Return our ranges
return registryEraRanges;
}
#else
private static EraInfo[] GetErasFromRegistry()
{
return null;
}
#endif
//
// Compare two era ranges, eg just the ticks
// Remember the era array is supposed to be in reverse chronological order
//
private static int CompareEraRanges(EraInfo a, EraInfo b)
{
return b.ticks.CompareTo(a.ticks);
}
//
// GetEraFromValue
//
// Parse the registry value name/data pair into an era
//
// Registry values look like:
// yyyy.mm.dd=era_abbrev_english_englishabbrev
//
// Where yyyy.mm.dd is the registry value name, and also the date of the era start.
// yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
// era is the Japanese Era name
// abbrev is the Abbreviated Japanese Era Name
// english is the English name for the Era (unused)
// englishabbrev is the Abbreviated English name for the era.
// . is a delimiter, but the value of . doesn't matter.
// '_' marks the space between the japanese era name, japanese abbreviated era name
// english name, and abbreviated english names.
private static EraInfo GetEraFromValue(String value, String data)
{
// Need inputs
if (value == null || data == null) return null;
//
// Get Date
//
// Need exactly 10 characters in name for date
// yyyy.mm.dd although the . can be any character
if (value.Length != 10) return null;
int year;
int month;
int day;
if (!Number.TryParseInt32(value.Substring(0,4), NumberStyles.None, NumberFormatInfo.InvariantInfo, out year) ||
!Number.TryParseInt32(value.Substring(5,2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out month) ||
!Number.TryParseInt32(value.Substring(8,2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out day))
{
// Couldn't convert integer, fail
return null;
}
//
// Get Strings
//
// Needs to be a certain length e_a_E_A at least (7 chars, exactly 4 groups)
String[] names = data.Split(new char[] {'_'});
// Should have exactly 4 parts
// 0 - Era Name
// 1 - Abbreviated Era Name
// 2 - English Era Name
// 3 - Abbreviated English Era Name
if (names.Length != 4) return null;
// Each part should have data in it
if (names[0].Length == 0 ||
names[1].Length == 0 ||
names[2].Length == 0 ||
names[3].Length == 0)
return null;
//
// Now we have an era we can build
// Note that the era # and max era year need cleaned up after sorting
// Don't use the full English Era Name (names[2])
//
return new EraInfo( 0, year, month, day, year - 1, 1, 0,
names[0], names[1], names[3]);
}
internal static volatile Calendar s_defaultInstance;
internal GregorianCalendarHelper helper;
/*=================================GetDefaultInstance==========================
**Action: Internal method to provide a default intance of JapaneseCalendar. Used by NLS+ implementation
** and other calendars.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
internal static Calendar GetDefaultInstance() {
if (s_defaultInstance == null) {
s_defaultInstance = new JapaneseCalendar();
}
return (s_defaultInstance);
}
public JapaneseCalendar() {
try {
new CultureInfo("ja-JP");
} catch (ArgumentException e) {
throw new TypeInitializationException(this.GetType().FullName, e);
}
helper = new GregorianCalendarHelper(this, GetEraInfo());
}
internal override int ID {
get {
return (CAL_JAPAN);
}
}
public override DateTime AddMonths(DateTime time, int months) {
return (helper.AddMonths(time, months));
}
public override DateTime AddYears(DateTime time, int years) {
return (helper.AddYears(time, years));
}
/*=================================GetDaysInMonth==========================
**Action: Returns the number of days in the month given by the year and month arguments.
**Returns: The number of days in the given month.
**Arguments:
** year The year in Japanese calendar.
** month The month
** era The Japanese era value.
**Exceptions
** ArgumentException If month is less than 1 or greater * than 12.
============================================================================*/
public override int GetDaysInMonth(int year, int month, int era) {
return (helper.GetDaysInMonth(year, month, era));
}
public override int GetDaysInYear(int year, int era) {
return (helper.GetDaysInYear(year, era));
}
public override int GetDayOfMonth(DateTime time) {
return (helper.GetDayOfMonth(time));
}
public override DayOfWeek GetDayOfWeek(DateTime time) {
return (helper.GetDayOfWeek(time));
}
public override int GetDayOfYear(DateTime time)
{
return (helper.GetDayOfYear(time));
}
public override int GetMonthsInYear(int year, int era)
{
return (helper.GetMonthsInYear(year, era));
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
return (helper.GetWeekOfYear(time, rule, firstDayOfWeek));
}
/*=================================GetEra==========================
**Action: Get the era value of the specified time.
**Returns: The era value for the specified time.
**Arguments:
** time the specified date time.
**Exceptions: ArgumentOutOfRangeException if time is out of the valid era ranges.
============================================================================*/
public override int GetEra(DateTime time) {
return (helper.GetEra(time));
}
public override int GetMonth(DateTime time) {
return (helper.GetMonth(time));
}
public override int GetYear(DateTime time) {
return (helper.GetYear(time));
}
public override bool IsLeapDay(int year, int month, int day, int era)
{
return (helper.IsLeapDay(year, month, day, era));
}
public override bool IsLeapYear(int year, int era) {
return (helper.IsLeapYear(year, era));
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetLeapMonth(int year, int era)
{
return (helper.GetLeapMonth(year, era));
}
public override bool IsLeapMonth(int year, int month, int era) {
return (helper.IsLeapMonth(year, month, era));
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) {
return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era));
}
// For Japanese calendar, four digit year is not used. Few emperors will live for more than one hundred years.
// Therefore, for any two digit number, we just return the original number.
public override int ToFourDigitYear(int year) {
if (year <= 0) {
throw new ArgumentOutOfRangeException("year",
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
Contract.EndContractBlock();
if (year > helper.MaxYear) {
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
1,
helper.MaxYear));
}
return (year);
}
public override int[] Eras {
get {
return (helper.Eras);
}
}
//
// Return the various era strings
// Note: The arrays are backwards of the eras
//
internal static String[] EraNames()
{
EraInfo[] eras = GetEraInfo();
String[] eraNames = new String[eras.Length];
for (int i = 0; i < eras.Length; i++)
{
// Strings are in chronological order, eras are backwards order.
eraNames[i] = eras[eras.Length - i - 1].eraName;
}
return eraNames;
}
internal static String[] AbbrevEraNames()
{
EraInfo[] eras = GetEraInfo();
String[] erasAbbrev = new String[eras.Length];
for (int i = 0; i < eras.Length; i++)
{
// Strings are in chronological order, eras are backwards order.
erasAbbrev[i] = eras[eras.Length - i - 1].abbrevEraName;
}
return erasAbbrev;
}
internal static String[] EnglishEraNames()
{
EraInfo[] eras = GetEraInfo();
String[] erasEnglish = new String[eras.Length];
for (int i = 0; i < eras.Length; i++)
{
// Strings are in chronological order, eras are backwards order.
erasEnglish[i] = eras[eras.Length - i - 1].englishEraName;
}
return erasEnglish;
}
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 99;
internal override bool IsValidYear(int year, int era) {
return helper.IsValidYear(year, era);
}
public override int TwoDigitYearMax {
get {
if (twoDigitYearMax == -1) {
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
set {
VerifyWritable();
if (value < 99 || value > helper.MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
99,
helper.MaxYear));
}
twoDigitYearMax = value;
}
}
}
}
| |
namespace android.speech
{
[global::MonoJavaBridge.JavaClass()]
public partial class RecognizerIntent : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static RecognizerIntent()
{
InitJNI();
}
protected RecognizerIntent(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _getVoiceDetailsIntent7308;
public static global::android.content.Intent getVoiceDetailsIntent(android.content.Context arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.speech.RecognizerIntent.staticClass, global::android.speech.RecognizerIntent._getVoiceDetailsIntent7308, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.Intent;
}
public static global::java.lang.String EXTRA_CALLING_PACKAGE
{
get
{
return "calling_package";
}
}
public static global::java.lang.String ACTION_RECOGNIZE_SPEECH
{
get
{
return "android.speech.action.RECOGNIZE_SPEECH";
}
}
public static global::java.lang.String ACTION_WEB_SEARCH
{
get
{
return "android.speech.action.WEB_SEARCH";
}
}
public static global::java.lang.String EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS
{
get
{
return "android.speech.extras.SPEECH_INPUT_MINIMUM_LENGTH_MILLIS";
}
}
public static global::java.lang.String EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS
{
get
{
return "android.speech.extras.SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS";
}
}
public static global::java.lang.String EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS
{
get
{
return "android.speech.extras.SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS";
}
}
public static global::java.lang.String EXTRA_LANGUAGE_MODEL
{
get
{
return "android.speech.extra.LANGUAGE_MODEL";
}
}
public static global::java.lang.String LANGUAGE_MODEL_FREE_FORM
{
get
{
return "free_form";
}
}
public static global::java.lang.String LANGUAGE_MODEL_WEB_SEARCH
{
get
{
return "web_search";
}
}
public static global::java.lang.String EXTRA_PROMPT
{
get
{
return "android.speech.extra.PROMPT";
}
}
public static global::java.lang.String EXTRA_LANGUAGE
{
get
{
return "android.speech.extra.LANGUAGE";
}
}
public static global::java.lang.String EXTRA_MAX_RESULTS
{
get
{
return "android.speech.extra.MAX_RESULTS";
}
}
public static global::java.lang.String EXTRA_PARTIAL_RESULTS
{
get
{
return "android.speech.extra.PARTIAL_RESULTS";
}
}
public static global::java.lang.String EXTRA_RESULTS_PENDINGINTENT
{
get
{
return "android.speech.extra.RESULTS_PENDINGINTENT";
}
}
public static global::java.lang.String EXTRA_RESULTS_PENDINGINTENT_BUNDLE
{
get
{
return "android.speech.extra.RESULTS_PENDINGINTENT_BUNDLE";
}
}
public static int RESULT_NO_MATCH
{
get
{
return 1;
}
}
public static int RESULT_CLIENT_ERROR
{
get
{
return 2;
}
}
public static int RESULT_SERVER_ERROR
{
get
{
return 3;
}
}
public static int RESULT_NETWORK_ERROR
{
get
{
return 4;
}
}
public static int RESULT_AUDIO_ERROR
{
get
{
return 5;
}
}
public static global::java.lang.String EXTRA_RESULTS
{
get
{
return "android.speech.extra.RESULTS";
}
}
public static global::java.lang.String DETAILS_META_DATA
{
get
{
return "android.speech.DETAILS";
}
}
public static global::java.lang.String ACTION_GET_LANGUAGE_DETAILS
{
get
{
return "android.speech.action.GET_LANGUAGE_DETAILS";
}
}
public static global::java.lang.String EXTRA_ONLY_RETURN_LANGUAGE_PREFERENCE
{
get
{
return "android.speech.extra.ONLY_RETURN_LANGUAGE_PREFERENCE";
}
}
public static global::java.lang.String EXTRA_LANGUAGE_PREFERENCE
{
get
{
return "android.speech.extra.LANGUAGE_PREFERENCE";
}
}
public static global::java.lang.String EXTRA_SUPPORTED_LANGUAGES
{
get
{
return "android.speech.extra.SUPPORTED_LANGUAGES";
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.speech.RecognizerIntent.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/speech/RecognizerIntent"));
global::android.speech.RecognizerIntent._getVoiceDetailsIntent7308 = @__env.GetStaticMethodIDNoThrow(global::android.speech.RecognizerIntent.staticClass, "getVoiceDetailsIntent", "(Landroid/content/Context;)Landroid/content/Intent;");
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Exceptions;
using Microsoft.Build.Shared;
using Microsoft.Build.Utilities;
using Shouldly;
using Xunit;
namespace Microsoft.Build.UnitTests
{
public class ScannerTest
{
private MockElementLocation _elementLocation = MockElementLocation.Instance;
/// <summary>
/// Tests that we give a useful error position (not 0 for example)
/// </summary>
[Fact]
public void ErrorPosition()
{
string[,] tests = {
{ "1==1.1.", "7", "AllowAll"}, // Position of second '.'
{ "1==0xFG", "7", "AllowAll"}, // Position of G
{ "1==-0xF", "6", "AllowAll"}, // Position of x
{ "1234=5678", "6", "AllowAll"}, // Position of '5'
{ " ", "2", "AllowAll"}, // Position of End of Input
{ " (", "3", "AllowAll"}, // Position of End of Input
{ " false or ", "12", "AllowAll"}, // Position of End of Input
{ " \"foo", "2", "AllowAll"}, // Position of open quote
{ " @(foo", "2", "AllowAll"}, // Position of @
{ " @(", "2", "AllowAll"}, // Position of @
{ " $", "2", "AllowAll"}, // Position of $
{ " $(foo", "2", "AllowAll"}, // Position of $
{ " $(", "2", "AllowAll"}, // Position of $
{ " $", "2", "AllowAll"}, // Position of $
{ " @(foo)", "2", "AllowProperties"}, // Position of @
{ " '@(foo)'", "3", "AllowProperties"}, // Position of @
/* test escaped chars: message shows them escaped so count should include them */
{ "'%24%28x' == '%24(x''", "21", "AllowAll"} // Position of extra quote
};
// Some errors are caught by the Parser, not merely by the Lexer/Scanner. So we have to do a full Parse,
// rather than just calling AdvanceToScannerError(). (The error location is still supplied by the Scanner.)
for (int i = 0; i < tests.GetLength(0); i++)
{
Parser parser = null;
try
{
parser = new Parser();
ParserOptions options = (ParserOptions)Enum.Parse(typeof(ParserOptions), tests[i, 2], true /* case-insensitive */);
parser.Parse(tests[i, 0], options, _elementLocation);
}
catch (InvalidProjectFileException ex)
{
Console.WriteLine(ex.Message);
Assert.Equal(Convert.ToInt32(tests[i, 1]), parser.errorPosition);
}
}
}
/// <summary>
/// Advance to the point of the lexer error. If the error is only caught by the parser, this isn't useful.
/// </summary>
/// <param name="lexer"></param>
private void AdvanceToScannerError(Scanner lexer)
{
while (lexer.Advance() && !lexer.IsNext(Token.TokenType.EndOfInput));
}
/// <summary>
/// Tests the special error for "=".
/// </summary>
[Fact]
public void SingleEquals()
{
Scanner lexer = new Scanner("a=b", ParserOptions.AllowProperties);
AdvanceToScannerError(lexer);
Assert.Equal("IllFormedEqualsInCondition", lexer.GetErrorResource());
Assert.Equal("b", lexer.UnexpectedlyFound);
}
/// <summary>
/// Tests the special errors for "$(" and "$x" and similar cases
/// </summary>
[Fact]
public void IllFormedProperty()
{
Scanner lexer = new Scanner("$(", ParserOptions.AllowProperties);
AdvanceToScannerError(lexer);
Assert.Equal("IllFormedPropertyCloseParenthesisInCondition", lexer.GetErrorResource());
lexer = new Scanner("$x", ParserOptions.AllowProperties);
AdvanceToScannerError(lexer);
Assert.Equal("IllFormedPropertyOpenParenthesisInCondition", lexer.GetErrorResource());
}
/// <summary>
/// Tests the space errors case
/// </summary>
[Theory]
[InlineData("$(x )")]
[InlineData("$( x)")]
[InlineData("$([MSBuild]::DoSomething($(space ))")]
[InlineData("$([MSBuild]::DoSomething($(_space ))")]
public void SpaceProperty(string pattern)
{
Scanner lexer = new Scanner(pattern, ParserOptions.AllowProperties);
AdvanceToScannerError(lexer);
Assert.Equal("IllFormedPropertySpaceInCondition", lexer.GetErrorResource());
}
/// <summary>
/// Tests the space not next to end so no errors case
/// </summary>
[Theory]
[InlineData("$(x.StartsWith( 'y' ))")]
[InlineData("$(x.StartsWith ('y'))")]
[InlineData("$( x.StartsWith( $(SpacelessProperty) ) )")]
[InlineData("$( x.StartsWith( $(_SpacelessProperty) ) )")]
[InlineData("$(x.StartsWith('Foo', StringComparison.InvariantCultureIgnoreCase))")]
public void SpaceInMiddleOfProperty(string pattern)
{
Scanner lexer = new Scanner(pattern, ParserOptions.AllowProperties);
AdvanceToScannerError(lexer);
lexer._errorState.ShouldBeFalse();
}
[Fact]
public void SpacePropertyOptOutWave16_10()
{
using TestEnvironment env = TestEnvironment.Create();
ChangeWaves.ResetStateForTests();
env.SetEnvironmentVariable("MSBUILDDISABLEFEATURESFROMVERSION", ChangeWaves.Wave16_10.ToString());
BuildEnvironmentHelper.ResetInstance_ForUnitTestsOnly();
Scanner lexer = new Scanner("$(x )", ParserOptions.AllowProperties);
AdvanceToScannerError(lexer);
Assert.Null(lexer.UnexpectedlyFound);
lexer = new Scanner("$( x)", ParserOptions.AllowProperties);
AdvanceToScannerError(lexer);
Assert.Null(lexer.UnexpectedlyFound);
ChangeWaves.ResetStateForTests();
}
/// <summary>
/// Tests the special errors for "@(" and "@x" and similar cases.
/// </summary>
[Fact]
public void IllFormedItemList()
{
Scanner lexer = new Scanner("@(", ParserOptions.AllowAll);
AdvanceToScannerError(lexer);
Assert.Equal("IllFormedItemListCloseParenthesisInCondition", lexer.GetErrorResource());
Assert.Null(lexer.UnexpectedlyFound);
lexer = new Scanner("@x", ParserOptions.AllowAll);
AdvanceToScannerError(lexer);
Assert.Equal("IllFormedItemListOpenParenthesisInCondition", lexer.GetErrorResource());
Assert.Null(lexer.UnexpectedlyFound);
lexer = new Scanner("@(x", ParserOptions.AllowAll);
AdvanceToScannerError(lexer);
Assert.Equal("IllFormedItemListCloseParenthesisInCondition", lexer.GetErrorResource());
Assert.Null(lexer.UnexpectedlyFound);
lexer = new Scanner("@(x->'%(y)", ParserOptions.AllowAll);
AdvanceToScannerError(lexer);
Assert.Equal("IllFormedItemListQuoteInCondition", lexer.GetErrorResource());
Assert.Null(lexer.UnexpectedlyFound);
lexer = new Scanner("@(x->'%(y)', 'x", ParserOptions.AllowAll);
AdvanceToScannerError(lexer);
Assert.Equal("IllFormedItemListQuoteInCondition", lexer.GetErrorResource());
Assert.Null(lexer.UnexpectedlyFound);
lexer = new Scanner("@(x->'%(y)', 'x'", ParserOptions.AllowAll);
AdvanceToScannerError(lexer);
Assert.Equal("IllFormedItemListCloseParenthesisInCondition", lexer.GetErrorResource());
Assert.Null(lexer.UnexpectedlyFound);
}
/// <summary>
/// Tests the special error for unterminated quotes.
/// Note, scanner only understands single quotes.
/// </summary>
[Fact]
public void IllFormedQuotedString()
{
Scanner lexer = new Scanner("false or 'abc", ParserOptions.AllowAll);
AdvanceToScannerError(lexer);
Assert.Equal("IllFormedQuotedStringInCondition", lexer.GetErrorResource());
Assert.Null(lexer.UnexpectedlyFound);
lexer = new Scanner("\'", ParserOptions.AllowAll);
AdvanceToScannerError(lexer);
Assert.Equal("IllFormedQuotedStringInCondition", lexer.GetErrorResource());
Assert.Null(lexer.UnexpectedlyFound);
}
/// <summary>
/// </summary>
[Fact]
public void NumericSingleTokenTests()
{
Scanner lexer = new Scanner("1234", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.Numeric));
Assert.Equal(0, String.Compare("1234", lexer.IsNextString()));
lexer = new Scanner("-1234", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.Numeric));
Assert.Equal(0, String.Compare("-1234", lexer.IsNextString()));
lexer = new Scanner("+1234", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.Numeric));
Assert.Equal(0, String.Compare("+1234", lexer.IsNextString()));
lexer = new Scanner("1234.1234", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.Numeric));
Assert.Equal(0, String.Compare("1234.1234", lexer.IsNextString()));
lexer = new Scanner(".1234", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.Numeric));
Assert.Equal(0, String.Compare(".1234", lexer.IsNextString()));
lexer = new Scanner("1234.", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.Numeric));
Assert.Equal(0, String.Compare("1234.", lexer.IsNextString()));
lexer = new Scanner("0x1234", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.Numeric));
Assert.Equal(0, String.Compare("0x1234", lexer.IsNextString()));
lexer = new Scanner("0X1234abcd", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.Numeric));
Assert.Equal(0, String.Compare("0X1234abcd", lexer.IsNextString()));
lexer = new Scanner("0x1234ABCD", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.Numeric));
Assert.Equal(0, String.Compare("0x1234ABCD", lexer.IsNextString()));
}
/// <summary>
/// </summary>
[Fact]
public void PropsStringsAndBooleanSingleTokenTests()
{
Scanner lexer = new Scanner("$(foo)", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.Property));
lexer = new Scanner("@(foo)", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.ItemList));
lexer = new Scanner("abcde", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.String));
Assert.Equal(0, String.Compare("abcde", lexer.IsNextString()));
lexer = new Scanner("'abc-efg'", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.String));
Assert.Equal(0, String.Compare("abc-efg", lexer.IsNextString()));
lexer = new Scanner("and", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.And));
Assert.Equal(0, String.Compare("and", lexer.IsNextString()));
lexer = new Scanner("or", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.Or));
Assert.Equal(0, String.Compare("or", lexer.IsNextString()));
lexer = new Scanner("AnD", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.And));
Assert.Equal(0, String.Compare(Token.And.String, lexer.IsNextString()));
lexer = new Scanner("Or", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.Or));
Assert.Equal(0, String.Compare(Token.Or.String, lexer.IsNextString()));
}
/// <summary>
/// </summary>
[Fact]
public void SimpleSingleTokenTests()
{
Scanner lexer = new Scanner("(", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.LeftParenthesis));
lexer = new Scanner(")", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.RightParenthesis));
lexer = new Scanner(",", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.Comma));
lexer = new Scanner("==", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.EqualTo));
lexer = new Scanner("!=", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.NotEqualTo));
lexer = new Scanner("<", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.LessThan));
lexer = new Scanner(">", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.GreaterThan));
lexer = new Scanner("<=", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.LessThanOrEqualTo));
lexer = new Scanner(">=", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.GreaterThanOrEqualTo));
lexer = new Scanner("!", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.Not));
}
/// <summary>
/// </summary>
[Fact]
public void StringEdgeTests()
{
Scanner lexer = new Scanner("@(Foo, ' ')", ParserOptions.AllowAll);
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.ItemList));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.EndOfInput));
lexer = new Scanner("'@(Foo, ' ')'", ParserOptions.AllowAll);
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.EndOfInput));
lexer = new Scanner("'%40(( '", ParserOptions.AllowAll);
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.EndOfInput));
lexer = new Scanner("'@(Complex_ItemType-123, ';')' == ''", ParserOptions.AllowAll);
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.EqualTo));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.EndOfInput));
}
/// <summary>
/// </summary>
[Fact]
public void FunctionTests()
{
Scanner lexer = new Scanner("Foo()", ParserOptions.AllowAll);
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Function));
Assert.Equal(0, String.Compare("Foo", lexer.IsNextString()));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis));
lexer = new Scanner("Foo( 1 )", ParserOptions.AllowAll);
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Function));
Assert.Equal(0, String.Compare("Foo", lexer.IsNextString()));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis));
lexer = new Scanner("Foo( $(Property) )", ParserOptions.AllowAll);
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Function));
Assert.Equal(0, String.Compare("Foo", lexer.IsNextString()));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Property));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis));
lexer = new Scanner("Foo( @(ItemList) )", ParserOptions.AllowAll);
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Function));
Assert.Equal(0, String.Compare("Foo", lexer.IsNextString()));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.ItemList));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis));
lexer = new Scanner("Foo( simplestring )", ParserOptions.AllowAll);
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Function));
Assert.Equal(0, String.Compare("Foo", lexer.IsNextString()));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis));
lexer = new Scanner("Foo( 'Not a Simple String' )", ParserOptions.AllowAll);
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Function));
Assert.Equal(0, String.Compare("Foo", lexer.IsNextString()));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis));
lexer = new Scanner("Foo( 'Not a Simple String', 1234 )", ParserOptions.AllowAll);
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Function));
Assert.Equal(0, String.Compare("Foo", lexer.IsNextString()));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Comma));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis));
lexer = new Scanner("Foo( $(Property), 'Not a Simple String', 1234 )", ParserOptions.AllowAll);
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Function));
Assert.Equal(0, String.Compare("Foo", lexer.IsNextString()));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Property));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Comma));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Comma));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis));
lexer = new Scanner("Foo( @(ItemList), $(Property), simplestring, 'Not a Simple String', 1234 )", ParserOptions.AllowAll);
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Function));
Assert.Equal(0, String.Compare("Foo", lexer.IsNextString()));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.ItemList));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Comma));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Property));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Comma));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Comma));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Comma));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis));
}
/// <summary>
/// </summary>
[Fact]
public void ComplexTests1()
{
Scanner lexer = new Scanner("'String with a $(Property) inside'", ParserOptions.AllowAll);
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String));
Assert.Equal(0, String.Compare("String with a $(Property) inside", lexer.IsNextString()));
lexer = new Scanner("'String with an embedded \\' in it'", ParserOptions.AllowAll);
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String));
// Assert.AreEqual(String.Compare("String with an embedded ' in it", lexer.IsNextString()), 0);
lexer = new Scanner("'String with a $(Property) inside'", ParserOptions.AllowAll);
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String));
Assert.Equal(0, String.Compare("String with a $(Property) inside", lexer.IsNextString()));
lexer = new Scanner("@(list, ' ')", ParserOptions.AllowAll);
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.ItemList));
Assert.Equal(0, String.Compare("@(list, ' ')", lexer.IsNextString()));
lexer = new Scanner("@(files->'%(Filename)')", ParserOptions.AllowAll);
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.ItemList));
Assert.Equal(0, String.Compare("@(files->'%(Filename)')", lexer.IsNextString()));
}
/// <summary>
/// </summary>
[Fact]
public void ComplexTests2()
{
Scanner lexer = new Scanner("1234", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
lexer = new Scanner("'abc-efg'==$(foo)", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.String));
lexer.Advance();
Assert.True(lexer.IsNext(Token.TokenType.EqualTo));
lexer.Advance();
Assert.True(lexer.IsNext(Token.TokenType.Property));
lexer.Advance();
Assert.True(lexer.IsNext(Token.TokenType.EndOfInput));
lexer = new Scanner("$(debug)!=true", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.Property));
lexer.Advance();
Assert.True(lexer.IsNext(Token.TokenType.NotEqualTo));
lexer.Advance();
Assert.True(lexer.IsNext(Token.TokenType.String));
lexer.Advance();
Assert.True(lexer.IsNext(Token.TokenType.EndOfInput));
lexer = new Scanner("$(VERSION)<5", ParserOptions.AllowAll);
Assert.True(lexer.Advance());
Assert.True(lexer.IsNext(Token.TokenType.Property));
lexer.Advance();
Assert.True(lexer.IsNext(Token.TokenType.LessThan));
lexer.Advance();
Assert.True(lexer.IsNext(Token.TokenType.Numeric));
lexer.Advance();
Assert.True(lexer.IsNext(Token.TokenType.EndOfInput));
}
/// <summary>
/// Tests all tokens with no whitespace and whitespace.
/// </summary>
[Fact]
public void WhitespaceTests()
{
Scanner lexer;
Console.WriteLine("here");
lexer = new Scanner("$(DEBUG) and $(FOO)", ParserOptions.AllowAll);
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Property));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.And));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Property));
lexer = new Scanner("1234$(DEBUG)0xabcd@(foo)asdf<>'foo'<=false>=true==1234!=", ParserOptions.AllowAll);
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Property));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.ItemList));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LessThan));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.GreaterThan));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LessThanOrEqualTo));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.GreaterThanOrEqualTo));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.EqualTo));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.NotEqualTo));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.EndOfInput));
lexer = new Scanner(" 1234 $(DEBUG) 0xabcd \n@(foo) \nasdf \n< \n> \n'foo' \n<= \nfalse \n>= \ntrue \n== \n 1234 \n!= ", ParserOptions.AllowAll);
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Property));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.ItemList));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LessThan));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.GreaterThan));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LessThanOrEqualTo));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.GreaterThanOrEqualTo));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.EqualTo));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.NotEqualTo));
Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.EndOfInput));
}
/// <summary>
/// Tests the parsing of item lists.
/// </summary>
[Fact]
public void ItemListTests()
{
Scanner lexer = new Scanner("@(foo)", ParserOptions.AllowProperties);
Assert.False(lexer.Advance());
Assert.Equal(0, String.Compare(lexer.GetErrorResource(), "ItemListNotAllowedInThisConditional"));
lexer = new Scanner("1234 '@(foo)'", ParserOptions.AllowProperties);
Assert.True(lexer.Advance());
Assert.False(lexer.Advance());
Assert.Equal(0, String.Compare(lexer.GetErrorResource(), "ItemListNotAllowedInThisConditional"));
lexer = new Scanner("'1234 @(foo)'", ParserOptions.AllowProperties);
Assert.False(lexer.Advance());
Assert.Equal(0, String.Compare(lexer.GetErrorResource(), "ItemListNotAllowedInThisConditional"));
}
/// <summary>
/// Tests that shouldn't work.
/// </summary>
[Fact]
public void NegativeTests()
{
Scanner lexer = new Scanner("'$(DEBUG) == true", ParserOptions.AllowAll);
Assert.False(lexer.Advance());
}
}
}
| |
#pragma warning disable 1591
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace Braintree
{
public class TransactionGatewayRejectionReason : Enumeration
{
public static readonly TransactionGatewayRejectionReason APPLICATION_INCOMPLETE = new TransactionGatewayRejectionReason("application_incomplete");
public static readonly TransactionGatewayRejectionReason AVS = new TransactionGatewayRejectionReason("avs");
public static readonly TransactionGatewayRejectionReason AVS_AND_CVV = new TransactionGatewayRejectionReason("avs_and_cvv");
public static readonly TransactionGatewayRejectionReason CVV = new TransactionGatewayRejectionReason("cvv");
public static readonly TransactionGatewayRejectionReason DUPLICATE = new TransactionGatewayRejectionReason("duplicate");
public static readonly TransactionGatewayRejectionReason FRAUD = new TransactionGatewayRejectionReason("fraud");
public static readonly TransactionGatewayRejectionReason THREE_D_SECURE = new TransactionGatewayRejectionReason("three_d_secure");
public static readonly TransactionGatewayRejectionReason UNRECOGNIZED = new TransactionGatewayRejectionReason("unrecognized");
public static readonly TransactionGatewayRejectionReason[] ALL = {
APPLICATION_INCOMPLETE, AVS, AVS_AND_CVV, CVV, DUPLICATE, FRAUD, THREE_D_SECURE, UNRECOGNIZED
};
protected TransactionGatewayRejectionReason(string name) : base(name) {}
}
public class TransactionEscrowStatus : Enumeration
{
public static readonly TransactionEscrowStatus HOLD_PENDING = new TransactionEscrowStatus("hold_pending");
public static readonly TransactionEscrowStatus HELD = new TransactionEscrowStatus("held");
public static readonly TransactionEscrowStatus RELEASE_PENDING = new TransactionEscrowStatus("release_pending");
public static readonly TransactionEscrowStatus RELEASED = new TransactionEscrowStatus("released");
public static readonly TransactionEscrowStatus REFUNDED = new TransactionEscrowStatus("refunded");
public static readonly TransactionEscrowStatus UNRECOGNIZED = new TransactionEscrowStatus("unrecognized");
public static readonly TransactionEscrowStatus[] ALL = {
HELD, HOLD_PENDING, RELEASE_PENDING, RELEASED, REFUNDED, UNRECOGNIZED
};
protected TransactionEscrowStatus(string name) : base(name) {}
}
public class TransactionStatus : Enumeration
{
public static readonly TransactionStatus AUTHORIZATION_EXPIRED = new TransactionStatus("authorization_expired");
public static readonly TransactionStatus AUTHORIZED = new TransactionStatus("authorized");
public static readonly TransactionStatus AUTHORIZING = new TransactionStatus("authorizing");
public static readonly TransactionStatus FAILED = new TransactionStatus("failed");
public static readonly TransactionStatus GATEWAY_REJECTED = new TransactionStatus("gateway_rejected");
public static readonly TransactionStatus PROCESSOR_DECLINED = new TransactionStatus("processor_declined");
public static readonly TransactionStatus SETTLED = new TransactionStatus("settled");
public static readonly TransactionStatus SETTLING = new TransactionStatus("settling");
public static readonly TransactionStatus SUBMITTED_FOR_SETTLEMENT = new TransactionStatus("submitted_for_settlement");
public static readonly TransactionStatus VOIDED = new TransactionStatus("voided");
public static readonly TransactionStatus UNRECOGNIZED = new TransactionStatus("unrecognized");
public static readonly TransactionStatus SETTLEMENT_CONFIRMED = new TransactionStatus("settlement_confirmed");
public static readonly TransactionStatus SETTLEMENT_DECLINED = new TransactionStatus("settlement_declined");
public static readonly TransactionStatus SETTLEMENT_PENDING = new TransactionStatus("settlement_pending");
public static readonly TransactionStatus[] ALL = {
AUTHORIZATION_EXPIRED, AUTHORIZED, AUTHORIZING, FAILED, GATEWAY_REJECTED, PROCESSOR_DECLINED,
SETTLED, SETTLEMENT_CONFIRMED, SETTLEMENT_DECLINED, SETTLEMENT_PENDING, SETTLING, SUBMITTED_FOR_SETTLEMENT, VOIDED, UNRECOGNIZED
};
protected TransactionStatus(string name) : base(name) {}
}
public class TransactionIndustryType : Enumeration
{
public static readonly TransactionIndustryType LODGING = new TransactionIndustryType("lodging");
public static readonly TransactionIndustryType TRAVEL_AND_CRUISE = new TransactionIndustryType("travel_cruise");
protected TransactionIndustryType(string name) : base(name) {}
}
public class TransactionSource : Enumeration
{
public static readonly TransactionSource API = new TransactionSource("api");
public static readonly TransactionSource CONTROL_PANEL = new TransactionSource("control_panel");
public static readonly TransactionSource RECURRING = new TransactionSource("recurring");
public static readonly TransactionSource UNRECOGNIZED = new TransactionSource("unrecognized");
public static readonly TransactionSource[] ALL = { API, CONTROL_PANEL, RECURRING, UNRECOGNIZED };
protected TransactionSource(string name) : base(name) {}
}
public class TransactionType : Enumeration
{
public static readonly TransactionType CREDIT = new TransactionType("credit");
public static readonly TransactionType SALE = new TransactionType("sale");
public static readonly TransactionType UNRECOGNIZED = new TransactionType("unrecognized");
public static readonly TransactionType[] ALL = { CREDIT, SALE, UNRECOGNIZED };
protected TransactionType(string name) : base(name) {}
}
public class TransactionCreatedUsing : Enumeration
{
public static readonly TransactionCreatedUsing FULL_INFORMATION = new TransactionCreatedUsing("full_information");
public static readonly TransactionCreatedUsing TOKEN = new TransactionCreatedUsing("token");
public static readonly TransactionCreatedUsing UNRECOGNIZED = new TransactionCreatedUsing("unrecognized");
public static readonly TransactionCreatedUsing[] ALL = { FULL_INFORMATION, TOKEN, UNRECOGNIZED };
protected TransactionCreatedUsing(string name) : base(name) {}
}
public class PaymentInstrumentType : Enumeration
{
public static readonly PaymentInstrumentType PAYPAL_ACCOUNT = new PaymentInstrumentType("paypal_account");
public static readonly PaymentInstrumentType EUROPE_BANK_ACCOUNT= new PaymentInstrumentType("europe_bank_account");
public static readonly PaymentInstrumentType CREDIT_CARD = new PaymentInstrumentType("credit_card");
public static readonly PaymentInstrumentType COINBASE_ACCOUNT= new PaymentInstrumentType("coinbase_account");
public static readonly PaymentInstrumentType APPLE_PAY_CARD = new PaymentInstrumentType("apple_pay_card");
public static readonly PaymentInstrumentType ANDROID_PAY_CARD = new PaymentInstrumentType("android_pay_card");
public static readonly PaymentInstrumentType ANY = new PaymentInstrumentType("any");
public static readonly PaymentInstrumentType UNKNOWN = new PaymentInstrumentType("unknown");
public static readonly PaymentInstrumentType[] ALL = { PAYPAL_ACCOUNT, EUROPE_BANK_ACCOUNT, CREDIT_CARD, COINBASE_ACCOUNT, ANDROID_PAY_CARD, APPLE_PAY_CARD, ANY, UNKNOWN };
protected PaymentInstrumentType(string name) : base(name) {}
}
/// <summary>
/// A transaction returned by the Braintree Gateway
/// </summary>
/// <example>
/// Transactions can be retrieved via the gateway using the associated transaction id:
/// <code>
/// Transaction transaction = gateway.Transaction.Find("transactionId");
/// </code>
/// For more information about Transactions, see <a href="http://www.braintreepayments.com/gateway/transaction-api" target="_blank">http://www.braintreepaymentsolutions.com/gateway/transaction-api</a>
/// </example>
public class Transaction
{
public string Id { get; protected set; }
public List<AddOn> AddOns { get; protected set; }
public decimal? Amount { get; protected set; }
public string AvsErrorResponseCode { get; protected set; }
public string AvsPostalCodeResponseCode { get; protected set; }
public string AvsStreetAddressResponseCode { get; protected set; }
public Address BillingAddress { get; protected set; }
public string Channel { get; protected set; }
public DateTime? CreatedAt { get; protected set; }
public CreditCard CreditCard { get; protected set; }
public string CurrencyIsoCode { get; protected set; }
public Customer Customer { get; protected set; }
public string CvvResponseCode { get; protected set; }
public Descriptor Descriptor { get; protected set; }
public List<Discount> Discounts { get; protected set; }
public List<Dispute> Disputes { get; protected set; }
public TransactionGatewayRejectionReason GatewayRejectionReason { get; protected set; }
public string MerchantAccountId { get; protected set; }
public string OrderId { get; protected set; }
public string PlanId { get; protected set; }
public string ProcessorAuthorizationCode { get; protected set; }
public string ProcessorResponseCode { get; protected set; }
public string ProcessorResponseText { get; protected set; }
public string ProcessorSettlementResponseCode { get; protected set; }
public string ProcessorSettlementResponseText { get; protected set; }
public string AdditionalProcessorResponse { get; protected set; }
public string VoiceReferralNumber { get; protected set; }
public string PurchaseOrderNumber { get; protected set; }
public bool? Recurring { get; protected set; }
public string RefundedTransactionId { get; protected set; }
[Obsolete("Use Transaction.RefundIds")]
public string RefundId { get; protected set; }
public List<string> RefundIds { get; protected set; }
public List<string> PartialSettlementTransactionIds { get; protected set; }
public string AuthorizedTransactionId { get; protected set; }
public string SettlementBatchId { get; protected set; }
public Address ShippingAddress { get; protected set; }
public TransactionEscrowStatus EscrowStatus { get; protected set; }
public TransactionStatus Status { get; protected set; }
public StatusEvent[] StatusHistory { get; protected set; }
public string SubscriptionId { get; protected set; }
public Subscription Subscription { get; protected set; }
public decimal? TaxAmount { get; protected set; }
public bool? TaxExempt { get; protected set; }
public TransactionType Type { get; protected set; }
public DateTime? UpdatedAt { get; protected set; }
public Dictionary<string, string> CustomFields { get; protected set; }
public decimal? ServiceFeeAmount { get; protected set; }
public DisbursementDetails DisbursementDetails { get; protected set; }
public ApplePayDetails ApplePayDetails { get; protected set; }
public AndroidPayDetails AndroidPayDetails { get; protected set; }
public PayPalDetails PayPalDetails { get; protected set; }
public CoinbaseDetails CoinbaseDetails { get; protected set; }
public PaymentInstrumentType PaymentInstrumentType { get; protected set; }
public RiskData RiskData { get; protected set; }
public ThreeDSecureInfo ThreeDSecureInfo { get; protected set; }
private BraintreeGateway Gateway;
protected internal Transaction(NodeWrapper node, BraintreeGateway gateway)
{
Gateway = gateway;
if (node == null) return;
Id = node.GetString("id");
Amount = node.GetDecimal("amount");
AvsErrorResponseCode = node.GetString("avs-error-response-code");
AvsPostalCodeResponseCode = node.GetString("avs-postal-code-response-code");
AvsStreetAddressResponseCode = node.GetString("avs-street-address-response-code");
GatewayRejectionReason = (TransactionGatewayRejectionReason)CollectionUtil.Find(
TransactionGatewayRejectionReason.ALL,
node.GetString("gateway-rejection-reason"),
TransactionGatewayRejectionReason.UNRECOGNIZED
);
PaymentInstrumentType = (PaymentInstrumentType)CollectionUtil.Find(
PaymentInstrumentType.ALL,
node.GetString("payment-instrument-type"),
PaymentInstrumentType.UNKNOWN
);
Channel = node.GetString("channel");
OrderId = node.GetString("order-id");
Status = (TransactionStatus)CollectionUtil.Find(TransactionStatus.ALL, node.GetString("status"), TransactionStatus.UNRECOGNIZED);
EscrowStatus = (TransactionEscrowStatus)CollectionUtil.Find(
TransactionEscrowStatus.ALL,
node.GetString("escrow-status"),
TransactionEscrowStatus.UNRECOGNIZED
);
List<NodeWrapper> statusNodes = node.GetList("status-history/status-event");
StatusHistory = new StatusEvent[statusNodes.Count];
for (int i = 0; i < statusNodes.Count; i++)
{
StatusHistory[i] = new StatusEvent(statusNodes[i]);
}
Type = (TransactionType)CollectionUtil.Find(TransactionType.ALL, node.GetString("type"), TransactionType.UNRECOGNIZED);
MerchantAccountId = node.GetString("merchant-account-id");
ProcessorAuthorizationCode = node.GetString("processor-authorization-code");
ProcessorResponseCode = node.GetString("processor-response-code");
ProcessorResponseText = node.GetString("processor-response-text");
ProcessorSettlementResponseCode = node.GetString("processor-settlement-response-code");
ProcessorSettlementResponseText = node.GetString("processor-settlement-response-text");
AdditionalProcessorResponse = node.GetString("additional-processor-response");
VoiceReferralNumber = node.GetString("voice-referral-number");
PurchaseOrderNumber = node.GetString("purchase-order-number");
Recurring = node.GetBoolean("recurring");
RefundedTransactionId = node.GetString("refunded-transaction-id");
#pragma warning disable 0618
RefundId = node.GetString("refund-id");
#pragma warning restore 0618
RefundIds = node.GetStrings("refund-ids/*");
PartialSettlementTransactionIds = node.GetStrings("partial-settlement-transaction-ids/*");
AuthorizedTransactionId = node.GetString("authorized-transaction-id");
SettlementBatchId = node.GetString("settlement-batch-id");
PlanId = node.GetString("plan-id");
SubscriptionId = node.GetString("subscription-id");
TaxAmount = node.GetDecimal("tax-amount");
TaxExempt = node.GetBoolean("tax-exempt");
CustomFields = node.GetDictionary("custom-fields");
CreditCard = new CreditCard(node.GetNode("credit-card"), gateway);
Subscription = new Subscription(node.GetNode("subscription"), gateway);
Customer = new Customer(node.GetNode("customer"), gateway);
CurrencyIsoCode = node.GetString("currency-iso-code");
CvvResponseCode = node.GetString("cvv-response-code");
Descriptor = new Descriptor(node.GetNode("descriptor"));
ServiceFeeAmount = node.GetDecimal("service-fee-amount");
DisbursementDetails = new DisbursementDetails(node.GetNode("disbursement-details"));
var paypalNode = node.GetNode("paypal");
if (paypalNode != null)
{
PayPalDetails = new PayPalDetails(paypalNode);
}
var coinbaseNode = node.GetNode("coinbase-account");
if (coinbaseNode != null)
{
CoinbaseDetails = new CoinbaseDetails(coinbaseNode);
}
var applePayNode = node.GetNode("apple-pay");
if (applePayNode != null)
{
ApplePayDetails = new ApplePayDetails(applePayNode);
}
var androidPayNode = node.GetNode("android-pay-card");
if (androidPayNode != null)
{
AndroidPayDetails = new AndroidPayDetails(androidPayNode);
}
BillingAddress = new Address(node.GetNode("billing"));
ShippingAddress = new Address(node.GetNode("shipping"));
CreatedAt = node.GetDateTime("created-at");
UpdatedAt = node.GetDateTime("updated-at");
AddOns = new List<AddOn>();
foreach (var addOnResponse in node.GetList("add-ons/add-on")) {
AddOns.Add(new AddOn(addOnResponse));
}
Discounts = new List<Discount>();
foreach (var discountResponse in node.GetList("discounts/discount")) {
Discounts.Add(new Discount(discountResponse));
}
Disputes = new List<Dispute>();
foreach (var dispute in node.GetList("disputes/dispute")) {
Disputes.Add(new Dispute(dispute));
}
var riskDataNode = node.GetNode("risk-data");
if (riskDataNode != null){
RiskData = new RiskData(riskDataNode);
}
var threeDSecureInfoNode = node.GetNode("three-d-secure-info");
if (threeDSecureInfoNode != null && !threeDSecureInfoNode.IsEmpty()){
ThreeDSecureInfo = new ThreeDSecureInfo(threeDSecureInfoNode);
}
}
/// <summary>
/// Returns the current <see cref="CreditCard"/> associated with this transaction if one exists
/// </summary>
/// <returns>
/// The current <see cref="CreditCard"/> associated with this transaction if one exists
/// </returns>
/// <remarks>
/// When retrieving a transaction from the gateway, the credit card used in the transaction is returned in the response.
/// If the credit card record has been updated in the vault since the transaction occurred, this method can be used to
/// retrieve the updated credit card information. This is typically useful in situations where a transaction fails, for
/// example when a credit card expires, and a new transaction needs to be submitted once the new credit card information
/// has been submitted.
/// </remarks>
/// <example>
/// The vault <see cref="CreditCard"/> can be retrieved from the transaction directly:
/// <code>
/// Transaction transaction = gateway.Transaction.Find("transactionId");
/// CreditCard creditCard = transaction.GetVaultCreditCard();
/// </code>
/// </example>
/// <example>
/// Failed transactions can be resubmitted with updated <see cref="CreditCard"/> information:
/// <code>
/// Transaction failedTransaction = gateway.Transaction.Find("transactionId");
/// CreditCard updatedCreditCard = transaction.GetVaultCreditCard();
///
/// TransactionRequest request = new TransactionRequest
/// {
/// Amount = failedTransaction.Amount,
/// PaymentMethodToken = updatedCreditCard.Token
/// };
///
/// Result<Transaction> result = gateway.Transaction.Sale(request);
/// </code>
/// </example>
public virtual CreditCard GetVaultCreditCard()
{
if (CreditCard.Token == null) return null;
return new CreditCardGateway(Gateway).Find(CreditCard.Token);
}
/// <summary>
/// Returns the current <see cref="Customer"/> associated with this transaction if one exists
/// </summary>
/// <returns>
/// The current <see cref="Customer"/> associated with this transaction if one exists
/// </returns>
/// <remarks>
/// When retrieving a transaction from the gateway, the customer associated with the transaction is returned in the response.
/// If the customer record has been updated in the vault since the transaction occurred, this method can be used to
/// retrieve the updated customer information.
/// </remarks>
/// <example>
/// The vault <see cref="Customer"/> can be retrieved from the transaction directly:
/// <code>
/// Transaction transaction = gateway.Transaction.Find("transactionId");
/// Customer customer = transaction.GetVaultCustomer();
/// </code>
/// </example>
public virtual Customer GetVaultCustomer()
{
if (Customer.Id == null) return null;
return new CustomerGateway(Gateway).Find(Customer.Id);
}
/// <summary>
/// Returns the current billing <see cref="Address"/> associated with this transaction if one exists
/// </summary>
/// <returns>
/// The current billing <see cref="Address"/> associated with this transaction if one exists
/// </returns>
/// <remarks>
/// When retrieving a transaction from the gateway, the billing address associated with the transaction is returned in the response.
/// If the billing address has been updated in the vault since the transaction occurred, this method can be used to
/// retrieve the updated billing address.
/// </remarks>
/// <example>
/// The vault billing <see cref="Address"/> can be retrieved from the transaction directly:
/// <code>
/// Transaction transaction = gateway.Transaction.Find("transactionId");
/// Address billingAddress = transaction.GetVaultBillingAddress();
/// </code>
/// </example>
public virtual Address GetVaultBillingAddress()
{
if (BillingAddress.Id == null) return null;
return new AddressGateway(Gateway).Find(Customer.Id, BillingAddress.Id);
}
/// <summary>
/// Returns the current shipping <see cref="Address"/> associated with this transaction if one exists
/// </summary>
/// <returns>
/// The current shipping <see cref="Address"/> associated with this transaction if one exists
/// </returns>
/// <remarks>
/// When retrieving a transaction from the gateway, the shipping address associated with the transaction is returned in the response.
/// If the shipping address has been updated in the vault since the transaction occurred, this method can be used to
/// retrieve the updated shipping address.
/// </remarks>
/// <example>
/// The vault shipping <see cref="Address"/> can be retrieved from the transaction directly:
/// <code>
/// Transaction transaction = gateway.Transaction.Find("transactionId");
/// Address shippingAddress = transaction.GetVaultShippingAddress();
/// </code>
/// </example>
public virtual Address GetVaultShippingAddress()
{
if (ShippingAddress.Id == null) return null;
return new AddressGateway(Gateway).Find(Customer.Id, ShippingAddress.Id);
}
public bool IsDisbursed()
{
return DisbursementDetails.IsValid();
}
}
}
| |
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Spatial.Prefix.Tree;
using Lucene.Net.Util;
using Spatial4n.Core.Shapes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace Lucene.Net.Spatial.Prefix
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Traverses a <see cref="SpatialPrefixTree">SpatialPrefixTree</see> indexed field, using the template &
/// visitor design patterns for subclasses to guide the traversal and collect
/// matching documents.
/// <para/>
/// Subclasses implement <see cref="Filter.GetDocIdSet(AtomicReaderContext, IBits)"/>
/// by instantiating a custom <see cref="VisitorTemplate"/> subclass (i.e. an anonymous inner class) and implement the
/// required methods.
///
/// @lucene.internal
/// </summary>
public abstract class AbstractVisitingPrefixTreeFilter : AbstractPrefixTreeFilter
{
// Historical note: this code resulted from a refactoring of RecursivePrefixTreeFilter,
// which in turn came out of SOLR-2155
protected readonly int m_prefixGridScanLevel;//at least one less than grid.getMaxLevels()
public AbstractVisitingPrefixTreeFilter(IShape queryShape, string fieldName, SpatialPrefixTree grid,
int detailLevel, int prefixGridScanLevel)
: base(queryShape, fieldName, grid, detailLevel)
{
this.m_prefixGridScanLevel = Math.Max(0, Math.Min(prefixGridScanLevel, grid.MaxLevels - 1));
Debug.Assert(detailLevel <= grid.MaxLevels);
}
public override bool Equals(object o)
{
if (!base.Equals(o))
{
return false;//checks getClass == o.getClass & instanceof
}
//Ignore prefixGridScanLevel as it is merely a tuning parameter.
return true;
}
public override int GetHashCode()
{
int result = base.GetHashCode();
return result;
}
#region Nested type: VisitorTemplate
/// <summary>
/// An abstract class designed to make it easy to implement predicates or
/// other operations on a <see cref="SpatialPrefixTree"/> indexed field. An instance
/// of this class is not designed to be re-used across AtomicReaderContext
/// instances so simply create a new one for each call to, say a
/// <see cref="Lucene.Net.Search.Filter.GetDocIdSet(Lucene.Net.Index.AtomicReaderContext, Lucene.Net.Util.IBits)"/>.
/// The <see cref="GetDocIdSet()"/> method here starts the work. It first checks
/// that there are indexed terms; if not it quickly returns null. Then it calls
/// <see cref="Start()">Start()</see> so a subclass can set up a return value, like an
/// <see cref="Lucene.Net.Util.FixedBitSet"/>. Then it starts the traversal
/// process, calling <see cref="FindSubCellsToVisit(Lucene.Net.Spatial.Prefix.Tree.Cell)"/>
/// which by default finds the top cells that intersect <c>queryShape</c>. If
/// there isn't an indexed cell for a corresponding cell returned for this
/// method then it's short-circuited until it finds one, at which point
/// <see cref="Visit(Lucene.Net.Spatial.Prefix.Tree.Cell)"/> is called. At
/// some depths, of the tree, the algorithm switches to a scanning mode that
/// calls <see cref="VisitScanned(Lucene.Net.Spatial.Prefix.Tree.Cell)"/>
/// for each leaf cell found.
///
/// @lucene.internal
/// </summary>
public abstract class VisitorTemplate : BaseTermsEnumTraverser
{
/* Future potential optimizations:
* Can a polygon query shape be optimized / made-simpler at recursive depths
(e.g. intersection of shape + cell box)
* RE "scan" vs divide & conquer performance decision:
We should use termsEnum.docFreq() as an estimate on the number of places at
this depth. It would be nice if termsEnum knew how many terms
start with the current term without having to repeatedly next() & test to find out.
* Perhaps don't do intermediate seek()'s to cells above detailLevel that have Intersects
relation because we won't be collecting those docs any way. However seeking
does act as a short-circuit. So maybe do some percent of the time or when the level
is above some threshold.
* Each shape.relate(otherShape) result could be cached since much of the same relations
will be invoked when multiple segments are involved.
*/
protected readonly bool m_hasIndexedLeaves;//if false then we can skip looking for them
private VNode curVNode;//current pointer, derived from query shape
private BytesRef curVNodeTerm = new BytesRef();//curVNode.cell's term.
private Cell scanCell;
private BytesRef thisTerm; //the result of termsEnum.term()
public VisitorTemplate(AbstractVisitingPrefixTreeFilter outerInstance, AtomicReaderContext context, IBits acceptDocs,
bool hasIndexedLeaves)
: base(outerInstance, context, acceptDocs)
{
this.m_hasIndexedLeaves = hasIndexedLeaves;
}
public virtual DocIdSet GetDocIdSet()
{
Debug.Assert(curVNode == null, "Called more than once?");
if (m_termsEnum == null)
{
return null;
}
//advance
if ((thisTerm = m_termsEnum.Next()) == null)
{
return null;// all done
}
curVNode = new VNode(null);
curVNode.Reset(m_outerInstance.m_grid.WorldCell);
Start();
AddIntersectingChildren();
while (thisTerm != null)//terminates for other reasons too!
{
//Advance curVNode pointer
if (curVNode.children != null)
{
//-- HAVE CHILDREN: DESCEND
// LUCENENET NOTE: Must call this line before calling MoveNext()
// on the enumerator.
//if we put it there then it has something
PreSiblings(curVNode);
// LUCENENET IMPORTANT: Must not call this inline with Debug.Assert
// because the compiler removes Debug.Assert statements in release mode!!
bool hasNext = curVNode.children.MoveNext();
Debug.Assert(hasNext);
curVNode = curVNode.children.Current;
}
else
{
//-- NO CHILDREN: ADVANCE TO NEXT SIBLING
VNode parentVNode = curVNode.parent;
while (true)
{
if (parentVNode == null)
{
goto main_break;// all done
}
if (parentVNode.children.MoveNext())
{
//advance next sibling
curVNode = parentVNode.children.Current;
break;
}
else
{
//reached end of siblings; pop up
PostSiblings(parentVNode);
parentVNode.children = null;
//GC
parentVNode = parentVNode.parent;
}
}
}
//Seek to curVNode's cell (or skip if termsEnum has moved beyond)
curVNodeTerm.Bytes = curVNode.cell.GetTokenBytes();
curVNodeTerm.Length = curVNodeTerm.Bytes.Length;
int compare = m_termsEnum.Comparer.Compare(thisTerm, curVNodeTerm);
if (compare > 0)
{
// leap frog (termsEnum is beyond where we would otherwise seek)
Debug.Assert(!m_context.AtomicReader.GetTerms(m_outerInstance.m_fieldName).GetIterator(null).SeekExact(curVNodeTerm), "should be absent");
}
else
{
if (compare < 0)
{
// Seek !
TermsEnum.SeekStatus seekStatus = m_termsEnum.SeekCeil(curVNodeTerm);
if (seekStatus == TermsEnum.SeekStatus.END)
{
break;// all done
}
thisTerm = m_termsEnum.Term;
if (seekStatus == TermsEnum.SeekStatus.NOT_FOUND)
{
continue; // leap frog
}
}
// Visit!
bool descend = Visit(curVNode.cell);
//advance
if ((thisTerm = m_termsEnum.Next()) == null)
{
break;// all done
}
if (descend)
{
AddIntersectingChildren();
}
}
;
}//main loop
main_break: { }
return Finish();
}
/// <summary>
/// Called initially, and whenever <see cref="Visit(Lucene.Net.Spatial.Prefix.Tree.Cell)"/>
/// returns true.
/// </summary>
/// <exception cref="IOException"></exception>
private void AddIntersectingChildren()
{
Debug.Assert(thisTerm != null);
Cell cell = curVNode.cell;
if (cell.Level >= m_outerInstance.m_detailLevel)
{
throw new InvalidOperationException("Spatial logic error");
}
//Check for adjacent leaf (happens for indexed non-point shapes)
if (m_hasIndexedLeaves && cell.Level != 0)
{
//If the next indexed term just adds a leaf marker ('+') to cell,
// then add all of those docs
Debug.Assert(StringHelper.StartsWith(thisTerm, curVNodeTerm));//TODO refactor to use method on curVNode.cell
scanCell = m_outerInstance.m_grid.GetCell(thisTerm.Bytes, thisTerm.Offset, thisTerm.Length, scanCell);
if (scanCell.Level == cell.Level && scanCell.IsLeaf)
{
VisitLeaf(scanCell);
//advance
if ((thisTerm = m_termsEnum.Next()) == null)
{
return;// all done
}
}
}
//Decide whether to continue to divide & conquer, or whether it's time to
// scan through terms beneath this cell.
// Scanning is a performance optimization trade-off.
//TODO use termsEnum.docFreq() as heuristic
bool scan = cell.Level >= ((AbstractVisitingPrefixTreeFilter)m_outerInstance).m_prefixGridScanLevel;//simple heuristic
if (!scan)
{
//Divide & conquer (ultimately termsEnum.seek())
IEnumerator<Cell> subCellsIter = FindSubCellsToVisit(cell);
if (!subCellsIter.MoveNext())
{
return;//not expected
}
curVNode.children = new VNodeCellIterator(this, subCellsIter, new VNode(curVNode));
}
else
{
//Scan (loop of termsEnum.next())
Scan(m_outerInstance.m_detailLevel);
}
}
/// <summary>
/// Called when doing a divide & conquer to find the next intersecting cells
/// of the query shape that are beneath <paramref name="cell"/>. <paramref name="cell"/> is
/// guaranteed to have an intersection and thus this must return some number
/// of nodes.
/// </summary>
protected internal virtual IEnumerator<Cell> FindSubCellsToVisit(Cell cell)
{
return cell.GetSubCells(m_outerInstance.m_queryShape).GetEnumerator();
}
/// <summary>
/// Scans (<c>termsEnum.Next()</c>) terms until a term is found that does
/// not start with curVNode's cell. If it finds a leaf cell or a cell at
/// level <paramref name="scanDetailLevel"/> then it calls
/// <see cref="VisitScanned(Lucene.Net.Spatial.Prefix.Tree.Cell)"/>.
/// </summary>
/// <exception cref="IOException"></exception>
protected internal virtual void Scan(int scanDetailLevel)
{
for (;
thisTerm != null && StringHelper.StartsWith(thisTerm, curVNodeTerm);//TODO refactor to use method on curVNode.cell
thisTerm = m_termsEnum.Next())
{
scanCell = m_outerInstance.m_grid.GetCell(thisTerm.Bytes, thisTerm.Offset, thisTerm.Length, scanCell);
int termLevel = scanCell.Level;
if (termLevel < scanDetailLevel)
{
if (scanCell.IsLeaf)
VisitScanned(scanCell);
}
else if (termLevel == scanDetailLevel)
{
if (!scanCell.IsLeaf)//LUCENE-5529
VisitScanned(scanCell);
}
}//term loop
}
#region Nested type: VNodeCellIterator
/// <summary>
/// Used for <see cref="VNode.children"/>.
/// </summary>
private class VNodeCellIterator : IEnumerator<VNode>
{
private readonly VisitorTemplate outerInstance;
internal readonly IEnumerator<Cell> cellIter;
private readonly VNode vNode;
private bool first = true;
internal VNodeCellIterator(VisitorTemplate outerInstance, IEnumerator<Cell> cellIter, VNode vNode)
{
this.outerInstance = outerInstance;
//term loop
this.cellIter = cellIter;
this.vNode = vNode;
}
//it always removes
#region IEnumerator<VNode> Members
public void Dispose()
{
cellIter.Dispose();
}
public bool MoveNext()
{
//Debug.Assert(cellIter.Current != null);
// LUCENENET NOTE: The consumer of this class calls
// cellIter.MoveNext() before it is instantiated.
// So, the first call here
// to MoveNext() must not move the cursor.
bool result;
if (!first)
{
result = cellIter.MoveNext();
}
else
{
result = true;
first = false;
}
// LUCENENET NOTE: Need to skip this call
// if there are no more results because null
// is not allowed
if (result == true)
{
vNode.Reset(cellIter.Current);
}
return result;
}
public void Reset()
{
cellIter.Reset();
}
public VNode Current => vNode;
object IEnumerator.Current => Current;
#endregion
}
#endregion
/// <summary>Called first to setup things.</summary>
/// <exception cref="IOException"></exception>
protected internal abstract void Start();
/// <summary>Called last to return the result.</summary>
/// <exception cref="IOException"></exception>
protected internal abstract DocIdSet Finish();
/// <summary>
/// Visit an indexed cell returned from
/// <see cref="FindSubCellsToVisit(Lucene.Net.Spatial.Prefix.Tree.Cell)"/>.
/// </summary>
/// <param name="cell">An intersecting cell.</param>
/// <returns>
/// true to descend to more levels. It is an error to return true
/// if cell.Level == detailLevel
/// </returns>
/// <exception cref="IOException"></exception>
protected internal abstract bool Visit(Cell cell);
/// <summary>Called after visit() returns true and an indexed leaf cell is found.</summary>
/// <remarks>
/// Called after Visit() returns true and an indexed leaf cell is found. An
/// indexed leaf cell means associated documents generally won't be found at
/// further detail levels.
/// </remarks>
/// <exception cref="IOException"></exception>
protected internal abstract void VisitLeaf(Cell cell);
/// <summary>
/// The cell is either indexed as a leaf or is the last level of detail. It
/// might not even intersect the query shape, so be sure to check for that.
/// </summary>
/// <exception cref="IOException"></exception>
protected internal abstract void VisitScanned(Cell cell);
protected internal virtual void PreSiblings(VNode vNode)
{
}
protected internal virtual void PostSiblings(VNode vNode)
{
}
//class VisitorTemplate
}
#endregion
#region Nested type: VNode
/// <summary>
/// A Visitor node/cell found via the query shape for <see cref="VisitorTemplate"/>.
/// Sometimes these are reset(cell). It's like a LinkedList node but forms a
/// tree.
///
/// @lucene.internal
/// </summary>
public class VNode
{
//Note: The VNode tree adds more code to debug/maintain v.s. a flattened
// LinkedList that we used to have. There is more opportunity here for
// custom behavior (see preSiblings & postSiblings) but that's not
// leveraged yet. Maybe this is slightly more GC friendly.
internal readonly VNode parent;//only null at the root
internal IEnumerator<VNode> children;//null, then sometimes set, then null
internal Cell cell;//not null (except initially before reset())
/// <summary>Call <see cref="Reset(Cell)"/> after to set the cell.</summary>
internal VNode(VNode parent)
{
// remember to call reset(cell) after
this.parent = parent;
}
internal virtual void Reset(Cell cell)
{
Debug.Assert(cell != null);
this.cell = cell;
Debug.Assert(children == null);
}
}
#endregion
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Avalonia.Platform;
namespace Avalonia.Shared.PlatformSupport
{
/// <summary>
/// Loads assets compiled into the application binary.
/// </summary>
public class AssetLoader : IAssetLoader
{
private static readonly Dictionary<string, AssemblyDescriptor> AssemblyNameCache
= new Dictionary<string, AssemblyDescriptor>();
private AssemblyDescriptor _defaultAssembly;
/// <summary>
/// Initializes a new instance of the <see cref="AssetLoader"/> class.
/// </summary>
/// <param name="assembly">
/// The default assembly from which to load assets for which no assembly is specified.
/// </param>
public AssetLoader(Assembly assembly = null)
{
if (assembly == null)
assembly = Assembly.GetEntryAssembly();
if (assembly != null)
_defaultAssembly = new AssemblyDescriptor(assembly);
}
/// <summary>
/// Sets the default assembly from which to load assets for which no assembly is specified.
/// </summary>
/// <param name="assembly">The default assembly.</param>
public void SetDefaultAssembly(Assembly assembly)
{
_defaultAssembly = new AssemblyDescriptor(assembly);
}
/// <summary>
/// Checks if an asset with the specified URI exists.
/// </summary>
/// <param name="uri">The URI.</param>
/// <param name="baseUri">
/// A base URI to use if <paramref name="uri"/> is relative.
/// </param>
/// <returns>True if the asset could be found; otherwise false.</returns>
public bool Exists(Uri uri, Uri baseUri = null)
{
return GetAsset(uri, baseUri) != null;
}
/// <summary>
/// Opens the resource with the requested URI.
/// </summary>
/// <param name="uri">The URI.</param>
/// <param name="baseUri">
/// A base URI to use if <paramref name="uri"/> is relative.
/// </param>
/// <returns>A stream containing the resource contents.</returns>
/// <exception cref="FileNotFoundException">
/// The resource was not found.
/// </exception>
public Stream Open(Uri uri, Uri baseUri = null)
{
var asset = GetAsset(uri, baseUri);
if (asset == null)
{
throw new FileNotFoundException($"The resource {uri} could not be found.");
}
return asset.GetStream();
}
private IAssetDescriptor GetAsset(Uri uri, Uri baseUri)
{
if (!uri.IsAbsoluteUri || uri.Scheme == "resm")
{
var asm = GetAssembly(uri) ?? GetAssembly(baseUri) ?? _defaultAssembly;
if (asm == null)
{
throw new ArgumentException(
"No default assembly, entry assembly or explicit assembly specified; " +
"don't know where to look up for the resource, try specifiyng assembly explicitly.");
}
IAssetDescriptor rv;
var resourceKey = uri.AbsolutePath;
asm.Resources.TryGetValue(resourceKey, out rv);
return rv;
}
throw new ArgumentException($"Invalid uri, see https://github.com/AvaloniaUI/Avalonia/issues/282#issuecomment-166982104", nameof(uri));
}
private AssemblyDescriptor GetAssembly(Uri uri)
{
if (uri != null)
{
var qs = ParseQueryString(uri);
string assemblyName;
if (qs.TryGetValue("assembly", out assemblyName))
{
return GetAssembly(assemblyName);
}
}
return null;
}
private AssemblyDescriptor GetAssembly(string name)
{
if (name == null)
{
return _defaultAssembly;
}
AssemblyDescriptor rv;
if (!AssemblyNameCache.TryGetValue(name, out rv))
{
var loadedAssemblies = AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetLoadedAssemblies();
var match = loadedAssemblies.FirstOrDefault(a => a.GetName().Name == name);
if (match != null)
{
AssemblyNameCache[name] = rv = new AssemblyDescriptor(match);
}
else
{
// iOS does not support loading assemblies dynamically!
//
#if NETSTANDARD
AssemblyNameCache[name] = rv = new AssemblyDescriptor(Assembly.Load(new AssemblyName(name)));
#elif __IOS__
throw new InvalidOperationException(
$"Assembly {name} needs to be referenced and explicitly loaded before loading resources");
#else
AssemblyNameCache[name] = rv = new AssemblyDescriptor(Assembly.Load(name));
#endif
}
}
return rv;
}
private Dictionary<string, string> ParseQueryString(Uri uri)
{
return uri.Query.TrimStart('?')
.Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries)
.Select(p => p.Split('='))
.ToDictionary(p => p[0], p => p[1]);
}
private interface IAssetDescriptor
{
Stream GetStream();
}
private class AssemblyResourceDescriptor : IAssetDescriptor
{
private readonly Assembly _asm;
private readonly string _name;
public AssemblyResourceDescriptor(Assembly asm, string name)
{
_asm = asm;
_name = name;
}
public Stream GetStream()
{
return _asm.GetManifestResourceStream(_name);
}
}
private class AssemblyDescriptor
{
public AssemblyDescriptor(Assembly assembly)
{
Assembly = assembly;
if (assembly != null)
{
Resources = assembly.GetManifestResourceNames()
.ToDictionary(n => n, n => (IAssetDescriptor)new AssemblyResourceDescriptor(assembly, n));
Name = assembly.GetName().Name;
}
}
public Assembly Assembly { get; }
public Dictionary<string, IAssetDescriptor> Resources { get; }
public string Name { get; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Android.App;
using Android.Bluetooth;
using Android.Bluetooth.LE;
using Android.OS;
using Android.Content;
using Java.Util;
using Plugin.BLE.Abstractions;
using Plugin.BLE.Abstractions.Contracts;
using Plugin.BLE.Extensions;
using Object = Java.Lang.Object;
using Trace = Plugin.BLE.Abstractions.Trace;
namespace Plugin.BLE.Android
{
public class Adapter : AdapterBase
{
private readonly BluetoothManager _bluetoothManager;
private readonly BluetoothAdapter _bluetoothAdapter;
private readonly Api18BleScanCallback _api18ScanCallback;
private readonly Api21BleScanCallback _api21ScanCallback;
private readonly GattCallback _gattCallback;
public override IList<IDevice> ConnectedDevices => ConnectedDeviceRegistry.Values.ToList();
/// <summary>
/// Used to store all connected devices
/// </summary>
public Dictionary<string, IDevice> ConnectedDeviceRegistry { get; }
/// <summary>
/// Registry used to store device instances for pending operations : connect
/// </summary>
public Dictionary<string, IDevice> DeviceOperationRegistry { get; }
public Adapter(BluetoothManager bluetoothManager)
{
_bluetoothManager = bluetoothManager;
_bluetoothAdapter = bluetoothManager.Adapter;
DeviceOperationRegistry = new Dictionary<string, IDevice>();
ConnectedDeviceRegistry = new Dictionary<string, IDevice>();
// TODO: bonding
//var bondStatusBroadcastReceiver = new BondStatusBroadcastReceiver();
//Application.Context.RegisterReceiver(bondStatusBroadcastReceiver,
// new IntentFilter(BluetoothDevice.ActionBondStateChanged));
////forward events from broadcast receiver
//bondStatusBroadcastReceiver.BondStateChanged += (s, args) =>
//{
// //DeviceBondStateChanged(this, args);
//};
if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
{
_api21ScanCallback = new Api21BleScanCallback(this);
}
else
{
_api18ScanCallback = new Api18BleScanCallback(this);
}
_gattCallback = new GattCallback(this);
}
protected override Task StartScanningForDevicesNativeAsync(Guid[] serviceUuids, bool allowDuplicatesKey, CancellationToken scanCancellationToken)
{
// clear out the list
DiscoveredDevices.Clear();
if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop)
{
StartScanningOld(serviceUuids);
}
else
{
StartScanningNew(serviceUuids);
}
return Task.FromResult(true);
}
private void StartScanningOld(Guid[] serviceUuids)
{
var hasFilter = serviceUuids?.Any() ?? false;
UUID[] uuids = null;
if (hasFilter)
{
uuids = serviceUuids.Select(u => UUID.FromString(u.ToString())).ToArray();
}
Trace.Message("Adapter < 21: Starting a scan for devices.");
#pragma warning disable 618
_bluetoothAdapter.StartLeScan(uuids, _api18ScanCallback);
#pragma warning restore 618
}
private void StartScanningNew(Guid[] serviceUuids)
{
var hasFilter = serviceUuids?.Any() ?? false;
List<ScanFilter> scanFilters = null;
if (hasFilter)
{
scanFilters = new List<ScanFilter>();
foreach (var serviceUuid in serviceUuids)
{
var sfb = new ScanFilter.Builder();
sfb.SetServiceUuid(ParcelUuid.FromString(serviceUuid.ToString()));
scanFilters.Add(sfb.Build());
}
}
var ssb = new ScanSettings.Builder();
ssb.SetScanMode(ScanMode.ToNative());
//ssb.SetCallbackType(ScanCallbackType.AllMatches);
if (_bluetoothAdapter.BluetoothLeScanner != null)
{
Trace.Message($"Adapter >=21: Starting a scan for devices. ScanMode: {ScanMode}");
if (hasFilter)
{
Trace.Message($"ScanFilters: {string.Join(", ", serviceUuids)}");
}
_bluetoothAdapter.BluetoothLeScanner.StartScan(scanFilters, ssb.Build(), _api21ScanCallback);
}
else
{
Trace.Message("Adapter >= 21: Scan failed. Bluetooth is probably off");
}
}
protected override void StopScanNative()
{
if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop)
{
Trace.Message("Adapter < 21: Stopping the scan for devices.");
#pragma warning disable 618
_bluetoothAdapter.StopLeScan(_api18ScanCallback);
#pragma warning restore 618
}
else
{
Trace.Message("Adapter >= 21: Stopping the scan for devices.");
_bluetoothAdapter.BluetoothLeScanner?.StopScan(_api21ScanCallback);
}
}
protected override Task ConnectToDeviceNativeAsync(IDevice device, ConnectParameters connectParameters, CancellationToken cancellationToken)
{
AddToDeviceOperationRegistry(device);
if (connectParameters.ForceBleTransport)
{
ConnectToGattForceBleTransportAPI(device, connectParameters.AutoConnect);
}
else
{
((BluetoothDevice)device.NativeDevice).ConnectGatt(Application.Context, connectParameters.AutoConnect, _gattCallback);
}
return Task.FromResult(true);
}
private void ConnectToGattForceBleTransportAPI(IDevice device, bool autoconnect)
{
var nativeDevice = ((BluetoothDevice)device.NativeDevice);
//This parameter is present from API 18 but only public from API 23
//So reflection is used before API 23
if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop)
{
//no transport mode before lollipop, it will probably not work... gattCallBackError 133 again alas
nativeDevice.ConnectGatt(Application.Context, autoconnect, _gattCallback);
}
else if (Build.VERSION.SdkInt < BuildVersionCodes.M)
{
var m = nativeDevice.Class.GetDeclaredMethod("connectGatt", Java.Lang.Class.FromType(typeof(Context)),
Java.Lang.Boolean.Type,
Java.Lang.Class.FromType(typeof(BluetoothGattCallback)),
Java.Lang.Integer.Type);
var transport = nativeDevice.Class.GetDeclaredField("TRANSPORT_LE").GetInt(null); // LE = 2, BREDR = 1, AUTO = 0
m.Invoke(nativeDevice, Application.Context, false, _gattCallback, transport);
}
else
{
nativeDevice.ConnectGatt(Application.Context, autoconnect, _gattCallback, BluetoothTransports.Le);
}
}
protected override void DisconnectDeviceNative(IDevice device)
{
//make sure everything is disconnected
AddToDeviceOperationRegistry(device);
((Device)device).Disconnect();
}
public override async Task<IDevice> ConnectToKnownDeviceAsync(Guid deviceGuid, ConnectParameters connectParameters = default(ConnectParameters), CancellationToken cancellationToken = default(CancellationToken))
{
var macBytes = deviceGuid.ToByteArray().Skip(10).Take(6).ToArray();
var nativeDevice = _bluetoothAdapter.GetRemoteDevice(macBytes);
var device = new Device(this, nativeDevice, null, null, 0, new byte[] { });
await ConnectToDeviceAsync(device, connectParameters, cancellationToken);
return device;
}
public override List<IDevice> GetSystemConnectedOrPairedDevices(Guid[] services = null)
{
if (services != null)
{
Trace.Message("Caution: GetSystemConnectedDevices does not take into account the 'services' parameter on Android.");
}
//add dualMode type too as they are BLE too ;)
var connectedDevices = _bluetoothManager.GetConnectedDevices(ProfileType.Gatt).Where(d => d.Type == BluetoothDeviceType.Le || d.Type == BluetoothDeviceType.Dual);
var bondedDevices = _bluetoothAdapter.BondedDevices.Where(d => d.Type == BluetoothDeviceType.Le || d.Type == BluetoothDeviceType.Dual);
return connectedDevices.Union(bondedDevices, new DeviceComparer()).Select(d => new Device(this, d, null, null, 0)).Cast<IDevice>().ToList();
}
private class DeviceComparer : IEqualityComparer<BluetoothDevice>
{
public bool Equals(BluetoothDevice x, BluetoothDevice y)
{
return x.Address == y.Address;
}
public int GetHashCode(BluetoothDevice obj)
{
return obj.GetHashCode();
}
}
private void AddToDeviceOperationRegistry(IDevice device)
{
var nativeDevice = ((BluetoothDevice)device.NativeDevice);
DeviceOperationRegistry[nativeDevice.Address] = device;
}
public class Api18BleScanCallback : Object, BluetoothAdapter.ILeScanCallback
{
private readonly Adapter _adapter;
public Api18BleScanCallback(Adapter adapter)
{
_adapter = adapter;
}
public void OnLeScan(BluetoothDevice bleDevice, int rssi, byte[] scanRecord)
{
Trace.Message("Adapter.LeScanCallback: " + bleDevice.Name);
_adapter.HandleDiscoveredDevice(new Device(_adapter, bleDevice, null, null, rssi, scanRecord));
}
}
public class Api21BleScanCallback : ScanCallback
{
private readonly Adapter _adapter;
public Api21BleScanCallback(Adapter adapter)
{
_adapter = adapter;
}
public override void OnScanFailed(ScanFailure errorCode)
{
Trace.Message("Adapter: Scan failed with code {0}", errorCode);
base.OnScanFailed(errorCode);
}
public override void OnScanResult(ScanCallbackType callbackType, ScanResult result)
{
base.OnScanResult(callbackType, result);
/* Might want to transition to parsing the API21+ ScanResult, but sort of a pain for now
List<AdvertisementRecord> records = new List<AdvertisementRecord>();
records.Add(new AdvertisementRecord(AdvertisementRecordType.Flags, BitConverter.GetBytes(result.ScanRecord.AdvertiseFlags)));
if (!string.IsNullOrEmpty(result.ScanRecord.DeviceName))
{
records.Add(new AdvertisementRecord(AdvertisementRecordType.CompleteLocalName, Encoding.UTF8.GetBytes(result.ScanRecord.DeviceName)));
}
for (int i = 0; i < result.ScanRecord.ManufacturerSpecificData.Size(); i++)
{
int key = result.ScanRecord.ManufacturerSpecificData.KeyAt(i);
var arr = result.ScanRecord.GetManufacturerSpecificData(key);
byte[] data = new byte[arr.Length + 2];
BitConverter.GetBytes((ushort)key).CopyTo(data,0);
arr.CopyTo(data, 2);
records.Add(new AdvertisementRecord(AdvertisementRecordType.ManufacturerSpecificData, data));
}
foreach(var uuid in result.ScanRecord.ServiceUuids)
{
records.Add(new AdvertisementRecord(AdvertisementRecordType.UuidsIncomplete128Bit, uuid.Uuid.));
}
foreach(var key in result.ScanRecord.ServiceData.Keys)
{
records.Add(new AdvertisementRecord(AdvertisementRecordType.ServiceData, result.ScanRecord.ServiceData));
}*/
var device = new Device(_adapter, result.Device, null, null, result.Rssi, result.ScanRecord.GetBytes());
//Device device;
//if (result.ScanRecord.ManufacturerSpecificData.Size() > 0)
//{
// int key = result.ScanRecord.ManufacturerSpecificData.KeyAt(0);
// byte[] mdata = result.ScanRecord.GetManufacturerSpecificData(key);
// byte[] mdataWithKey = new byte[mdata.Length + 2];
// BitConverter.GetBytes((ushort)key).CopyTo(mdataWithKey, 0);
// mdata.CopyTo(mdataWithKey, 2);
// device = new Device(result.Device, null, null, result.Rssi, mdataWithKey);
//}
//else
//{
// device = new Device(result.Device, null, null, result.Rssi, new byte[0]);
//}
_adapter.HandleDiscoveredDevice(device);
}
}
}
}
| |
//
// Copyright 2012, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;
# if ! __UNIFIED__
using MonoTouch.UIKit;
using MonoTouch.Foundation;
#else
using UIKit;
using Foundation;
#endif
using Xamarin.Controls;
using Xamarin.Utilities.iOS;
namespace Xamarin.Auth
{
internal class FormAuthenticatorController : UITableViewController
{
FormAuthenticator authenticator;
ProgressLabel progress;
CancellationTokenSource cancelSource;
public FormAuthenticatorController (FormAuthenticator authenticator)
: base (UITableViewStyle.Grouped)
{
this.authenticator = authenticator;
Title = authenticator.Title;
TableView.DataSource = new FormDataSource (this);
TableView.Delegate = new FormDelegate (this);
if (authenticator.AllowCancel) {
NavigationItem.LeftBarButtonItem = new UIBarButtonItem (
UIBarButtonSystemItem.Cancel,
delegate {
StopProgress();
authenticator.OnCancelled();
});
}
}
void HandleSubmit ()
{
if (progress == null) {
progress = new ProgressLabel (NSBundle.MainBundle.LocalizedString ("Verifying", "Verifying status message when adding accounts"));
NavigationItem.TitleView = progress;
progress.StartAnimating ();
}
cancelSource = new CancellationTokenSource ();
authenticator.SignInAsync (cancelSource.Token).ContinueWith (task => {
StopProgress ();
if (task.IsFaulted) {
this.ShowError ("Error Signing In", task.Exception);
}
else {
authenticator.OnSucceeded (task.Result);
}
}, TaskScheduler.FromCurrentSynchronizationContext ());
}
void StopProgress ()
{
if (progress != null) {
progress.StopAnimating ();
NavigationItem.TitleView = null;
progress = null;
}
}
class FormDelegate : UITableViewDelegate
{
FormAuthenticatorController controller;
public FormDelegate (FormAuthenticatorController controller)
{
this.controller = controller;
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
tableView.ResignFirstResponder ();
if (indexPath.Section == 1) {
tableView.DeselectRow (indexPath, true);
((FormDataSource)tableView.DataSource).ResignFirstResponder ();
controller.HandleSubmit ();
}
else if (indexPath.Section == 2) {
tableView.DeselectRow (indexPath, true);
UIApplication.SharedApplication.OpenUrl (
new NSUrl (controller.authenticator.CreateAccountLink.AbsoluteUri));
}
}
}
class FieldCell : UITableViewCell
{
public static readonly UIFont LabelFont = UIFont.BoldSystemFontOfSize (16);
public static readonly UIFont FieldFont = UIFont.SystemFontOfSize (16);
static readonly UIColor FieldColor = UIColor.FromRGB (56, 84, 135);
public UITextField TextField { get; private set; }
#if ! __UNIFIED__
public FieldCell (FormAuthenticatorField field, float fieldXPosition, Action handleReturn)
#else
public FieldCell(FormAuthenticatorField field, nfloat fieldXPosition, Action handleReturn)
#endif
: base (UITableViewCellStyle.Default, "Field")
{
SelectionStyle = UITableViewCellSelectionStyle.None;
TextLabel.Text = field.Title;
var hang = 3;
var h = FieldFont.PointSize + hang;
var cellSize = Frame.Size;
#if ! __UNIFIED__
TextField = new UITextField (new RectangleF (
fieldXPosition, (cellSize.Height - h)/2,
cellSize.Width - fieldXPosition - 12, h)) {
#else
TextField = new UITextField(new CoreGraphics.CGRect(
fieldXPosition, (cellSize.Height - h) / 2,
cellSize.Width - fieldXPosition - 12, h))
{
#endif
Font = FieldFont,
Placeholder = field.Placeholder,
Text = field.Value,
TextColor = FieldColor,
AutoresizingMask = UIViewAutoresizing.FlexibleWidth,
SecureTextEntry = (field.FieldType == FormAuthenticatorFieldType.Password),
KeyboardType = (field.FieldType == FormAuthenticatorFieldType.Email) ?
UIKeyboardType.EmailAddress :
UIKeyboardType.Default,
AutocorrectionType = (field.FieldType == FormAuthenticatorFieldType.PlainText) ?
UITextAutocorrectionType.Yes :
UITextAutocorrectionType.No,
AutocapitalizationType = UITextAutocapitalizationType.None,
ShouldReturn = delegate {
handleReturn ();
return false;
},
};
TextField.EditingDidEnd += delegate {
field.Value = TextField.Text;
};
ContentView.AddSubview (TextField);
}
}
class FormDataSource : UITableViewDataSource
{
FormAuthenticatorController controller;
public FormDataSource (FormAuthenticatorController controller)
{
this.controller = controller;
}
#if ! __UNIFIED__
public override int NumberOfSections (UITableView tableView)
#else
public override nint NumberOfSections (UITableView tableView)
#endif
{
return 2 + (controller.authenticator.CreateAccountLink != null ? 1 : 0);
}
#if ! __UNIFIED__
public override int RowsInSection (UITableView tableView, int section)
#else
public override nint RowsInSection (UITableView tableView, nint section)
#endif
{
if (section == 0) {
return controller.authenticator.Fields.Count;
}
else {
return 1;
}
}
FieldCell[] fieldCells = null;
public void SelectNext ()
{
for (var i = 0; i < controller.authenticator.Fields.Count; i++) {
if (fieldCells[i].TextField.IsFirstResponder) {
if (i + 1 < fieldCells.Length) {
fieldCells[i+1].TextField.BecomeFirstResponder ();
return;
}
else {
fieldCells[i].TextField.ResignFirstResponder ();
controller.HandleSubmit ();
return;
}
}
}
}
public void ResignFirstResponder ()
{
foreach (var cell in fieldCells) {
cell.TextField.ResignFirstResponder ();
}
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
if (indexPath.Section == 0) {
if (fieldCells == null) {
var fieldXPosition = controller
.authenticator
.Fields
#if ! __UNIFIED__
.Select (f => tableView.StringSize (f.Title, FieldCell.LabelFont).Width)
#else
.Select(f => UIKit.UIStringDrawing.StringSize(f.Title, FieldCell.LabelFont).Width)
#endif
.Max ();
fieldXPosition += 36;
fieldCells = controller
.authenticator
.Fields
#if ! __UNIFIED__
.Select (f => new FieldCell (f, fieldXPosition, SelectNext))
#else
.Select(f => new FieldCell(f, fieldXPosition, SelectNext))
#endif
.ToArray ();
}
return fieldCells[indexPath.Row];
}
else if (indexPath.Section == 1) {
var cell = tableView.DequeueReusableCell ("SignIn");
if (cell == null) {
cell = new UITableViewCell (UITableViewCellStyle.Default, "SignIn");
cell.TextLabel.TextAlignment = UITextAlignment.Center;
}
cell.TextLabel.Text = NSBundle.MainBundle.LocalizedString ("Sign In", "Sign In button title");
return cell;
}
else {
var cell = tableView.DequeueReusableCell ("CreateAccount");
if (cell == null) {
cell = new UITableViewCell (UITableViewCellStyle.Default, "CreateAccount");
cell.TextLabel.TextAlignment = UITextAlignment.Center;
}
cell.TextLabel.Text = NSBundle.MainBundle.LocalizedString ("Create Account", "Create Account button title");
return cell;
}
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="WeakEventTable.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description: Storage for the "weak event listener" pattern.
// See WeakEventManager.cs for an overview.
//
//---------------------------------------------------------------------------
using System;
using System.Diagnostics; // Debug
using System.Collections; // Hashtable
using System.Collections.Specialized; // HybridDictionary
using System.Runtime.CompilerServices; // RuntimeHelpers
using System.Security; // [SecurityCritical,SecurityTreatAsSafe]
using System.Threading; // [ThreadStatic]
using System.Windows; // WeakEventManager
using System.Windows.Threading; // DispatcherObject
using MS.Utility; // FrugalList
namespace MS.Internal
{
/// <summary>
/// This class manages the correspondence between event types and
/// event managers, in support of the "weak event listener" pattern.
/// It also stores data on behalf of the managers; a manager can store
/// data of its own choosing, indexed by the pair (manager, source).
/// </summary>
internal class WeakEventTable : DispatcherObject
{
#region Constructors
//
// Constructors
//
/// <summary>
/// Create a new instance of WeakEventTable.
/// </summary>
/// <SecurityNote>
/// Critical: This code calls into Link demanded methods
/// (AppDomain.DomainUnload and AppDomain.ProcessExit) to attach handlers
/// TreatAsSafe: This code does not take any parameter or return state.
/// It simply attaches private call back.
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
private WeakEventTable()
{
WeakEventTableShutDownListener listener = new WeakEventTableShutDownListener(this);
}
#endregion Constructors
#region Internal Properties
//
// Internal Properties
//
/// <summary>
/// Return the WeakEventTable for the current thread
/// </summary>
internal static WeakEventTable CurrentWeakEventTable
{
get
{
// _currentTable is [ThreadStatic], so there's one per thread
if (_currentTable == null)
{
_currentTable = new WeakEventTable();
}
return _currentTable;
}
}
/// <summary>
/// Take a read-lock on the table, and return the IDisposable.
/// Queries to the table should occur within a
/// "using (Table.ReadLock) { ... }" clause, except for queries
/// that are already within a write lock.
/// </summary>
internal IDisposable ReadLock
{
get { return _lock.ReadLock; }
}
/// <summary>
/// Take a write-lock on the table, and return the IDisposable.
/// All modifications to the table should occur within a
/// "using (Table.WriteLock) { ... }" clause.
/// </summary>
internal IDisposable WriteLock
{
get { return _lock.WriteLock; }
}
/// <summary>
/// Get or set the manager instance for the given type.
/// </summary>
internal WeakEventManager this[Type managerType]
{
get { return (WeakEventManager)_managerTable[managerType]; }
set { _managerTable[managerType] = value; }
}
/// <summary>
/// Get or set the manager instance for the given event.
/// </summary>
internal WeakEventManager this[Type eventSourceType, string eventName]
{
get
{
EventNameKey key = new EventNameKey(eventSourceType, eventName);
return (WeakEventManager)_eventNameTable[key];
}
set
{
EventNameKey key = new EventNameKey(eventSourceType, eventName);
_eventNameTable[key] = value;
}
}
/// <summary>
/// Get or set the data stored by the given manager for the given source.
/// </summary>
internal object this[WeakEventManager manager, object source]
{
get
{
EventKey key = new EventKey(manager, source);
object result = _dataTable[key];
return result;
}
set
{
EventKey key = new EventKey(manager, source, true);
_dataTable[key] = value;
}
}
/// <summary>
/// Indicates whether cleanup is enabled.
/// </summary>
/// <remarks>
/// Normally cleanup is always enabled, but a perf test environment might
/// want to disable cleanup so that it doesn't interfere with the real
/// perf measurements.
/// </remarks>
internal bool IsCleanupEnabled
{
get { return _cleanupEnabled; }
set { _cleanupEnabled = value; }
}
#endregion Internal Properties
#region Internal Methods
//
// Internal Methods
//
/// <summary>
/// Remove the data for the given manager and source.
/// </summary>
internal void Remove(WeakEventManager manager, object source)
{
EventKey key = new EventKey(manager, source);
_dataTable.Remove(key);
}
/// <summary>
/// Schedule a cleanup pass. This can be called from any thread.
/// </summary>
internal void ScheduleCleanup()
{
// only the first request after a previous cleanup should schedule real work
if (Interlocked.Increment(ref _cleanupRequests) == 1)
{
Dispatcher.BeginInvoke(DispatcherPriority.ContextIdle, new DispatcherOperationCallback(CleanupOperation), null);
}
}
/// <summary>
/// Perform a cleanup pass.
/// </summary>
internal static bool Cleanup()
{
return CurrentWeakEventTable.Purge(false);
}
#endregion Internal Methods
#region Private Methods
//
// Private Methods
//
// run a cleanup pass
private object CleanupOperation(object arg)
{
// allow new requests, even if cleanup is disabled
Interlocked.Exchange(ref _cleanupRequests, 0);
if (IsCleanupEnabled)
{
Purge(false);
}
return null;
}
// remove dead entries. When purgeAll is true, remove all entries.
private bool Purge(bool purgeAll)
{
bool foundDirt = false;
using (this.WriteLock)
{
// copy the keys into a separate array, so that later on
// we can change the table while iterating over the keys
ICollection ic = _dataTable.Keys;
EventKey[] keys = new EventKey[ic.Count];
ic.CopyTo(keys, 0);
for (int i=keys.Length-1; i>=0; --i)
{
object data = _dataTable[keys[i]];
// a purge earlier in the loop may have removed keys[i],
// in which case there's nothing more to do
if (data != null)
{
object source = keys[i].Source;
foundDirt |= keys[i].Manager.PurgeInternal(source, data, purgeAll);
// if source has been GC'd, remove its data
if (!purgeAll && source == null)
{
_dataTable.Remove(keys[i]);
}
}
}
if (purgeAll)
{
_managerTable.Clear();
_dataTable.Clear();
}
}
return foundDirt;
}
// do the final cleanup when the Dispatcher or AppDomain is shut down
private void OnShutDown()
{
Purge(true);
// remove the table from thread storage
_currentTable = null;
}
#endregion Private Methods
#region Private Fields
//
// Private Fields
//
private Hashtable _managerTable = new Hashtable(); // maps manager type -> instance
private Hashtable _dataTable = new Hashtable(); // maps EventKey -> data
private Hashtable _eventNameTable = new Hashtable(); // maps <Type,name> -> manager
ReaderWriterLockWrapper _lock = new ReaderWriterLockWrapper();
private int _cleanupRequests;
private bool _cleanupEnabled = true;
[ThreadStatic]
private static WeakEventTable _currentTable; // one table per thread
#endregion Private Fields
#region WeakEventTableShutDownListener
private sealed class WeakEventTableShutDownListener : ShutDownListener
{
/// <SecurityNote>
/// Critical: accesses AppDomain.DomainUnload event
/// TreatAsSafe: This code does not take any parameter or return state.
/// It simply attaches private callbacks.
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
public WeakEventTableShutDownListener(WeakEventTable target) : base(target)
{
}
internal override void OnShutDown(object target, object sender, EventArgs e)
{
WeakEventTable table = (WeakEventTable)target;
table.OnShutDown();
}
}
#endregion WeakEventTableShutDownListener
#region Table Keys
// the key for the data table: <manager, ((source)), hashcode>
private struct EventKey
{
internal EventKey(WeakEventManager manager, object source, bool useWeakRef)
{
_manager = manager;
_source = new WeakReference(source);
_hashcode = unchecked(manager.GetHashCode() + RuntimeHelpers.GetHashCode(source));
}
internal EventKey(WeakEventManager manager, object source)
{
_manager = manager;
_source = source;
_hashcode = unchecked(manager.GetHashCode() + RuntimeHelpers.GetHashCode(source));
}
internal object Source
{
get { return ((WeakReference)_source).Target; }
}
internal WeakEventManager Manager
{
get { return _manager; }
}
public override int GetHashCode()
{
#if DEBUG
WeakReference wr = _source as WeakReference;
object source = (wr != null) ? wr.Target : _source;
if (source != null)
{
int hashcode = unchecked(_manager.GetHashCode() + RuntimeHelpers.GetHashCode(source));
Debug.Assert(hashcode == _hashcode, "hashcodes disagree");
}
#endif
return _hashcode;
}
public override bool Equals(object o)
{
if (o is EventKey)
{
WeakReference wr;
EventKey ek = (EventKey)o;
if (_manager != ek._manager || _hashcode != ek._hashcode)
return false;
wr = this._source as WeakReference;
object s1 = (wr != null) ? wr.Target : this._source;
wr = ek._source as WeakReference;
object s2 = (wr != null) ? wr.Target : ek._source;
if (s1!=null && s2!=null)
return (s1 == s2);
else
return (_source == ek._source);
}
else
{
return false;
}
}
public static bool operator==(EventKey key1, EventKey key2)
{
return key1.Equals(key2);
}
public static bool operator!=(EventKey key1, EventKey key2)
{
return !key1.Equals(key2);
}
WeakEventManager _manager;
object _source; // lookup: direct ref; In table: WeakRef
int _hashcode; // cached, in case source is GC'd
}
// the key for the event name table: <ownerType, eventName>
private struct EventNameKey
{
public EventNameKey(Type eventSourceType, string eventName)
{
_eventSourceType = eventSourceType;
_eventName = eventName;
}
public override int GetHashCode()
{
return unchecked(_eventSourceType.GetHashCode() + _eventName.GetHashCode());
}
public override bool Equals(object o)
{
if (o is EventNameKey)
{
EventNameKey that = (EventNameKey)o;
return (this._eventSourceType == that._eventSourceType && this._eventName == that._eventName);
}
else
return false;
}
public static bool operator==(EventNameKey key1, EventNameKey key2)
{
return key1.Equals(key2);
}
public static bool operator!=(EventNameKey key1, EventNameKey key2)
{
return !key1.Equals(key2);
}
Type _eventSourceType;
string _eventName;
}
#endregion Table Keys
}
}
| |
// 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.Contracts;
using System.Net;
using System.Net.Http;
namespace System.ServiceModel.Channels
{
public sealed class HttpResponseMessageProperty : IMessageProperty, IMergeEnabledMessageProperty
{
private TraditionalHttpResponseMessageProperty _traditionalProperty;
private HttpResponseMessageBackedProperty _httpBackedProperty;
private bool _useHttpBackedProperty;
private bool _initialCopyPerformed;
public HttpResponseMessageProperty()
{
_traditionalProperty = new TraditionalHttpResponseMessageProperty();
_useHttpBackedProperty = false;
}
internal HttpResponseMessageProperty(WebHeaderCollection originalHeaders)
{
_traditionalProperty = new TraditionalHttpResponseMessageProperty(originalHeaders);
_useHttpBackedProperty = false;
}
internal HttpResponseMessageProperty(HttpResponseMessage httpResponseMessage)
{
_httpBackedProperty = new HttpResponseMessageBackedProperty(httpResponseMessage);
_useHttpBackedProperty = true;
}
public static string Name
{
get { return "httpResponse"; }
}
public WebHeaderCollection Headers
{
get
{
return _useHttpBackedProperty ?
_httpBackedProperty.Headers :
_traditionalProperty.Headers;
}
}
public HttpStatusCode StatusCode
{
get
{
return _useHttpBackedProperty ?
_httpBackedProperty.StatusCode :
_traditionalProperty.StatusCode;
}
set
{
int valueInt = (int)value;
if (valueInt < 100 || valueInt > 599)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
string.Format(SRServiceModel.ValueMustBeInRange, 100, 599)));
}
if (_useHttpBackedProperty)
{
_httpBackedProperty.StatusCode = value;
}
else
{
_traditionalProperty.StatusCode = value;
}
}
}
internal bool HasStatusCodeBeenSet
{
get
{
return _useHttpBackedProperty ?
true :
_traditionalProperty.HasStatusCodeBeenSet;
}
}
public string StatusDescription
{
get
{
return _useHttpBackedProperty ?
_httpBackedProperty.StatusDescription :
_traditionalProperty.StatusDescription;
}
set
{
if (_useHttpBackedProperty)
{
_httpBackedProperty.StatusDescription = value;
}
else
{
_traditionalProperty.StatusDescription = value;
}
}
}
public bool SuppressEntityBody
{
get
{
return _useHttpBackedProperty ?
_httpBackedProperty.SuppressEntityBody :
_traditionalProperty.SuppressEntityBody;
}
set
{
if (_useHttpBackedProperty)
{
_httpBackedProperty.SuppressEntityBody = value;
}
else
{
_traditionalProperty.SuppressEntityBody = value;
}
}
}
public bool SuppressPreamble
{
get
{
return _useHttpBackedProperty ?
false :
_traditionalProperty.SuppressPreamble;
}
set
{
if (!_useHttpBackedProperty)
{
_traditionalProperty.SuppressPreamble = value;
}
}
}
public HttpResponseMessage HttpResponseMessage
{
get
{
if (_useHttpBackedProperty)
{
return _httpBackedProperty.HttpResponseMessage;
}
return null;
}
}
internal static HttpResponseMessage GetHttpResponseMessageFromMessage(Message message)
{
HttpResponseMessage httpResponseMessage = null;
HttpResponseMessageProperty property = message.Properties.GetValue<HttpResponseMessageProperty>(HttpResponseMessageProperty.Name);
if (property != null)
{
httpResponseMessage = property.HttpResponseMessage;
if (httpResponseMessage != null)
{
httpResponseMessage.CopyPropertiesFromMessage(message);
message.EnsureReadMessageState();
}
}
return httpResponseMessage;
}
IMessageProperty IMessageProperty.CreateCopy()
{
if (!_useHttpBackedProperty ||
!_initialCopyPerformed)
{
_initialCopyPerformed = true;
return this;
}
return _httpBackedProperty.CreateTraditionalResponseMessageProperty();
}
bool IMergeEnabledMessageProperty.TryMergeWithProperty(object propertyToMerge)
{
// The ImmutableDispatchRuntime will merge MessageProperty instances from the
// OperationContext (that were created before the response message was created) with
// MessageProperty instances on the message itself. The message's version of the
// HttpResponseMessageProperty may hold a reference to an HttpResponseMessage, and this
// cannot be discarded, so values from the OperationContext's property must be set on
// the message's version without completely replacing the message's property.
if (_useHttpBackedProperty)
{
HttpResponseMessageProperty responseProperty = propertyToMerge as HttpResponseMessageProperty;
if (responseProperty != null)
{
if (!responseProperty._useHttpBackedProperty)
{
_httpBackedProperty.MergeWithTraditionalProperty(responseProperty._traditionalProperty);
responseProperty._traditionalProperty = null;
responseProperty._httpBackedProperty = _httpBackedProperty;
responseProperty._useHttpBackedProperty = true;
}
return true;
}
}
return false;
}
private class TraditionalHttpResponseMessageProperty
{
public const HttpStatusCode DefaultStatusCode = HttpStatusCode.OK;
public const string DefaultStatusDescription = null; // null means use description from status code
private HttpStatusCode _statusCode;
public TraditionalHttpResponseMessageProperty()
{
_statusCode = DefaultStatusCode;
this.StatusDescription = DefaultStatusDescription;
}
private WebHeaderCollection _headers;
private WebHeaderCollection _originalHeaders;
public TraditionalHttpResponseMessageProperty(WebHeaderCollection originalHeaders) : this()
{
_originalHeaders = originalHeaders;
}
public WebHeaderCollection Headers
{
get
{
if (_headers == null)
{
_headers = new WebHeaderCollection();
if (_originalHeaders != null)
{
foreach (var headerKey in _originalHeaders.AllKeys)
{
_headers[headerKey] = _originalHeaders[headerKey];
}
_originalHeaders = null;
}
}
return _headers;
}
}
public HttpStatusCode StatusCode
{
get
{
return _statusCode;
}
set
{
_statusCode = value;
this.HasStatusCodeBeenSet = true;
}
}
public bool HasStatusCodeBeenSet { get; private set; }
public string StatusDescription { get; set; }
public bool SuppressEntityBody { get; set; }
public bool SuppressPreamble { get; set; }
}
private class HttpResponseMessageBackedProperty
{
public HttpResponseMessageBackedProperty(HttpResponseMessage httpResponseMessage)
{
Contract.Assert(httpResponseMessage != null, "The 'httpResponseMessage' property should never be null.");
this.HttpResponseMessage = httpResponseMessage;
}
public HttpResponseMessage HttpResponseMessage { get; private set; }
private WebHeaderCollection _headers;
public WebHeaderCollection Headers
{
get
{
if (_headers == null)
{
_headers = this.HttpResponseMessage.ToWebHeaderCollection();
}
return _headers;
}
}
public HttpStatusCode StatusCode
{
get
{
return this.HttpResponseMessage.StatusCode;
}
set
{
this.HttpResponseMessage.StatusCode = value;
}
}
public string StatusDescription
{
get
{
return this.HttpResponseMessage.ReasonPhrase;
}
set
{
this.HttpResponseMessage.ReasonPhrase = value;
}
}
public bool SuppressEntityBody
{
get
{
HttpContent content = this.HttpResponseMessage.Content;
if (content != null)
{
long? contentLength = content.Headers.ContentLength;
if (!contentLength.HasValue ||
(contentLength.HasValue && contentLength.Value > 0))
{
return false;
}
}
return true;
}
set
{
HttpContent content = this.HttpResponseMessage.Content;
if (value && content != null &&
(!content.Headers.ContentLength.HasValue ||
content.Headers.ContentLength.Value > 0))
{
HttpContent newContent = new ByteArrayContent(Array.Empty<byte>());
foreach (KeyValuePair<string, IEnumerable<string>> header in content.Headers)
{
newContent.Headers.AddHeaderWithoutValidation(header);
}
this.HttpResponseMessage.Content = newContent;
content.Dispose();
}
else if (!value && content == null)
{
this.HttpResponseMessage.Content = new ByteArrayContent(Array.Empty<byte>());
}
}
}
public HttpResponseMessageProperty CreateTraditionalResponseMessageProperty()
{
HttpResponseMessageProperty copiedProperty = new HttpResponseMessageProperty();
foreach (var headerKey in this.Headers.AllKeys)
{
copiedProperty.Headers[headerKey] = this.Headers[headerKey];
}
if (this.StatusCode != TraditionalHttpResponseMessageProperty.DefaultStatusCode)
{
copiedProperty.StatusCode = this.StatusCode;
}
copiedProperty.StatusDescription = this.StatusDescription;
copiedProperty.SuppressEntityBody = this.SuppressEntityBody;
return copiedProperty;
}
public void MergeWithTraditionalProperty(TraditionalHttpResponseMessageProperty propertyToMerge)
{
if (propertyToMerge.HasStatusCodeBeenSet)
{
this.StatusCode = propertyToMerge.StatusCode;
}
if (propertyToMerge.StatusDescription != TraditionalHttpResponseMessageProperty.DefaultStatusDescription)
{
this.StatusDescription = propertyToMerge.StatusDescription;
}
this.SuppressEntityBody = propertyToMerge.SuppressEntityBody;
this.HttpResponseMessage.MergeWebHeaderCollection(propertyToMerge.Headers);
}
}
}
}
| |
// 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.Reflection;
using System.Reflection.Emit;
using Xunit;
namespace System.Reflection.Emit.Lightweight.Tests
{
public class DynamicMethodCreateDelegateStaticTests
{
private const string c_DYNAMIC_METHOD_NAME = "TestDynamicMethodA";
private readonly Type _DYNAMIC_METHOD_OWNER_TYPE = typeof(TestCreateDelegateOwner2);
private readonly Type _DYNAMIC_METHOD_OWNER_DERIVED_TYPE = typeof(TestCreateDelegateOwner2Derived);
private const string c_FIELD_NAME = "_id";
public Module CurrentModule
{
get
{
return typeof(DynamicMethodCreateDelegateStaticTests).GetTypeInfo().Assembly.ManifestModule;
}
}
[Fact]
public void PosTest1()
{
DynamicMethod testDynMethod;
FieldInfo fieldInfo;
TestCreateDelegateOwner2 target = new TestCreateDelegateOwner2();
int newId = 100;
bool actualResult;
fieldInfo = _DYNAMIC_METHOD_OWNER_TYPE.GetField(
c_FIELD_NAME,
BindingFlags.NonPublic |
BindingFlags.Instance);
testDynMethod = this.CreateDynMethod(_DYNAMIC_METHOD_OWNER_TYPE);
this.EmitDynMethodBody(testDynMethod, fieldInfo);
UseLikeStatic2 staticCallBack = (UseLikeStatic2)testDynMethod.CreateDelegate(typeof(UseLikeStatic2));
actualResult = target.ID == staticCallBack(target, newId);
actualResult = (target.ID == newId) && actualResult;
Assert.True(actualResult, "Failed to create delegate for dynamic method.");
}
[Fact]
public void PosTest2()
{
DynamicMethod testDynMethod;
FieldInfo fieldInfo;
TestCreateDelegateOwner2Derived target = new TestCreateDelegateOwner2Derived();
int newId = 100;
bool actualResult;
fieldInfo = _DYNAMIC_METHOD_OWNER_TYPE.GetField(
c_FIELD_NAME,
BindingFlags.NonPublic |
BindingFlags.Instance);
testDynMethod = this.CreateDynMethod(_DYNAMIC_METHOD_OWNER_TYPE);
this.EmitDynMethodBody(testDynMethod, fieldInfo);
UseLikeStatic2 staticCallBack = (UseLikeStatic2)testDynMethod.CreateDelegate(typeof(UseLikeStatic2));
actualResult = target.ID == staticCallBack(target, newId);
actualResult = (target.ID == newId) && actualResult;
Assert.True(actualResult, "Failed to create delegate for dynamic method.");
}
[Fact]
public void PosTest3()
{
DynamicMethod testDynMethod;
FieldInfo fieldInfo;
TestCreateDelegateOwner2 target = new TestCreateDelegateOwner2();
int newId = 100;
bool actualResult;
fieldInfo = _DYNAMIC_METHOD_OWNER_TYPE.GetField(
c_FIELD_NAME,
BindingFlags.NonPublic |
BindingFlags.Instance);
testDynMethod = this.CreateDynMethod(this.CurrentModule);
this.EmitDynMethodBody(testDynMethod, fieldInfo);
UseLikeStatic2 staticCallBack = (UseLikeStatic2)testDynMethod.CreateDelegate(typeof(UseLikeStatic2));
actualResult = target.ID == staticCallBack(target, newId);
actualResult = (target.ID == newId) && actualResult;
Assert.True(actualResult, "Failed to create delegate for dynamic method.");
}
[Fact]
public void PosTest4()
{
DynamicMethod testDynMethod;
FieldInfo fieldInfo;
TestCreateDelegateOwner2Derived target = new TestCreateDelegateOwner2Derived();
int newId = 100;
bool actualResult;
fieldInfo = _DYNAMIC_METHOD_OWNER_TYPE.GetField(
c_FIELD_NAME,
BindingFlags.NonPublic |
BindingFlags.Instance);
testDynMethod = this.CreateDynMethod(this.CurrentModule);
this.EmitDynMethodBody(testDynMethod, fieldInfo);
UseLikeStatic2 staticCallBack = (UseLikeStatic2)testDynMethod.CreateDelegate(typeof(UseLikeStatic2));
actualResult = target.ID == staticCallBack(target, newId);
actualResult = (target.ID == newId) && actualResult;
Assert.True(actualResult, "Failed to create delegate for dynamic method.");
}
[Fact]
public void NegTest1()
{
DynamicMethod testDynMethod;
TestCreateDelegateOwner2 target = new TestCreateDelegateOwner2();
testDynMethod = this.CreateDynMethod(_DYNAMIC_METHOD_OWNER_TYPE);
Assert.Throws<InvalidOperationException>(() =>
{
UseLikeStatic2 staticCallBack = (UseLikeStatic2)testDynMethod.CreateDelegate(typeof(UseLikeStatic2));
});
}
[Fact]
public void NegTest2()
{
DynamicMethod testDynMethod;
FieldInfo fieldInfo;
TestCreateDelegateOwner2 target = new TestCreateDelegateOwner2();
fieldInfo = _DYNAMIC_METHOD_OWNER_TYPE.GetField(
c_FIELD_NAME,
BindingFlags.NonPublic |
BindingFlags.Instance);
testDynMethod = this.CreateDynMethod(_DYNAMIC_METHOD_OWNER_TYPE);
this.EmitDynMethodBody(testDynMethod, fieldInfo);
Assert.Throws<ArgumentException>(() =>
{
InvalidRetType2 invalidCallBack = (InvalidRetType2)testDynMethod.CreateDelegate(typeof(InvalidRetType2));
});
}
[Fact]
public void NegTest3()
{
DynamicMethod testDynMethod;
FieldInfo fieldInfo;
TestCreateDelegateOwner2 target = new TestCreateDelegateOwner2();
fieldInfo = _DYNAMIC_METHOD_OWNER_TYPE.GetField(
c_FIELD_NAME,
BindingFlags.NonPublic |
BindingFlags.Instance);
testDynMethod = this.CreateDynMethod(_DYNAMIC_METHOD_OWNER_TYPE);
this.EmitDynMethodBody(testDynMethod, fieldInfo);
Assert.Throws<ArgumentException>(() =>
{
WrongParamNumber2 invalidCallBack = (WrongParamNumber2)testDynMethod.CreateDelegate(typeof(WrongParamNumber2));
});
}
[Fact]
public void NegTest4()
{
DynamicMethod testDynMethod;
FieldInfo fieldInfo;
TestCreateDelegateOwner2 target = new TestCreateDelegateOwner2();
fieldInfo = _DYNAMIC_METHOD_OWNER_TYPE.GetField(
c_FIELD_NAME,
BindingFlags.NonPublic |
BindingFlags.Instance);
testDynMethod = this.CreateDynMethod(_DYNAMIC_METHOD_OWNER_TYPE);
this.EmitDynMethodBody(testDynMethod, fieldInfo);
Assert.Throws<ArgumentException>(() =>
{
InvalidParamType2 invalidCallBack = (InvalidParamType2)testDynMethod.CreateDelegate(typeof(InvalidParamType2));
});
}
private DynamicMethod CreateDynMethod(Type dynMethodOwnerType)
{
Type retType = typeof(int);
Type[] paramTypes = new Type[]
{
_DYNAMIC_METHOD_OWNER_TYPE,
typeof(int)
};
return new DynamicMethod(c_DYNAMIC_METHOD_NAME,
retType,
paramTypes,
dynMethodOwnerType);
}
private DynamicMethod CreateDynMethod(Module mod)
{
Type retType = typeof(int);
Type[] paramTypes = new Type[]
{
_DYNAMIC_METHOD_OWNER_TYPE,
typeof(int)
};
return new DynamicMethod(c_DYNAMIC_METHOD_NAME,
retType,
paramTypes,
mod,
true);
}
private void EmitDynMethodBody(DynamicMethod dynMethod, FieldInfo fld)
{
ILGenerator methodIL = dynMethod.GetILGenerator();
methodIL.Emit(OpCodes.Ldarg_0);
methodIL.Emit(OpCodes.Ldfld, fld);
methodIL.Emit(OpCodes.Ldarg_0);
methodIL.Emit(OpCodes.Ldarg_1);
methodIL.Emit(OpCodes.Stfld, fld);
methodIL.Emit(OpCodes.Ret);
}
}
internal class TestCreateDelegateOwner2
{
private int _id; //c_FIELD_NAME
public TestCreateDelegateOwner2(int id)
{
_id = id;
}
public TestCreateDelegateOwner2() : this(0)
{
}
public int ID
{
get { return _id; }
}
}
internal class TestCreateDelegateOwner2Derived : TestCreateDelegateOwner2
{
public TestCreateDelegateOwner2Derived(int id)
: base(id)
{
}
public TestCreateDelegateOwner2Derived()
: base()
{
}
}
internal delegate int UseLikeStatic2(TestCreateDelegateOwner2 owner, int id);
internal delegate TestCreateDelegateOwner2 InvalidRetType2(TestCreateDelegateOwner2 owner, int id);
internal delegate int WrongParamNumber2(TestCreateDelegateOwner2 owner, int id, int m);
internal delegate int InvalidParamType2(int id, TestCreateDelegateOwner2 owner);
}
| |
using System;
using System.Linq.Expressions;
using AutoMapper.Internal;
using System.Linq;
namespace AutoMapper
{
internal class MappingExpression : IMappingExpression, IMemberConfigurationExpression
{
private readonly TypeMap _typeMap;
private readonly Func<Type, object> _typeConverterCtor;
private PropertyMap _propertyMap;
public MappingExpression(TypeMap typeMap, Func<Type, object> typeConverterCtor)
{
_typeMap = typeMap;
_typeConverterCtor = typeConverterCtor;
}
public void ConvertUsing<TTypeConverter>()
{
ConvertUsing(typeof(TTypeConverter));
}
public void ConvertUsing(Type typeConverterType)
{
var interfaceType = typeof(ITypeConverter<,>).MakeGenericType(_typeMap.SourceType, _typeMap.DestinationType);
var convertMethodType = interfaceType.IsAssignableFrom(typeConverterType) ? interfaceType : typeConverterType;
var converter = new DeferredInstantiatedConverter(convertMethodType, BuildCtor<object>(typeConverterType));
_typeMap.UseCustomMapper(converter.Convert);
}
public IMappingExpression WithProfile(string profileName)
{
_typeMap.Profile = profileName;
return this;
}
public IMappingExpression ForMember(string name, Action<IMemberConfigurationExpression> memberOptions)
{
IMemberAccessor destProperty = new PropertyAccessor(_typeMap.DestinationType.GetProperty(name));
ForDestinationMember(destProperty, memberOptions);
return new MappingExpression(_typeMap, _typeConverterCtor);
}
private void ForDestinationMember(IMemberAccessor destinationProperty, Action<IMemberConfigurationExpression> memberOptions)
{
_propertyMap = _typeMap.FindOrCreatePropertyMapFor(destinationProperty);
memberOptions(this);
}
public void MapFrom(string sourceMember)
{
var members = _typeMap.SourceType.GetMember(sourceMember);
if (!members.Any()) throw new AutoMapperConfigurationException(string.Format("Unable to find source member {0} on type {1}", sourceMember, _typeMap.SourceType.FullName));
if (members.Skip(1).Any()) throw new AutoMapperConfigurationException(string.Format("Source member {0} is ambiguous on type {1}", sourceMember, _typeMap.SourceType.FullName));
var member = members.Single();
_propertyMap.SourceMember = member;
_propertyMap.AssignCustomValueResolver(member.ToMemberGetter());
}
public IResolutionExpression ResolveUsing(IValueResolver valueResolver)
{
_propertyMap.AssignCustomValueResolver(valueResolver);
return new ResolutionExpression(_typeMap.SourceType, _propertyMap);
}
public IResolverConfigurationExpression ResolveUsing(Type valueResolverType)
{
var resolver = new DeferredInstantiatedResolver(BuildCtor<IValueResolver>(valueResolverType));
ResolveUsing(resolver);
return new ResolutionExpression(_typeMap.SourceType, _propertyMap);
}
public IResolverConfigurationExpression ResolveUsing<TValueResolver>()
{
var resolver = new DeferredInstantiatedResolver(BuildCtor<IValueResolver>((typeof(TValueResolver))));
ResolveUsing(resolver);
return new ResolutionExpression(_typeMap.SourceType, _propertyMap);
}
public void Ignore()
{
_propertyMap.Ignore();
}
private Func<ResolutionContext, TServiceType> BuildCtor<TServiceType>(Type type)
{
return context =>
{
if (context.Options.ServiceCtor != null)
{
var obj = context.Options.ServiceCtor(type);
if (obj != null)
return (TServiceType)obj;
}
return (TServiceType)_typeConverterCtor(type);
};
}
}
internal class MappingExpression<TSource, TDestination> : IMappingExpression<TSource, TDestination>, IMemberConfigurationExpression<TSource>, IFormatterCtorConfigurator
{
private readonly TypeMap _typeMap;
private readonly Func<Type, object> _serviceCtor;
private readonly IProfileExpression _configurationContainer;
private PropertyMap _propertyMap;
public MappingExpression(TypeMap typeMap, Func<Type, object> serviceCtor, IProfileExpression configurationContainer)
{
_typeMap = typeMap;
_serviceCtor = serviceCtor;
_configurationContainer = configurationContainer;
}
public IMappingExpression<TSource, TDestination> ForMember(Expression<Func<TDestination, object>> destinationMember,
Action<IMemberConfigurationExpression<TSource>> memberOptions)
{
var memberInfo = ReflectionHelper.FindProperty(destinationMember);
IMemberAccessor destProperty = memberInfo.ToMemberAccessor();
ForDestinationMember(destProperty, memberOptions);
return new MappingExpression<TSource, TDestination>(_typeMap, _serviceCtor, _configurationContainer);
}
public IMappingExpression<TSource, TDestination> ForMember(string name,
Action<IMemberConfigurationExpression<TSource>> memberOptions)
{
IMemberAccessor destProperty = new PropertyAccessor(typeof(TDestination).GetProperty(name));
ForDestinationMember(destProperty, memberOptions);
return new MappingExpression<TSource, TDestination>(_typeMap, _serviceCtor, _configurationContainer);
}
public void ForAllMembers(Action<IMemberConfigurationExpression<TSource>> memberOptions)
{
var typeInfo = new TypeInfo(_typeMap.DestinationType);
typeInfo.GetPublicWriteAccessors().Each(acc => ForDestinationMember(acc.ToMemberAccessor(), memberOptions));
}
public IMappingExpression<TSource, TDestination> Include<TOtherSource, TOtherDestination>()
where TOtherSource : TSource
where TOtherDestination : TDestination
{
_typeMap.IncludeDerivedTypes(typeof(TOtherSource), typeof(TOtherDestination));
return this;
}
public IMappingExpression<TSource, TDestination> WithProfile(string profileName)
{
_typeMap.Profile = profileName;
return this;
}
public void SkipFormatter<TValueFormatter>() where TValueFormatter : IValueFormatter
{
_propertyMap.AddFormatterToSkip<TValueFormatter>();
}
public IFormatterCtorExpression<TValueFormatter> AddFormatter<TValueFormatter>() where TValueFormatter : IValueFormatter
{
var formatter = new DeferredInstantiatedFormatter(BuildCtor<IValueFormatter>(typeof(TValueFormatter)));
AddFormatter(formatter);
return new FormatterCtorExpression<TValueFormatter>(this);
}
public IFormatterCtorExpression AddFormatter(Type valueFormatterType)
{
var formatter = new DeferredInstantiatedFormatter(BuildCtor<IValueFormatter>(valueFormatterType));
AddFormatter(formatter);
return new FormatterCtorExpression(valueFormatterType, this);
}
public void AddFormatter(IValueFormatter formatter)
{
_propertyMap.AddFormatter(formatter);
}
public void NullSubstitute(object nullSubstitute)
{
_propertyMap.SetNullSubstitute(nullSubstitute);
}
public IResolverConfigurationExpression<TSource, TValueResolver> ResolveUsing<TValueResolver>() where TValueResolver : IValueResolver
{
var resolver = new DeferredInstantiatedResolver(BuildCtor<IValueResolver>(typeof(TValueResolver)));
ResolveUsing(resolver);
return new ResolutionExpression<TSource, TValueResolver>(_propertyMap);
}
public IResolverConfigurationExpression<TSource> ResolveUsing(Type valueResolverType)
{
var resolver = new DeferredInstantiatedResolver(BuildCtor<IValueResolver>(valueResolverType));
ResolveUsing(resolver);
return new ResolutionExpression<TSource>(_propertyMap);
}
public IResolutionExpression<TSource> ResolveUsing(IValueResolver valueResolver)
{
_propertyMap.AssignCustomValueResolver(valueResolver);
return new ResolutionExpression<TSource>(_propertyMap);
}
public void ResolveUsing(Func<TSource, object> resolver)
{
_propertyMap.AssignCustomValueResolver(new DelegateBasedResolver<TSource>(resolver));
}
public void MapFrom<TMember>(Expression<Func<TSource, TMember>> sourceMember)
{
_propertyMap.SetCustomValueResolverExpression(sourceMember);
}
public void UseValue<TValue>(TValue value)
{
MapFrom(src => value);
}
public void UseValue(object value)
{
_propertyMap.AssignCustomValueResolver(new DelegateBasedResolver<TSource>(src => value));
}
public void Condition(Func<TSource, bool> condition)
{
Condition(context => condition((TSource)context.Parent.SourceValue));
}
public IMappingExpression<TSource, TDestination> MaxDepth(int depth)
{
_typeMap.SetCondition(o => PassesDepthCheck(o, depth));
return this;
}
public IMappingExpression<TSource, TDestination> ConstructUsingServiceLocator()
{
_typeMap.ConstructDestinationUsingServiceLocator = true;
return this;
}
public IMappingExpression<TDestination, TSource> ReverseMap()
{
return _configurationContainer.CreateMap<TDestination, TSource>();
}
public IMappingExpression<TSource, TDestination> ForSourceMember(Expression<Func<TSource, object>> sourceMember, Action<ISourceMemberConfigurationExpression<TSource>> memberOptions)
{
var srcConfig = new SourceMappingExpression(_typeMap, sourceMember);
memberOptions(srcConfig);
return this;
}
private static bool PassesDepthCheck(ResolutionContext context, int maxDepth)
{
if (context.InstanceCache.ContainsKey(context))
{
// return true if we already mapped this value and it's in the cache
return true;
}
ResolutionContext contextCopy = context;
int currentDepth = 1;
// walk parents to determine current depth
while (contextCopy.Parent != null)
{
if (contextCopy.SourceType == context.TypeMap.SourceType &&
contextCopy.DestinationType == context.TypeMap.DestinationType)
{
// same source and destination types appear higher up in the hierarchy
currentDepth++;
}
contextCopy = contextCopy.Parent;
}
return currentDepth <= maxDepth;
}
public void Condition(Func<ResolutionContext, bool> condition)
{
_propertyMap.ApplyCondition(condition);
}
public void Ignore()
{
_propertyMap.Ignore();
}
public void UseDestinationValue()
{
_propertyMap.UseDestinationValue = true;
}
public void SetMappingOrder(int mappingOrder)
{
_propertyMap.SetMappingOrder(mappingOrder);
}
public void ConstructFormatterBy(Type formatterType, Func<IValueFormatter> instantiator)
{
_propertyMap.RemoveLastFormatter();
_propertyMap.AddFormatter(new DeferredInstantiatedFormatter(ctxt => instantiator()));
}
public void ConvertUsing(Func<TSource, TDestination> mappingFunction)
{
_typeMap.UseCustomMapper(source => mappingFunction((TSource)source.SourceValue));
}
public void ConvertUsing(Func<ResolutionContext, TDestination> mappingFunction)
{
_typeMap.UseCustomMapper(context => mappingFunction(context));
}
public void ConvertUsing(Func<ResolutionContext, TSource, TDestination> mappingFunction)
{
_typeMap.UseCustomMapper(source => mappingFunction(source, (TSource)source.SourceValue));
}
public void ConvertUsing(ITypeConverter<TSource, TDestination> converter)
{
ConvertUsing(converter.Convert);
}
public void ConvertUsing<TTypeConverter>() where TTypeConverter : ITypeConverter<TSource, TDestination>
{
var converter = new DeferredInstantiatedConverter<TSource, TDestination>(BuildCtor<ITypeConverter<TSource, TDestination>>(typeof(TTypeConverter)));
ConvertUsing(converter.Convert);
}
public IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination> beforeFunction)
{
_typeMap.AddBeforeMapAction((src, dest) => beforeFunction((TSource)src, (TDestination)dest));
return this;
}
public IMappingExpression<TSource, TDestination> BeforeMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination>
{
Action<TSource, TDestination> beforeFunction = (src, dest) => ((TMappingAction)_serviceCtor(typeof(TMappingAction))).Process(src, dest);
return BeforeMap(beforeFunction);
}
public IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination> afterFunction)
{
_typeMap.AddAfterMapAction((src, dest) => afterFunction((TSource)src, (TDestination)dest));
return this;
}
public IMappingExpression<TSource, TDestination> AfterMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination>
{
Action<TSource, TDestination> afterFunction = (src, dest) => ((TMappingAction)_serviceCtor(typeof(TMappingAction))).Process(src, dest);
return AfterMap(afterFunction);
}
public IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, TDestination> ctor)
{
return ConstructUsing(ctxt => ctor((TSource) ctxt.SourceValue));
}
public IMappingExpression<TSource, TDestination> ConstructUsing(Func<ResolutionContext, TDestination> ctor)
{
_typeMap.DestinationCtor = ctxt => ctor(ctxt);
return this;
}
private void ForDestinationMember(IMemberAccessor destinationProperty, Action<IMemberConfigurationExpression<TSource>> memberOptions)
{
_propertyMap = _typeMap.FindOrCreatePropertyMapFor(destinationProperty);
memberOptions(this);
}
public void As<T>()
{
_typeMap.DestinationTypeOverride = typeof(T);
}
private Func<ResolutionContext, TServiceType> BuildCtor<TServiceType>(Type type)
{
return context =>
{
if (context.Options.ServiceCtor != null)
{
var obj = context.Options.ServiceCtor(type);
if (obj != null)
return (TServiceType)obj;
}
return (TServiceType)_serviceCtor(type);
};
}
private class SourceMappingExpression : ISourceMemberConfigurationExpression<TSource>
{
private readonly SourceMemberConfig _sourcePropertyConfig;
public SourceMappingExpression(TypeMap typeMap, LambdaExpression sourceMember)
{
var memberInfo = ReflectionHelper.FindProperty(sourceMember);
_sourcePropertyConfig = typeMap.FindOrCreateSourceMemberConfigFor(memberInfo);
}
public void Ignore()
{
_sourcePropertyConfig.Ignore();
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.TextManager.Interop;
using TestUtilities.Mocks;
namespace Microsoft.VisualStudioTools.MockVsTests
{
internal class MockVsTextLines : IVsTextLines, IVsPersistDocData, IVsExpansion
{
private readonly MockTextBuffer _buffer;
private readonly IServiceProvider _serviceProvider;
internal uint _docCookie;
public MockVsTextLines(IServiceProvider serviceProvider, MockTextBuffer buffer)
{
_serviceProvider = serviceProvider;
_buffer = buffer;
}
public int AdviseTextLinesEvents(IVsTextLinesEvents pSink, out uint pdwCookie)
{
throw new NotImplementedException();
}
public int CanReplaceLines(int iStartLine, int iStartIndex, int iEndLine, int iEndIndex, int iNewLen)
{
throw new NotImplementedException();
}
public int CopyLineText(int iStartLine, int iStartIndex, int iEndLine, int iEndIndex, IntPtr pszBuf, ref int pcchBuf)
{
throw new NotImplementedException();
}
public int CreateEditPoint(int iLine, int iIndex, out object ppEditPoint)
{
throw new NotImplementedException();
}
public int CreateLineMarker(int iMarkerType, int iStartLine, int iStartIndex, int iEndLine, int iEndIndex, IVsTextMarkerClient pClient, IVsTextLineMarker[] ppMarker)
{
throw new NotImplementedException();
}
public int CreateTextPoint(int iLine, int iIndex, out object ppTextPoint)
{
throw new NotImplementedException();
}
public int EnumMarkers(int iStartLine, int iStartIndex, int iEndLine, int iEndIndex, int iMarkerType, uint dwFlags, out IVsEnumLineMarkers ppEnum)
{
throw new NotImplementedException();
}
public int FindMarkerByLineIndex(int iMarkerType, int iStartingLine, int iStartingIndex, uint dwFlags, out IVsTextLineMarker ppMarker)
{
throw new NotImplementedException();
}
public int GetLanguageServiceID(out Guid pguidLangService)
{
throw new NotImplementedException();
}
public int GetLastLineIndex(out int piLine, out int piIndex)
{
throw new NotImplementedException();
}
public int GetLengthOfLine(int iLine, out int piLength)
{
throw new NotImplementedException();
}
public int GetLineCount(out int piLineCount)
{
throw new NotImplementedException();
}
public int GetLineData(int iLine, LINEDATA[] pLineData, MARKERDATA[] pMarkerData)
{
throw new NotImplementedException();
}
public int GetLineDataEx(uint dwFlags, int iLine, int iStartIndex, int iEndIndex, LINEDATAEX[] pLineData, MARKERDATA[] pMarkerData)
{
throw new NotImplementedException();
}
public int GetLineIndexOfPosition(int iPosition, out int piLine, out int piColumn)
{
throw new NotImplementedException();
}
public int GetLineText(int iStartLine, int iStartIndex, int iEndLine, int iEndIndex, out string pbstrBuf)
{
throw new NotImplementedException();
}
public int GetMarkerData(int iTopLine, int iBottomLine, MARKERDATA[] pMarkerData)
{
throw new NotImplementedException();
}
public int GetPairExtents(TextSpan[] pSpanIn, TextSpan[] pSpanOut)
{
throw new NotImplementedException();
}
public int GetPositionOfLine(int iLine, out int piPosition)
{
throw new NotImplementedException();
}
public int GetPositionOfLineIndex(int iLine, int iIndex, out int piPosition)
{
throw new NotImplementedException();
}
public int GetSize(out int piLength)
{
throw new NotImplementedException();
}
public int GetStateFlags(out uint pdwReadOnlyFlags)
{
throw new NotImplementedException();
}
public int GetUndoManager(out VisualStudio.OLE.Interop.IOleUndoManager ppUndoManager)
{
throw new NotImplementedException();
}
public int IVsTextLinesReserved1(int iLine, LINEDATA[] pLineData, int fAttributes)
{
throw new NotImplementedException();
}
public int InitializeContent(string pszText, int iLength)
{
throw new NotImplementedException();
}
public int LockBuffer()
{
throw new NotImplementedException();
}
public int LockBufferEx(uint dwFlags)
{
throw new NotImplementedException();
}
public int ReleaseLineData(LINEDATA[] pLineData)
{
throw new NotImplementedException();
}
public int ReleaseLineDataEx(LINEDATAEX[] pLineData)
{
throw new NotImplementedException();
}
public int ReleaseMarkerData(MARKERDATA[] pMarkerData)
{
throw new NotImplementedException();
}
public int Reload(int fUndoable)
{
throw new NotImplementedException();
}
public int ReloadLines(int iStartLine, int iStartIndex, int iEndLine, int iEndIndex, IntPtr pszText, int iNewLen, TextSpan[] pChangedSpan)
{
throw new NotImplementedException();
}
public int ReplaceLines(int iStartLine, int iStartIndex, int iEndLine, int iEndIndex, IntPtr pszText, int iNewLen, TextSpan[] pChangedSpan)
{
throw new NotImplementedException();
}
public int ReplaceLinesEx(uint dwFlags, int iStartLine, int iStartIndex, int iEndLine, int iEndIndex, IntPtr pszText, int iNewLen, TextSpan[] pChangedSpan)
{
throw new NotImplementedException();
}
public int Reserved1()
{
throw new NotImplementedException();
}
public int Reserved10()
{
throw new NotImplementedException();
}
public int Reserved2()
{
throw new NotImplementedException();
}
public int Reserved3()
{
throw new NotImplementedException();
}
public int Reserved4()
{
throw new NotImplementedException();
}
public int Reserved5()
{
throw new NotImplementedException();
}
public int Reserved6()
{
throw new NotImplementedException();
}
public int Reserved7()
{
throw new NotImplementedException();
}
public int Reserved8()
{
throw new NotImplementedException();
}
public int Reserved9()
{
throw new NotImplementedException();
}
public int SetLanguageServiceID(ref Guid guidLangService)
{
throw new NotImplementedException();
}
public int SetStateFlags(uint dwReadOnlyFlags)
{
throw new NotImplementedException();
}
public int UnadviseTextLinesEvents(uint dwCookie)
{
throw new NotImplementedException();
}
public int UnlockBuffer()
{
throw new NotImplementedException();
}
public int UnlockBufferEx(uint dwFlags)
{
throw new NotImplementedException();
}
public int Close()
{
return VSConstants.S_OK;
}
public int GetGuidEditorType(out Guid pClassID)
{
throw new NotImplementedException();
}
public int IsDocDataDirty(out int pfDirty)
{
throw new NotImplementedException();
}
public int IsDocDataReloadable(out int pfReloadable)
{
throw new NotImplementedException();
}
public int LoadDocData(string pszMkDocument)
{
throw new NotImplementedException();
}
public int OnRegisterDocData(uint docCookie, IVsHierarchy pHierNew, uint itemidNew)
{
_docCookie = docCookie;
return VSConstants.S_OK;
}
public int ReloadDocData(uint grfFlags)
{
throw new NotImplementedException();
}
public int RenameDocData(uint grfAttribs, IVsHierarchy pHierNew, uint itemidNew, string pszMkDocumentNew)
{
var textDoc = _buffer.Properties.GetProperty<ITextDocument>(typeof(ITextDocument));
textDoc.Rename(pszMkDocumentNew);
return VSConstants.S_OK;
}
public int SaveDocData(VSSAVEFLAGS dwSave, out string pbstrMkDocumentNew, out int pfSaveCanceled)
{
throw new NotImplementedException();
}
public int SetUntitledDocPath(string pszDocDataPath)
{
throw new NotImplementedException();
}
public int InsertExpansion(TextSpan tsContext, TextSpan tsInsertPos, IVsExpansionClient pExpansionClient, Guid guidLang, out IVsExpansionSession pSession)
{
throw new NotImplementedException();
}
public int InsertNamedExpansion(string bstrTitle, string bstrPath, TextSpan tsInsertPos, IVsExpansionClient pExpansionClient, Guid guidLang, int fShowDisambiguationUI, out IVsExpansionSession pSession)
{
throw new NotImplementedException();
}
public int InsertSpecificExpansion(MSXML.IXMLDOMNode pSnippet, TextSpan tsInsertPos, IVsExpansionClient pExpansionClient, Guid guidLang, string pszRelativePath, out IVsExpansionSession pSession)
{
throw new NotImplementedException();
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Targets
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Threading;
using NLog.Common;
using NLog.Internal.NetworkSenders;
using NLog.Layouts;
/// <summary>
/// Sends log messages over the network.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/Network-target">Documentation on NLog Wiki</seealso>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/Network/NLog.config" />
/// <p>
/// This assumes just one target and a single rule. More configuration
/// options are described <a href="config.html">here</a>.
/// </p>
/// <p>
/// To set up the log target programmatically use code like this:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/Network/Simple/Example.cs" />
/// <p>
/// To print the results, use any application that's able to receive messages over
/// TCP or UDP. <a href="http://m.nu/program/util/netcat/netcat.html">NetCat</a> is
/// a simple but very powerful command-line tool that can be used for that. This image
/// demonstrates the NetCat tool receiving log messages from Network target.
/// </p>
/// <img src="examples/targets/Screenshots/Network/Output.gif" />
/// <p>
/// NOTE: If your receiver application is ever likely to be off-line, don't use TCP protocol
/// or you'll get TCP timeouts and your application will be very slow.
/// Either switch to UDP transport or use <a href="target.AsyncWrapper.html">AsyncWrapper</a> target
/// so that your application threads will not be blocked by the timing-out connection attempts.
/// </p>
/// <p>
/// There are two specialized versions of the Network target: <a href="target.Chainsaw.html">Chainsaw</a>
/// and <a href="target.NLogViewer.html">NLogViewer</a> which write to instances of Chainsaw log4j viewer
/// or NLogViewer application respectively.
/// </p>
/// </example>
[Target("Network")]
public class NetworkTarget : TargetWithLayout
{
private Dictionary<string, LinkedListNode<NetworkSender>> currentSenderCache = new Dictionary<string, LinkedListNode<NetworkSender>>();
private LinkedList<NetworkSender> openNetworkSenders = new LinkedList<NetworkSender>();
/// <summary>
/// Initializes a new instance of the <see cref="NetworkTarget" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
public NetworkTarget()
{
this.SenderFactory = NetworkSenderFactory.Default;
this.Encoding = Encoding.UTF8;
this.OnOverflow = NetworkTargetOverflowAction.Split;
this.KeepConnection = true;
this.MaxMessageSize = 65000;
this.ConnectionCacheSize = 5;
}
/// <summary>
/// Initializes a new instance of the <see cref="NetworkTarget" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
/// <param name="name">Name of the target.</param>
public NetworkTarget(string name) : this()
{
this.Name = name;
}
/// <summary>
/// Gets or sets the network address.
/// </summary>
/// <remarks>
/// The network address can be:
/// <ul>
/// <li>tcp://host:port - TCP (auto select IPv4/IPv6) (not supported on Windows Phone 7.0)</li>
/// <li>tcp4://host:port - force TCP/IPv4 (not supported on Windows Phone 7.0)</li>
/// <li>tcp6://host:port - force TCP/IPv6 (not supported on Windows Phone 7.0)</li>
/// <li>udp://host:port - UDP (auto select IPv4/IPv6, not supported on Silverlight and on Windows Phone 7.0)</li>
/// <li>udp4://host:port - force UDP/IPv4 (not supported on Silverlight and on Windows Phone 7.0)</li>
/// <li>udp6://host:port - force UDP/IPv6 (not supported on Silverlight and on Windows Phone 7.0)</li>
/// <li>http://host:port/pageName - HTTP using POST verb</li>
/// <li>https://host:port/pageName - HTTPS using POST verb</li>
/// </ul>
/// For SOAP-based webservice support over HTTP use WebService target.
/// </remarks>
/// <docgen category='Connection Options' order='10' />
public Layout Address { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to keep connection open whenever possible.
/// </summary>
/// <docgen category='Connection Options' order='10' />
[DefaultValue(true)]
public bool KeepConnection { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to append newline at the end of log message.
/// </summary>
/// <docgen category='Layout Options' order='10' />
[DefaultValue(false)]
public bool NewLine { get; set; }
/// <summary>
/// Gets or sets the maximum message size in bytes.
/// </summary>
/// <docgen category='Layout Options' order='10' />
[DefaultValue(65000)]
public int MaxMessageSize { get; set; }
/// <summary>
/// Gets or sets the size of the connection cache (number of connections which are kept alive).
/// </summary>
/// <docgen category="Connection Options" order="10"/>
[DefaultValue(5)]
public int ConnectionCacheSize { get; set; }
/// <summary>
/// Gets or sets the maximum current connections. 0 = no maximum.
/// </summary>
/// <docgen category="Connection Options" order="10"/>
[DefaultValue(0)]
public int MaxConnections { get; set; }
/// <summary>
/// Gets or sets the action that should be taken if the will be more connections than <see cref="MaxConnections"/>.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public NetworkTargetConnectionsOverflowAction OnConnectionOverflow { get; set; }
/// <summary>
/// Gets or sets the maximum queue size.
/// </summary>
[DefaultValue(0)]
public int MaxQueueSize { get; set; }
/// <summary>
/// Gets or sets the action that should be taken if the message is larger than
/// maxMessageSize.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public NetworkTargetOverflowAction OnOverflow { get; set; }
/// <summary>
/// Gets or sets the encoding to be used.
/// </summary>
/// <docgen category='Layout Options' order='10' />
[DefaultValue("utf-8")]
public Encoding Encoding { get; set; }
internal INetworkSenderFactory SenderFactory { get; set; }
/// <summary>
/// Flush any pending log messages asynchronously (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
int remainingCount = 0;
AsyncContinuation continuation =
ex =>
{
// ignore exception
if (Interlocked.Decrement(ref remainingCount) == 0)
{
asyncContinuation(null);
}
};
lock (this.openNetworkSenders)
{
remainingCount = this.openNetworkSenders.Count;
if (remainingCount == 0)
{
// nothing to flush
asyncContinuation(null);
}
else
{
// otherwise call FlushAsync() on all senders
// and invoke continuation at the very end
foreach (var openSender in this.openNetworkSenders)
{
openSender.FlushAsync(continuation);
}
}
}
}
/// <summary>
/// Closes the target.
/// </summary>
protected override void CloseTarget()
{
base.CloseTarget();
lock (this.openNetworkSenders)
{
foreach (var openSender in this.openNetworkSenders)
{
openSender.Close(ex => { });
}
this.openNetworkSenders.Clear();
}
}
/// <summary>
/// Sends the
/// rendered logging event over the network optionally concatenating it with a newline character.
/// </summary>
/// <param name="logEvent">The logging event.</param>
protected override void Write(AsyncLogEventInfo logEvent)
{
string address = this.Address.Render(logEvent.LogEvent);
byte[] bytes = this.GetBytesToWrite(logEvent.LogEvent);
if (this.KeepConnection)
{
var senderNode = this.GetCachedNetworkSender(address);
this.ChunkedSend(
senderNode.Value,
bytes,
ex =>
{
if (ex != null)
{
InternalLogger.Error(ex, "Error when sending.");
this.ReleaseCachedConnection(senderNode);
}
logEvent.Continuation(ex);
});
}
else
{
NetworkSender sender;
LinkedListNode<NetworkSender> linkedListNode;
lock (this.openNetworkSenders)
{
//handle too many connections
var tooManyConnections = this.openNetworkSenders.Count >= MaxConnections;
if (tooManyConnections && MaxConnections > 0)
{
switch (this.OnConnectionOverflow)
{
case NetworkTargetConnectionsOverflowAction.DiscardMessage:
InternalLogger.Warn("Discarding message otherwise to many connections.");
logEvent.Continuation(null);
return;
case NetworkTargetConnectionsOverflowAction.AllowNewConnnection:
InternalLogger.Debug("Too may connections, but this is allowed");
break;
case NetworkTargetConnectionsOverflowAction.Block:
while (this.openNetworkSenders.Count >= this.MaxConnections)
{
InternalLogger.Debug("Blocking networktarget otherwhise too many connections.");
System.Threading.Monitor.Wait(this.openNetworkSenders);
InternalLogger.Trace("Entered critical section.");
}
InternalLogger.Trace("Limit ok.");
break;
}
}
sender = this.SenderFactory.Create(address, MaxQueueSize);
sender.Initialize();
linkedListNode = this.openNetworkSenders.AddLast(sender);
}
this.ChunkedSend(
sender,
bytes,
ex =>
{
lock (this.openNetworkSenders)
{
TryRemove(this.openNetworkSenders, linkedListNode);
if (this.OnConnectionOverflow == NetworkTargetConnectionsOverflowAction.Block)
{
System.Threading.Monitor.PulseAll(this.openNetworkSenders);
}
}
if (ex != null)
{
InternalLogger.Error(ex, "Error when sending.");
}
sender.Close(ex2 => { });
logEvent.Continuation(ex);
});
}
}
/// <summary>
/// Try to remove.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="node"></param>
/// <returns>removed something?</returns>
private static bool TryRemove<T>(LinkedList<T> list, LinkedListNode<T> node)
{
if (node == null || list != node.List)
{
return false;
}
list.Remove(node);
return true;
}
/// <summary>
/// Gets the bytes to be written.
/// </summary>
/// <param name="logEvent">Log event.</param>
/// <returns>Byte array.</returns>
protected virtual byte[] GetBytesToWrite(LogEventInfo logEvent)
{
string text;
if (this.NewLine)
{
text = this.Layout.Render(logEvent) + "\r\n";
}
else
{
text = this.Layout.Render(logEvent);
}
return this.Encoding.GetBytes(text);
}
private LinkedListNode<NetworkSender> GetCachedNetworkSender(string address)
{
lock (this.currentSenderCache)
{
LinkedListNode<NetworkSender> senderNode;
// already have address
if (this.currentSenderCache.TryGetValue(address, out senderNode))
{
senderNode.Value.CheckSocket();
return senderNode;
}
if (this.currentSenderCache.Count >= this.ConnectionCacheSize)
{
// make room in the cache by closing the least recently used connection
int minAccessTime = int.MaxValue;
LinkedListNode<NetworkSender> leastRecentlyUsed = null;
foreach (var pair in this.currentSenderCache)
{
var networkSender = pair.Value.Value;
if (networkSender.LastSendTime < minAccessTime)
{
minAccessTime = networkSender.LastSendTime;
leastRecentlyUsed = pair.Value;
}
}
if (leastRecentlyUsed != null)
{
this.ReleaseCachedConnection(leastRecentlyUsed);
}
}
var sender = this.SenderFactory.Create(address, MaxQueueSize);
sender.Initialize();
lock (this.openNetworkSenders)
{
senderNode = this.openNetworkSenders.AddLast(sender);
}
this.currentSenderCache.Add(address, senderNode);
return senderNode;
}
}
private void ReleaseCachedConnection(LinkedListNode<NetworkSender> senderNode)
{
lock (this.currentSenderCache)
{
var networkSender = senderNode.Value;
lock (this.openNetworkSenders)
{
if(TryRemove(this.openNetworkSenders,senderNode))
{
// only remove it once
networkSender.Close(ex => { });
}
}
LinkedListNode<NetworkSender> sender2;
// make sure the current sender for this address is the one we want to remove
if (this.currentSenderCache.TryGetValue(networkSender.Address, out sender2))
{
if (ReferenceEquals(senderNode, sender2))
{
this.currentSenderCache.Remove(networkSender.Address);
}
}
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", Justification = "Using property names in message.")]
private void ChunkedSend(NetworkSender sender, byte[] buffer, AsyncContinuation continuation)
{
int tosend = buffer.Length;
int pos = 0;
AsyncContinuation sendNextChunk = null;
sendNextChunk = ex =>
{
if (ex != null)
{
continuation(ex);
return;
}
if (tosend <= 0)
{
continuation(null);
return;
}
int chunksize = tosend;
if (chunksize > this.MaxMessageSize)
{
if (this.OnOverflow == NetworkTargetOverflowAction.Discard)
{
continuation(null);
return;
}
if (this.OnOverflow == NetworkTargetOverflowAction.Error)
{
continuation(new OverflowException("Attempted to send a message larger than MaxMessageSize (" + this.MaxMessageSize + "). Actual size was: " + buffer.Length + ". Adjust OnOverflow and MaxMessageSize parameters accordingly."));
return;
}
chunksize = this.MaxMessageSize;
}
int pos0 = pos;
tosend -= chunksize;
pos += chunksize;
sender.Send(buffer, pos0, chunksize, sendNextChunk);
};
sendNextChunk(null);
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for SecurityRulesOperations.
/// </summary>
public static partial class SecurityRulesOperationsExtensions
{
/// <summary>
/// Deletes the specified network security rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
public static void Delete(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName)
{
operations.DeleteAsync(resourceGroupName, networkSecurityGroupName, securityRuleName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified network security rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get the specified network security rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
public static SecurityRule Get(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName)
{
return operations.GetAsync(resourceGroupName, networkSecurityGroupName, securityRuleName).GetAwaiter().GetResult();
}
/// <summary>
/// Get the specified network security rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SecurityRule> GetAsync(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a security rule in the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create or update network security rule
/// operation.
/// </param>
public static SecurityRule CreateOrUpdate(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a security rule in the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create or update network security rule
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SecurityRule> CreateOrUpdateAsync(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all security rules in a network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
public static IPage<SecurityRule> List(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName)
{
return operations.ListAsync(resourceGroupName, networkSecurityGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all security rules in a network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SecurityRule>> ListAsync(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified network security rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
public static void BeginDelete(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName)
{
operations.BeginDeleteAsync(resourceGroupName, networkSecurityGroupName, securityRuleName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified network security rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates or updates a security rule in the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create or update network security rule
/// operation.
/// </param>
public static SecurityRule BeginCreateOrUpdate(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a security rule in the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create or update network security rule
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SecurityRule> BeginCreateOrUpdateAsync(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all security rules in a network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<SecurityRule> ListNext(this ISecurityRulesOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all security rules in a network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SecurityRule>> ListNextAsync(this ISecurityRulesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
/******************************************************************************
* Copyright (C) Leap Motion, Inc. 2011-2017. *
* Leap Motion proprietary and confidential. *
* *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
******************************************************************************/
using UnityEngine;
using UnityEngine.SceneManagement;
using System;
using System.Collections.Generic;
namespace Leap.Unity.RuntimeGizmos {
/// <summary>
/// Have your MonoBehaviour implement this interface to be able to draw runtime gizmos.
/// You must also have a RuntimeGizmoManager component in the scene to recieve callbacks.
/// </summary>
public interface IRuntimeGizmoComponent {
void OnDrawRuntimeGizmos(RuntimeGizmoDrawer drawer);
}
[ExecuteInEditMode]
public class RuntimeGizmoManager : MonoBehaviour {
public const string DEFAULT_SHADER_NAME = "Hidden/Runtime Gizmos";
public const int CIRCLE_RESOLUTION = 32;
[Tooltip("Should the gizmos be visible in the game view.")]
[SerializeField]
protected bool _displayInGameView = true;
[Tooltip("Should the gizmos be visible in a build.")]
[SerializeField]
protected bool _enabledForBuild = true;
[Tooltip("The mesh to use for the filled sphere gizmo.")]
[SerializeField]
protected Mesh _sphereMesh;
[Tooltip("The shader to use for rendering gizmos.")]
[SerializeField]
protected Shader _gizmoShader;
protected Mesh _cubeMesh, _wireCubeMesh, _wireSphereMesh;
protected static RuntimeGizmoDrawer _backDrawer = null;
protected static RuntimeGizmoDrawer _frontDrawer = null;
private bool _readyForSwap = false;
/// <summary>
/// Subscribe to this event if you want to draw gizmos after rendering is complete. Doing gizmo
/// rendering inside of the normal Camera.onPoseRender event will cause rendering artifacts.
/// </summary>
public static event Action<RuntimeGizmoDrawer> OnPostRenderGizmos;
/// <summary>
/// Tries to get a gizmo drawer. Will fail if there is no Gizmo manager in the
/// scene, or if it is disabled.
///
/// The gizmo matrix will be set to the identity matrix.
/// The gizmo color will be set to white.
/// </summary>
public static bool TryGetGizmoDrawer(out RuntimeGizmoDrawer drawer) {
drawer = _backDrawer;
if (drawer != null) {
drawer.ResetMatrixAndColorState();
return true;
} else {
return false;
}
}
/// <summary>
/// Tries to get a gizmo drawer for a given gameObject. Will fail if there is no
/// gizmo manager in the scene, or if it is disabled. Will also fail if there is
/// a disable RuntimeGizmoToggle as a parent of the gameObject.
///
/// The gizmo matrix will be set to the identity matrix.
/// The gizmo color will be set to white.
/// </summary>
public static bool TryGetGizmoDrawer(GameObject attatchedGameObject, out RuntimeGizmoDrawer drawer) {
drawer = _backDrawer;
if (drawer != null && !areGizmosDisabled(attatchedGameObject.transform)) {
drawer.ResetMatrixAndColorState();
return true;
} else {
return false;
}
}
protected virtual void OnValidate() {
if (_gizmoShader == null) {
_gizmoShader = Shader.Find(DEFAULT_SHADER_NAME);
}
Material tempMat = new Material(_gizmoShader);
tempMat.hideFlags = HideFlags.HideAndDontSave;
if (tempMat.passCount != 4) {
Debug.LogError("Shader " + _gizmoShader + " does not have 4 passes and cannot be used as a gizmo shader.");
_gizmoShader = Shader.Find(DEFAULT_SHADER_NAME);
}
if (_frontDrawer != null && _backDrawer != null) {
assignDrawerParams();
}
}
protected virtual void Reset() {
_gizmoShader = Shader.Find(DEFAULT_SHADER_NAME);
}
protected virtual void OnEnable() {
#if !UNITY_EDITOR
if (!_enabledForBuild) {
enabled = false;
return;
}
#endif
_frontDrawer = new RuntimeGizmoDrawer();
_backDrawer = new RuntimeGizmoDrawer();
_frontDrawer.BeginGuard();
if (_gizmoShader == null) {
_gizmoShader = Shader.Find(DEFAULT_SHADER_NAME);
}
generateMeshes();
assignDrawerParams();
//Unsubscribe to prevent double-subscription
Camera.onPostRender -= onPostRender;
Camera.onPostRender += onPostRender;
}
protected virtual void OnDisable() {
_frontDrawer = null;
_backDrawer = null;
Camera.onPostRender -= onPostRender;
}
private List<GameObject> _objList = new List<GameObject>();
private List<IRuntimeGizmoComponent> _gizmoList = new List<IRuntimeGizmoComponent>();
protected virtual void Update() {
Scene scene = SceneManager.GetActiveScene();
scene.GetRootGameObjects(_objList);
for (int i = 0; i < _objList.Count; i++) {
GameObject obj = _objList[i];
obj.GetComponentsInChildren(false, _gizmoList);
for (int j = 0; j < _gizmoList.Count; j++) {
if (areGizmosDisabled((_gizmoList[j] as Component).transform)) {
continue;
}
_backDrawer.ResetMatrixAndColorState();
try {
_gizmoList[j].OnDrawRuntimeGizmos(_backDrawer);
} catch (Exception e) {
Debug.LogException(e);
}
}
}
_readyForSwap = true;
}
protected void onPostRender(Camera camera) {
#if UNITY_EDITOR
//Hard-coded name of the camera used to generate the pre-render view
if (camera.gameObject.name == "PreRenderCamera") {
return;
}
bool isSceneCamera = camera.gameObject.hideFlags == HideFlags.HideAndDontSave;
if (!isSceneCamera && !_displayInGameView) {
return;
}
#endif
if (_readyForSwap) {
if (OnPostRenderGizmos != null) {
_backDrawer.ResetMatrixAndColorState();
OnPostRenderGizmos(_backDrawer);
}
RuntimeGizmoDrawer tempDrawer = _backDrawer;
_backDrawer = _frontDrawer;
_frontDrawer = tempDrawer;
//Guard the front drawer for rendering
_frontDrawer.BeginGuard();
//Unguard the back drawer to allow gizmos to be drawn to it
_backDrawer.EndGuard();
_readyForSwap = false;
_backDrawer.ClearAllGizmos();
}
_frontDrawer.DrawAllGizmosToScreen();
}
protected static bool areGizmosDisabled(Transform transform) {
bool isDisabled = false;
do {
var toggle = transform.GetComponentInParent<RuntimeGizmoToggle>();
if (toggle == null) {
break;
}
if (!toggle.enabled) {
isDisabled = true;
break;
}
transform = transform.parent;
} while (transform != null);
return isDisabled;
}
private void assignDrawerParams() {
if (_gizmoShader != null) {
_frontDrawer.gizmoShader = _gizmoShader;
_backDrawer.gizmoShader = _gizmoShader;
}
_frontDrawer.sphereMesh = _sphereMesh;
_frontDrawer.cubeMesh = _cubeMesh;
_frontDrawer.wireSphereMesh = _wireSphereMesh;
_frontDrawer.wireCubeMesh = _wireCubeMesh;
_backDrawer.sphereMesh = _sphereMesh;
_backDrawer.cubeMesh = _cubeMesh;
_backDrawer.wireSphereMesh = _wireSphereMesh;
_backDrawer.wireCubeMesh = _wireCubeMesh;
}
private void generateMeshes() {
_cubeMesh = new Mesh();
_cubeMesh.name = "RuntimeGizmoCube";
_cubeMesh.hideFlags = HideFlags.HideAndDontSave;
List<Vector3> verts = new List<Vector3>();
List<int> indexes = new List<int>();
Vector3[] faces = new Vector3[] { Vector3.forward, Vector3.right, Vector3.up };
for (int i = 0; i < 3; i++) {
addQuad(verts, indexes, faces[(i + 0) % 3], -faces[(i + 1) % 3], faces[(i + 2) % 3]);
addQuad(verts, indexes, -faces[(i + 0) % 3], faces[(i + 1) % 3], faces[(i + 2) % 3]);
}
_cubeMesh.SetVertices(verts);
_cubeMesh.SetIndices(indexes.ToArray(), MeshTopology.Quads, 0);
_cubeMesh.RecalculateNormals();
_cubeMesh.RecalculateBounds();
_cubeMesh.UploadMeshData(true);
_wireCubeMesh = new Mesh();
_wireCubeMesh.name = "RuntimeWireCubeMesh";
_wireCubeMesh.hideFlags = HideFlags.HideAndDontSave;
verts.Clear();
indexes.Clear();
for (int dx = 1; dx >= -1; dx -= 2) {
for (int dy = 1; dy >= -1; dy -= 2) {
for (int dz = 1; dz >= -1; dz -= 2) {
verts.Add(0.5f * new Vector3(dx, dy, dz));
}
}
}
addCorner(indexes, 0, 1, 2, 4);
addCorner(indexes, 3, 1, 2, 7);
addCorner(indexes, 5, 1, 4, 7);
addCorner(indexes, 6, 2, 4, 7);
_wireCubeMesh.SetVertices(verts);
_wireCubeMesh.SetIndices(indexes.ToArray(), MeshTopology.Lines, 0);
_wireCubeMesh.RecalculateBounds();
_wireCubeMesh.UploadMeshData(true);
_wireSphereMesh = new Mesh();
_wireSphereMesh.name = "RuntimeWireSphereMesh";
_wireSphereMesh.hideFlags = HideFlags.HideAndDontSave;
verts.Clear();
indexes.Clear();
int totalVerts = CIRCLE_RESOLUTION * 3;
for (int i = 0; i < CIRCLE_RESOLUTION; i++) {
float angle = Mathf.PI * 2 * i / CIRCLE_RESOLUTION;
float dx = 0.5f * Mathf.Cos(angle);
float dy = 0.5f * Mathf.Sin(angle);
for (int j = 0; j < 3; j++) {
indexes.Add((i * 3 + j + 0) % totalVerts);
indexes.Add((i * 3 + j + 3) % totalVerts);
}
verts.Add(new Vector3(dx, dy, 0));
verts.Add(new Vector3(0, dx, dy));
verts.Add(new Vector3(dx, 0, dy));
}
_wireSphereMesh.SetVertices(verts);
_wireSphereMesh.SetIndices(indexes.ToArray(), MeshTopology.Lines, 0);
_wireSphereMesh.RecalculateBounds();
_wireSphereMesh.UploadMeshData(true);
}
private void addQuad(List<Vector3> verts, List<int> indexes, Vector3 normal, Vector3 axis1, Vector3 axis2) {
indexes.Add(verts.Count + 0);
indexes.Add(verts.Count + 1);
indexes.Add(verts.Count + 2);
indexes.Add(verts.Count + 3);
verts.Add(0.5f * (normal + axis1 + axis2));
verts.Add(0.5f * (normal + axis1 - axis2));
verts.Add(0.5f * (normal - axis1 - axis2));
verts.Add(0.5f * (normal - axis1 + axis2));
}
private void addCorner(List<int> indexes, int a, int b, int c, int d) {
indexes.Add(a); indexes.Add(b);
indexes.Add(a); indexes.Add(c);
indexes.Add(a); indexes.Add(d);
}
}
public class RuntimeGizmoDrawer {
public const int UNLIT_SOLID_PASS = 0;
public const int UNLIT_TRANSPARENT_PASS = 1;
public const int SHADED_SOLID_PASS = 2;
public const int SHADED_TRANSPARENT_PASS = 3;
private List<OperationType> _operations = new List<OperationType>();
private List<Matrix4x4> _matrices = new List<Matrix4x4>();
private List<Color> _colors = new List<Color>();
private List<Line> _lines = new List<Line>();
private List<Mesh> _meshes = new List<Mesh>();
private Color _currColor = Color.white;
private Matrix4x4 _currMatrix = Matrix4x4.identity;
private Stack<Matrix4x4> _matrixStack = new Stack<Matrix4x4>();
private bool _isInWireMode = false;
private Material _gizmoMaterial;
private int _operationCountOnGuard = -1;
public Shader gizmoShader {
get {
if (_gizmoMaterial == null) {
return null;
} else {
return _gizmoMaterial.shader;
}
}
set {
if (_gizmoMaterial == null) {
_gizmoMaterial = new Material(value);
_gizmoMaterial.name = "Runtime Gizmo Material";
_gizmoMaterial.hideFlags = HideFlags.HideAndDontSave;
} else {
_gizmoMaterial.shader = value;
}
}
}
public Mesh cubeMesh, wireCubeMesh, sphereMesh, wireSphereMesh;
/// <summary>
/// Begins a draw-guard. If any gizmos are drawn to this drawer an exception will be thrown at the end of the guard.
/// </summary>
public void BeginGuard() {
_operationCountOnGuard = _operations.Count;
}
/// <summary>
/// Ends a draw-guard. If any gizmos were drawn to this drawer during the guard, an exception will be thrown.
/// </summary>
public void EndGuard() {
bool wereGizmosDrawn = _operations.Count > _operationCountOnGuard;
_operationCountOnGuard = -1;
if (wereGizmosDrawn) {
Debug.LogError("New gizmos were drawn to the front buffer! Make sure to never keep a reference to a Drawer, always get a new one every time you want to start drawing.");
}
}
/// <summary>
/// Causes all remaining gizmos drawing to be done in the local coordinate space of the given transform.
/// </summary>
public void RelativeTo(Transform transform) {
matrix = transform.localToWorldMatrix;
}
/// <summary>
/// Saves the current gizmo matrix to the gizmo matrix stack.
/// </summary>
public void PushMatrix() {
_matrixStack.Push(_currMatrix);
}
/// <summary>
/// Restores the current gizmo matrix from the gizmo matrix stack.
/// </summary>
public void PopMatrix() {
matrix = _matrixStack.Pop();
}
/// <summary>
/// Resets the matrix to the identity matrix and the color to white.
/// </summary>
public void ResetMatrixAndColorState() {
matrix = Matrix4x4.identity;
color = Color.white;
}
/// <summary>
/// Sets or gets the color for the gizmos that will be drawn next.
/// </summary>
public Color color {
get {
return _currColor;
}
set {
if (_currColor == value) {
return;
}
_currColor = value;
_operations.Add(OperationType.SetColor);
_colors.Add(_currColor);
}
}
/// <summary>
/// Sets or gets the matrix used to transform all gizmos.
/// </summary>
public Matrix4x4 matrix {
get {
return _currMatrix;
}
set {
if (_currMatrix == value) {
return;
}
_currMatrix = value;
_operations.Add(OperationType.SetMatrix);
_matrices.Add(_currMatrix);
}
}
/// <summary>
/// Draw a filled gizmo mesh using the given matrix transform.
/// </summary>
public void DrawMesh(Mesh mesh, Matrix4x4 matrix) {
setWireMode(false);
drawMeshInternal(mesh, matrix);
}
/// <summary>
/// Draws a filled gizmo mesh at the given transform location.
/// </summary>
public void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Vector3 scale) {
DrawMesh(mesh, Matrix4x4.TRS(position, rotation, scale));
}
/// <summary>
/// Draws a wire gizmo mesh using the given matrix transform.
/// </summary>
public void DrawWireMesh(Mesh mesh, Matrix4x4 matrix) {
setWireMode(true);
drawMeshInternal(mesh, matrix);
}
/// <summary>
/// Draws a wire gizmo mesh at the given transform location.
/// </summary>
public void DrawWireMesh(Mesh mesh, Vector3 position, Quaternion rotation, Vector3 scale) {
DrawWireMesh(mesh, Matrix4x4.TRS(position, rotation, scale));
}
/// <summary>
/// Draws a gizmo line that connects the two positions.
/// </summary>
public void DrawLine(Vector3 a, Vector3 b) {
_operations.Add(OperationType.DrawLine);
_lines.Add(new Line(a, b));
}
/// <summary>
/// Draws a filled gizmo cube at the given position with the given size.
/// </summary>
public void DrawCube(Vector3 position, Vector3 size) {
DrawMesh(cubeMesh, position, Quaternion.identity, size);
}
/// <summary>
/// Draws a wire gizmo cube at the given position with the given size.
/// </summary>
public void DrawWireCube(Vector3 position, Vector3 size) {
DrawWireMesh(wireCubeMesh, position, Quaternion.identity, size);
}
/// <summary>
/// Draws a filled gizmo sphere at the given position with the given radius.
/// </summary>
public void DrawSphere(Vector3 center, float radius) {
//Throw an error here so we can give a more specific error than the more
//general one which will be thrown later for a null mesh.
if (sphereMesh == null) {
throw new InvalidOperationException("Cannot draw a sphere because the Runtime Gizmo Manager does not have a sphere mesh assigned!");
}
DrawMesh(sphereMesh, center, Quaternion.identity, Vector3.one * radius * 2);
}
/// <summary>
/// Draws a wire gizmo sphere at the given position with the given radius.
/// </summary>
public void DrawWireSphere(Vector3 center, float radius) {
DrawWireMesh(wireSphereMesh, center, Quaternion.identity, Vector3.one * radius * 2);
}
/// <summary>
/// Draws a wire gizmo circle at the given position, with the given normal and radius.
/// </summary>
public void DrawWireCircle(Vector3 center, Vector3 direction, float radius) {
PushMatrix();
matrix = Matrix4x4.TRS(center, Quaternion.LookRotation(direction), Vector3.one) *
matrix *
Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(1, 1, 0));
DrawWireSphere(Vector3.zero, radius);
PopMatrix();
}
/// <summary>
/// Draws a wire gizmo capsule at the given position, with the given start and end points and radius.
/// </summary>
public void DrawWireCapsule(Vector3 start, Vector3 end, float radius) {
Vector3 up = (end - start).normalized * radius;
Vector3 forward = Vector3.Slerp(up, -up, 0.5F);
Vector3 right = Vector3.Cross(up, forward).normalized * radius;
float height = (start - end).magnitude;
// Radial circles
DrawLineWireCircle(start, up, radius, 8);
DrawLineWireCircle(end, -up, radius, 8);
// Sides
DrawLine(start + right, end + right);
DrawLine(start - right, end - right);
DrawLine(start + forward, end + forward);
DrawLine(start - forward, end - forward);
// Endcaps
DrawWireArc(start, right, forward, radius, 0.5F, 8);
DrawWireArc(start, forward, -right, radius, 0.5F, 8);
DrawWireArc(end, right, -forward, radius, 0.5F, 8);
DrawWireArc(end, forward, right, radius, 0.5F, 8);
}
private void DrawLineWireCircle(Vector3 center, Vector3 normal, float radius, int numCircleSegments = 16) {
DrawWireArc(center, normal, Vector3.Slerp(normal, -normal, 0.5F), radius, 1.0F, numCircleSegments);
}
public void DrawWireArc(Vector3 center, Vector3 normal, Vector3 radialStartDirection, float radius, float fractionOfCircleToDraw, int numCircleSegments = 16) {
normal = normal.normalized;
Vector3 radiusVector = radialStartDirection.normalized * radius;
Vector3 nextVector;
int numSegmentsToDraw = (int)(numCircleSegments * fractionOfCircleToDraw);
for (int i = 0; i < numSegmentsToDraw; i++) {
nextVector = Quaternion.AngleAxis(360F / numCircleSegments, normal) * radiusVector;
DrawLine(center + radiusVector, center + nextVector);
radiusVector = nextVector;
}
}
private List<Collider> _colliderList = new List<Collider>();
public void DrawColliders(GameObject gameObject, bool useWireframe = true,
bool traverseHierarchy = true,
bool drawTriggers = false) {
PushMatrix();
if (traverseHierarchy) {
gameObject.GetComponentsInChildren(_colliderList);
} else {
gameObject.GetComponents(_colliderList);
}
for (int i = 0; i < _colliderList.Count; i++) {
Collider collider = _colliderList[i];
RelativeTo(collider.transform);
if (collider.isTrigger && !drawTriggers) { continue; }
if (collider is BoxCollider) {
BoxCollider box = collider as BoxCollider;
if (useWireframe) {
DrawWireCube(box.center, box.size);
} else {
DrawCube(box.center, box.size);
}
} else if (collider is SphereCollider) {
SphereCollider sphere = collider as SphereCollider;
if (useWireframe) {
DrawWireSphere(sphere.center, sphere.radius);
} else {
DrawSphere(sphere.center, sphere.radius);
}
} else if (collider is CapsuleCollider) {
CapsuleCollider capsule = collider as CapsuleCollider;
if (useWireframe) {
Vector3 capsuleDir;
switch (capsule.direction) {
case 0: capsuleDir = Vector3.right; break;
case 1: capsuleDir = Vector3.up; break;
case 2: default: capsuleDir = Vector3.forward; break;
}
DrawWireCapsule(capsule.center + capsuleDir * (capsule.height / 2F - capsule.radius),
capsule.center - capsuleDir * (capsule.height / 2F - capsule.radius), capsule.radius);
} else {
Vector3 size = Vector3.zero;
size += Vector3.one * capsule.radius * 2;
size += new Vector3(capsule.direction == 0 ? 1 : 0,
capsule.direction == 1 ? 1 : 0,
capsule.direction == 2 ? 1 : 0) * (capsule.height - capsule.radius * 2);
DrawCube(capsule.center, size);
}
} else if (collider is MeshCollider) {
MeshCollider mesh = collider as MeshCollider;
if (mesh.sharedMesh != null) {
if (useWireframe) {
DrawWireMesh(mesh.sharedMesh, Matrix4x4.identity);
} else {
DrawMesh(mesh.sharedMesh, Matrix4x4.identity);
}
}
}
}
PopMatrix();
}
public void ClearAllGizmos() {
_operations.Clear();
_matrices.Clear();
_colors.Clear();
_lines.Clear();
_meshes.Clear();
_isInWireMode = false;
_currMatrix = Matrix4x4.identity;
_currColor = Color.white;
}
public void DrawAllGizmosToScreen() {
try {
int matrixIndex = 0;
int colorIndex = 0;
int lineIndex = 0;
int meshIndex = 0;
int currPass = -1;
_currMatrix = Matrix4x4.identity;
_currColor = Color.white;
GL.wireframe = false;
for (int i = 0; i < _operations.Count; i++) {
OperationType type = _operations[i];
switch (type) {
case OperationType.SetMatrix:
_currMatrix = _matrices[matrixIndex++];
break;
case OperationType.SetColor:
_currColor = _colors[colorIndex++];
currPass = -1; //force pass to be set the next time we need to draw
break;
case OperationType.ToggleWireframe:
GL.wireframe = !GL.wireframe;
break;
case OperationType.DrawLine:
setPass(ref currPass, isUnlit: true);
GL.Begin(GL.LINES);
Line line = _lines[lineIndex++];
GL.Vertex(_currMatrix.MultiplyPoint(line.a));
GL.Vertex(_currMatrix.MultiplyPoint(line.b));
GL.End();
break;
case OperationType.DrawMesh:
if (GL.wireframe) {
setPass(ref currPass, isUnlit: true);
} else {
setPass(ref currPass, isUnlit: false);
}
Graphics.DrawMeshNow(_meshes[meshIndex++], _currMatrix * _matrices[matrixIndex++]);
break;
default:
throw new InvalidOperationException("Unexpected operation type " + type);
}
}
} finally {
GL.wireframe = false;
}
}
private void setPass(ref int currPass, bool isUnlit) {
int newPass;
if (isUnlit) {
if (_currColor.a < 1) {
newPass = UNLIT_TRANSPARENT_PASS;
} else {
newPass = UNLIT_SOLID_PASS;
}
} else {
if (_currColor.a < 1) {
newPass = SHADED_TRANSPARENT_PASS;
} else {
newPass = SHADED_SOLID_PASS;
}
}
if (currPass != newPass) {
currPass = newPass;
_gizmoMaterial.color = _currColor;
_gizmoMaterial.SetPass(currPass);
}
}
private void drawMeshInternal(Mesh mesh, Matrix4x4 matrix) {
if (mesh == null) {
throw new InvalidOperationException("Mesh cannot be null!");
}
_operations.Add(OperationType.DrawMesh);
_meshes.Add(mesh);
_matrices.Add(matrix);
}
private void setWireMode(bool wireMode) {
if (_isInWireMode != wireMode) {
_operations.Add(OperationType.ToggleWireframe);
_isInWireMode = wireMode;
}
}
private enum OperationType {
SetMatrix,
ToggleWireframe,
SetColor,
DrawLine,
DrawMesh
}
private struct Line {
public Vector3 a, b;
public Line(Vector3 a, Vector3 b) {
this.a = a;
this.b = b;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Xml;
using System.Xml.Serialization;
using SoapCore.ServiceModel;
namespace SoapCore
{
internal class ServiceBodyWriter : BodyWriter
{
private readonly SoapSerializer _serializer;
private readonly OperationDescription _operation;
private readonly string _serviceNamespace;
private readonly string _envelopeName;
private readonly string _resultName;
private readonly object _result;
private readonly Dictionary<string, object> _outResults;
public ServiceBodyWriter(SoapSerializer serializer, OperationDescription operation, object result, Dictionary<string, object> outResults) : base(isBuffered: true)
{
_serializer = serializer;
_operation = operation;
_serviceNamespace = operation.Contract.Namespace;
_envelopeName = operation.Name + "Response";
_resultName = operation.ReturnName;
_result = result;
_outResults = outResults ?? new Dictionary<string, object>();
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
switch (_serializer)
{
case SoapSerializer.XmlSerializer:
OnWriteXmlSerializerBodyContents(writer);
break;
case SoapSerializer.DataContractSerializer:
OnWriteDataContractSerializerBodyContents(writer);
break;
default:
throw new NotImplementedException($"Unknown serializer {_serializer}");
}
}
private static void WriteStream(XmlDictionaryWriter writer, object value)
{
int blockSize = 256;
int bytesRead = 0;
byte[] block = new byte[blockSize];
var stream = (Stream)value;
stream.Position = 0;
while (true)
{
bytesRead = stream.Read(block, 0, blockSize);
if (bytesRead > 0)
{
writer.WriteBase64(block, 0, bytesRead);
}
else
{
break;
}
if (blockSize < 65536 && bytesRead == blockSize)
{
blockSize = blockSize * 16;
block = new byte[blockSize];
}
}
}
private void OnWriteXmlSerializerBodyContents(XmlDictionaryWriter writer)
{
Debug.Assert(_outResults != null, "Object should set empty out results");
// Do not wrap old-style single element response into additional xml element for xml serializer
var needResponseEnvelope = _result == null || (_outResults.Count > 0) || !_operation.IsMessageContractResponse;
if (needResponseEnvelope)
{
writer.WriteStartElement(_envelopeName, _serviceNamespace);
}
if (_result != null)
{
// see https://referencesource.microsoft.com/System.Xml/System/Xml/Serialization/XmlSerializer.cs.html#c97688a6c07294d5
var resultType = _result.GetType();
var xmlRootAttr = resultType.GetTypeInfo().GetCustomAttributes<XmlRootAttribute>().FirstOrDefault();
var messageContractAttribute = resultType.GetTypeInfo().GetCustomAttribute<MessageContractAttribute>();
var xmlName = _operation.ReturnElementName ?? messageContractAttribute?.WrapperName
?? (needResponseEnvelope
? (string.IsNullOrWhiteSpace(xmlRootAttr?.ElementName)
? _resultName
: xmlRootAttr.ElementName)
: (string.IsNullOrWhiteSpace(xmlRootAttr?.ElementName)
? resultType.Name
: xmlRootAttr.ElementName));
var xmlNs = _operation.ReturnNamespace ?? messageContractAttribute?.WrapperNamespace
?? (string.IsNullOrWhiteSpace(xmlRootAttr?.Namespace)
? _serviceNamespace
: xmlRootAttr.Namespace);
if (_operation.ReturnsChoice)
{
foreach (var ch in _operation.ReturnChoices)
{
if (ch.Type == resultType)
{
xmlName = ch.Name ?? xmlName;
xmlNs = ch.Namespace ?? xmlNs;
break;
}
}
}
var xmlArrayAttr = _operation.DispatchMethod.GetCustomAttribute<XmlArrayAttribute>();
if (xmlArrayAttr != null && resultType.IsArray)
{
var serializer = CachedXmlSerializer.GetXmlSerializer(resultType.GetElementType(), xmlName, xmlNs);
serializer.SerializeArray(writer, (object[])_result);
}
else
{
// This behavior is opt-in i.e. you have to explicitly have a [MessageContract(IsWrapped=false)]
// to have the message body members inlined.
var shouldInline = (messageContractAttribute != null && messageContractAttribute.IsWrapped == false) || resultType.GetMembersWithAttribute<MessageHeaderAttribute>().Any();
if (shouldInline)
{
var memberInformation = resultType.GetMembersWithAttribute<MessageBodyMemberAttribute>().Select(mi => new
{
Member = mi,
MessageBodyMemberAttribute = mi.GetCustomAttribute<MessageBodyMemberAttribute>()
}).OrderBy(x => x.MessageBodyMemberAttribute?.Order ?? 0);
if (messageContractAttribute != null && messageContractAttribute.IsWrapped)
{
writer.WriteStartElement(resultType.Name, xmlNs);
}
foreach (var memberInfo in memberInformation)
{
var memberType = memberInfo.Member.GetPropertyOrFieldType();
var memberValue = memberInfo.Member.GetPropertyOrFieldValue(_result);
var memberName = memberInfo.MessageBodyMemberAttribute?.Name ?? memberInfo.Member.Name;
var memberNamespace = memberInfo.MessageBodyMemberAttribute?.Namespace ?? _serviceNamespace;
var serializer = CachedXmlSerializer.GetXmlSerializer(memberType, memberName, memberNamespace);
if (memberValue is Stream)
{
writer.WriteStartElement(memberName, _serviceNamespace);
WriteStream(writer, memberValue);
writer.WriteEndElement();
}
else
{
serializer.Serialize(writer, memberValue);
}
}
if (messageContractAttribute != null && messageContractAttribute.IsWrapped)
{
writer.WriteEndElement();
}
}
else
{
var serializer = CachedXmlSerializer.GetXmlSerializer(resultType, xmlName, xmlNs);
if (_result is Stream)
{
writer.WriteStartElement(_resultName, _serviceNamespace);
WriteStream(writer, _result);
writer.WriteEndElement();
}
else
{
//https://github.com/DigDes/SoapCore/issues/385
if (_operation.DispatchMethod.GetCustomAttribute<XmlSerializerFormatAttribute>()?.Style == OperationFormatStyle.Rpc)
{
var importer = new SoapReflectionImporter(_serviceNamespace);
var typeMapping = importer.ImportTypeMapping(resultType);
var accessor = typeMapping.GetType().GetProperty("Accessor", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(typeMapping);
accessor?.GetType().GetProperty("Name", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.SetValue(accessor, xmlName);
new XmlSerializer(typeMapping).Serialize(writer, _result);
}
else
{
//https://github.com/DigDes/SoapCore/issues/719
serializer.Serialize(writer, _result);
}
}
}
}
}
foreach (var outResult in _outResults)
{
string value = null;
if (outResult.Value is Guid)
{
value = outResult.Value.ToString();
}
else if (outResult.Value is bool)
{
value = outResult.Value.ToString().ToLower();
}
else if (outResult.Value is string)
{
value = System.Security.SecurityElement.Escape(outResult.Value.ToString());
}
else if (outResult.Value is Enum)
{
value = outResult.Value.ToString();
}
else if (outResult.Value == null)
{
value = null;
}
else
{
//for complex types
using (var stream = new MemoryStream())
{
// write element with name as outResult.Key and type information as outResultType
// i.e. <outResult.Key xsi:type="outResultType" ... />
var outResultType = outResult.Value.GetType();
var serializer = CachedXmlSerializer.GetXmlSerializer(outResultType, outResult.Key, _serviceNamespace);
serializer.Serialize(stream, outResult.Value);
//add outResultType. ugly, but working
stream.Position = 0;
XmlDocument xdoc = new XmlDocument();
xdoc.Load(stream);
var attr = xdoc.CreateAttribute("xsi", "type", Namespaces.XMLNS_XSI);
attr.Value = outResultType.Name;
xdoc.DocumentElement.Attributes.Prepend(attr);
writer.WriteRaw(xdoc.DocumentElement.OuterXml);
}
}
if (value != null)
{
writer.WriteRaw(string.Format("<{0}>{1}</{0}>", outResult.Key, value));
}
}
if (needResponseEnvelope)
{
writer.WriteEndElement();
}
}
private void OnWriteDataContractSerializerBodyContents(XmlDictionaryWriter writer)
{
Debug.Assert(_outResults != null, "Object should set empty out results");
writer.WriteStartElement(_envelopeName, _serviceNamespace);
if (_result != null)
{
if (_result is Stream)
{
writer.WriteStartElement(_resultName, _serviceNamespace);
WriteStream(writer, _result);
writer.WriteEndElement();
}
else
{
// When operation return type is `System.Object` the `DataContractSerializer` adds `i:type` attribute with the correct object type
Type resultType = _operation.ReturnType;
IEnumerable<Type> serviceKnownTypes = _operation
.GetServiceKnownTypesHierarchy()
.Select(x => x.Type);
// When `KnownTypeAttribute` is present the `DataContractSerializer` adds `i:type` attribute with the correct object type
DataContractSerializer serializer = resultType.TryGetBaseTypeWithKnownTypes(out Type resultBaseTypeWithKnownTypes)
? new DataContractSerializer(resultBaseTypeWithKnownTypes, _resultName, _serviceNamespace, serviceKnownTypes)
: new DataContractSerializer(resultType, _resultName, _serviceNamespace, serviceKnownTypes);
serializer.WriteObject(writer, _result);
}
}
foreach (var outResult in _outResults)
{
string value = null;
if (outResult.Value is Guid)
{
value = outResult.Value.ToString();
}
else if (outResult.Value is bool)
{
value = outResult.Value.ToString().ToLower();
}
else if (outResult.Value is string)
{
value = System.Security.SecurityElement.Escape(outResult.Value.ToString());
}
else if (outResult.Value is Enum)
{
value = outResult.Value.ToString();
}
else if (outResult.Value == null)
{
value = null;
}
else
{
//for complex types
using (var stream = new MemoryStream())
{
Type outResultType = outResult.Value.GetType();
IEnumerable<Type> serviceKnownTypes = _operation
.GetServiceKnownTypesHierarchy()
.Select(x => x.Type);
var serializer = new DataContractSerializer(outResultType, serviceKnownTypes);
serializer.WriteObject(stream, outResult.Value);
stream.Position = 0;
using (var reader = XmlReader.Create(stream))
{
reader.MoveToContent();
value = reader.ReadInnerXml();
}
}
}
if (value != null)
{
writer.WriteRaw(string.Format("<{0}>{1}</{0}>", outResult.Key, value));
}
}
writer.WriteEndElement();
}
}
}
| |
/*
* CP20278.cs - IBM EBCDIC (Finland/Sweden) code page.
*
* Copyright (c) 2002 Southern Storm Software, Pty Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Generated from "ibm-278.ucm".
namespace I18N.Rare
{
using System;
using I18N.Common;
public class CP20278 : ByteEncoding
{
public CP20278()
: base(20278, ToChars, "IBM EBCDIC (Finland/Sweden)",
"IBM278", "IBM278", "IBM278",
false, false, false, false, 1252)
{}
private static readonly char[] ToChars = {
'\u0000', '\u0001', '\u0002', '\u0003', '\u009C', '\u0009',
'\u0086', '\u007F', '\u0097', '\u008D', '\u008E', '\u000B',
'\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011',
'\u0012', '\u0013', '\u009D', '\u0085', '\u0008', '\u0087',
'\u0018', '\u0019', '\u0092', '\u008F', '\u001C', '\u001D',
'\u001E', '\u001F', '\u0080', '\u0081', '\u0082', '\u0083',
'\u0084', '\u000A', '\u0017', '\u001B', '\u0088', '\u0089',
'\u008A', '\u008B', '\u008C', '\u0005', '\u0006', '\u0007',
'\u0090', '\u0091', '\u0016', '\u0093', '\u0094', '\u0095',
'\u0096', '\u0004', '\u0098', '\u0099', '\u009A', '\u009B',
'\u0014', '\u0015', '\u009E', '\u001A', '\u0020', '\u00A0',
'\u00E2', '\u007B', '\u00E0', '\u00E1', '\u00E3', '\u007D',
'\u00E7', '\u00F1', '\u00A7', '\u002E', '\u003C', '\u0028',
'\u002B', '\u0021', '\u0026', '\u0060', '\u00EA', '\u00EB',
'\u00E8', '\u00ED', '\u00EE', '\u00EF', '\u00EC', '\u00DF',
'\u00A4', '\u00C5', '\u002A', '\u0029', '\u003B', '\u005E',
'\u002D', '\u002F', '\u00C2', '\u0023', '\u00C0', '\u00C1',
'\u00C3', '\u0024', '\u00C7', '\u00D1', '\u00F6', '\u002C',
'\u0025', '\u005F', '\u003E', '\u003F', '\u00F8', '\u005C',
'\u00CA', '\u00CB', '\u00C8', '\u00CD', '\u00CE', '\u00CF',
'\u00CC', '\u00E9', '\u003A', '\u00C4', '\u00D6', '\u0027',
'\u003D', '\u0022', '\u00D8', '\u0061', '\u0062', '\u0063',
'\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069',
'\u00AB', '\u00BB', '\u00F0', '\u00FD', '\u00FE', '\u00B1',
'\u00B0', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E',
'\u006F', '\u0070', '\u0071', '\u0072', '\u00AA', '\u00BA',
'\u00E6', '\u00B8', '\u00C6', '\u005D', '\u00B5', '\u00FC',
'\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078',
'\u0079', '\u007A', '\u00A1', '\u00BF', '\u00D0', '\u00DD',
'\u00DE', '\u00AE', '\u00A2', '\u00A3', '\u00A5', '\u00B7',
'\u00A9', '\u005B', '\u00B6', '\u00BC', '\u00BD', '\u00BE',
'\u00AC', '\u007C', '\u00AF', '\u00A8', '\u00B4', '\u00D7',
'\u00E4', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045',
'\u0046', '\u0047', '\u0048', '\u0049', '\u00AD', '\u00F4',
'\u00A6', '\u00F2', '\u00F3', '\u00F5', '\u00E5', '\u004A',
'\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050',
'\u0051', '\u0052', '\u00B9', '\u00FB', '\u007E', '\u00F9',
'\u00FA', '\u00FF', '\u00C9', '\u00F7', '\u0053', '\u0054',
'\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A',
'\u00B2', '\u00D4', '\u0040', '\u00D2', '\u00D3', '\u00D5',
'\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035',
'\u0036', '\u0037', '\u0038', '\u0039', '\u00B3', '\u00DB',
'\u00DC', '\u00D9', '\u00DA', '\u009F',
};
protected override void ToBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(chars[charIndex++]);
if(ch >= 4) switch(ch)
{
case 0x000B:
case 0x000C:
case 0x000D:
case 0x000E:
case 0x000F:
case 0x0010:
case 0x0011:
case 0x0012:
case 0x0013:
case 0x0018:
case 0x0019:
case 0x001C:
case 0x001D:
case 0x001E:
case 0x001F:
case 0x00B6:
break;
case 0x0004: ch = 0x37; break;
case 0x0005: ch = 0x2D; break;
case 0x0006: ch = 0x2E; break;
case 0x0007: ch = 0x2F; break;
case 0x0008: ch = 0x16; break;
case 0x0009: ch = 0x05; break;
case 0x000A: ch = 0x25; break;
case 0x0014: ch = 0x3C; break;
case 0x0015: ch = 0x3D; break;
case 0x0016: ch = 0x32; break;
case 0x0017: ch = 0x26; break;
case 0x001A: ch = 0x3F; break;
case 0x001B: ch = 0x27; break;
case 0x0020: ch = 0x40; break;
case 0x0021: ch = 0x4F; break;
case 0x0022: ch = 0x7F; break;
case 0x0023: ch = 0x63; break;
case 0x0024: ch = 0x67; break;
case 0x0025: ch = 0x6C; break;
case 0x0026: ch = 0x50; break;
case 0x0027: ch = 0x7D; break;
case 0x0028: ch = 0x4D; break;
case 0x0029: ch = 0x5D; break;
case 0x002A: ch = 0x5C; break;
case 0x002B: ch = 0x4E; break;
case 0x002C: ch = 0x6B; break;
case 0x002D: ch = 0x60; break;
case 0x002E: ch = 0x4B; break;
case 0x002F: ch = 0x61; break;
case 0x0030:
case 0x0031:
case 0x0032:
case 0x0033:
case 0x0034:
case 0x0035:
case 0x0036:
case 0x0037:
case 0x0038:
case 0x0039:
ch += 0x00C0;
break;
case 0x003A: ch = 0x7A; break;
case 0x003B: ch = 0x5E; break;
case 0x003C: ch = 0x4C; break;
case 0x003D: ch = 0x7E; break;
case 0x003E: ch = 0x6E; break;
case 0x003F: ch = 0x6F; break;
case 0x0040: ch = 0xEC; break;
case 0x0041:
case 0x0042:
case 0x0043:
case 0x0044:
case 0x0045:
case 0x0046:
case 0x0047:
case 0x0048:
case 0x0049:
ch += 0x0080;
break;
case 0x004A:
case 0x004B:
case 0x004C:
case 0x004D:
case 0x004E:
case 0x004F:
case 0x0050:
case 0x0051:
case 0x0052:
ch += 0x0087;
break;
case 0x0053:
case 0x0054:
case 0x0055:
case 0x0056:
case 0x0057:
case 0x0058:
case 0x0059:
case 0x005A:
ch += 0x008F;
break;
case 0x005B: ch = 0xB5; break;
case 0x005C: ch = 0x71; break;
case 0x005D: ch = 0x9F; break;
case 0x005E: ch = 0x5F; break;
case 0x005F: ch = 0x6D; break;
case 0x0060: ch = 0x51; break;
case 0x0061:
case 0x0062:
case 0x0063:
case 0x0064:
case 0x0065:
case 0x0066:
case 0x0067:
case 0x0068:
case 0x0069:
ch += 0x0020;
break;
case 0x006A:
case 0x006B:
case 0x006C:
case 0x006D:
case 0x006E:
case 0x006F:
case 0x0070:
case 0x0071:
case 0x0072:
ch += 0x0027;
break;
case 0x0073:
case 0x0074:
case 0x0075:
case 0x0076:
case 0x0077:
case 0x0078:
case 0x0079:
case 0x007A:
ch += 0x002F;
break;
case 0x007B: ch = 0x43; break;
case 0x007C: ch = 0xBB; break;
case 0x007D: ch = 0x47; break;
case 0x007E: ch = 0xDC; break;
case 0x007F: ch = 0x07; break;
case 0x0080:
case 0x0081:
case 0x0082:
case 0x0083:
case 0x0084:
ch -= 0x0060;
break;
case 0x0085: ch = 0x15; break;
case 0x0086: ch = 0x06; break;
case 0x0087: ch = 0x17; break;
case 0x0088:
case 0x0089:
case 0x008A:
case 0x008B:
case 0x008C:
ch -= 0x0060;
break;
case 0x008D: ch = 0x09; break;
case 0x008E: ch = 0x0A; break;
case 0x008F: ch = 0x1B; break;
case 0x0090: ch = 0x30; break;
case 0x0091: ch = 0x31; break;
case 0x0092: ch = 0x1A; break;
case 0x0093:
case 0x0094:
case 0x0095:
case 0x0096:
ch -= 0x0060;
break;
case 0x0097: ch = 0x08; break;
case 0x0098:
case 0x0099:
case 0x009A:
case 0x009B:
ch -= 0x0060;
break;
case 0x009C: ch = 0x04; break;
case 0x009D: ch = 0x14; break;
case 0x009E: ch = 0x3E; break;
case 0x009F: ch = 0xFF; break;
case 0x00A0: ch = 0x41; break;
case 0x00A1: ch = 0xAA; break;
case 0x00A2: ch = 0xB0; break;
case 0x00A3: ch = 0xB1; break;
case 0x00A4: ch = 0x5A; break;
case 0x00A5: ch = 0xB2; break;
case 0x00A6: ch = 0xCC; break;
case 0x00A7: ch = 0x4A; break;
case 0x00A8: ch = 0xBD; break;
case 0x00A9: ch = 0xB4; break;
case 0x00AA: ch = 0x9A; break;
case 0x00AB: ch = 0x8A; break;
case 0x00AC: ch = 0xBA; break;
case 0x00AD: ch = 0xCA; break;
case 0x00AE: ch = 0xAF; break;
case 0x00AF: ch = 0xBC; break;
case 0x00B0: ch = 0x90; break;
case 0x00B1: ch = 0x8F; break;
case 0x00B2: ch = 0xEA; break;
case 0x00B3: ch = 0xFA; break;
case 0x00B4: ch = 0xBE; break;
case 0x00B5: ch = 0xA0; break;
case 0x00B7: ch = 0xB3; break;
case 0x00B8: ch = 0x9D; break;
case 0x00B9: ch = 0xDA; break;
case 0x00BA: ch = 0x9B; break;
case 0x00BB: ch = 0x8B; break;
case 0x00BC: ch = 0xB7; break;
case 0x00BD: ch = 0xB8; break;
case 0x00BE: ch = 0xB9; break;
case 0x00BF: ch = 0xAB; break;
case 0x00C0: ch = 0x64; break;
case 0x00C1: ch = 0x65; break;
case 0x00C2: ch = 0x62; break;
case 0x00C3: ch = 0x66; break;
case 0x00C4: ch = 0x7B; break;
case 0x00C5: ch = 0x5B; break;
case 0x00C6: ch = 0x9E; break;
case 0x00C7: ch = 0x68; break;
case 0x00C8: ch = 0x74; break;
case 0x00C9: ch = 0xE0; break;
case 0x00CA: ch = 0x72; break;
case 0x00CB: ch = 0x73; break;
case 0x00CC: ch = 0x78; break;
case 0x00CD: ch = 0x75; break;
case 0x00CE: ch = 0x76; break;
case 0x00CF: ch = 0x77; break;
case 0x00D0: ch = 0xAC; break;
case 0x00D1: ch = 0x69; break;
case 0x00D2: ch = 0xED; break;
case 0x00D3: ch = 0xEE; break;
case 0x00D4: ch = 0xEB; break;
case 0x00D5: ch = 0xEF; break;
case 0x00D6: ch = 0x7C; break;
case 0x00D7: ch = 0xBF; break;
case 0x00D8: ch = 0x80; break;
case 0x00D9: ch = 0xFD; break;
case 0x00DA: ch = 0xFE; break;
case 0x00DB: ch = 0xFB; break;
case 0x00DC: ch = 0xFC; break;
case 0x00DD: ch = 0xAD; break;
case 0x00DE: ch = 0xAE; break;
case 0x00DF: ch = 0x59; break;
case 0x00E0: ch = 0x44; break;
case 0x00E1: ch = 0x45; break;
case 0x00E2: ch = 0x42; break;
case 0x00E3: ch = 0x46; break;
case 0x00E4: ch = 0xC0; break;
case 0x00E5: ch = 0xD0; break;
case 0x00E6: ch = 0x9C; break;
case 0x00E7: ch = 0x48; break;
case 0x00E8: ch = 0x54; break;
case 0x00E9: ch = 0x79; break;
case 0x00EA: ch = 0x52; break;
case 0x00EB: ch = 0x53; break;
case 0x00EC: ch = 0x58; break;
case 0x00ED: ch = 0x55; break;
case 0x00EE: ch = 0x56; break;
case 0x00EF: ch = 0x57; break;
case 0x00F0: ch = 0x8C; break;
case 0x00F1: ch = 0x49; break;
case 0x00F2: ch = 0xCD; break;
case 0x00F3: ch = 0xCE; break;
case 0x00F4: ch = 0xCB; break;
case 0x00F5: ch = 0xCF; break;
case 0x00F6: ch = 0x6A; break;
case 0x00F7: ch = 0xE1; break;
case 0x00F8: ch = 0x70; break;
case 0x00F9: ch = 0xDD; break;
case 0x00FA: ch = 0xDE; break;
case 0x00FB: ch = 0xDB; break;
case 0x00FC: ch = 0xA1; break;
case 0x00FD: ch = 0x8D; break;
case 0x00FE: ch = 0x8E; break;
case 0x00FF: ch = 0xDF; break;
case 0x0110: ch = 0xAC; break;
case 0x203E: ch = 0xBC; break;
case 0xFF01: ch = 0x4F; break;
case 0xFF02: ch = 0x7F; break;
case 0xFF03: ch = 0x63; break;
case 0xFF04: ch = 0x67; break;
case 0xFF05: ch = 0x6C; break;
case 0xFF06: ch = 0x50; break;
case 0xFF07: ch = 0x7D; break;
case 0xFF08: ch = 0x4D; break;
case 0xFF09: ch = 0x5D; break;
case 0xFF0A: ch = 0x5C; break;
case 0xFF0B: ch = 0x4E; break;
case 0xFF0C: ch = 0x6B; break;
case 0xFF0D: ch = 0x60; break;
case 0xFF0E: ch = 0x4B; break;
case 0xFF0F: ch = 0x61; break;
case 0xFF10:
case 0xFF11:
case 0xFF12:
case 0xFF13:
case 0xFF14:
case 0xFF15:
case 0xFF16:
case 0xFF17:
case 0xFF18:
case 0xFF19:
ch -= 0xFE20;
break;
case 0xFF1A: ch = 0x7A; break;
case 0xFF1B: ch = 0x5E; break;
case 0xFF1C: ch = 0x4C; break;
case 0xFF1D: ch = 0x7E; break;
case 0xFF1E: ch = 0x6E; break;
case 0xFF1F: ch = 0x6F; break;
case 0xFF20: ch = 0xEC; break;
case 0xFF21:
case 0xFF22:
case 0xFF23:
case 0xFF24:
case 0xFF25:
case 0xFF26:
case 0xFF27:
case 0xFF28:
case 0xFF29:
ch -= 0xFE60;
break;
case 0xFF2A:
case 0xFF2B:
case 0xFF2C:
case 0xFF2D:
case 0xFF2E:
case 0xFF2F:
case 0xFF30:
case 0xFF31:
case 0xFF32:
ch -= 0xFE59;
break;
case 0xFF33:
case 0xFF34:
case 0xFF35:
case 0xFF36:
case 0xFF37:
case 0xFF38:
case 0xFF39:
case 0xFF3A:
ch -= 0xFE51;
break;
case 0xFF3B: ch = 0xB5; break;
case 0xFF3C: ch = 0x71; break;
case 0xFF3D: ch = 0x9F; break;
case 0xFF3E: ch = 0x5F; break;
case 0xFF3F: ch = 0x6D; break;
case 0xFF40: ch = 0x51; break;
case 0xFF41:
case 0xFF42:
case 0xFF43:
case 0xFF44:
case 0xFF45:
case 0xFF46:
case 0xFF47:
case 0xFF48:
case 0xFF49:
ch -= 0xFEC0;
break;
case 0xFF4A:
case 0xFF4B:
case 0xFF4C:
case 0xFF4D:
case 0xFF4E:
case 0xFF4F:
case 0xFF50:
case 0xFF51:
case 0xFF52:
ch -= 0xFEB9;
break;
case 0xFF53:
case 0xFF54:
case 0xFF55:
case 0xFF56:
case 0xFF57:
case 0xFF58:
case 0xFF59:
case 0xFF5A:
ch -= 0xFEB1;
break;
case 0xFF5B: ch = 0x43; break;
case 0xFF5C: ch = 0xBB; break;
case 0xFF5D: ch = 0x47; break;
case 0xFF5E: ch = 0xDC; break;
default: ch = 0x3F; break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
protected override void ToBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(s[charIndex++]);
if(ch >= 4) switch(ch)
{
case 0x000B:
case 0x000C:
case 0x000D:
case 0x000E:
case 0x000F:
case 0x0010:
case 0x0011:
case 0x0012:
case 0x0013:
case 0x0018:
case 0x0019:
case 0x001C:
case 0x001D:
case 0x001E:
case 0x001F:
case 0x00B6:
break;
case 0x0004: ch = 0x37; break;
case 0x0005: ch = 0x2D; break;
case 0x0006: ch = 0x2E; break;
case 0x0007: ch = 0x2F; break;
case 0x0008: ch = 0x16; break;
case 0x0009: ch = 0x05; break;
case 0x000A: ch = 0x25; break;
case 0x0014: ch = 0x3C; break;
case 0x0015: ch = 0x3D; break;
case 0x0016: ch = 0x32; break;
case 0x0017: ch = 0x26; break;
case 0x001A: ch = 0x3F; break;
case 0x001B: ch = 0x27; break;
case 0x0020: ch = 0x40; break;
case 0x0021: ch = 0x4F; break;
case 0x0022: ch = 0x7F; break;
case 0x0023: ch = 0x63; break;
case 0x0024: ch = 0x67; break;
case 0x0025: ch = 0x6C; break;
case 0x0026: ch = 0x50; break;
case 0x0027: ch = 0x7D; break;
case 0x0028: ch = 0x4D; break;
case 0x0029: ch = 0x5D; break;
case 0x002A: ch = 0x5C; break;
case 0x002B: ch = 0x4E; break;
case 0x002C: ch = 0x6B; break;
case 0x002D: ch = 0x60; break;
case 0x002E: ch = 0x4B; break;
case 0x002F: ch = 0x61; break;
case 0x0030:
case 0x0031:
case 0x0032:
case 0x0033:
case 0x0034:
case 0x0035:
case 0x0036:
case 0x0037:
case 0x0038:
case 0x0039:
ch += 0x00C0;
break;
case 0x003A: ch = 0x7A; break;
case 0x003B: ch = 0x5E; break;
case 0x003C: ch = 0x4C; break;
case 0x003D: ch = 0x7E; break;
case 0x003E: ch = 0x6E; break;
case 0x003F: ch = 0x6F; break;
case 0x0040: ch = 0xEC; break;
case 0x0041:
case 0x0042:
case 0x0043:
case 0x0044:
case 0x0045:
case 0x0046:
case 0x0047:
case 0x0048:
case 0x0049:
ch += 0x0080;
break;
case 0x004A:
case 0x004B:
case 0x004C:
case 0x004D:
case 0x004E:
case 0x004F:
case 0x0050:
case 0x0051:
case 0x0052:
ch += 0x0087;
break;
case 0x0053:
case 0x0054:
case 0x0055:
case 0x0056:
case 0x0057:
case 0x0058:
case 0x0059:
case 0x005A:
ch += 0x008F;
break;
case 0x005B: ch = 0xB5; break;
case 0x005C: ch = 0x71; break;
case 0x005D: ch = 0x9F; break;
case 0x005E: ch = 0x5F; break;
case 0x005F: ch = 0x6D; break;
case 0x0060: ch = 0x51; break;
case 0x0061:
case 0x0062:
case 0x0063:
case 0x0064:
case 0x0065:
case 0x0066:
case 0x0067:
case 0x0068:
case 0x0069:
ch += 0x0020;
break;
case 0x006A:
case 0x006B:
case 0x006C:
case 0x006D:
case 0x006E:
case 0x006F:
case 0x0070:
case 0x0071:
case 0x0072:
ch += 0x0027;
break;
case 0x0073:
case 0x0074:
case 0x0075:
case 0x0076:
case 0x0077:
case 0x0078:
case 0x0079:
case 0x007A:
ch += 0x002F;
break;
case 0x007B: ch = 0x43; break;
case 0x007C: ch = 0xBB; break;
case 0x007D: ch = 0x47; break;
case 0x007E: ch = 0xDC; break;
case 0x007F: ch = 0x07; break;
case 0x0080:
case 0x0081:
case 0x0082:
case 0x0083:
case 0x0084:
ch -= 0x0060;
break;
case 0x0085: ch = 0x15; break;
case 0x0086: ch = 0x06; break;
case 0x0087: ch = 0x17; break;
case 0x0088:
case 0x0089:
case 0x008A:
case 0x008B:
case 0x008C:
ch -= 0x0060;
break;
case 0x008D: ch = 0x09; break;
case 0x008E: ch = 0x0A; break;
case 0x008F: ch = 0x1B; break;
case 0x0090: ch = 0x30; break;
case 0x0091: ch = 0x31; break;
case 0x0092: ch = 0x1A; break;
case 0x0093:
case 0x0094:
case 0x0095:
case 0x0096:
ch -= 0x0060;
break;
case 0x0097: ch = 0x08; break;
case 0x0098:
case 0x0099:
case 0x009A:
case 0x009B:
ch -= 0x0060;
break;
case 0x009C: ch = 0x04; break;
case 0x009D: ch = 0x14; break;
case 0x009E: ch = 0x3E; break;
case 0x009F: ch = 0xFF; break;
case 0x00A0: ch = 0x41; break;
case 0x00A1: ch = 0xAA; break;
case 0x00A2: ch = 0xB0; break;
case 0x00A3: ch = 0xB1; break;
case 0x00A4: ch = 0x5A; break;
case 0x00A5: ch = 0xB2; break;
case 0x00A6: ch = 0xCC; break;
case 0x00A7: ch = 0x4A; break;
case 0x00A8: ch = 0xBD; break;
case 0x00A9: ch = 0xB4; break;
case 0x00AA: ch = 0x9A; break;
case 0x00AB: ch = 0x8A; break;
case 0x00AC: ch = 0xBA; break;
case 0x00AD: ch = 0xCA; break;
case 0x00AE: ch = 0xAF; break;
case 0x00AF: ch = 0xBC; break;
case 0x00B0: ch = 0x90; break;
case 0x00B1: ch = 0x8F; break;
case 0x00B2: ch = 0xEA; break;
case 0x00B3: ch = 0xFA; break;
case 0x00B4: ch = 0xBE; break;
case 0x00B5: ch = 0xA0; break;
case 0x00B7: ch = 0xB3; break;
case 0x00B8: ch = 0x9D; break;
case 0x00B9: ch = 0xDA; break;
case 0x00BA: ch = 0x9B; break;
case 0x00BB: ch = 0x8B; break;
case 0x00BC: ch = 0xB7; break;
case 0x00BD: ch = 0xB8; break;
case 0x00BE: ch = 0xB9; break;
case 0x00BF: ch = 0xAB; break;
case 0x00C0: ch = 0x64; break;
case 0x00C1: ch = 0x65; break;
case 0x00C2: ch = 0x62; break;
case 0x00C3: ch = 0x66; break;
case 0x00C4: ch = 0x7B; break;
case 0x00C5: ch = 0x5B; break;
case 0x00C6: ch = 0x9E; break;
case 0x00C7: ch = 0x68; break;
case 0x00C8: ch = 0x74; break;
case 0x00C9: ch = 0xE0; break;
case 0x00CA: ch = 0x72; break;
case 0x00CB: ch = 0x73; break;
case 0x00CC: ch = 0x78; break;
case 0x00CD: ch = 0x75; break;
case 0x00CE: ch = 0x76; break;
case 0x00CF: ch = 0x77; break;
case 0x00D0: ch = 0xAC; break;
case 0x00D1: ch = 0x69; break;
case 0x00D2: ch = 0xED; break;
case 0x00D3: ch = 0xEE; break;
case 0x00D4: ch = 0xEB; break;
case 0x00D5: ch = 0xEF; break;
case 0x00D6: ch = 0x7C; break;
case 0x00D7: ch = 0xBF; break;
case 0x00D8: ch = 0x80; break;
case 0x00D9: ch = 0xFD; break;
case 0x00DA: ch = 0xFE; break;
case 0x00DB: ch = 0xFB; break;
case 0x00DC: ch = 0xFC; break;
case 0x00DD: ch = 0xAD; break;
case 0x00DE: ch = 0xAE; break;
case 0x00DF: ch = 0x59; break;
case 0x00E0: ch = 0x44; break;
case 0x00E1: ch = 0x45; break;
case 0x00E2: ch = 0x42; break;
case 0x00E3: ch = 0x46; break;
case 0x00E4: ch = 0xC0; break;
case 0x00E5: ch = 0xD0; break;
case 0x00E6: ch = 0x9C; break;
case 0x00E7: ch = 0x48; break;
case 0x00E8: ch = 0x54; break;
case 0x00E9: ch = 0x79; break;
case 0x00EA: ch = 0x52; break;
case 0x00EB: ch = 0x53; break;
case 0x00EC: ch = 0x58; break;
case 0x00ED: ch = 0x55; break;
case 0x00EE: ch = 0x56; break;
case 0x00EF: ch = 0x57; break;
case 0x00F0: ch = 0x8C; break;
case 0x00F1: ch = 0x49; break;
case 0x00F2: ch = 0xCD; break;
case 0x00F3: ch = 0xCE; break;
case 0x00F4: ch = 0xCB; break;
case 0x00F5: ch = 0xCF; break;
case 0x00F6: ch = 0x6A; break;
case 0x00F7: ch = 0xE1; break;
case 0x00F8: ch = 0x70; break;
case 0x00F9: ch = 0xDD; break;
case 0x00FA: ch = 0xDE; break;
case 0x00FB: ch = 0xDB; break;
case 0x00FC: ch = 0xA1; break;
case 0x00FD: ch = 0x8D; break;
case 0x00FE: ch = 0x8E; break;
case 0x00FF: ch = 0xDF; break;
case 0x0110: ch = 0xAC; break;
case 0x203E: ch = 0xBC; break;
case 0xFF01: ch = 0x4F; break;
case 0xFF02: ch = 0x7F; break;
case 0xFF03: ch = 0x63; break;
case 0xFF04: ch = 0x67; break;
case 0xFF05: ch = 0x6C; break;
case 0xFF06: ch = 0x50; break;
case 0xFF07: ch = 0x7D; break;
case 0xFF08: ch = 0x4D; break;
case 0xFF09: ch = 0x5D; break;
case 0xFF0A: ch = 0x5C; break;
case 0xFF0B: ch = 0x4E; break;
case 0xFF0C: ch = 0x6B; break;
case 0xFF0D: ch = 0x60; break;
case 0xFF0E: ch = 0x4B; break;
case 0xFF0F: ch = 0x61; break;
case 0xFF10:
case 0xFF11:
case 0xFF12:
case 0xFF13:
case 0xFF14:
case 0xFF15:
case 0xFF16:
case 0xFF17:
case 0xFF18:
case 0xFF19:
ch -= 0xFE20;
break;
case 0xFF1A: ch = 0x7A; break;
case 0xFF1B: ch = 0x5E; break;
case 0xFF1C: ch = 0x4C; break;
case 0xFF1D: ch = 0x7E; break;
case 0xFF1E: ch = 0x6E; break;
case 0xFF1F: ch = 0x6F; break;
case 0xFF20: ch = 0xEC; break;
case 0xFF21:
case 0xFF22:
case 0xFF23:
case 0xFF24:
case 0xFF25:
case 0xFF26:
case 0xFF27:
case 0xFF28:
case 0xFF29:
ch -= 0xFE60;
break;
case 0xFF2A:
case 0xFF2B:
case 0xFF2C:
case 0xFF2D:
case 0xFF2E:
case 0xFF2F:
case 0xFF30:
case 0xFF31:
case 0xFF32:
ch -= 0xFE59;
break;
case 0xFF33:
case 0xFF34:
case 0xFF35:
case 0xFF36:
case 0xFF37:
case 0xFF38:
case 0xFF39:
case 0xFF3A:
ch -= 0xFE51;
break;
case 0xFF3B: ch = 0xB5; break;
case 0xFF3C: ch = 0x71; break;
case 0xFF3D: ch = 0x9F; break;
case 0xFF3E: ch = 0x5F; break;
case 0xFF3F: ch = 0x6D; break;
case 0xFF40: ch = 0x51; break;
case 0xFF41:
case 0xFF42:
case 0xFF43:
case 0xFF44:
case 0xFF45:
case 0xFF46:
case 0xFF47:
case 0xFF48:
case 0xFF49:
ch -= 0xFEC0;
break;
case 0xFF4A:
case 0xFF4B:
case 0xFF4C:
case 0xFF4D:
case 0xFF4E:
case 0xFF4F:
case 0xFF50:
case 0xFF51:
case 0xFF52:
ch -= 0xFEB9;
break;
case 0xFF53:
case 0xFF54:
case 0xFF55:
case 0xFF56:
case 0xFF57:
case 0xFF58:
case 0xFF59:
case 0xFF5A:
ch -= 0xFEB1;
break;
case 0xFF5B: ch = 0x43; break;
case 0xFF5C: ch = 0xBB; break;
case 0xFF5D: ch = 0x47; break;
case 0xFF5E: ch = 0xDC; break;
default: ch = 0x3F; break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
}; // class CP20278
public class ENCibm278 : CP20278
{
public ENCibm278() : base() {}
}; // class ENCibm278
}; // namespace I18N.Rare
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Linq.Parallel.Tests
{
public static class OfTypeTests
{
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void OfType_Unordered_AllValid(int count)
{
IntegerRangeSet seen = new IntegerRangeSet(0, count);
foreach (int i in UnorderedSources.Default(count).Select(x => (object)x).OfType<int>())
{
seen.Add(i);
}
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void OfType_Unordered_AllValid_Longrunning()
{
OfType_Unordered_AllValid(Sources.OuterLoopCount);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_AllValid(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = 0;
foreach (int i in query.Select(x => (object)x).OfType<int>())
{
Assert.Equal(seen++, i);
}
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.OuterLoopRanges), MemberType = typeof(Sources))]
public static void OfType_AllValid_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_AllValid(labeled, count);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void OfType_Unordered_AllValid_NotPipelined(int count)
{
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(UnorderedSources.Default(count).Select(x => (object)x).OfType<int>().ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void OfType_Unordered_AllValid_NotPipelined_Longrunning()
{
OfType_Unordered_AllValid_NotPipelined(Sources.OuterLoopCount);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_AllValid_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = 0;
Assert.All(query.Select(x => (object)x).OfType<int>().ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.OuterLoopRanges), MemberType = typeof(Sources))]
public static void OfType_AllValid_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_AllValid_NotPipelined(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_NoneValid(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
Assert.Empty(query.OfType<long>());
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), new[] { 1024 * 64 }, MemberType = typeof(Sources))]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 1024 * 64 }, MemberType = typeof(UnorderedSources))]
public static void OfType_NoneValid_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_NoneValid(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_NoneValid_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
Assert.Empty(query.OfType<long>().ToList());
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), new[] { 1024 * 64 }, MemberType = typeof(Sources))]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 1024 * 64 }, MemberType = typeof(UnorderedSources))]
public static void OfType_NoneValid_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_NoneValid_NotPipelined(labeled, count);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void OfType_Unordered_SomeValid(int count)
{
IntegerRangeSet seen = new IntegerRangeSet(count / 2, (count + 1) / 2);
foreach (int i in UnorderedSources.Default(count).Select(x => x >= count / 2 ? (object)x : x.ToString()).OfType<int>())
{
seen.Add(i);
}
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void OfType_Unordered_SomeValid_Longrunning()
{
OfType_Unordered_SomeValid(Sources.OuterLoopCount);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_SomeValid(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = count / 2;
foreach (int i in query.Select(x => x >= count / 2 ? (object)x : x.ToString()).OfType<int>())
{
Assert.Equal(seen++, i);
}
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.OuterLoopRanges), MemberType = typeof(Sources))]
public static void OfType_SomeValid_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_SomeValid(labeled, count);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void OfType_Unordered_SomeValid_NotPipelined(int count)
{
IntegerRangeSet seen = new IntegerRangeSet(count / 2, (count + 1) / 2);
Assert.All(UnorderedSources.Default(count).Select(x => x >= count / 2 ? (object)x : x.ToString()).OfType<int>().ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void OfType_Unordered_SomeValid_NotPipelined_Longrunning()
{
OfType_Unordered_SomeValid_NotPipelined(Sources.OuterLoopCount);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_SomeValid_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = count / 2;
Assert.All(query.Select(x => x >= count / 2 ? (object)x : x.ToString()).OfType<int>().ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.OuterLoopRanges), MemberType = typeof(Sources))]
public static void OfType_SomeValid_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_SomeValid_NotPipelined(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_SomeInvalidNull(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = count / 2;
Assert.All(query.Select(x => x >= count / 2 ? (object)x : null).OfType<int>(), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.OuterLoopRanges), MemberType = typeof(Sources))]
public static void OfType_SomeInvalidNull_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_SomeInvalidNull(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_SomeValidNull(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int nullCount = 0;
int seen = count / 2;
Assert.All(query.Select(x => x >= count / 2 ? (object)(x.ToString()) : (object)(string)null).OfType<string>(),
x =>
{
if (string.IsNullOrEmpty(x)) nullCount++;
else Assert.Equal(seen++, int.Parse(x));
});
Assert.Equal(count, seen);
Assert.Equal(0, nullCount);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.OuterLoopRanges), MemberType = typeof(Sources))]
public static void OfType_SomeValidNull_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_SomeValidNull(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_SomeNull(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int nullCount = 0;
int seen = count / 2;
Assert.All(query.Select(x => x >= count / 2 ? (object)(int?)x : (int?)null).OfType<int?>(),
x =>
{
if (!x.HasValue) nullCount++;
else Assert.Equal(seen++, x.Value);
});
Assert.Equal(count, seen);
Assert.Equal(0, nullCount);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.OuterLoopRanges), MemberType = typeof(Sources))]
public static void OfType_SomeNull_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_SomeNull(labeled, count);
}
[Fact]
public static void OfType_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<object>)null).OfType<int>());
}
}
}
| |
// SummaryTableItem.cs: SummaryTable DocView Item.
//
// Author: Mike Kestner <mkestner@novell.com>
//
// Copyright (c) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
namespace Monodoc.Widgets {
using System;
using System.Collections.Generic;
using Pango;
internal interface ITableSummary {
string Name { get; }
System.Xml.XmlElement Summary { get; }
}
internal class SummaryTableItem : DocViewItem {
class RowItem : DocViewItem {
DocView view;
DocViewItem caption;
DocViewItem summ;
int cap_width;
public RowItem (DocView view, ITableSummary node)
{
this.view = view;
caption = new LinkItem (view, node.Name, node as DocNode);
summ = new KitchenSinkItem (view, node.Summary);
}
public DocViewItem CaptionItem {
get { return caption; }
}
public int CaptionWidth {
set { cap_width = value; }
}
public override void Update (int width)
{
sz.Width = width;
summ.Update (width - cap_width - 2 * Padding);
if (summ.Size.Height > caption.Size.Height)
sz.Height = summ.Size.Height;
else
sz.Height = caption.Size.Height;
sz.Height += 2 * Padding;
caption.Location = new Gdk.Point (Padding, Padding);
summ.Location = new Gdk.Point (cap_width + Padding, Padding);
}
protected override void OnPaint (Gdk.Drawable win, Gdk.Point offset, Gdk.Rectangle clip)
{
Gdk.Rectangle r = new Gdk.Rectangle (offset.X + Location.X, offset.Y + Location.Y, cap_width, sz.Height);
if (r.IntersectsWith (clip)) {
win.DrawRectangle (view.Style.MidGC (0), false, r);
caption.Paint (win, Globalize (offset), clip);
}
r.X += cap_width;
r.Width = sz.Width - cap_width - 1;
if (r.IntersectsWith (clip)) {
win.DrawRectangle (view.Style.MidGC (0), false, r);
summ.Paint (win, Globalize (offset), clip);
}
}
public override void Event (EventInfo info)
{
info.Position = Localize (info.Position);
if (caption.Contains (info.Position))
caption.Event (info);
else if (summ.Contains (info.Position))
summ.Event (info);
}
}
DocView view;
List<RowItem> rows = new List <RowItem> ();
LabelItem label;
string column_heading;
public SummaryTableItem (DocView view, string label, string caption_heading, List<ITableSummary> rows)
{
this.view = view;
this.label = new LabelItem (view, label);
column_heading = caption_heading;
foreach (ITableSummary node in rows)
this.rows.Add (new RowItem (view, node));
}
const int table_offset = 20;
int cap_width;
Gdk.Rectangle heading_area;
Gdk.Rectangle expander_area;
bool expanded = true;
public override void Update (int width)
{
expander_area = new Gdk.Rectangle (Padding, 0, view.LineHeight, view.LineHeight);
label.Update (-1);
label.Location = new Gdk.Point (table_offset, 0);
if (!expanded) {
sz = new Gdk.Size (width, label.Size.Height);
return;
}
cap_width = 0;
foreach (RowItem row in rows) {
row.CaptionItem.Update (-1);
if (row.CaptionItem.Size.Width > cap_width)
cap_width = row.CaptionItem.Size.Width;
}
cap_width += 2 * Padding;
width -= table_offset + Padding;
int table_width;
if (cap_width > (width / 2))
table_width = 2 * cap_width;
else
table_width = width;
sz.Width = table_width + table_offset + Padding;
int height = label.Size.Height + Padding;
heading_area = new Gdk.Rectangle (table_offset, height, table_width, view.LineHeight + Padding);
height += heading_area.Height;
foreach (RowItem row in rows) {
row.CaptionWidth = cap_width;
row.Update (table_width);
row.Location = new Gdk.Point (table_offset, height);
height += row.Size.Height;
}
sz.Height = height;
}
protected override void OnPaint (Gdk.Drawable win, Gdk.Point offset, Gdk.Rectangle clip)
{
Gdk.Point adj = Globalize (offset);
Gtk.Style.PaintExpander (view.Style, win, Gtk.StateType.Normal, clip, view, null, adj.X + 10, adj.Y + 6, expanded ? Gtk.ExpanderStyle.Expanded : Gtk.ExpanderStyle.Collapsed);
label.Paint (win, adj, clip);
if (!expanded)
return;
Gdk.Rectangle r = heading_area;
r.X += adj.X;
r.Y += adj.Y;
if (r.IntersectsWith (clip)) {
win.DrawRectangle (view.Style.DarkGC (0), true, r);
Pango.Layout layout = view.Layout;
layout.Width = -1;
layout.Alignment = Alignment.Left;
layout.SetText (column_heading);
win.DrawLayout (view.Style.TextGC (0), r.X + Padding, r.Y + Padding, layout);
layout.SetText ("Description");
win.DrawLayout (view.Style.TextGC (0), r.X + cap_width + Padding, r.Y + Padding, layout);
}
foreach (RowItem row in rows)
row.Paint (win, adj, clip);
}
public override void Event (EventInfo info)
{
info.Position = Localize (info.Position);
if (expander_area.Contains (info.Position)) {
expanded = !expanded;
view.Reflow ();
return;
}
foreach (RowItem row in rows)
if (row.Contains (info.Position))
row.Event (info);
}
}
}
| |
//------------------------------------------------------------------------------
// <license file="UintMap.cs">
//
// The use and distribution terms for this software are contained in the file
// named 'LICENSE', which can be found in the resources directory of this
// distribution.
//
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// </license>
//------------------------------------------------------------------------------
using System;
using System.Runtime.InteropServices;
namespace EcmaScript.NET.Collections
{
/// <summary> Map to associate non-negative integers to objects or integers.
/// The map does not synchronize any of its operation, so either use
/// it from a single thread or do own synchronization or perform all mutation
/// operations on one thread before passing the map to others.
///
/// </summary>
public class UintMap
{
virtual public bool Empty
{
get
{
return keyCount == 0;
}
}
/// <summary>Return array of present keys </summary>
virtual public int [] Keys
{
get
{
int [] keys = this.keys;
int n = keyCount;
int [] result = new int [n];
for (int i = 0; n != 0; ++i) {
int entry = keys [i];
if (entry != EMPTY && entry != DELETED) {
result [--n] = entry;
}
}
return result;
}
}
// Map implementation via hashtable,
// follows "The Art of Computer Programming" by Donald E. Knuth
public UintMap ()
: this (4)
{
}
public UintMap (int initialCapacity)
{
if (initialCapacity < 0)
Context.CodeBug ();
// Table grow when number of stored keys >= 3/4 of max capacity
int minimalCapacity = initialCapacity * 4 / 3;
int i;
for (i = 2; (1 << i) < minimalCapacity; ++i) {
}
power = i;
if (check && power < 2)
Context.CodeBug ();
}
public virtual int size ()
{
return keyCount;
}
public virtual bool has (int key)
{
if (key < 0)
Context.CodeBug ();
return 0 <= findIndex (key);
}
/// <summary> Get object value assigned with key.</summary>
/// <returns> key object value or null if key is absent
/// </returns>
public virtual object getObject (int key)
{
if (key < 0)
Context.CodeBug ();
if (values != null) {
int index = findIndex (key);
if (0 <= index) {
return values [index];
}
}
return null;
}
/// <summary> Get integer value assigned with key.</summary>
/// <returns> key integer value or defaultValue if key is absent
/// </returns>
public virtual int getInt (int key, int defaultValue)
{
if (key < 0)
Context.CodeBug ();
int index = findIndex (key);
if (0 <= index) {
if (ivaluesShift != 0) {
return keys [ivaluesShift + index];
}
return 0;
}
return defaultValue;
}
/// <summary> Get integer value assigned with key.</summary>
/// <returns> key integer value or defaultValue if key does not exist or does
/// not have int value
/// </returns>
/// <throws> RuntimeException if key does not exist </throws>
public virtual int getExistingInt (int key)
{
if (key < 0)
Context.CodeBug ();
int index = findIndex (key);
if (0 <= index) {
if (ivaluesShift != 0) {
return keys [ivaluesShift + index];
}
return 0;
}
// Key must exist
Context.CodeBug ();
return 0;
}
/// <summary> Set object value of the key.
/// If key does not exist, also set its int value to 0.
/// </summary>
public virtual void put (int key, object value)
{
if (key < 0)
Context.CodeBug ();
int index = ensureIndex (key, false);
if (values == null) {
values = new object [1 << power];
}
values [index] = value;
}
/// <summary> Set int value of the key.
/// If key does not exist, also set its object value to null.
/// </summary>
public virtual void put (int key, int value)
{
if (key < 0)
Context.CodeBug ();
int index = ensureIndex (key, true);
if (ivaluesShift == 0) {
int N = 1 << power;
// keys.length can be N * 2 after clear which set ivaluesShift to 0
if (keys.Length != N * 2) {
int [] tmp = new int [N * 2];
Array.Copy (keys, 0, tmp, 0, N);
keys = tmp;
}
ivaluesShift = N;
}
keys [ivaluesShift + index] = value;
}
public virtual void remove (int key)
{
if (key < 0)
Context.CodeBug ();
int index = findIndex (key);
if (0 <= index) {
keys [index] = DELETED;
--keyCount;
// Allow to GC value and make sure that new key with the deleted
// slot shall get proper default values
if (values != null) {
values [index] = null;
}
if (ivaluesShift != 0) {
keys [ivaluesShift + index] = 0;
}
}
}
public virtual void clear ()
{
int N = 1 << power;
if (keys != null) {
for (int i = 0; i != N; ++i) {
keys [i] = EMPTY;
}
if (values != null) {
for (int i = 0; i != N; ++i) {
values [i] = null;
}
}
}
ivaluesShift = 0;
keyCount = 0;
occupiedCount = 0;
}
private static int tableLookupStep (int fraction, int mask, int power)
{
int shift = 32 - 2 * power;
if (shift >= 0) {
return (((int)((uint)fraction >> shift)) & mask) | 1;
}
else {
return (fraction & (int)((uint)mask >> -shift)) | 1;
}
}
private int findIndex (int key)
{
int [] keys = this.keys;
if (keys != null) {
int fraction = key * A;
int index = (int)((uint)fraction >> (32 - power));
int entry = keys [index];
if (entry == key) {
return index;
}
if (entry != EMPTY) {
// Search in table after first failed attempt
int mask = (1 << power) - 1;
int step = tableLookupStep (fraction, mask, power);
int n = 0;
do {
if (check) {
if (n >= occupiedCount)
Context.CodeBug ();
++n;
}
index = (index + step) & mask;
entry = keys [index];
if (entry == key) {
return index;
}
}
while (entry != EMPTY);
}
}
return -1;
}
// Insert key that is not present to table without deleted entries
// and enough free space
private int insertNewKey (int key)
{
if (check && occupiedCount != keyCount)
Context.CodeBug ();
if (check && keyCount == 1 << power)
Context.CodeBug ();
int [] keys = this.keys;
int fraction = key * A;
int index = (int)((uint)fraction >> (32 - power));
if (keys [index] != EMPTY) {
int mask = (1 << power) - 1;
int step = tableLookupStep (fraction, mask, power);
int firstIndex = index;
do {
if (check && keys [index] == DELETED)
Context.CodeBug ();
index = (index + step) & mask;
if (check && firstIndex == index)
Context.CodeBug ();
}
while (keys [index] != EMPTY);
}
keys [index] = key;
++occupiedCount;
++keyCount;
return index;
}
private void rehashTable (bool ensureIntSpace)
{
if (keys != null) {
// Check if removing deleted entries would free enough space
if (keyCount * 2 >= occupiedCount) {
// Need to grow: less then half of deleted entries
++power;
}
}
int N = 1 << power;
int [] old = keys;
int oldShift = ivaluesShift;
if (oldShift == 0 && !ensureIntSpace) {
keys = new int [N];
}
else {
ivaluesShift = N;
keys = new int [N * 2];
}
for (int i = 0; i != N; ++i) {
keys [i] = EMPTY;
}
object [] oldValues = values;
if (oldValues != null) {
values = new object [N];
}
int oldCount = keyCount;
occupiedCount = 0;
if (oldCount != 0) {
keyCount = 0;
for (int i = 0, remaining = oldCount; remaining != 0; ++i) {
int key = old [i];
if (key != EMPTY && key != DELETED) {
int index = insertNewKey (key);
if (oldValues != null) {
values [index] = oldValues [i];
}
if (oldShift != 0) {
keys [ivaluesShift + index] = old [oldShift + i];
}
--remaining;
}
}
}
}
// Ensure key index creating one if necessary
private int ensureIndex (int key, bool intType)
{
int index = -1;
int firstDeleted = -1;
int [] keys = this.keys;
if (keys != null) {
int fraction = key * A;
index = (int)((uint)fraction >> (32 - power));
int entry = keys [index];
if (entry == key) {
return index;
}
if (entry != EMPTY) {
if (entry == DELETED) {
firstDeleted = index;
}
// Search in table after first failed attempt
int mask = (1 << power) - 1;
int step = tableLookupStep (fraction, mask, power);
int n = 0;
do {
if (check) {
if (n >= occupiedCount)
Context.CodeBug ();
++n;
}
index = (index + step) & mask;
entry = keys [index];
if (entry == key) {
return index;
}
if (entry == DELETED && firstDeleted < 0) {
firstDeleted = index;
}
}
while (entry != EMPTY);
}
}
// Inserting of new key
if (check && keys != null && keys [index] != EMPTY)
Context.CodeBug ();
if (firstDeleted >= 0) {
index = firstDeleted;
}
else {
// Need to consume empty entry: check occupation level
if (keys == null || occupiedCount * 4 >= (1 << power) * 3) {
// Too litle unused entries: rehash
rehashTable (intType);
keys = this.keys;
return insertNewKey (key);
}
++occupiedCount;
}
keys [index] = key;
++keyCount;
return index;
}
// A == golden_ratio * (1 << 32) = ((sqrt(5) - 1) / 2) * (1 << 32)
// See Knuth etc.
private const int A = unchecked ((int)0x9e3779b9);
private const int EMPTY = -1;
private const int DELETED = -2;
// Structure of kyes and values arrays (N == 1 << power):
// keys[0 <= i < N]: key value or EMPTY or DELETED mark
// values[0 <= i < N]: value of key at keys[i]
// keys[N <= i < 2N]: int values of keys at keys[i - N]
private int [] keys;
private object [] values;
private int power;
private int keyCount;
private int occupiedCount; // == keyCount + deleted_count
// If ivaluesShift != 0, keys[ivaluesShift + index] contains integer
// values associated with keys
private int ivaluesShift;
// If true, enables consitency checks
private static readonly bool check = false; // TODO: make me a preprocessor directive
}
}
| |
// 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.Globalization;
//Parse(System.String,System.Globalization.NumberStyles,System.IFormatProvider)
public class Int32Parse3
{
#region Privates
private CultureInfo CurrentCulture = TestLibrary.Utilities.CurrentCulture;
private CultureInfo customCulture = null;
private CultureInfo CustomCulture
{
get
{
if (null == customCulture)
{
customCulture = new CultureInfo(CurrentCulture.Name);
NumberFormatInfo nfi = CustomCulture.NumberFormat;
nfi.NumberGroupSeparator = ",";
nfi.NumberGroupSizes = new int[] { 3 };
nfi.NegativeSign = "-";
nfi.NumberNegativePattern = 1;
customCulture.NumberFormat = nfi;
}
return customCulture;
}
}
#endregion
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
// retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1:Test the method with the cultureinfo parameter which implemented the IFormatProvider interface ");
try
{
string s1 = "1,000";
int i1 = Int32.Parse(s1, System.Globalization.NumberStyles.AllowThousands, CustomCulture);
if (i1 != 1000)
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected. ");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2:Test the method with the numberformatinfo parameter which implemented the IFormatProvider interface ");
try
{
// if NumberFormatInfo is null, created without any argument, Parse uses CurrrentCulture
TestLibrary.Utilities.CurrentCulture = CustomCulture;
string s1 = " 3,000 ";
int i1 = Int32.Parse(s1, System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.AllowLeadingWhite | System.Globalization.NumberStyles.AllowTrailingWhite, new NumberFormatInfo());
if (i1 != 3000)
{
TestLibrary.TestFramework.LogError("003", "The result is not the value as expected. ");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
finally
{
TestLibrary.Utilities.CurrentCulture = CurrentCulture;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3:Test the method with the DateTimeFormatInfo parameter which implemented the IFormatProvider interface ");
try
{
TestLibrary.Utilities.CurrentCulture = CustomCulture;
string s1 = "-56,466";
int i1 = Int32.Parse(s1, System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.AllowLeadingSign, new DateTimeFormatInfo());
if (i1 != -56466)
{
TestLibrary.TestFramework.LogError("005", "The result is not the value as expected. ");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
finally
{
TestLibrary.Utilities.CurrentCulture = CurrentCulture;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Test special string \"-3.456.789\" using the cultureinfo parameter");
try
{
string s1 = "-3.456.789";
int i1 = Int32.Parse(s1, System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.AllowLeadingSign, new CultureInfo("pt-BR"));
if (i1 != -3456789)
{
TestLibrary.TestFramework.LogError("007", "The result is not the value as expected. ");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
/*
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Test special string \" 3 456 78\" using the cultureinfo parameter");
try
{
string s1 = " 3 456 78";
int i1 = Int32.Parse(s1, System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.AllowLeadingWhite, new CultureInfo("sma-SE"));
if (i1 != 345678)
{
TestLibrary.TestFramework.LogError("009", "The result is not the value as expected. ");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
*/
public bool PosTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest6: Using the null reference as the third parameter IFormatProvider");
try
{
string s1 = " 345678";
int i1 = Int32.Parse(s1, System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.AllowLeadingWhite, null);
if (i1 != 345678)
{
TestLibrary.TestFramework.LogError("011", "The result is not the value as expected. ");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1:Set the parameter string to null reference ");
try
{
String s1 = null;
int i1 = Int32.Parse(s1, System.Globalization.NumberStyles.AllowThousands, new CultureInfo("en-US"));
TestLibrary.TestFramework.LogError("101", "The ArgumentNullException was not thrown as expected ");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2:Test the ArgumentException");
try
{
String s1 = "1000";
int i1 = 54543;
System.Globalization.NumberStyles Ns = (System.Globalization.NumberStyles)i1;
Int32 i2 = Int32.Parse(s1, Ns, new CultureInfo("en-US"));
TestLibrary.TestFramework.LogError("103", "the Method did not throw a ArgumentException,patameter is: " + s1);
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3:Using improper cultureinfo");
try
{
String s1 = "1 000";
Int32 i2 = Int32.Parse(s1, System.Globalization.NumberStyles.AllowThousands, CustomCulture);
TestLibrary.TestFramework.LogError("105", "the Method did not throw a FormatException,patameter is: " + s1);
retVal = false;
}
catch (FormatException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4:Test the OverflowException");
try
{
String s1 = "2,147,483,650";
Int32 i2 = Int32.Parse(s1, System.Globalization.NumberStyles.AllowThousands, CustomCulture);
TestLibrary.TestFramework.LogError("107", "the Method did not throw an OverflowException,patameter is: " + s1);
retVal = false;
}
catch (System.OverflowException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("108", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
Int32Parse3 test = new Int32Parse3();
TestLibrary.TestFramework.BeginTestCase("Int32Parse3");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
/*
* Copyright (c) 2015, InWorldz Halcyon Developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of halcyon nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenSim.Framework;
namespace InWorldz.Testing
{
public class MockClientAPI : IClientAPI
{
public OpenMetaverse.Vector3 StartPos
{
get
{
return OpenMetaverse.Vector3.Zero;
}
set
{
}
}
public OpenMetaverse.UUID AgentId { get; set; }
public OpenMetaverse.UUID SessionId { get; set; }
public OpenMetaverse.UUID SecureSessionId
{
get { return OpenMetaverse.UUID.Zero; }
}
public OpenMetaverse.UUID ActiveGroupId
{
get { return OpenMetaverse.UUID.Zero; }
}
public string ActiveGroupName
{
get { return ""; }
}
public ulong ActiveGroupPowers
{
get { return 0; }
}
public ulong GetGroupPowers(OpenMetaverse.UUID groupID)
{
return 0;
}
public bool IsGroupMember(OpenMetaverse.UUID GroupID)
{
return true;
}
public string FirstName
{
get { return "Mock"; }
}
public string LastName
{
get { return "User"; }
}
public IScene Scene
{
get { return null; }
}
public int NextAnimationSequenceNumber
{
get { return 0; }
}
public string Name
{
get { return "Mock User"; }
}
public bool IsActive
{
get { return true; }
}
public bool SendLogoutPacketWhenClosing
{
set { }
}
public uint CircuitCode { get; set; }
#pragma warning disable 0067 // disable "X is never used"
public event Action<int> OnSetThrottles;
public event GenericMessage OnGenericMessage;
public event ImprovedInstantMessage OnInstantMessage;
public event ChatMessage OnChatFromClient;
public event TextureRequest OnRequestTexture;
public event RezObject OnRezObject;
public event ModifyTerrain OnModifyTerrain;
public event BakeTerrain OnBakeTerrain;
public event EstateChangeInfo OnEstateChangeInfo;
public event SimWideDeletesDelegate OnSimWideDeletes;
public event SetAppearance OnSetAppearance;
public event AvatarNowWearing OnAvatarNowWearing;
public event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv;
public event RezMultipleAttachmentsFromInv OnRezMultipleAttachmentsFromInv;
public event UUIDNameRequest OnDetachAttachmentIntoInv;
public event ObjectAttach OnObjectAttach;
public event ObjectDeselect OnObjectDetach;
public event ObjectDrop OnObjectDrop;
public event StartAnim OnStartAnim;
public event StopAnim OnStopAnim;
public event LinkObjects OnLinkObjects;
public event DelinkObjects OnDelinkObjects;
public event RequestMapBlocks OnRequestMapBlocks;
public event RequestMapName OnMapNameRequest;
public event TeleportLocationRequest OnTeleportLocationRequest;
public event DisconnectUser OnDisconnectUser;
public event RequestAvatarProperties OnRequestAvatarProperties;
public event RequestAvatarInterests OnRequestAvatarInterests;
public event SetAlwaysRun OnSetAlwaysRun;
public event TeleportLandmarkRequest OnTeleportLandmarkRequest;
public event DeRezObjects OnDeRezObjects;
public event Action<IClientAPI> OnRegionHandShakeReply;
public event GenericCall2 OnRequestWearables;
public event GenericCall2 OnCompleteMovementToRegion;
public event UpdateAgent OnAgentUpdate;
public event AgentRequestSit OnAgentRequestSit;
public event AgentSit OnAgentSit;
public event AvatarPickerRequest OnAvatarPickerRequest;
public event Action<IClientAPI> OnRequestAvatarsData;
public event AddNewPrim OnAddPrim;
public event FetchInventory OnAgentDataUpdateRequest;
public event TeleportLocationRequest OnSetStartLocationRequest;
public event RequestGodlikePowers OnRequestGodlikePowers;
public event GodKickUser OnGodKickUser;
public event ObjectDuplicate OnObjectDuplicate;
public event ObjectDuplicateOnRay OnObjectDuplicateOnRay;
public event GrabObject OnGrabObject;
public event DeGrabObject OnDeGrabObject;
public event MoveObject OnGrabUpdate;
public event SpinStart OnSpinStart;
public event SpinObject OnSpinUpdate;
public event SpinStop OnSpinStop;
public event UpdateShape OnUpdatePrimShape;
public event ObjectExtraParams OnUpdateExtraParams;
public event ObjectRequest OnObjectRequest;
public event ObjectSelect OnObjectSelect;
public event ObjectDeselect OnObjectDeselect;
public event GenericCall7 OnObjectDescription;
public event GenericCall7 OnObjectName;
public event GenericCall7 OnObjectClickAction;
public event GenericCall7 OnObjectMaterial;
public event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily;
public event UpdatePrimFlags OnUpdatePrimFlags;
public event UpdatePrimTexture OnUpdatePrimTexture;
public event UpdateVectorWithUndoSupport OnUpdatePrimGroupPosition;
public event UpdateVectorWithUndoSupport OnUpdatePrimSinglePosition;
public event UpdatePrimRotation OnUpdatePrimGroupRotation;
public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation;
public event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition;
public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation;
public event UpdateVector OnUpdatePrimScale;
public event UpdateVector OnUpdatePrimGroupScale;
public event StatusChange OnChildAgentStatus;
public event GenericCall2 OnStopMovement;
public event Action<OpenMetaverse.UUID> OnRemoveAvatar;
public event ObjectPermissions OnObjectPermissions;
public event CreateNewInventoryItem OnCreateNewInventoryItem;
public event LinkInventoryItem OnLinkInventoryItem;
public event CreateInventoryFolder OnCreateNewInventoryFolder;
public event UpdateInventoryFolder OnUpdateInventoryFolder;
public event MoveInventoryFolder OnMoveInventoryFolder;
public event FetchInventoryDescendents OnFetchInventoryDescendents;
public event PurgeInventoryDescendents OnPurgeInventoryDescendents;
public event FetchInventory OnFetchInventory;
public event RequestTaskInventory OnRequestTaskInventory;
public event UpdateInventoryItem OnUpdateInventoryItem;
public event CopyInventoryItem OnCopyInventoryItem;
public event MoveInventoryItem OnMoveInventoryItem;
public event RemoveInventoryFolder OnRemoveInventoryFolder;
public event RemoveInventoryItem OnRemoveInventoryItem;
public event RemoveInventoryItem OnPreRemoveInventoryItem;
public event UDPAssetUploadRequest OnAssetUploadRequest;
public event XferReceive OnXferReceive;
public event RequestXfer OnRequestXfer;
public event ConfirmXfer OnConfirmXfer;
public event AbortXfer OnAbortXfer;
public event RezScript OnRezScript;
public event UpdateTaskInventory OnUpdateTaskInventory;
public event MoveTaskInventory OnMoveTaskItem;
public event RemoveTaskInventory OnRemoveTaskItem;
public event RequestAsset OnRequestAsset;
public event UUIDNameRequest OnNameFromUUIDRequest;
public event ParcelAccessListRequest OnParcelAccessListRequest;
public event ParcelAccessListUpdateRequest OnParcelAccessListUpdateRequest;
public event ParcelPropertiesRequest OnParcelPropertiesRequest;
public event ParcelDivideRequest OnParcelDivideRequest;
public event ParcelJoinRequest OnParcelJoinRequest;
public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest;
public event ParcelSelectObjects OnParcelSelectObjects;
public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest;
public event ParcelAbandonRequest OnParcelAbandonRequest;
public event ParcelGodForceOwner OnParcelGodForceOwner;
public event ParcelReclaim OnParcelReclaim;
public event ParcelReturnObjectsRequest OnParcelReturnObjectsRequest;
public event ParcelDeedToGroup OnParcelDeedToGroup;
public event RegionInfoRequest OnRegionInfoRequest;
public event EstateCovenantRequest OnEstateCovenantRequest;
public event FriendActionDelegate OnApproveFriendRequest;
public event FriendActionDelegate OnDenyFriendRequest;
public event FriendshipTermination OnTerminateFriendship;
public event MoneyTransferRequest OnMoneyTransferRequest;
public event EconomyDataRequest OnEconomyDataRequest;
public event MoneyBalanceRequest OnMoneyBalanceRequest;
public event UpdateAvatarProperties OnUpdateAvatarProperties;
public event AvatarInterestsUpdate OnAvatarInterestsUpdate;
public event ParcelBuy OnParcelBuy;
public event RequestPayPrice OnRequestPayPrice;
public event ObjectSaleInfo OnObjectSaleInfo;
public event ObjectBuy OnObjectBuy;
public event BuyObjectInventory OnBuyObjectInventory;
public event RequestTerrain OnRequestTerrain;
public event RequestTerrain OnUploadTerrain;
public event ObjectIncludeInSearch OnObjectIncludeInSearch;
public event UUIDNameRequest OnTeleportHomeRequest;
public event ScriptAnswer OnScriptAnswer;
public event AgentSit OnUndo;
public event AgentSit OnRedo;
public event LandUndo OnLandUndo;
public event ForceReleaseControls OnForceReleaseControls;
public event GodLandStatRequest OnLandStatRequest;
public event DetailedEstateDataRequest OnDetailedEstateDataRequest;
public event SetEstateFlagsRequest OnSetEstateFlagsRequest;
public event SetEstateTerrainBaseTexture OnSetEstateTerrainBaseTexture;
public event SetEstateTerrainDetailTexture OnSetEstateTerrainDetailTexture;
public event SetEstateTerrainTextureHeights OnSetEstateTerrainTextureHeights;
public event CommitEstateTerrainTextureRequest OnCommitEstateTerrainTextureRequest;
public event SetRegionTerrainSettings OnSetRegionTerrainSettings;
public event EstateRestartSimRequest OnEstateRestartSimRequest;
public event EstateChangeCovenantRequest OnEstateChangeCovenantRequest;
public event UpdateEstateAccessDeltaRequest OnUpdateEstateAccessDeltaRequest;
public event SimulatorBlueBoxMessageRequest OnSimulatorBlueBoxMessageRequest;
public event EstateBlueBoxMessageRequest OnEstateBlueBoxMessageRequest;
public event EstateDebugRegionRequest OnEstateDebugRegionRequest;
public event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest;
public event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest;
public event UUIDNameRequest OnUUIDGroupNameRequest;
public event RegionHandleRequest OnRegionHandleRequest;
public event ParcelInfoRequest OnParcelInfoRequest;
public event RequestObjectPropertiesFamily OnObjectGroupRequest;
public event ScriptReset OnScriptReset;
public event GetScriptRunning OnGetScriptRunning;
public event SetScriptRunning OnSetScriptRunning;
public event UpdateVector OnAutoPilotGo;
public event TerrainUnacked OnUnackedTerrain;
public event ActivateGestures OnActivateGestures;
public event DeactivateGestures OnDeactivateGestures;
public event ObjectOwner OnObjectOwner;
public event DirPlacesQuery OnDirPlacesQuery;
public event DirFindQuery OnDirFindQuery;
public event DirLandQuery OnDirLandQuery;
public event DirPopularQuery OnDirPopularQuery;
public event DirClassifiedQuery OnDirClassifiedQuery;
public event EventInfoRequest OnEventInfoRequest;
public event ParcelSetOtherCleanTime OnParcelSetOtherCleanTime;
public event MapItemRequest OnMapItemRequest;
public event OfferCallingCard OnOfferCallingCard;
public event AcceptCallingCard OnAcceptCallingCard;
public event DeclineCallingCard OnDeclineCallingCard;
public event SoundTrigger OnSoundTrigger;
public event StartLure OnStartLure;
public event TeleportLureRequest OnTeleportLureRequest;
public event NetworkStats OnNetworkStatsUpdate;
public event ClassifiedInfoRequest OnClassifiedInfoRequest;
public event ClassifiedInfoUpdate OnClassifiedInfoUpdate;
public event ClassifiedDelete OnClassifiedDelete;
public event ClassifiedDelete OnClassifiedGodDelete;
public event EventNotificationAddRequest OnEventNotificationAddRequest;
public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest;
public event EventGodDelete OnEventGodDelete;
public event ParcelDwellRequest OnParcelDwellRequest;
public event UserInfoRequest OnUserInfoRequest;
public event UpdateUserInfo OnUpdateUserInfo;
public event RetrieveInstantMessages OnRetrieveInstantMessages;
public event PickDelete OnPickDelete;
public event PickGodDelete OnPickGodDelete;
public event PickInfoUpdate OnPickInfoUpdate;
public event AvatarNotesUpdate OnAvatarNotesUpdate;
public event MuteListRequest OnMuteListRequest;
public event MuteListEntryUpdate OnUpdateMuteListEntry;
public event MuteListEntryRemove OnRemoveMuteListEntry;
public event PlacesQuery OnPlacesQuery;
public event GrantUserRights OnGrantUserRights;
public event FreezeUserUpdate OnParcelFreezeUser;
public event EjectUserUpdate OnParcelEjectUser;
public event GroupVoteHistoryRequest OnGroupVoteHistoryRequest;
public event GroupAccountDetailsRequest OnGroupAccountDetailsRequest;
public event GroupAccountSummaryRequest OnGroupAccountSummaryRequest;
public event GroupAccountTransactionsRequest OnGroupAccountTransactionsRequest;
public event AgentCachedTextureRequest OnAgentCachedTextureRequest;
public event ActivateGroup OnActivateGroup;
public event GodlikeMessage OnGodlikeMessage;
public event GodlikeMessage OnEstateTelehubRequest;
#pragma warning restore 0067
public System.Net.IPEndPoint RemoteEndPoint
{
get { return new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 18374); }
}
public bool IsLoggingOut
{
get
{
return false;
}
set
{
}
}
public void SetDebugPacketLevel(int newDebug)
{
}
public void ProcessInPacket(OpenMetaverse.Packets.Packet NewPack)
{
}
public void Close()
{
var connClosed = this.OnConnectionClosed;
if (connClosed != null)
{
connClosed(this);
}
}
public void Kick(string message)
{
}
public void Start()
{
}
public void SendWearables(AvatarWearable[] wearables, int serial)
{
}
public void SendAppearance(OpenMetaverse.UUID agentID, byte[] visualParams, byte[] textureEntry)
{
}
public void SendStartPingCheck(byte seq)
{
}
public void SendKillObject(ulong regionHandle, uint localID)
{
}
public void SendKillObjects(ulong regionHandle, uint[] localID)
{
}
public void SendAnimations(OpenMetaverse.UUID[] animID, int[] seqs, OpenMetaverse.UUID sourceAgentId, OpenMetaverse.UUID[] objectIDs)
{
}
public void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args)
{
}
public void SendChatMessage(string message, byte type, OpenMetaverse.Vector3 fromPos, string fromName, OpenMetaverse.UUID fromAgentID, byte source, byte audible)
{
}
public void SendInstantMessage(GridInstantMessage im)
{
}
public void SendGenericMessage(string method, List<string> message)
{
}
public void SendLayerData(float[] map)
{
}
public void SendLayerData(int px, int py, float[] map)
{
}
public void SendWindData(OpenMetaverse.Vector2[] windSpeeds)
{
}
public void SendCloudData(float[] cloudCover)
{
}
public void MoveAgentIntoRegion(RegionInfo regInfo, OpenMetaverse.Vector3 pos, OpenMetaverse.Vector3 look)
{
}
public void InformClientOfNeighbour(ulong neighbourHandle, System.Net.IPEndPoint neighbourExternalEndPoint)
{
}
public AgentCircuitData RequestClientInfo()
{
AgentCircuitData agentData = new AgentCircuitData();
agentData.AgentID = AgentId;
// agentData.Appearance
// agentData.BaseFolder
agentData.CapsPath = OpenMetaverse.UUID.Random().ToString();
agentData.child = false;
agentData.CircuitCode = 100;
agentData.ClientVersion = "Test Client";
agentData.FirstName = "Mock";
// agentData.InventoryFolder
agentData.LastName = "User";
agentData.SecureSessionID = OpenMetaverse.UUID.Random();
agentData.SessionID = OpenMetaverse.UUID.Random();
return agentData;
}
public void SendMapBlock(List<MapBlockData> mapBlocks, uint flag)
{
}
public void SendLocalTeleport(OpenMetaverse.Vector3 position, OpenMetaverse.Vector3 lookAt, uint flags)
{
}
public void SendTeleportFailed(string reason)
{
}
public void SendTeleportLocationStart()
{
}
public void SendPayPrice(OpenMetaverse.UUID objectID, int[] payPrice)
{
}
public void SendAvatarData(ulong regionHandle, string firstName, string lastName, string grouptitle, OpenMetaverse.UUID avatarID, uint avatarLocalID,
OpenMetaverse.Vector3 Pos, byte[] textureEntry, uint parentID, OpenMetaverse.Quaternion rotation, OpenMetaverse.Vector4 collisionPlane,
OpenMetaverse.Vector3 velocity, bool immediate)
{
}
public void SendAvatarTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, OpenMetaverse.Vector3 position, OpenMetaverse.Vector3 velocity, OpenMetaverse.Vector3 acceleration, OpenMetaverse.Quaternion rotation, OpenMetaverse.UUID agentid, OpenMetaverse.Vector4 collisionPlane)
{
}
public void SendCoarseLocationUpdate(List<OpenMetaverse.UUID> users, List<OpenMetaverse.Vector3> CoarseLocations)
{
}
public void AttachObject(uint localID, OpenMetaverse.Quaternion rotation, byte attachPoint, OpenMetaverse.UUID ownerID)
{
}
public void SetChildAgentThrottle(byte[] throttle)
{
}
public void SendPrimitiveToClient(object sop, uint clientFlags, OpenMetaverse.Vector3 lpos)
{
}
public void SendPrimitiveToClientImmediate(object sop, uint clientFlags, OpenMetaverse.Vector3 lpos)
{
}
public void SendPrimTerseUpdate(object sop)
{
}
public void SendInventoryFolderDetails(OpenMetaverse.UUID ownerID, InventoryFolderBase folder, List<InventoryItemBase> items, List<InventoryFolderBase> folders, bool fetchFolders, bool fetchItems)
{
}
public void FlushPrimUpdates()
{
}
public void SendInventoryItemDetails(OpenMetaverse.UUID ownerID, InventoryItemBase item)
{
}
public void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackId)
{
}
public void SendRemoveInventoryItem(OpenMetaverse.UUID itemID)
{
}
public void SendTakeControls(int controls, bool TakeControls, bool passToAgent)
{
}
public void SendTakeControls2(int controls1, bool takeControls1, bool passToAgent1,
int controls2, bool takeControls2, bool passToAgent2)
{
}
public void SendTaskInventory(OpenMetaverse.UUID taskID, short serial, byte[] fileName)
{
}
public void SendBulkUpdateInventory(InventoryNodeBase node)
{
}
public void SendXferPacket(ulong xferID, uint packet, byte[] data)
{
}
public void SendEconomyData(float EnergyEfficiency, int ObjectCapacity, int ObjectCount, int PriceEnergyUnit, int PriceGroupCreate, int PriceObjectClaim, float PriceObjectRent, float PriceObjectScaleFactor, int PriceParcelClaim, float PriceParcelClaimFactor, int PriceParcelRent, int PricePublicObjectDecay, int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice, float TeleportPriceExponent)
{
}
public void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data)
{
}
public void SendAgentDataUpdate(OpenMetaverse.UUID agentid, OpenMetaverse.UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle)
{
}
public void SendPreLoadSound(OpenMetaverse.UUID objectID, OpenMetaverse.UUID ownerID, OpenMetaverse.UUID soundID)
{
}
public void SendPlayAttachedSound(OpenMetaverse.UUID soundID, OpenMetaverse.UUID objectID, OpenMetaverse.UUID ownerID, float gain, byte flags)
{
}
public void SendTriggeredSound(OpenMetaverse.UUID soundID, OpenMetaverse.UUID ownerID, OpenMetaverse.UUID objectID, OpenMetaverse.UUID parentID, ulong handle, OpenMetaverse.Vector3 position, float gain)
{
}
public void SendAttachedSoundGainChange(OpenMetaverse.UUID objectID, float gain)
{
}
public void SendNameReply(OpenMetaverse.UUID profileId, string firstname, string lastname)
{
}
public void SendAlertMessage(string message)
{
}
public void SendAgentAlertMessage(string message, bool modal)
{
}
public void SendLoadURL(string objectname, OpenMetaverse.UUID objectID, OpenMetaverse.UUID ownerID, bool groupOwned, string message, string url)
{
}
public void SendDialog(string objectname, OpenMetaverse.UUID objectID, OpenMetaverse.UUID ownerID, string ownerFirstname, string ownerLastname, string msg, OpenMetaverse.UUID textureID, int ch, string[] buttonlabels)
{
}
public bool AddMoney(int debit)
{
return true;
}
public void SendSunPos(OpenMetaverse.Vector3 sunPos, OpenMetaverse.Vector3 sunVel, ulong CurrentTime, uint SecondsPerSunCycle, uint SecondsPerYear, float OrbitalPosition)
{
}
public void SendViewerEffect(OpenMetaverse.Packets.ViewerEffectPacket.EffectBlock[] effectBlocks)
{
}
public void SendViewerTime(int phase)
{
}
public OpenMetaverse.UUID GetDefaultAnimation(string name)
{
return OpenMetaverse.UUID.Zero;
}
public void SendAvatarProperties(OpenMetaverse.UUID avatarID, string aboutText, string bornOn, byte[] charterMember, string flAbout, uint flags, OpenMetaverse.UUID flImageID, OpenMetaverse.UUID imageID, string profileURL, OpenMetaverse.UUID partnerID)
{
}
public void SendAvatarInterests(OpenMetaverse.UUID avatarID, uint skillsMask, string skillsText, uint wantToMask, string wantToText, string languagesText)
{
}
public void SendScriptQuestion(OpenMetaverse.UUID taskID, string taskName, string ownerName, OpenMetaverse.UUID itemID, int question)
{
}
public void SendHealth(float health)
{
}
public void SendEstateUUIDList(OpenMetaverse.UUID invoice, int whichList, OpenMetaverse.UUID[] UUIDList, uint estateID)
{
}
public void SendBannedUserList(OpenMetaverse.UUID invoice, EstateBan[] banlist, uint estateID)
{
}
public void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args)
{
}
public void SendEstateCovenantInformation(OpenMetaverse.UUID covenant, uint lastUpdated)
{
}
public void SendDetailedEstateData(OpenMetaverse.UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, OpenMetaverse.UUID covenant, uint covenantLastUpdated, string abuseEmail, OpenMetaverse.UUID estateOwner)
{
}
public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, LandData landData, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags)
{
}
public void SendLandAccessListData(List<OpenMetaverse.UUID> avatars, uint accessFlag, int localLandID)
{
}
public void SendForceClientSelectObjects(List<uint> objectIDs)
{
}
public void SendLandObjectOwners(LandData land, List<OpenMetaverse.UUID> groups, Dictionary<OpenMetaverse.UUID, int> ownersAndCount)
{
}
public void SendLandParcelOverlay(byte[] data, int sequence_id)
{
}
public void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time)
{
}
public void SendParcelMediaUpdate(string mediaUrl, OpenMetaverse.UUID mediaTextureID, byte autoScale, string mediaType, string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop)
{
}
public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, OpenMetaverse.UUID AssetFullID)
{
}
public void SendConfirmXfer(ulong xferID, uint PacketID)
{
}
public void SendXferRequest(ulong XferID, short AssetType, OpenMetaverse.UUID vFileID, byte FilePath, byte[] FileName)
{
}
public void SendInitiateDownload(string simFileName, string clientFileName)
{
}
public void SendImageFirstPart(ushort numParts, OpenMetaverse.UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec)
{
}
public void SendImageNextPart(ushort partNumber, OpenMetaverse.UUID imageUuid, byte[] imageData)
{
}
public void SendImageNotFound(OpenMetaverse.UUID imageid)
{
}
public void SendDisableSimulator()
{
}
public void SendSimStats(SimStats stats)
{
}
public void SendObjectPropertiesFamilyData(uint RequestFlags, OpenMetaverse.UUID ObjectUUID, OpenMetaverse.UUID OwnerID, OpenMetaverse.UUID GroupID, uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask, uint NextOwnerMask, int OwnershipCost, byte SaleType, int SalePrice, uint Category, OpenMetaverse.UUID LastOwnerID, string ObjectName, string Description)
{
}
public void SendObjectPropertiesReply(OpenMetaverse.UUID ItemID, ulong CreationDate, OpenMetaverse.UUID CreatorUUID, OpenMetaverse.UUID FolderUUID, OpenMetaverse.UUID FromTaskUUID, OpenMetaverse.UUID GroupUUID, short InventorySerial, OpenMetaverse.UUID LastOwnerUUID, OpenMetaverse.UUID ObjectUUID, OpenMetaverse.UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName, string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask, uint BaseMask, uint FoldedOwnerMask, uint FoldedNextOwnerMask, byte saleType, int salePrice)
{
}
public void SendAgentOffline(OpenMetaverse.UUID[] agentIDs)
{
}
public void SendAgentOnline(OpenMetaverse.UUID[] agentIDs)
{
}
public void SendSitResponse(OpenMetaverse.UUID TargetID, OpenMetaverse.Vector3 OffsetPos, OpenMetaverse.Quaternion SitOrientation, bool autopilot, OpenMetaverse.Vector3 CameraAtOffset, OpenMetaverse.Vector3 CameraEyeOffset, bool ForceMouseLook)
{
}
public void SendAdminResponse(OpenMetaverse.UUID Token, uint AdminLevel)
{
}
public void SendGroupMembership(GroupMembershipData[] GroupMembership)
{
}
public void SendGroupNameReply(OpenMetaverse.UUID groupLLUID, string GroupName)
{
}
public void SendJoinGroupReply(OpenMetaverse.UUID groupID, bool success)
{
}
public void SendEjectGroupMemberReply(OpenMetaverse.UUID agentID, OpenMetaverse.UUID groupID, bool success)
{
}
public void SendLeaveGroupReply(OpenMetaverse.UUID groupID, bool success)
{
}
public void SendCreateGroupReply(OpenMetaverse.UUID groupID, bool success, string message)
{
}
public void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, List<LandStatReportItem> lsrpl)
{
}
public void SendScriptRunningReply(OpenMetaverse.UUID objectID, OpenMetaverse.UUID itemID, bool running)
{
}
public void SendAsset(AssetBase asset, AssetRequestInfo req)
{
}
public void SendTexture(AssetBase TextureAsset)
{
}
public byte[] GetThrottlesPacked(float multiplier)
{
return new byte[0];
}
public event ViewerEffectEventHandler OnViewerEffect;
public event Action<IClientAPI> OnLogout;
public event Action<IClientAPI> OnConnectionClosed;
public void SendBlueBoxMessage(OpenMetaverse.UUID FromAvatarID, string FromAvatarName, string Message)
{
}
public void SendLogoutPacket()
{
}
public void SetClientInfo(ClientInfo info)
{
}
public void SetClientOption(string option, string value)
{
}
public string GetClientOption(string option)
{
return "";
}
public void SendSetFollowCamProperties(OpenMetaverse.UUID objectID, Dictionary<int, float> parameters)
{
}
public void SendClearFollowCamProperties(OpenMetaverse.UUID objectID)
{
}
public void SendRegionHandle(OpenMetaverse.UUID regoinID, ulong handle)
{
}
public void SendParcelInfo(RegionInfo info, LandData land, OpenMetaverse.UUID parcelID, uint x, uint y)
{
}
public void SendScriptTeleportRequest(string objName, string simName, OpenMetaverse.Vector3 pos, OpenMetaverse.Vector3 lookAt)
{
}
public void SendDirPlacesReply(OpenMetaverse.UUID queryID, DirPlacesReplyData[] data)
{
}
public void SendDirPeopleReply(OpenMetaverse.UUID queryID, DirPeopleReplyData[] data)
{
}
public void SendDirEventsReply(OpenMetaverse.UUID queryID, DirEventsReplyData[] data)
{
}
public void SendDirGroupsReply(OpenMetaverse.UUID queryID, DirGroupsReplyData[] data)
{
}
public void SendDirClassifiedReply(OpenMetaverse.UUID queryID, DirClassifiedReplyData[] data)
{
}
public void SendDirLandReply(OpenMetaverse.UUID queryID, DirLandReplyData[] data)
{
}
public void SendDirPopularReply(OpenMetaverse.UUID queryID, DirPopularReplyData[] data)
{
}
public void SendEventInfoReply(EventData info)
{
}
public void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags)
{
}
public void SendAvatarGroupsReply(OpenMetaverse.UUID avatarID, GroupMembershipData[] data)
{
}
public void SendOfferCallingCard(OpenMetaverse.UUID srcID, OpenMetaverse.UUID transactionID)
{
}
public void SendAcceptCallingCard(OpenMetaverse.UUID transactionID)
{
}
public void SendDeclineCallingCard(OpenMetaverse.UUID transactionID)
{
}
public void SendTerminateFriend(OpenMetaverse.UUID exFriendID)
{
}
public void SendAvatarClassifiedReply(OpenMetaverse.UUID targetID, OpenMetaverse.UUID[] classifiedID, string[] name)
{
}
public void SendAvatarInterestsReply(OpenMetaverse.UUID avatarID, uint skillsMask, string skillsText, uint wantToMask, string wantToTask, string languagesText)
{
}
public void SendClassifiedInfoReply(OpenMetaverse.UUID classifiedID, OpenMetaverse.UUID creatorID, uint creationDate, uint expirationDate, uint category, string name, string description, OpenMetaverse.UUID parcelID, uint parentEstate, OpenMetaverse.UUID snapshotID, string simName, OpenMetaverse.Vector3 globalPos, string parcelName, byte classifiedFlags, int price)
{
}
public void SendAgentDropGroup(OpenMetaverse.UUID groupID)
{
}
public void RefreshGroupMembership()
{
}
public void SendAvatarNotesReply(OpenMetaverse.UUID targetID, string text)
{
}
public void SendAvatarPicksReply(OpenMetaverse.UUID targetID, Dictionary<OpenMetaverse.UUID, string> picks)
{
}
public void SendPickInfoReply(OpenMetaverse.UUID pickID, OpenMetaverse.UUID creatorID, bool topPick, OpenMetaverse.UUID parcelID, string name, string desc, OpenMetaverse.UUID snapshotID, string user, string originalName, string simName, OpenMetaverse.Vector3 posGlobal, int sortOrder, bool enabled)
{
}
public void SendAvatarClassifiedReply(OpenMetaverse.UUID targetID, Dictionary<OpenMetaverse.UUID, string> classifieds)
{
}
public void SendParcelDwellReply(int localID, OpenMetaverse.UUID parcelID, float dwell)
{
}
public void SendUserInfoReply(bool imViaEmail, bool visible, string email)
{
}
public void SendUseCachedMuteList()
{
}
public void SendMuteListUpdate(string filename)
{
}
public void KillEndDone()
{
}
public bool AddGenericPacketHandler(string MethodName, GenericMessage handler)
{
return true;
}
public void SendChangeUserRights(OpenMetaverse.UUID agent, OpenMetaverse.UUID agentRelated, int relatedRights)
{
}
public void SendTextBoxRequest(string message, int chatChannel, string objectname, OpenMetaverse.UUID ownerID, string firstName, string lastName, OpenMetaverse.UUID objectId)
{
}
public void FreezeMe(uint flags, OpenMetaverse.UUID whoKey, string who)
{
}
public void SendAbortXfer(ulong id, int result)
{
}
public void RunAttachmentOperation(Action action)
{
}
public void SendAgentCachedTexture(List<CachedAgentArgs> args)
{
}
public void SendTelehubInfo(OpenMetaverse.Vector3 TelehubPos, OpenMetaverse.Quaternion TelehubRot, List<OpenMetaverse.Vector3> SpawnPoint, OpenMetaverse.UUID ObjectID, string nameT)
{
}
public void HandleWithInventoryWriteThread(Action toHandle)
{
}
public Task PauseUpdatesAndFlush()
{
return null;
}
public void ResumeUpdates(IEnumerable<uint> excludeObjectIds)
{
}
public void WaitForClose()
{
}
public void AfterAttachedToConnection(OpenSim.Framework.AgentCircuitData c)
{
}
public void SendMoneyBalance(OpenMetaverse.UUID transaction, bool success, string description, int balance, OpenMetaverse.Packets.MoneyBalanceReplyPacket.TransactionInfoBlock transInfo)
{
}
public List<AgentGroupData> GetAllGroupPowers()
{
return new List<AgentGroupData>();
}
public void SetGroupPowers(IEnumerable<AgentGroupData> groupPowers)
{
}
public int GetThrottleTotal()
{
return 0;
}
public void SetActiveGroupInfo(AgentGroupData activeGroup)
{
}
}
}
| |
/*
* Farseer Physics Engine based on Box2D.XNA port:
* Copyright (c) 2010 Ian Qvist
*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using FarseerPhysics.Common;
using Duality;
namespace FarseerPhysics.Collision.Shapes
{
/// <summary>
/// A line segment (edge) Shape. These can be connected in chains or loops
/// to other edge Shapes. The connectivity information is used to ensure
/// correct contact normals.
/// </summary>
public class EdgeShape : Shape
{
public bool HasVertex0, HasVertex3;
/// <summary>
/// Optional adjacent vertices. These are used for smooth collision.
/// </summary>
public Vector2 Vertex0;
/// <summary>
/// Optional adjacent vertices. These are used for smooth collision.
/// </summary>
public Vector2 Vertex3;
/// <summary>
/// Edge start vertex
/// </summary>
private Vector2 _vertex1;
/// <summary>
/// Edge end vertex
/// </summary>
private Vector2 _vertex2;
internal EdgeShape()
: base(0)
{
this.ShapeType = ShapeType.Edge;
this._radius = Settings.PolygonRadius;
}
public EdgeShape(Vector2 start, Vector2 end)
: base(0)
{
this.ShapeType = ShapeType.Edge;
this._radius = Settings.PolygonRadius;
Set(start, end);
}
public override int ChildCount
{
get { return 1; }
}
/// <summary>
/// These are the edge vertices
/// </summary>
public Vector2 Vertex1
{
get { return this._vertex1; }
set
{
this._vertex1 = value;
ComputeProperties();
}
}
/// <summary>
/// These are the edge vertices
/// </summary>
public Vector2 Vertex2
{
get { return this._vertex2; }
set
{
this._vertex2 = value;
ComputeProperties();
}
}
/// <summary>
/// Set this as an isolated edge.
/// </summary>
/// <param name="start">The start.</param>
/// <param name="end">The end.</param>
public void Set(Vector2 start, Vector2 end)
{
this._vertex1 = start;
this._vertex2 = end;
this.HasVertex0 = false;
this.HasVertex3 = false;
ComputeProperties();
}
public override Shape Clone()
{
EdgeShape edge = new EdgeShape();
edge._radius = this._radius;
edge._density = this._density;
edge.HasVertex0 = this.HasVertex0;
edge.HasVertex3 = this.HasVertex3;
edge.Vertex0 = this.Vertex0;
edge._vertex1 = this._vertex1;
edge._vertex2 = this._vertex2;
edge.Vertex3 = this.Vertex3;
edge.MassData = this.MassData;
return edge;
}
/// <summary>
/// Test a point for containment in this shape. This only works for convex shapes.
/// </summary>
/// <param name="transform">The shape world transform.</param>
/// <param name="point">a point in world coordinates.</param>
/// <returns>True if the point is inside the shape</returns>
public override bool TestPoint(ref Transform transform, ref Vector2 point)
{
return false;
}
/// <summary>
/// Cast a ray against a child shape.
/// </summary>
/// <param name="output">The ray-cast results.</param>
/// <param name="input">The ray-cast input parameters.</param>
/// <param name="transform">The transform to be applied to the shape.</param>
/// <param name="childIndex">The child shape index.</param>
/// <returns>True if the ray-cast hits the shape</returns>
public override bool RayCast(out RayCastOutput output, ref RayCastInput input,
ref Transform transform, int childIndex)
{
// p = p1 + t * d
// v = v1 + s * e
// p1 + t * d = v1 + s * e
// s * e - t * d = p1 - v1
output = new RayCastOutput();
// Put the ray into the edge's frame of reference.
Vector2 p1 = MathUtils.MultiplyT(ref transform.R, input.Point1 - transform.Position);
Vector2 p2 = MathUtils.MultiplyT(ref transform.R, input.Point2 - transform.Position);
Vector2 d = p2 - p1;
Vector2 v1 = this._vertex1;
Vector2 v2 = this._vertex2;
Vector2 e = v2 - v1;
Vector2 normal = new Vector2(e.Y, -e.X);
normal.Normalize();
// q = p1 + t * d
// dot(normal, q - v1) = 0
// dot(normal, p1 - v1) + t * dot(normal, d) = 0
float numerator = Vector2.Dot(normal, v1 - p1);
float denominator = Vector2.Dot(normal, d);
if (denominator == 0.0f)
{
return false;
}
float t = numerator / denominator;
if (t < 0.0f || 1.0f < t)
{
return false;
}
Vector2 q = p1 + t * d;
// q = v1 + s * r
// s = dot(q - v1, r) / dot(r, r)
Vector2 r = v2 - v1;
float rr = Vector2.Dot(r, r);
if (rr == 0.0f)
{
return false;
}
float s = Vector2.Dot(q - v1, r) / rr;
if (s < 0.0f || 1.0f < s)
{
return false;
}
output.Fraction = t;
if (numerator > 0.0f)
{
output.Normal = -normal;
}
else
{
output.Normal = normal;
}
return true;
}
/// <summary>
/// Given a transform, compute the associated axis aligned bounding box for a child shape.
/// </summary>
/// <param name="aabb">The aabb results.</param>
/// <param name="transform">The world transform of the shape.</param>
/// <param name="childIndex">The child shape index.</param>
public override void ComputeAABB(out AABB aabb, ref Transform transform, int childIndex)
{
Vector2 v1 = MathUtils.Multiply(ref transform, this._vertex1);
Vector2 v2 = MathUtils.Multiply(ref transform, this._vertex2);
Vector2 lower = Vector2.Min(v1, v2);
Vector2 upper = Vector2.Max(v1, v2);
Vector2 r = new Vector2(this.Radius, this.Radius);
aabb.LowerBound = lower - r;
aabb.UpperBound = upper + r;
}
/// <summary>
/// Compute the mass properties of this shape using its dimensions and density.
/// The inertia tensor is computed about the local origin, not the centroid.
/// </summary>
public override void ComputeProperties()
{
this.MassData.Centroid = 0.5f * (this._vertex1 + this._vertex2);
}
public override float ComputeSubmergedArea(Vector2 normal, float offset, Transform xf, out Vector2 sc)
{
sc = Vector2.Zero;
return 0;
}
public bool CompareTo(EdgeShape shape)
{
return (this.HasVertex0 == shape.HasVertex0 &&
this.HasVertex3 == shape.HasVertex3 &&
this.Vertex0 == shape.Vertex0 &&
this.Vertex1 == shape.Vertex1 &&
this.Vertex2 == shape.Vertex2 &&
this.Vertex3 == shape.Vertex3);
}
}
}
| |
using System;
using System.Text;
namespace Org.BouncyCastle.Utilities
{
/// <summary> General array utilities.</summary>
public sealed class Arrays
{
private Arrays()
{
}
public static bool AreEqual(
bool[] a,
bool[] b)
{
if (a == b)
return true;
if (a == null || b == null)
return false;
return HaveSameContents(a, b);
}
public static bool AreEqual(
char[] a,
char[] b)
{
if (a == b)
return true;
if (a == null || b == null)
return false;
return HaveSameContents(a, b);
}
/// <summary>
/// Are two arrays equal.
/// </summary>
/// <param name="a">Left side.</param>
/// <param name="b">Right side.</param>
/// <returns>True if equal.</returns>
public static bool AreEqual(
byte[] a,
byte[] b)
{
if (a == b)
return true;
if (a == null || b == null)
return false;
return HaveSameContents(a, b);
}
[Obsolete("Use 'AreEqual' method instead")]
public static bool AreSame(
byte[] a,
byte[] b)
{
return AreEqual(a, b);
}
/// <summary>
/// A constant time equals comparison - does not terminate early if
/// test will fail.
/// </summary>
/// <param name="a">first array</param>
/// <param name="b">second array</param>
/// <returns>true if arrays equal, false otherwise.</returns>
public static bool ConstantTimeAreEqual(
byte[] a,
byte[] b)
{
int i = a.Length;
if (i != b.Length)
return false;
int cmp = 0;
while (i != 0)
{
--i;
cmp |= (a[i] ^ b[i]);
}
return cmp == 0;
}
public static bool AreEqual(
int[] a,
int[] b)
{
if (a == b)
return true;
if (a == null || b == null)
return false;
return HaveSameContents(a, b);
}
private static bool HaveSameContents(
bool[] a,
bool[] b)
{
int i = a.Length;
if (i != b.Length)
return false;
while (i != 0)
{
--i;
if (a[i] != b[i])
return false;
}
return true;
}
private static bool HaveSameContents(
char[] a,
char[] b)
{
int i = a.Length;
if (i != b.Length)
return false;
while (i != 0)
{
--i;
if (a[i] != b[i])
return false;
}
return true;
}
private static bool HaveSameContents(
byte[] a,
byte[] b)
{
int i = a.Length;
if (i != b.Length)
return false;
while (i != 0)
{
--i;
if (a[i] != b[i])
return false;
}
return true;
}
private static bool HaveSameContents(
int[] a,
int[] b)
{
int i = a.Length;
if (i != b.Length)
return false;
while (i != 0)
{
--i;
if (a[i] != b[i])
return false;
}
return true;
}
public static string ToString(
object[] a)
{
StringBuilder sb = new StringBuilder('[');
if (a.Length > 0)
{
sb.Append(a[0]);
for (int index = 1; index < a.Length; ++index)
{
sb.Append(", ").Append(a[index]);
}
}
sb.Append(']');
return sb.ToString();
}
public static int GetHashCode(
byte[] data)
{
if (data == null)
{
return 0;
}
int i = data.Length;
int hc = i + 1;
while (--i >= 0)
{
hc *= 257;
hc ^= data[i];
}
return hc;
}
public static byte[] Clone(
byte[] data)
{
return data == null ? null : (byte[]) data.Clone();
}
public static int[] Clone(
int[] data)
{
return data == null ? null : (int[]) data.Clone();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using Xunit;
namespace System.IO.Tests
{
public static partial class PathTests
{
[Theory]
[InlineData(null, null, null)]
[InlineData(null, "exe", null)]
[InlineData("", "", "")]
[InlineData("file.exe", null, "file")]
[InlineData("file.exe", "", "file.")]
[InlineData("file", "exe", "file.exe")]
[InlineData("file", ".exe", "file.exe")]
[InlineData("file.txt", "exe", "file.exe")]
[InlineData("file.txt", ".exe", "file.exe")]
[InlineData("file.txt.bin", "exe", "file.txt.exe")]
[InlineData("dir/file.t", "exe", "dir/file.exe")]
[InlineData("dir/file.exe", "t", "dir/file.t")]
[InlineData("dir/file", "exe", "dir/file.exe")]
public static void ChangeExtension(string path, string newExtension, string expected)
{
if (expected != null)
expected = expected.Replace('/', Path.DirectorySeparatorChar);
if (path != null)
path = path.Replace('/', Path.DirectorySeparatorChar);
Assert.Equal(expected, Path.ChangeExtension(path, newExtension));
}
[Fact]
public static void GetDirectoryName_EmptyThrows()
{
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.GetDirectoryName(string.Empty));
}
[Theory,
InlineData(" "),
InlineData("\r\n")]
[ActiveIssue(21358)] // Pending CoreCLR behavior change
public static void GetDirectoryName_SpaceOrControlCharsThrowOnWindows(string path)
{
Action action = () => Path.GetDirectoryName(path);
if (PlatformDetection.IsWindows)
{
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.GetDirectoryName(path));
}
else
{
// These are valid paths on Unix
action();
}
}
[Theory]
[InlineData("\u00A0")] // Non-breaking Space
[InlineData("\u2028")] // Line separator
[InlineData("\u2029")] // Paragraph separator
[ActiveIssue(21358)] // Pending CoreCLR behavior change
public static void GetDirectoryName_NonControl(string path)
{
Assert.Equal(string.Empty, Path.GetDirectoryName(path));
}
[Theory]
[InlineData("\u00A0")] // Non-breaking Space
[InlineData("\u2028")] // Line separator
[InlineData("\u2029")] // Paragraph separator
[ActiveIssue(21358)] // Pending CoreCLR behavior change
public static void GetDirectoryName_NonControlWithSeparator(string path)
{
Assert.Equal(path, Path.GetDirectoryName(Path.Combine(path, path)));
}
[Theory]
[InlineData(null, null)]
[InlineData(".", "")]
[InlineData("..", "")]
[InlineData("baz", "")]
public static void GetDirectoryName(string path, string expected)
{
Assert.Equal(expected, Path.GetDirectoryName(path));
}
[Theory]
[InlineData(@"dir/baz", "dir")]
[InlineData(@"dir\baz", "dir")]
[InlineData(@"dir\baz\bar", @"dir\baz")]
[InlineData(@"dir\\baz", "dir")]
[InlineData(@" dir\baz", " dir")]
[InlineData(@" C:\dir\baz", @"C:\dir")]
[InlineData(@"..\..\files.txt", @"..\..")]
[InlineData(@"C:\", null)]
[InlineData(@"C:", null)]
[PlatformSpecific(TestPlatforms.Windows)] // Tests Windows-specific paths
public static void GetDirectoryName_Windows(string path, string expected)
{
Assert.Equal(expected, Path.GetDirectoryName(path));
}
[Theory]
[InlineData(@"dir/baz", @"dir")]
[InlineData(@"dir//baz", @"dir")]
[InlineData(@"dir\baz", @"")]
[InlineData(@"dir/baz/bar", @"dir/baz")]
[InlineData(@"../../files.txt", @"../..")]
[InlineData(@"/", null)]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests Unix-specific paths
public static void GetDirectoryName_Unix(string path, string expected)
{
Assert.Equal(expected, Path.GetDirectoryName(path));
}
[Fact]
public static void GetDirectoryName_CurrentDirectory()
{
string curDir = Directory.GetCurrentDirectory();
Assert.Equal(curDir, Path.GetDirectoryName(Path.Combine(curDir, "baz")));
Assert.Equal(null, Path.GetDirectoryName(Path.GetPathRoot(curDir)));
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // Checks Unix-specific special characters in directory path
[Fact]
public static void GetDirectoryName_ControlCharacters_Unix()
{
Assert.Equal(new string('\t', 1), Path.GetDirectoryName(Path.Combine(new string('\t', 1), "file")));
Assert.Equal(new string('\b', 2), Path.GetDirectoryName(Path.Combine(new string('\b', 2), "fi le")));
Assert.Equal(new string('\v', 3), Path.GetDirectoryName(Path.Combine(new string('\v', 3), "fi\nle")));
Assert.Equal(new string('\n', 4), Path.GetDirectoryName(Path.Combine(new string('\n', 4), "fi\rle")));
}
[Theory]
[InlineData("file.exe", ".exe")]
[InlineData("file", "")]
[InlineData(null, null)]
[InlineData("file.", "")]
[InlineData("file.s", ".s")]
[InlineData("test/file", "")]
[InlineData("test/file.extension", ".extension")]
public static void GetExtension(string path, string expected)
{
if (path != null)
{
path = path.Replace('/', Path.DirectorySeparatorChar);
}
Assert.Equal(expected, Path.GetExtension(path));
Assert.Equal(!string.IsNullOrEmpty(expected), Path.HasExtension(path));
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // Checks file extension behavior on Unix
[Theory]
[InlineData("file.e xe", ".e xe")]
[InlineData("file. ", ". ")]
[InlineData(" file. ", ". ")]
[InlineData(" file.extension", ".extension")]
[InlineData("file.exten\tsion", ".exten\tsion")]
public static void GetExtension_Unix(string path, string expected)
{
Assert.Equal(expected, Path.GetExtension(path));
Assert.Equal(!string.IsNullOrEmpty(expected), Path.HasExtension(path));
}
public static IEnumerable<object[]> GetFileName_TestData()
{
yield return new object[] { null, null };
yield return new object[] { ".", "." };
yield return new object[] { "..", ".." };
yield return new object[] { "file", "file" };
yield return new object[] { "file.", "file." };
yield return new object[] { "file.exe", "file.exe" };
yield return new object[] { Path.Combine("baz", "file.exe"), "file.exe" };
yield return new object[] { Path.Combine("bar", "baz", "file.exe"), "file.exe" };
yield return new object[] { Path.Combine("bar", "baz", "file.exe") + Path.DirectorySeparatorChar, "" };
}
[Theory]
[MemberData(nameof(GetFileName_TestData))]
public static void GetFileName(string path, string expected)
{
Assert.Equal(expected, Path.GetFileName(path));
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests Unix-specific valid file names
[Fact]
public static void GetFileName_Unix()
{
Assert.Equal(" . ", Path.GetFileName(" . "));
Assert.Equal(" .. ", Path.GetFileName(" .. "));
Assert.Equal("fi le", Path.GetFileName("fi le"));
Assert.Equal("fi le", Path.GetFileName("fi le"));
Assert.Equal("fi le", Path.GetFileName(Path.Combine("b \r\n ar", "fi le")));
}
public static IEnumerable<object[]> GetFileNameWithoutExtension_TestData()
{
yield return new object[] { null, null };
yield return new object[] { "", "" };
yield return new object[] { "file", "file" };
yield return new object[] { "file.exe", "file" };
yield return new object[] { Path.Combine("bar", "baz", "file.exe"), "file" };
yield return new object[] { Path.Combine("bar", "baz") + Path.DirectorySeparatorChar, "" };
}
[Theory]
[MemberData(nameof(GetFileNameWithoutExtension_TestData))]
public static void GetFileNameWithoutExtension(string path, string expected)
{
Assert.Equal(expected, Path.GetFileNameWithoutExtension(path));
}
[Fact]
public static void GetPathRoot_NullReturnsNull()
{
Assert.Null(Path.GetPathRoot(null));
}
[Fact]
public static void GetPathRoot_EmptyThrows()
{
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.GetPathRoot(string.Empty));
}
[Fact]
public static void GetPathRoot_Basic()
{
string cwd = Directory.GetCurrentDirectory();
Assert.Equal(cwd.Substring(0, cwd.IndexOf(Path.DirectorySeparatorChar) + 1), Path.GetPathRoot(cwd));
Assert.True(Path.IsPathRooted(cwd));
Assert.Equal(string.Empty, Path.GetPathRoot(@"file.exe"));
Assert.False(Path.IsPathRooted("file.exe"));
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests UNC
[Theory]
[InlineData(@"\\test\unc\path\to\something", @"\\test\unc")]
[InlineData(@"\\a\b\c\d\e", @"\\a\b")]
[InlineData(@"\\a\b\", @"\\a\b")]
[InlineData(@"\\a\b", @"\\a\b")]
[InlineData(@"\\test\unc", @"\\test\unc")]
public static void GetPathRoot_Windows_UncAndExtended(string value, string expected)
{
Assert.True(Path.IsPathRooted(value));
Assert.Equal(expected, Path.GetPathRoot(value));
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests UNC
[Theory]
[InlineData(@"\\?\UNC\test\unc", @"\\?\UNC", @"\\?\UNC\test\unc\path\to\something")]
[InlineData(@"\\?\UNC\test\unc", @"\\?\UNC", @"\\?\UNC\test\unc")]
[InlineData(@"\\?\UNC\a\b1", @"\\?\UNC", @"\\?\UNC\a\b1")]
[InlineData(@"\\?\UNC\a\b2", @"\\?\UNC", @"\\?\UNC\a\b2\")]
[InlineData(@"\\?\C:\", @"\\?\C:", @"\\?\C:\foo\bar.txt")]
public static void GetPathRoot_Windows_UncAndExtended_WithLegacySupport(string normalExpected, string legacyExpected, string value)
{
Assert.True(Path.IsPathRooted(value));
string expected = PathFeatures.IsUsingLegacyPathNormalization() ? legacyExpected : normalExpected;
Assert.Equal(expected, Path.GetPathRoot(value));
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests Windows-specific path convention
[Theory]
[InlineData(@"C:", @"C:")]
[InlineData(@"C:\", @"C:\")]
[InlineData(@"C:\\", @"C:\")]
[InlineData(@"C://", @"C:\")]
[InlineData(@"C:\foo1", @"C:\")]
[InlineData(@"C:\\foo2", @"C:\")]
[InlineData(@"C://foo3", @"C:\")]
public static void GetPathRoot_Windows(string value, string expected)
{
Assert.True(Path.IsPathRooted(value));
Assert.Equal(expected, Path.GetPathRoot(value));
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests Unix-specific path convention
[Fact]
public static void GetPathRoot_Unix()
{
// slashes are normal filename characters
string uncPath = @"\\test\unc\path\to\something";
Assert.False(Path.IsPathRooted(uncPath));
Assert.Equal(string.Empty, Path.GetPathRoot(uncPath));
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public static void IsPathRooted(string path)
{
Assert.False(Path.IsPathRooted(path));
}
// Testing invalid drive letters !(a-zA-Z)
[PlatformSpecific(TestPlatforms.Windows)]
[Theory]
[InlineData(@"@:\foo")] // 064 = @ 065 = A
[InlineData(@"[:\\")] // 091 = [ 090 = Z
[InlineData(@"`:\foo")] // 096 = ` 097 = a
[InlineData(@"{:\\")] // 123 = { 122 = z
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug fixed on Core where it would return true if the first char is not a drive letter followed by a VolumeSeparatorChar coreclr/10297")]
public static void IsPathRooted_Windows_Invalid(string value)
{
Assert.False(Path.IsPathRooted(value));
}
[Fact]
public static void GetRandomFileName()
{
char[] invalidChars = Path.GetInvalidFileNameChars();
var fileNames = new HashSet<string>();
for (int i = 0; i < 100; i++)
{
string s = Path.GetRandomFileName();
Assert.Equal(s.Length, 8 + 1 + 3);
Assert.Equal(s[8], '.');
Assert.Equal(-1, s.IndexOfAny(invalidChars));
Assert.True(fileNames.Add(s));
}
}
[Fact]
public static void GetInvalidPathChars()
{
Assert.NotNull(Path.GetInvalidPathChars());
Assert.NotSame(Path.GetInvalidPathChars(), Path.GetInvalidPathChars());
Assert.Equal((IEnumerable<char>)Path.GetInvalidPathChars(), Path.GetInvalidPathChars());
Assert.True(Path.GetInvalidPathChars().Length > 0);
Assert.All(Path.GetInvalidPathChars(), c =>
{
string bad = c.ToString();
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.ChangeExtension(bad, "ok"));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.Combine(bad, "ok"));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.Combine("ok", "ok", bad));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.Combine("ok", "ok", bad, "ok"));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.Combine(bad, bad, bad, bad, bad));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.GetDirectoryName(bad));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.GetExtension(bad));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.GetFileName(bad));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.GetFileNameWithoutExtension(bad));
AssertExtensions.Throws<ArgumentException>(c == 124 ? null : "path", null, () => Path.GetFullPath(bad));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.GetPathRoot(bad));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.IsPathRooted(bad));
});
}
[Fact]
public static void GetInvalidFileNameChars()
{
Assert.NotNull(Path.GetInvalidFileNameChars());
Assert.NotSame(Path.GetInvalidFileNameChars(), Path.GetInvalidFileNameChars());
Assert.Equal((IEnumerable<char>)Path.GetInvalidFileNameChars(), Path.GetInvalidFileNameChars());
Assert.True(Path.GetInvalidFileNameChars().Length > 0);
}
[Fact]
[OuterLoop]
public static void GetInvalidFileNameChars_OtherCharsValid()
{
string curDir = Directory.GetCurrentDirectory();
var invalidChars = new HashSet<char>(Path.GetInvalidFileNameChars());
for (int i = 0; i < char.MaxValue; i++)
{
char c = (char)i;
if (!invalidChars.Contains(c))
{
string name = "file" + c + ".txt";
Assert.Equal(Path.Combine(curDir, name), Path.GetFullPath(name));
}
}
}
[Fact]
public static void GetTempPath_Default()
{
string tmpPath = Path.GetTempPath();
Assert.False(string.IsNullOrEmpty(tmpPath));
Assert.Equal(tmpPath, Path.GetTempPath());
Assert.Equal(Path.DirectorySeparatorChar, tmpPath[tmpPath.Length - 1]);
Assert.True(Directory.Exists(tmpPath));
}
[PlatformSpecific(TestPlatforms.Windows)] // Sets environment vars with Windows-specific paths
[Theory]
[InlineData(@"C:\Users\someuser\AppData\Local\Temp\", @"C:\Users\someuser\AppData\Local\Temp")]
[InlineData(@"C:\Users\someuser\AppData\Local\Temp\", @"C:\Users\someuser\AppData\Local\Temp\")]
[InlineData(@"C:\", @"C:\")]
[InlineData(@"C:\tmp\", @"C:\tmp")]
[InlineData(@"C:\tmp\", @"C:\tmp\")]
public static void GetTempPath_SetEnvVar_Windows(string expected, string newTempPath)
{
GetTempPath_SetEnvVar("TMP", expected, newTempPath);
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // Sets environment vars with Unix-specific paths
[Theory]
[InlineData("/tmp/", "/tmp")]
[InlineData("/tmp/", "/tmp/")]
[InlineData("/", "/")]
[InlineData("/var/tmp/", "/var/tmp")]
[InlineData("/var/tmp/", "/var/tmp/")]
[InlineData("~/", "~")]
[InlineData("~/", "~/")]
[InlineData(".tmp/", ".tmp")]
[InlineData("./tmp/", "./tmp")]
[InlineData("/home/someuser/sometempdir/", "/home/someuser/sometempdir/")]
[InlineData("/home/someuser/some tempdir/", "/home/someuser/some tempdir/")]
[InlineData("/tmp/", null)]
public static void GetTempPath_SetEnvVar_Unix(string expected, string newTempPath)
{
GetTempPath_SetEnvVar("TMPDIR", expected, newTempPath);
}
private static void GetTempPath_SetEnvVar(string envVar, string expected, string newTempPath)
{
string original = Path.GetTempPath();
Assert.NotNull(original);
try
{
Environment.SetEnvironmentVariable(envVar, newTempPath);
Assert.Equal(
Path.GetFullPath(expected),
Path.GetFullPath(Path.GetTempPath()));
}
finally
{
Environment.SetEnvironmentVariable(envVar, original);
Assert.Equal(original, Path.GetTempPath());
}
}
[Fact]
public static void GetTempFileName()
{
string tmpFile = Path.GetTempFileName();
try
{
Assert.True(File.Exists(tmpFile));
Assert.Equal(".tmp", Path.GetExtension(tmpFile), ignoreCase: true, ignoreLineEndingDifferences: false, ignoreWhiteSpaceDifferences: false);
Assert.Equal(-1, tmpFile.IndexOfAny(Path.GetInvalidPathChars()));
using (FileStream fs = File.OpenRead(tmpFile))
{
Assert.Equal(0, fs.Length);
}
Assert.Equal(Path.Combine(Path.GetTempPath(), Path.GetFileName(tmpFile)), tmpFile);
}
finally
{
File.Delete(tmpFile);
}
}
[Theory]
[InlineData("\u0085")] // Next line
[InlineData("\u00A0")] // Non breaking space
[InlineData("\u2028")] // Line separator
[PlatformSpecific(TestPlatforms.Windows)]
[ActiveIssue(21358)] // Pending CoreCLR behavior change
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] // not NetFX
public static void GetFullPath_NonControlWhiteSpaceStays(string component)
{
// When not NetFX full path should not cut off component
string path = "C:\\Test" + component;
Assert.Equal(path, Path.GetFullPath(path));
}
[Theory]
[InlineData(" ")]
[InlineData(" ")]
[InlineData(" ")]
[PlatformSpecific(TestPlatforms.Windows)]
public static void GetFullPath_TrailingSpaceCut(string component)
{
// Windows cuts off any simple white space added to a path
string path = "C:\\Test" + component;
Assert.Equal("C:\\Test", Path.GetFullPath(path));
}
[Fact]
public static void GetFullPath_InvalidArgs()
{
Assert.Throws<ArgumentNullException>(() => Path.GetFullPath(null));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.GetFullPath(string.Empty));
}
public static IEnumerable<object[]> GetFullPath_BasicExpansions_TestData()
{
string curDir = Directory.GetCurrentDirectory();
yield return new object[] { curDir, curDir }; // Current directory => current directory
yield return new object[] { ".", curDir }; // "." => current directory
yield return new object[] { "..", Path.GetDirectoryName(curDir) }; // "." => up a directory
yield return new object[] { Path.Combine(curDir, ".", ".", ".", ".", "."), curDir }; // "dir/./././." => "dir"
yield return new object[] { curDir + new string(Path.DirectorySeparatorChar, 3) + ".", curDir }; // "dir///." => "dir"
yield return new object[] { Path.Combine(curDir, "..", Path.GetFileName(curDir), ".", "..", Path.GetFileName(curDir)), curDir }; // "dir/../dir/./../dir" => "dir"
yield return new object[] { Path.Combine(Path.GetPathRoot(curDir), "somedir", ".."), Path.GetPathRoot(curDir) }; // "C:\somedir\.." => "C:\"
yield return new object[] { Path.Combine(Path.GetPathRoot(curDir), "."), Path.GetPathRoot(curDir) }; // "C:\." => "C:\"
yield return new object[] { Path.Combine(Path.GetPathRoot(curDir), "..", "..", "..", ".."), Path.GetPathRoot(curDir) }; // "C:\..\..\..\.." => "C:\"
yield return new object[] { Path.GetPathRoot(curDir) + new string(Path.DirectorySeparatorChar, 3), Path.GetPathRoot(curDir) }; // "C:\\\" => "C:\"
// Path longer than MaxPath that normalizes down to less than MaxPath
const int Iters = 10000;
var longPath = new StringBuilder(curDir, curDir.Length + (Iters * 2));
for (int i = 0; i < 10000; i++)
{
longPath.Append(Path.DirectorySeparatorChar).Append('.');
}
yield return new object[] { longPath.ToString(), curDir };
}
[Theory]
[MemberData(nameof(GetFullPath_BasicExpansions_TestData))]
public static void GetFullPath_BasicExpansions(string path, string expected)
{
Assert.Equal(expected, Path.GetFullPath(path));
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests whitespace in paths on Unix
[Fact]
public static void GetFullPath_Unix_Whitespace()
{
string curDir = Directory.GetCurrentDirectory();
Assert.Equal("/ / ", Path.GetFullPath("/ // "));
Assert.Equal(Path.Combine(curDir, " "), Path.GetFullPath(" "));
Assert.Equal(Path.Combine(curDir, "\r\n"), Path.GetFullPath("\r\n"));
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests URIs as valid file names
[Theory]
[InlineData("http://www.microsoft.com")]
[InlineData("file://somefile")]
public static void GetFullPath_Unix_URIsAsFileNames(string uriAsFileName)
{
// URIs are valid filenames, though the multiple slashes will be consolidated in GetFullPath
Assert.Equal(
Path.Combine(Directory.GetCurrentDirectory(), uriAsFileName.Replace("//", "/")),
Path.GetFullPath(uriAsFileName));
}
[PlatformSpecific(TestPlatforms.Windows)] // Checks normalized long path (> MaxPath) on Windows
[Fact]
public static void GetFullPath_Windows_NormalizedLongPathTooLong()
{
// Try out a long path that normalizes down to more than MaxPath
string curDir = Directory.GetCurrentDirectory();
const int Iters = 260;
var longPath = new StringBuilder(curDir, curDir.Length + (Iters * 4));
for (int i = 0; i < Iters; i++)
{
longPath.Append(Path.DirectorySeparatorChar).Append('a').Append(Path.DirectorySeparatorChar).Append('.');
}
if (PathFeatures.AreAllLongPathsAvailable())
{
// Now no longer throws unless over ~32K
Assert.NotNull(Path.GetFullPath(longPath.ToString()));
}
else
{
Assert.Throws<PathTooLongException>(() => Path.GetFullPath(longPath.ToString()));
}
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests Windows-specific invalid paths
[Fact]
public static void GetFullPath_Windows_AlternateDataStreamsNotSupported()
{
// Throws via our invalid colon filtering
Assert.Throws<NotSupportedException>(() => Path.GetFullPath(@"bad:path"));
Assert.Throws<NotSupportedException>(() => Path.GetFullPath(@"C:\some\bad:path"));
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests Windows-specific invalid paths
[Theory]
[InlineData("http://www.microsoft.com")]
[InlineData("file://www.microsoft.com")]
public static void GetFullPath_Windows_URIFormatNotSupported(string path)
{
// Throws via our invalid colon filtering
if (!PathFeatures.IsUsingLegacyPathNormalization())
{
Assert.Throws<NotSupportedException>(() => Path.GetFullPath(path));
}
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests Windows-specific invalid paths
[Theory]
[InlineData(@"bad::$DATA")]
[InlineData(@"C :")]
[InlineData(@"C :\somedir")]
public static void GetFullPath_Windows_NotSupportedExceptionPaths(string path)
{
// Old path normalization throws ArgumentException, new one throws NotSupportedException
if (!PathFeatures.IsUsingLegacyPathNormalization())
{
Assert.Throws<NotSupportedException>(() => Path.GetFullPath(path));
}
else
{
AssertExtensions.Throws<ArgumentException>(null, () => Path.GetFullPath(path));
}
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests legitimate Windows paths that are now allowed
[Theory]
[InlineData(@"C:...")]
[InlineData(@"C:...\somedir")]
[InlineData(@"\.. .\")]
[InlineData(@"\. .\")]
[InlineData(@"\ .\")]
public static void GetFullPath_Windows_LegacyArgumentExceptionPaths(string path)
{
if (PathFeatures.IsUsingLegacyPathNormalization())
{
// We didn't allow these paths on < 4.6.2
AssertExtensions.Throws<ArgumentException>(null, () => Path.GetFullPath(path));
}
else
{
// These paths are legitimate Windows paths that can be created without extended syntax.
// We now allow them through.
Path.GetFullPath(path);
}
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests MaxPathNotTooLong on Windows
[Fact]
public static void GetFullPath_Windows_MaxPathNotTooLong()
{
string value = @"C:\" + new string('a', 255) + @"\";
if (PathFeatures.AreAllLongPathsAvailable())
{
// Shouldn't throw anymore
Path.GetFullPath(value);
}
else
{
Assert.Throws<PathTooLongException>(() => Path.GetFullPath(value));
}
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests PathTooLong on Windows
[Fact]
public static void GetFullPath_Windows_PathTooLong()
{
Assert.Throws<PathTooLongException>(() => Path.GetFullPath(@"C:\" + new string('a', short.MaxValue) + @"\"));
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests Windows-specific paths
[Theory]
[InlineData(@"C:\", @"C:\")]
[InlineData(@"C:\.", @"C:\")]
[InlineData(@"C:\..", @"C:\")]
[InlineData(@"C:\..\..", @"C:\")]
[InlineData(@"C:\A\..", @"C:\")]
[InlineData(@"C:\..\..\A\..", @"C:\")]
public static void GetFullPath_Windows_RelativeRoot(string path, string expected)
{
Assert.Equal(Path.GetFullPath(path), expected);
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests legitimate strage windows paths that are now allowed
[Fact]
public static void GetFullPath_Windows_StrangeButLegalPaths()
{
// These are legal and creatable without using extended syntax if you use a trailing slash
// (such as "md ...\"). We used to filter these out, but now allow them to prevent apps from
// being blocked when they hit these paths.
string curDir = Directory.GetCurrentDirectory();
if (PathFeatures.IsUsingLegacyPathNormalization())
{
// Legacy path Path.GetFullePath() ignores . when there is less or more that two, when there is .. in the path it returns one directory up.
Assert.Equal(
Path.GetFullPath(curDir + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ". " + Path.DirectorySeparatorChar));
Assert.Equal(
Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + "..." + Path.DirectorySeparatorChar));
Assert.Equal(
Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ".. " + Path.DirectorySeparatorChar));
}
else
{
Assert.NotEqual(
Path.GetFullPath(curDir + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ". " + Path.DirectorySeparatorChar));
Assert.NotEqual(
Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + "..." + Path.DirectorySeparatorChar));
Assert.NotEqual(
Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ".. " + Path.DirectorySeparatorChar));
}
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests Windows-specific paths
[Theory]
[InlineData(@"\\?\C:\ ")]
[InlineData(@"\\?\C:\ \ ")]
[InlineData(@"\\?\C:\ .")]
[InlineData(@"\\?\C:\ ..")]
[InlineData(@"\\?\C:\...")]
[InlineData(@"\\?\GLOBALROOT\")]
[InlineData(@"\\?\")]
[InlineData(@"\\?\.")]
[InlineData(@"\\?\..")]
[InlineData(@"\\?\\")]
[InlineData(@"\\?\C:\\")]
[InlineData(@"\\?\C:\|")]
[InlineData(@"\\?\C:\.")]
[InlineData(@"\\?\C:\..")]
[InlineData(@"\\?\C:\Foo1\.")]
[InlineData(@"\\?\C:\Foo2\..")]
[InlineData(@"\\?\UNC\")]
[InlineData(@"\\?\UNC\server1")]
[InlineData(@"\\?\UNC\server2\")]
[InlineData(@"\\?\UNC\server3\\")]
[InlineData(@"\\?\UNC\server4\..")]
[InlineData(@"\\?\UNC\server5\share\.")]
[InlineData(@"\\?\UNC\server6\share\..")]
[InlineData(@"\\?\UNC\a\b\\")]
[InlineData(@"\\.\")]
[InlineData(@"\\.\.")]
[InlineData(@"\\.\..")]
[InlineData(@"\\.\\")]
[InlineData(@"\\.\C:\\")]
[InlineData(@"\\.\C:\|")]
[InlineData(@"\\.\C:\.")]
[InlineData(@"\\.\C:\..")]
[InlineData(@"\\.\C:\Foo1\.")]
[InlineData(@"\\.\C:\Foo2\..")]
public static void GetFullPath_Windows_ValidExtendedPaths(string path)
{
if (PathFeatures.IsUsingLegacyPathNormalization())
{
// Legacy Path doesn't support any of these paths.
AssertExtensions.ThrowsAny<ArgumentException, NotSupportedException>(() => Path.GetFullPath(path));
return;
}
// None of these should throw
if (path.StartsWith(@"\\?\"))
{
Assert.Equal(path, Path.GetFullPath(path));
}
else
{
Path.GetFullPath(path);
}
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests Windows-specific paths
[Theory]
[InlineData(@"\\.\UNC\")]
[InlineData(@"\\.\UNC\LOCALHOST")]
[InlineData(@"\\.\UNC\localHOST\")]
[InlineData(@"\\.\UNC\LOcaLHOST\\")]
[InlineData(@"\\.\UNC\lOCALHOST\..")]
[InlineData(@"\\.\UNC\LOCALhost\share\.")]
[InlineData(@"\\.\UNC\loCALHOST\share\..")]
[InlineData(@"\\.\UNC\a\b\\")]
public static void GetFullPath_Windows_ValidLegacy_ValidExtendedPaths(string path)
{
// should not throw
Path.GetFullPath(path);
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests valid paths based on UNC
[Theory]
// https://github.com/dotnet/corefx/issues/11965
[InlineData(@"\\LOCALHOST\share\test.txt.~SS", @"\\LOCALHOST\share\test.txt.~SS")]
[InlineData(@"\\LOCALHOST\share1", @"\\LOCALHOST\share1")]
[InlineData(@"\\LOCALHOST\share2", @" \\LOCALHOST\share2")]
[InlineData(@"\\LOCALHOST\share3\dir", @"\\LOCALHOST\share3\dir")]
[InlineData(@"\\LOCALHOST\share4", @"\\LOCALHOST\share4\.")]
[InlineData(@"\\LOCALHOST\share5", @"\\LOCALHOST\share5\..")]
[InlineData(@"\\LOCALHOST\share6\", @"\\LOCALHOST\share6\ ")]
[InlineData(@"\\LOCALHOST\ share7\", @"\\LOCALHOST\ share7\")]
[InlineData(@"\\?\UNC\LOCALHOST\share8\test.txt.~SS", @"\\?\UNC\LOCALHOST\share8\test.txt.~SS")]
[InlineData(@"\\?\UNC\LOCALHOST\share9", @"\\?\UNC\LOCALHOST\share9")]
[InlineData(@"\\?\UNC\LOCALHOST\shareA\dir", @"\\?\UNC\LOCALHOST\shareA\dir")]
[InlineData(@"\\?\UNC\LOCALHOST\shareB\. ", @"\\?\UNC\LOCALHOST\shareB\. ")]
[InlineData(@"\\?\UNC\LOCALHOST\shareC\.. ", @"\\?\UNC\LOCALHOST\shareC\.. ")]
[InlineData(@"\\?\UNC\LOCALHOST\shareD\ ", @"\\?\UNC\LOCALHOST\shareD\ ")]
[InlineData(@"\\.\UNC\LOCALHOST\ shareE\", @"\\.\UNC\LOCALHOST\ shareE\")]
[InlineData(@"\\.\UNC\LOCALHOST\shareF\test.txt.~SS", @"\\.\UNC\LOCALHOST\shareF\test.txt.~SS")]
[InlineData(@"\\.\UNC\LOCALHOST\shareG", @"\\.\UNC\LOCALHOST\shareG")]
[InlineData(@"\\.\UNC\LOCALHOST\shareH\dir", @"\\.\UNC\LOCALHOST\shareH\dir")]
[InlineData(@"\\.\UNC\LOCALHOST\shareK\", @"\\.\UNC\LOCALHOST\shareK\ ")]
[InlineData(@"\\.\UNC\LOCALHOST\ shareL\", @"\\.\UNC\LOCALHOST\ shareL\")]
public static void GetFullPath_Windows_UNC_Valid(string expected, string input)
{
if (input.StartsWith(@"\\?\") && PathFeatures.IsUsingLegacyPathNormalization())
{
AssertExtensions.Throws<ArgumentException>(null, () => Path.GetFullPath(input));
}
else
{
Assert.Equal(expected, Path.GetFullPath(input));
}
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests valid paths based on UNC
[Theory]
[InlineData(@"\\.\UNC\LOCALHOST\shareI\", @"\\.\UNC\LOCALHOST\shareI", @"\\.\UNC\LOCALHOST\shareI\. ")]
[InlineData(@"\\.\UNC\LOCALHOST\shareJ\", @"\\.\UNC\LOCALHOST", @"\\.\UNC\LOCALHOST\shareJ\.. ")]
public static void GetFullPath_Windows_UNC_Valid_LegacyPathSupport(string normalExpected, string legacyExpected, string input)
{
string expected = PathFeatures.IsUsingLegacyPathNormalization() ? legacyExpected : normalExpected;
Assert.Equal(expected, Path.GetFullPath(input));
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests invalid paths based on UNC
[Theory]
[InlineData(@"\\")]
[InlineData(@"\\LOCALHOST")]
[InlineData(@"\\LOCALHOST\")]
[InlineData(@"\\LOCALHOST\\")]
[InlineData(@"\\LOCALHOST\..")]
public static void GetFullPath_Windows_UNC_Invalid(string invalidPath)
{
AssertExtensions.Throws<ArgumentException>(null, () => Path.GetFullPath(invalidPath));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get short path name
public static void GetFullPath_Windows_83Paths()
{
// Create a temporary file name with a name longer than 8.3 such that it'll need to be shortened.
string tempFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".txt");
File.Create(tempFilePath).Dispose();
try
{
// Get its short name
var sb = new StringBuilder(260);
if (GetShortPathName(tempFilePath, sb, sb.Capacity) > 0) // only proceed if we could successfully create the short name
{
string shortName = sb.ToString();
// Make sure the shortened name expands back to the original one
// Sometimes shortening or GetFullPath is changing the casing of "temp" on some test machines: normalize both sides
tempFilePath = Regex.Replace(tempFilePath, @"\\temp\\", @"\TEMP\", RegexOptions.IgnoreCase);
shortName = Regex.Replace(Path.GetFullPath(shortName), @"\\temp\\", @"\TEMP\", RegexOptions.IgnoreCase);
Assert.Equal(tempFilePath, shortName);
// Should work with device paths that aren't well-formed extended syntax
if (!PathFeatures.IsUsingLegacyPathNormalization())
{
Assert.Equal(@"\\.\" + tempFilePath, Path.GetFullPath(@"\\.\" + shortName));
Assert.Equal(@"\\?\" + tempFilePath, Path.GetFullPath(@"//?/" + shortName));
// Shouldn't mess with well-formed extended syntax
Assert.Equal(@"\\?\" + shortName, Path.GetFullPath(@"\\?\" + shortName));
}
// Validate case where short name doesn't expand to a real file
string invalidShortName = @"S:\DOESNT~1\USERNA~1.RED\LOCALS~1\Temp\bg3ylpzp";
Assert.Equal(invalidShortName, Path.GetFullPath(invalidShortName));
// Same thing, but with a long path that normalizes down to a short enough one
const int Iters = 1000;
var shortLongName = new StringBuilder(invalidShortName, invalidShortName.Length + (Iters * 2));
for (int i = 0; i < Iters; i++)
{
shortLongName.Append(Path.DirectorySeparatorChar).Append('.');
}
Assert.Equal(invalidShortName, Path.GetFullPath(shortLongName.ToString()));
}
}
finally
{
File.Delete(tempFilePath);
}
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests Windows-specific invalid paths
[Theory]
[InlineData('*')]
[InlineData('?')]
public static void GetFullPath_Windows_Wildcards(char wildcard)
{
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.GetFullPath("test" + wildcard + "ing"));
}
// Windows-only P/Invoke to create 8.3 short names from long names
[DllImport("kernel32.dll", EntryPoint = "GetShortPathNameW" ,CharSet = CharSet.Unicode)]
private static extern uint GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, int cchBuffer);
[Fact]
public static void InvalidPathChars_MatchesGetInvalidPathChars()
{
#pragma warning disable 0618
Assert.NotNull(Path.InvalidPathChars);
Assert.Equal(Path.GetInvalidPathChars(), Path.InvalidPathChars);
Assert.Same(Path.InvalidPathChars, Path.InvalidPathChars);
#pragma warning restore 0618
}
}
}
| |
// 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 ShiftLeftLogicalUInt3232()
{
var test = new SimpleUnaryOpTest__ShiftLeftLogicalUInt3232();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local 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__ShiftLeftLogicalUInt3232
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(UInt32);
private const int RetElementCount = VectorSize / sizeof(UInt32);
private static UInt32[] _data = new UInt32[Op1ElementCount];
private static Vector256<UInt32> _clsVar;
private Vector256<UInt32> _fld;
private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable;
static SimpleUnaryOpTest__ShiftLeftLogicalUInt3232()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__ShiftLeftLogicalUInt3232()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, new UInt32[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.ShiftLeftLogical(
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.ShiftLeftLogical(
Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.ShiftLeftLogical(
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.ShiftLeftLogical(
_clsVar,
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftLeftLogical(firstOp, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftLeftLogical(firstOp, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftLeftLogical(firstOp, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ShiftLeftLogicalUInt3232();
var result = Avx2.ShiftLeftLogical(test._fld, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.ShiftLeftLogical(_fld, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<UInt32> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt32[] firstOp, UInt32[] result, [CallerMemberName] string method = "")
{
if (0 != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (0!= result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.ShiftLeftLogical)}<UInt32>(Vector256<UInt32><9>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using ServiceStack;
using ServiceStack.Auth;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Amazon.DynamoDBv2.DataModel;
using Amazon.DynamoDBv2.DocumentModel;
using System.Linq;
using System.Globalization;
using Stateless;
using Serilog;
namespace ServiceStackAwsDynamoAuth
{
public class UserRegistration : IDisposable
{
//http://stackoverflow.com/questions/3588623/c-sharp-regex-for-a-username-with-a-few-restrictions
public static readonly Regex ValidUserNameRegEx = new Regex(@"^(?=.{3,15}$)([A-Za-z0-9][._-]?)*$", RegexOptions.Compiled);
private enum States
{
Unregistered,
Validating,
Registering,
Registered,
Updating,
Removing,
Removed,
}
private enum Triggers
{
Restore,
Validate,
Validated,
Register,
Registered,
Update,
Remove,
Removed,
Cleanup,
}
private readonly IUserAuth userAuth;
private readonly StateMachine<States, Triggers> fsm;
private readonly Document mapping;
private readonly AmazonDynamoDBClient client;
private readonly UserAuthTableConfiguraton configuration;
private readonly Table emailMappingTable;
private readonly Table usernameMappingTable;
public UserRegistration(IUserAuth userAuth, AmazonDynamoDBClient client, UserAuthTableConfiguraton configuration)
{
if (userAuth == null)
throw new ArgumentNullException("userAuth");
if (client == null)
throw new ArgumentNullException("client");
if (configuration == null)
throw new ArgumentNullException("configuration");
this.userAuth = userAuth;
this.client = client;
this.configuration = configuration;
this.fsm = new StateMachine<States, Triggers>(States.Unregistered);
this.fsm.Configure(States.Unregistered)
.OnEntryFrom(Triggers.Cleanup, this.Cleanup)
.Permit(Triggers.Validate, States.Validating)
.Permit(Triggers.Restore, States.Registered)
.PermitIf(Triggers.Register, States.Registering, () => this.Validated)
.PermitReentry(Triggers.Cleanup);
this.fsm.Configure(States.Validating)
.OnEntry(this.OnValidate)
.PermitIf(Triggers.Validated, States.Unregistered, () => !this.Registered)
.PermitIf(Triggers.Validated, States.Registered, () => this.Registered)
.Permit(Triggers.Cleanup, States.Unregistered)
.PermitReentry(Triggers.Validate);
this.fsm.Configure(States.Registering)
.OnEntry(this.OnRegistering)
.PermitIf(Triggers.Registered, States.Registered, () => this.Registered)
.Permit(Triggers.Cleanup, States.Unregistered);
this.fsm.Configure(States.Registered)
.OnEntry(this.OnRegistered)
.OnExit(this.LeavingRegistered)
.Permit(Triggers.Validate, States.Validating)
.PermitIf(Triggers.Update, States.Updating, () => this.Validated)
.Permit(Triggers.Remove, States.Removing)
.Permit(Triggers.Cleanup, States.Unregistered);
this.fsm.Configure(States.Updating)
.OnEntry(this.OnUpdating)
.PermitIf(Triggers.Registered, States.Registered, () => this.Registered)
.Permit(Triggers.Cleanup, States.Unregistered);
this.fsm.Configure(States.Removing)
.OnEntry(this.OnRemoving)
.PermitIf(Triggers.Removed, States.Removed, () => !this.Registered)
.Permit(Triggers.Cleanup, States.Unregistered);
this.mapping = new Document();
mapping[this.configuration.Fields.UserName] = NormaliseIdentifier(userAuth.UserName);
mapping[this.configuration.Fields.Email] = NormaliseIdentifier(userAuth.Email);
mapping[this.configuration.Fields.Id] = userAuth.Id;
this.emailMappingTable = Table.LoadTable(client, configuration.EmailToIdMappingTableName);
this.usernameMappingTable = Table.LoadTable(client, configuration.UserNameToIdMappingTableName);
}
public bool Validated { get; private set; }
public string ValidationMessage { get; private set; }
public bool Registered { get; private set; }
public UserAuth RegisteredUserAuth { get; private set; }
public bool EmailMapped { get; private set; }
public bool UserNameMapped { get; private set; }
public void Restore() {
this.fsm.Fire(Triggers.Cleanup);
this.fsm.Fire(Triggers.Restore);
}
public void Validate()
{
this.fsm.Fire(Triggers.Validate);
if (!this.Validated)
throw new ArgumentException(this.ValidationMessage);
this.fsm.Fire(Triggers.Validated);
}
public void Register()
{
this.Validate();
this.fsm.Fire(Triggers.Register);
this.fsm.Fire(Triggers.Registered);
}
public void Update()
{
if (this.RegisteredUserAuth == null) {
this.fsm.Fire(Triggers.Restore);
}
this.Validate();
this.fsm.Fire(Triggers.Update);
this.fsm.Fire(Triggers.Registered);
}
public void Remove()
{
if (this.RegisteredUserAuth == null) {
this.fsm.Fire(Triggers.Restore);
}
this.fsm.Fire(Triggers.Remove);
this.fsm.Fire(Triggers.Removed);
}
public void Dispose()
{
if (this.fsm.CanFire(Triggers.Cleanup))
this.fsm.Fire(Triggers.Cleanup);
}
private void OnValidate()
{
this.ValidateRules();
this.ValidateUserName();
this.ValidateEmail();
this.Validated = true;
}
private void ValidateRules()
{
if (this.userAuth.UserName.IsNullOrEmpty() && this.userAuth.Email.IsNullOrEmpty())
{
throw new ArgumentNullException("UserName or Email is required");
}
if (!this.userAuth.UserName.IsNullOrEmpty())
{
if (!ValidUserNameRegEx.IsMatch(this.userAuth.UserName))
{
throw new ArgumentException("UserName contains invalid characters", "UserName");
}
}
}
private void ValidateUserName()
{
var userName = NormaliseIdentifier(this.userAuth.UserName);
if (string.IsNullOrEmpty(userName))
return;
// check
var doc = this.usernameMappingTable.GetItem(userName);
if (doc != null && doc[this.configuration.Fields.Id].AsInt() != this.userAuth.Id)
{
Log.Verbose("{UserId} {UserName} already mapped to {Id}", this.userAuth.Id, this.userAuth.UserName, doc[this.configuration.Fields.Id].AsInt());
throw new ArgumentException("User {0} already exists".Fmt(this.userAuth.UserName));
}
Log.Information("{UserId} {UserName} validated", this.userAuth.Id, this.userAuth.UserName);
}
private void ValidateEmail()
{
var email = NormaliseIdentifier(this.userAuth.Email);
if (string.IsNullOrEmpty(email))
return;
// check
var doc = this.emailMappingTable.GetItem(email);
if (doc != null && doc[this.configuration.Fields.Id].AsInt() != this.userAuth.Id)
{
Log.Verbose("{UserId} {Email} already mapped to {Id}", this.userAuth.Id, this.userAuth.Email, doc[this.configuration.Fields.Id].AsInt());
throw new ArgumentException("Email {0} already exists".Fmt(this.userAuth.Email));
}
Log.Information("{UserId} {Email} validated", this.userAuth.Id, this.userAuth.Email);
}
private void OnRegistering()
{
if (this.RegisteredUserAuth != null)
return;
this.RegisterUserName();
this.RegisterEmail();
Log.Verbose("{UserId} registering {UserName} {Email}", this.userAuth.Id, this.userAuth.UserName, this.userAuth.Email);
// register user
using (var context = new DynamoDBContext(client))
{
var record = new UserAuth();
record.PopulateWith(this.userAuth);
context.Save<UserAuth>(record, new DynamoDBOperationConfig() {
OverrideTableName = this.configuration.UserAuthTableName,
ConditionalOperator = ConditionalOperatorValues.And,
});
this.RegisteredUserAuth = record;
}
this.Registered = true;
this.UserNameMapped = false;
this.EmailMapped = false;
Log.Information("{UserId} {UserName} {Email} registered", this.userAuth.Id, this.userAuth.UserName, this.userAuth.Email);
}
private void OnRegistered()
{
if (this.RegisteredUserAuth != null)
return;
Log.Verbose("{UserId} loading record {UserName} {Email}", this.userAuth.Id, this.userAuth.UserName, this.userAuth.Email);
// register user
using (var context = new DynamoDBContext(client))
{
this.RegisteredUserAuth = context.Load<UserAuth>(this.userAuth.Id, new DynamoDBOperationConfig() {
OverrideTableName = this.configuration.UserAuthTableName,
ConditionalOperator = ConditionalOperatorValues.And,
});
}
if (this.RegisteredUserAuth == null)
throw new ArgumentException(string.Format("UserAuth {0} not found", this.userAuth.Id));
this.Registered = true;
this.UserNameMapped = false;
this.EmailMapped = false;
Log.Information("{UserId} {UserName} {Email} registered", this.userAuth.Id, this.userAuth.UserName, this.userAuth.Email);
}
private void LeavingRegistered() {
this.Validated = false;
this.ValidationMessage = null;
}
private string NormaliseIdentifier(string value)
{
return (value ?? "").Trim().ToLowerInvariant();
}
private void OnUpdating()
{
var existingUserName = NormaliseIdentifier(this.RegisteredUserAuth.UserName);
var existingEmail = NormaliseIdentifier(this.RegisteredUserAuth.Email);
var currentUserName = NormaliseIdentifier(this.userAuth.UserName);
var currentEmail = NormaliseIdentifier(this.userAuth.Email);
// check if username and/or email has changed
// update and remove if need be
var usernameWasChanged = false;
var emailWasChanged = false;
if (string.Compare(existingUserName, currentUserName, StringComparison.InvariantCultureIgnoreCase) != 0)
{
Log.Verbose("{UserId} UserName attribute changed {PreviousUserName} -> {UserName}", this.userAuth.Id, this.RegisteredUserAuth.UserName, this.userAuth.UserName);
usernameWasChanged = true;
this.RegisterUserName();
}
if (string.Compare(existingEmail, currentEmail, StringComparison.InvariantCultureIgnoreCase) != 0)
{
Log.Verbose("{UserId} Email attribute changed {PreviousEmail} -> {Email}", this.userAuth.Id, this.RegisteredUserAuth.Email, this.userAuth.Email);
emailWasChanged = true;
this.RegisterEmail();
}
Log.Verbose("{UserId} updating {UserName} {Email}", this.userAuth.Id, this.userAuth.UserName, this.userAuth.Email);
// register user
using (var context = new DynamoDBContext(client))
{
var record = new UserAuth();
record.PopulateWith(this.userAuth);
context.Save(record, new DynamoDBOperationConfig() {
OverrideTableName = this.configuration.UserAuthTableName,
ConditionalOperator = ConditionalOperatorValues.And,
});
this.RegisteredUserAuth = record;
}
this.Registered = true;
this.UserNameMapped = false;
this.EmailMapped = false;
Log.Information("{UserId} {UserName} {Email} updated", this.userAuth.Id, this.userAuth.UserName, this.userAuth.Email);
if (usernameWasChanged && !string.IsNullOrEmpty(existingUserName))
{
Log.Verbose("{UserId} un-mapping previous {UserName}", this.userAuth.Id, existingUserName);
this.usernameMappingTable.DeleteItem(existingUserName);
this.UserNameMapped = false;
Log.Information("{UserId} {UserName} un-mapped", this.userAuth.Id, existingUserName);
}
if (emailWasChanged && !string.IsNullOrEmpty(existingEmail))
{
Log.Verbose("{UserId} un-mapping previous {Email}", this.userAuth.Id, existingEmail);
this.emailMappingTable.DeleteItem(existingEmail);
this.EmailMapped = false;
Log.Information("{UserId} {Email} un-mapped", this.userAuth.Id, existingEmail);
}
}
private void RegisterUserName()
{
var userName = NormaliseIdentifier(this.userAuth.UserName);
if (string.IsNullOrEmpty(userName))
return;
if (this.UserNameMapped)
{
Log.Verbose("{UserId} {UserName} already mapped", this.userAuth.Id, this.userAuth.UserName);
return;
}
Log.Verbose("{UserId} mapping {UserName}", this.userAuth.Id, this.userAuth.UserName);
this.usernameMappingTable.UpdateItem(this.mapping, new UpdateItemOperationConfig() {
ExpectedState = new ExpectedState() {
ConditionalOperator = ConditionalOperatorValues.And,
ExpectedValues = new Dictionary<string, ExpectedValue>() {
{ this.configuration.Fields.UserName, new ExpectedValue(false) },
},
},
ReturnValues = ReturnValues.None,
});
this.UserNameMapped = true;
Log.Information("{UserId} {UserName} mapped", this.userAuth.Id, this.userAuth.UserName);
}
private void RegisterEmail()
{
var email = NormaliseIdentifier(this.userAuth.Email);
if (string.IsNullOrEmpty(email))
return;
if (this.EmailMapped)
{
Log.Verbose("{UserId} {Email} already mapped", this.userAuth.Id, this.userAuth.Email);
return;
}
Log.Verbose("{UserId} mapping {Email}", this.userAuth.Id, this.userAuth.Email);
this.emailMappingTable.UpdateItem(this.mapping, new UpdateItemOperationConfig() {
ExpectedState = new ExpectedState() {
ConditionalOperator = ConditionalOperatorValues.And,
ExpectedValues = new Dictionary<string, ExpectedValue>() {
{ this.configuration.Fields.Email, new ExpectedValue(false) },
},
},
ReturnValues = ReturnValues.None,
});
this.EmailMapped = true;
Log.Information("{UserId} {Email} mapped", this.userAuth.Id, this.userAuth.Email);
}
private void OnRemoving()
{
var userName = NormaliseIdentifier(this.RegisteredUserAuth.UserName);
var email = NormaliseIdentifier(this.RegisteredUserAuth.Email);
this.UserNameMapped = !string.IsNullOrEmpty(userName);
this.EmailMapped = !string.IsNullOrEmpty(email);
Log.Verbose("{UserId} removing {UserName} {Email}", this.userAuth.Id, this.userAuth.UserName, this.userAuth.Email);
// register user
using (var context = new DynamoDBContext(client))
{
context.Delete<UserAuth>(this.userAuth.Id, new DynamoDBOperationConfig() {
OverrideTableName = this.configuration.UserAuthTableName,
ConditionalOperator = ConditionalOperatorValues.And,
});
this.RegisteredUserAuth = null;
}
this.Registered = false;
if (this.UserNameMapped)
{
Log.Verbose("{UserId} un-mapping {UserName}", this.userAuth.Id, this.userAuth.UserName);
this.usernameMappingTable.DeleteItem(userName);
this.UserNameMapped = false;
Log.Information("{UserId} {UserName} un-mapped", this.userAuth.Id, this.userAuth.UserName);
}
if (this.EmailMapped)
{
Log.Verbose("{UserId} un-mapping previous {Email}", this.userAuth.Id, this.userAuth.Email);
this.emailMappingTable.DeleteItem(email);
this.EmailMapped = false;
Log.Information("{UserId} {Email} un-mapped", this.userAuth.Id, this.userAuth.Email);
}
Log.Information("{UserId} {UserName} {Email} removed", this.userAuth.Id, this.userAuth.UserName, this.userAuth.Email);
}
private void Cleanup()
{
var config = new DeleteItemOperationConfig() {
ExpectedState = new ExpectedState() {
ConditionalOperator = ConditionalOperatorValues.And,
ExpectedValues = new Dictionary<string, ExpectedValue>() {
{ this.configuration.Fields.Email, new ExpectedValue(ScanOperator.Equal, this.userAuth.Email) },
{ this.configuration.Fields.Id, new ExpectedValue(ScanOperator.Equal, this.userAuth.Id) },
},
},
};
if (this.UserNameMapped)
{
Log.Verbose("{UserId} un-mapping {UserName}", this.userAuth.Id, this.userAuth.UserName);
this.usernameMappingTable.DeleteItem(NormaliseIdentifier(this.userAuth.UserName));
this.UserNameMapped = false;
Log.Information("{UserId} {UserName} un-mapped", this.userAuth.Id, this.userAuth.UserName);
}
if (this.EmailMapped)
{
Log.Verbose("{UserId} un-mapping {Email}", this.userAuth.Id, this.userAuth.Email);
this.emailMappingTable.DeleteItem(NormaliseIdentifier(this.userAuth.Email));
this.EmailMapped = false;
Log.Information("{UserId} {Email} un-mapped", this.userAuth.Id, this.userAuth.Email);
}
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Layouts
{
using System;
using NUnit.Framework;
#if !NUNIT
using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute;
using ExpectedException = Microsoft.VisualStudio.TestTools.UnitTesting.ExpectedExceptionAttribute;
#endif
using NLog.LayoutRenderers;
using NLog.LayoutRenderers.Wrappers;
using NLog.Layouts;
[TestFixture]
public class SimpleLayoutParserTests : NLogTestBase
{
[Test]
public void SimpleTest()
{
SimpleLayout l = "${message}";
Assert.AreEqual(1, l.Renderers.Count);
Assert.IsInstanceOfType(typeof(MessageLayoutRenderer), l.Renderers[0]);
}
[Test]
public void UnclosedTest()
{
new SimpleLayout("${message");
}
[Test]
public void SingleParamTest()
{
SimpleLayout l = "${mdc:item=AAA}";
Assert.AreEqual(1, l.Renderers.Count);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.IsNotNull(mdc);
Assert.AreEqual("AAA", mdc.Item);
}
[Test]
public void ValueWithColonTest()
{
SimpleLayout l = "${mdc:item=AAA\\:}";
Assert.AreEqual(1, l.Renderers.Count);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.IsNotNull(mdc);
Assert.AreEqual("AAA:", mdc.Item);
}
[Test]
public void ValueWithBracketTest()
{
SimpleLayout l = "${mdc:item=AAA\\}\\:}";
Assert.AreEqual("${mdc:item=AAA\\}\\:}", l.Text);
Assert.AreEqual(1, l.Renderers.Count);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.IsNotNull(mdc);
Assert.AreEqual("AAA}:", mdc.Item);
}
[Test]
public void DefaultValueTest()
{
SimpleLayout l = "${mdc:BBB}";
Assert.AreEqual(1, l.Renderers.Count);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.IsNotNull(mdc);
Assert.AreEqual("BBB", mdc.Item);
}
[Test]
public void DefaultValueWithBracketTest()
{
SimpleLayout l = "${mdc:AAA\\}\\:}";
Assert.AreEqual(l.Text, "${mdc:AAA\\}\\:}");
Assert.AreEqual(1, l.Renderers.Count);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.IsNotNull(mdc);
Assert.AreEqual("AAA}:", mdc.Item);
}
[Test]
public void DefaultValueWithOtherParametersTest()
{
SimpleLayout l = "${exception:message,type:separator=x}";
Assert.AreEqual(1, l.Renderers.Count);
ExceptionLayoutRenderer elr = l.Renderers[0] as ExceptionLayoutRenderer;
Assert.IsNotNull(elr);
Assert.AreEqual("message,type", elr.Format);
Assert.AreEqual("x", elr.Separator);
}
[Test]
public void EmptyValueTest()
{
SimpleLayout l = "${mdc:item=}";
Assert.AreEqual(1, l.Renderers.Count);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.IsNotNull(mdc);
Assert.AreEqual("", mdc.Item);
}
[Test]
public void NestedLayoutTest()
{
SimpleLayout l = "${rot13:inner=${ndc:topFrames=3:separator=x}}";
Assert.AreEqual(1, l.Renderers.Count);
var lr = l.Renderers[0] as Rot13LayoutRendererWrapper;
Assert.IsNotNull(lr);
var nestedLayout = lr.Inner as SimpleLayout;
Assert.IsNotNull(nestedLayout);
Assert.AreEqual("${ndc:topFrames=3:separator=x}", nestedLayout.Text);
Assert.AreEqual(1, nestedLayout.Renderers.Count);
var ndcLayoutRenderer = nestedLayout.Renderers[0] as NdcLayoutRenderer;
Assert.IsNotNull(ndcLayoutRenderer);
Assert.AreEqual(3, ndcLayoutRenderer.TopFrames);
Assert.AreEqual("x", ndcLayoutRenderer.Separator);
}
[Test]
public void DoubleNestedLayoutTest()
{
SimpleLayout l = "${rot13:inner=${rot13:inner=${ndc:topFrames=3:separator=x}}}";
Assert.AreEqual(1, l.Renderers.Count);
var lr = l.Renderers[0] as Rot13LayoutRendererWrapper;
Assert.IsNotNull(lr);
var nestedLayout0 = lr.Inner as SimpleLayout;
Assert.IsNotNull(nestedLayout0);
Assert.AreEqual("${rot13:inner=${ndc:topFrames=3:separator=x}}", nestedLayout0.Text);
var innerRot13 = nestedLayout0.Renderers[0] as Rot13LayoutRendererWrapper;
var nestedLayout = innerRot13.Inner as SimpleLayout;
Assert.IsNotNull(nestedLayout);
Assert.AreEqual("${ndc:topFrames=3:separator=x}", nestedLayout.Text);
Assert.AreEqual(1, nestedLayout.Renderers.Count);
var ndcLayoutRenderer = nestedLayout.Renderers[0] as NdcLayoutRenderer;
Assert.IsNotNull(ndcLayoutRenderer);
Assert.AreEqual(3, ndcLayoutRenderer.TopFrames);
Assert.AreEqual("x", ndcLayoutRenderer.Separator);
}
[Test]
public void DoubleNestedLayoutWithDefaultLayoutParametersTest()
{
SimpleLayout l = "${rot13:${rot13:${ndc:topFrames=3:separator=x}}}";
Assert.AreEqual(1, l.Renderers.Count);
var lr = l.Renderers[0] as Rot13LayoutRendererWrapper;
Assert.IsNotNull(lr);
var nestedLayout0 = lr.Inner as SimpleLayout;
Assert.IsNotNull(nestedLayout0);
Assert.AreEqual("${rot13:${ndc:topFrames=3:separator=x}}", nestedLayout0.Text);
var innerRot13 = nestedLayout0.Renderers[0] as Rot13LayoutRendererWrapper;
var nestedLayout = innerRot13.Inner as SimpleLayout;
Assert.IsNotNull(nestedLayout);
Assert.AreEqual("${ndc:topFrames=3:separator=x}", nestedLayout.Text);
Assert.AreEqual(1, nestedLayout.Renderers.Count);
var ndcLayoutRenderer = nestedLayout.Renderers[0] as NdcLayoutRenderer;
Assert.IsNotNull(ndcLayoutRenderer);
Assert.AreEqual(3, ndcLayoutRenderer.TopFrames);
Assert.AreEqual("x", ndcLayoutRenderer.Separator);
}
[Test]
public void AmbientPropertyTest()
{
SimpleLayout l = "${message:padding=10}";
Assert.AreEqual(1, l.Renderers.Count);
var pad = l.Renderers[0] as PaddingLayoutRendererWrapper;
Assert.IsNotNull(pad);
var message = ((SimpleLayout)pad.Inner).Renderers[0] as MessageLayoutRenderer;
Assert.IsNotNull(message);
}
[Test]
[ExpectedException(typeof(NLogConfigurationException))]
public void MissingLayoutRendererTest()
{
SimpleLayout l = "${rot13:${foobar}}";
Assert.IsNull(l);
}
[Test]
public void DoubleAmbientPropertyTest()
{
SimpleLayout l = "${message:uppercase=true:padding=10}";
Assert.AreEqual(1, l.Renderers.Count);
var upperCase = l.Renderers[0] as UppercaseLayoutRendererWrapper;
Assert.IsNotNull(upperCase);
var pad = ((SimpleLayout)upperCase.Inner).Renderers[0] as PaddingLayoutRendererWrapper;
Assert.IsNotNull(pad);
var message = ((SimpleLayout)pad.Inner).Renderers[0] as MessageLayoutRenderer;
Assert.IsNotNull(message);
}
[Test]
public void ReverseDoubleAmbientPropertyTest()
{
SimpleLayout l = "${message:padding=10:uppercase=true}";
Assert.AreEqual(1, l.Renderers.Count);
var pad = ((SimpleLayout)l).Renderers[0] as PaddingLayoutRendererWrapper;
Assert.IsNotNull(pad);
var upperCase = ((SimpleLayout)pad.Inner).Renderers[0] as UppercaseLayoutRendererWrapper;
Assert.IsNotNull(upperCase);
var message = ((SimpleLayout)upperCase.Inner).Renderers[0] as MessageLayoutRenderer;
Assert.IsNotNull(message);
}
[Test]
public void EscapeTest()
{
AssertEscapeRoundTrips(string.Empty);
AssertEscapeRoundTrips("hello ${${}} world!");
AssertEscapeRoundTrips("hello $");
AssertEscapeRoundTrips("hello ${");
AssertEscapeRoundTrips("hello $${{");
AssertEscapeRoundTrips("hello ${message}");
AssertEscapeRoundTrips("hello ${${level}}");
AssertEscapeRoundTrips("hello ${${level}${message}}");
}
[Test]
public void EvaluateTest()
{
var logEventInfo = LogEventInfo.CreateNullEvent();
logEventInfo.Level = LogLevel.Warn;
Assert.AreEqual("Warn", SimpleLayout.Evaluate("${level}", logEventInfo));
}
[Test]
public void EvaluateTest2()
{
Assert.AreEqual("Off", SimpleLayout.Evaluate("${level}"));
Assert.AreEqual(string.Empty, SimpleLayout.Evaluate("${message}"));
Assert.AreEqual(string.Empty, SimpleLayout.Evaluate("${logger}"));
}
private static void AssertEscapeRoundTrips(string originalString)
{
string escapedString = SimpleLayout.Escape(originalString);
SimpleLayout l = escapedString;
string renderedString = l.Render(LogEventInfo.CreateNullEvent());
Assert.AreEqual(originalString, renderedString);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Serialization
{
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System;
using System.Globalization;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.Diagnostics;
using System.Threading;
using System.Security;
using System.Net;
using System.Reflection;
public class XmlSchemas : CollectionBase, IEnumerable<XmlSchema>
{
private XmlSchemaSet _schemaSet;
private Hashtable _references;
private SchemaObjectCache _cache; // cached schema top-level items
private bool _shareTypes;
private Hashtable _mergedSchemas;
internal Hashtable delayedSchemas = new Hashtable();
private bool _isCompiled = false;
private static volatile XmlSchema s_xsd;
private static volatile XmlSchema s_xml;
public XmlSchema this[int index]
{
get { return (XmlSchema)List[index]; }
set { List[index] = value; }
}
public XmlSchema this[string ns]
{
get
{
IList values = (IList)SchemaSet.Schemas(ns);
if (values.Count == 0)
return null;
if (values.Count == 1)
return (XmlSchema)values[0];
throw new InvalidOperationException(SR.Format(SR.XmlSchemaDuplicateNamespace, ns));
}
}
public IList GetSchemas(string ns)
{
return (IList)SchemaSet.Schemas(ns);
}
internal SchemaObjectCache Cache
{
get
{
if (_cache == null)
_cache = new SchemaObjectCache();
return _cache;
}
}
internal Hashtable MergedSchemas
{
get
{
if (_mergedSchemas == null)
_mergedSchemas = new Hashtable();
return _mergedSchemas;
}
}
internal Hashtable References
{
get
{
if (_references == null)
_references = new Hashtable();
return _references;
}
}
internal XmlSchemaSet SchemaSet
{
get
{
if (_schemaSet == null)
{
_schemaSet = new XmlSchemaSet();
_schemaSet.XmlResolver = null;
_schemaSet.ValidationEventHandler += new ValidationEventHandler(IgnoreCompileErrors);
}
return _schemaSet;
}
}
internal int Add(XmlSchema schema, bool delay)
{
if (delay)
{
if (delayedSchemas[schema] == null)
delayedSchemas.Add(schema, schema);
return -1;
}
else
{
return Add(schema);
}
}
public int Add(XmlSchema schema)
{
if (List.Contains(schema))
return List.IndexOf(schema);
return List.Add(schema);
}
public int Add(XmlSchema schema, Uri baseUri)
{
if (List.Contains(schema))
return List.IndexOf(schema);
if (baseUri != null)
schema.BaseUri = baseUri;
return List.Add(schema);
}
public void Add(XmlSchemas schemas)
{
foreach (XmlSchema schema in schemas)
{
Add(schema);
}
}
public void AddReference(XmlSchema schema)
{
References[schema] = schema;
}
public void Insert(int index, XmlSchema schema)
{
List.Insert(index, schema);
}
public int IndexOf(XmlSchema schema)
{
return List.IndexOf(schema);
}
public bool Contains(XmlSchema schema)
{
return List.Contains(schema);
}
public bool Contains(string targetNamespace)
{
return SchemaSet.Contains(targetNamespace);
}
public void Remove(XmlSchema schema)
{
List.Remove(schema);
}
public void CopyTo(XmlSchema[] array, int index)
{
List.CopyTo(array, index);
}
protected override void OnInsert(int index, object value)
{
AddName((XmlSchema)value);
}
protected override void OnRemove(int index, object value)
{
RemoveName((XmlSchema)value);
}
protected override void OnClear()
{
_schemaSet = null;
}
protected override void OnSet(int index, object oldValue, object newValue)
{
RemoveName((XmlSchema)oldValue);
AddName((XmlSchema)newValue);
}
private void AddName(XmlSchema schema)
{
if (_isCompiled) throw new InvalidOperationException(SR.XmlSchemaCompiled);
if (SchemaSet.Contains(schema))
SchemaSet.Reprocess(schema);
else
{
Prepare(schema);
SchemaSet.Add(schema);
}
}
private void Prepare(XmlSchema schema)
{
// need to remove illegal <import> externals;
ArrayList removes = new ArrayList();
string ns = schema.TargetNamespace;
foreach (XmlSchemaExternal external in schema.Includes)
{
if (external is XmlSchemaImport)
{
if (ns == ((XmlSchemaImport)external).Namespace)
{
removes.Add(external);
}
}
}
foreach (XmlSchemaObject o in removes)
{
schema.Includes.Remove(o);
}
}
private void RemoveName(XmlSchema schema)
{
SchemaSet.Remove(schema);
}
public object Find(XmlQualifiedName name, Type type)
{
return Find(name, type, true);
}
internal object Find(XmlQualifiedName name, Type type, bool checkCache)
{
if (!IsCompiled)
{
foreach (XmlSchema schema in List)
{
Preprocess(schema);
}
}
IList values = (IList)SchemaSet.Schemas(name.Namespace);
if (values == null) return null;
foreach (XmlSchema schema in values)
{
Preprocess(schema);
XmlSchemaObject ret = null;
if (typeof(XmlSchemaType).IsAssignableFrom(type))
{
ret = schema.SchemaTypes[name];
if (ret == null || !type.IsAssignableFrom(ret.GetType()))
{
continue;
}
}
else if (type == typeof(XmlSchemaGroup))
{
ret = schema.Groups[name];
}
else if (type == typeof(XmlSchemaAttributeGroup))
{
ret = schema.AttributeGroups[name];
}
else if (type == typeof(XmlSchemaElement))
{
ret = schema.Elements[name];
}
else if (type == typeof(XmlSchemaAttribute))
{
ret = schema.Attributes[name];
}
else if (type == typeof(XmlSchemaNotation))
{
ret = schema.Notations[name];
}
#if DEBUG
else
{
// use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "XmlSchemas.Find: Invalid object type " + type.FullName));
}
#endif
if (ret != null && _shareTypes && checkCache && !IsReference(ret))
ret = Cache.AddItem(ret, name, this);
if (ret != null)
{
return ret;
}
}
return null;
}
IEnumerator<XmlSchema> IEnumerable<XmlSchema>.GetEnumerator()
{
return new XmlSchemaEnumerator(this);
}
internal static void Preprocess(XmlSchema schema)
{
if (!schema.IsPreprocessed)
{
try
{
XmlNameTable nameTable = new System.Xml.NameTable();
Preprocessor prep = new Preprocessor(nameTable, new SchemaNames(nameTable), null);
prep.SchemaLocations = new Hashtable();
prep.Execute(schema, schema.TargetNamespace, false);
}
catch (XmlSchemaException e)
{
throw CreateValidationException(e, e.Message);
}
}
}
public static bool IsDataSet(XmlSchema schema)
{
foreach (XmlSchemaObject o in schema.Items)
{
if (o is XmlSchemaElement)
{
XmlSchemaElement e = (XmlSchemaElement)o;
if (e.UnhandledAttributes != null)
{
foreach (XmlAttribute a in e.UnhandledAttributes)
{
if (a.LocalName == "IsDataSet" && a.NamespaceURI == "urn:schemas-microsoft-com:xml-msdata")
{
// currently the msdata:IsDataSet uses its own format for the boolean values
if (a.Value == "True" || a.Value == "true" || a.Value == "1") return true;
}
}
}
}
}
return false;
}
private void Merge(XmlSchema schema)
{
if (MergedSchemas[schema] != null)
return;
IList originals = (IList)SchemaSet.Schemas(schema.TargetNamespace);
if (originals != null && originals.Count > 0)
{
MergedSchemas.Add(schema, schema);
Merge(originals, schema);
}
else
{
Add(schema);
MergedSchemas.Add(schema, schema);
}
}
private void AddImport(IList schemas, string ns)
{
foreach (XmlSchema s in schemas)
{
bool add = true;
foreach (XmlSchemaExternal external in s.Includes)
{
if (external is XmlSchemaImport && ((XmlSchemaImport)external).Namespace == ns)
{
add = false;
break;
}
}
if (add)
{
XmlSchemaImport import = new XmlSchemaImport();
import.Namespace = ns;
s.Includes.Add(import);
}
}
}
private void Merge(IList originals, XmlSchema schema)
{
foreach (XmlSchema s in originals)
{
if (schema == s)
{
return;
}
}
foreach (XmlSchemaExternal external in schema.Includes)
{
if (external is XmlSchemaImport)
{
external.SchemaLocation = null;
if (external.Schema != null)
{
Merge(external.Schema);
}
else
{
AddImport(originals, ((XmlSchemaImport)external).Namespace);
}
}
else
{
if (external.Schema == null)
{
// we do not process includes or redefines by the schemaLocation
if (external.SchemaLocation != null)
{
throw new InvalidOperationException(SR.Format(SR.XmlSchemaIncludeLocation, this.GetType().Name, external.SchemaLocation));
}
}
else
{
external.SchemaLocation = null;
Merge(originals, external.Schema);
}
}
}
// bring all included items to the parent schema;
bool[] matchedItems = new bool[schema.Items.Count];
int count = 0;
for (int i = 0; i < schema.Items.Count; i++)
{
XmlSchemaObject o = schema.Items[i];
XmlSchemaObject dest = Find(o, originals);
if (dest != null)
{
if (!Cache.Match(dest, o, _shareTypes))
{
throw new InvalidOperationException(MergeFailedMessage(o, dest, schema.TargetNamespace));
}
matchedItems[i] = true;
count++;
}
}
if (count != schema.Items.Count)
{
XmlSchema destination = (XmlSchema)originals[0];
for (int i = 0; i < schema.Items.Count; i++)
{
if (!matchedItems[i])
{
destination.Items.Add(schema.Items[i]);
}
}
destination.IsPreprocessed = false;
Preprocess(destination);
}
}
private static string ItemName(XmlSchemaObject o)
{
if (o is XmlSchemaNotation)
{
return ((XmlSchemaNotation)o).Name;
}
else if (o is XmlSchemaGroup)
{
return ((XmlSchemaGroup)o).Name;
}
else if (o is XmlSchemaElement)
{
return ((XmlSchemaElement)o).Name;
}
else if (o is XmlSchemaType)
{
return ((XmlSchemaType)o).Name;
}
else if (o is XmlSchemaAttributeGroup)
{
return ((XmlSchemaAttributeGroup)o).Name;
}
else if (o is XmlSchemaAttribute)
{
return ((XmlSchemaAttribute)o).Name;
}
return null;
}
internal static XmlQualifiedName GetParentName(XmlSchemaObject item)
{
while (item.Parent != null)
{
if (item.Parent is XmlSchemaType)
{
XmlSchemaType type = (XmlSchemaType)item.Parent;
if (type.Name != null && type.Name.Length != 0)
{
return type.QualifiedName;
}
}
item = item.Parent;
}
return XmlQualifiedName.Empty;
}
private static string GetSchemaItem(XmlSchemaObject o, string ns, string details)
{
if (o == null)
{
return null;
}
while (o.Parent != null && !(o.Parent is XmlSchema))
{
o = o.Parent;
}
if (ns == null || ns.Length == 0)
{
XmlSchemaObject tmp = o;
while (tmp.Parent != null)
{
tmp = tmp.Parent;
}
if (tmp is XmlSchema)
{
ns = ((XmlSchema)tmp).TargetNamespace;
}
}
string item = null;
if (o is XmlSchemaNotation)
{
item = SR.Format(SR.XmlSchemaNamedItem, ns, "notation", ((XmlSchemaNotation)o).Name, details);
}
else if (o is XmlSchemaGroup)
{
item = SR.Format(SR.XmlSchemaNamedItem, ns, "group", ((XmlSchemaGroup)o).Name, details);
}
else if (o is XmlSchemaElement)
{
XmlSchemaElement e = ((XmlSchemaElement)o);
if (e.Name == null || e.Name.Length == 0)
{
XmlQualifiedName parentName = XmlSchemas.GetParentName(o);
// Element reference '{0}' declared in schema type '{1}' from namespace '{2}'
item = SR.Format(SR.XmlSchemaElementReference, e.RefName.ToString(), parentName.Name, parentName.Namespace);
}
else
{
item = SR.Format(SR.XmlSchemaNamedItem, ns, "element", e.Name, details);
}
}
else if (o is XmlSchemaType)
{
item = SR.Format(SR.XmlSchemaNamedItem, ns, o.GetType() == typeof(XmlSchemaSimpleType) ? "simpleType" : "complexType", ((XmlSchemaType)o).Name, null);
}
else if (o is XmlSchemaAttributeGroup)
{
item = SR.Format(SR.XmlSchemaNamedItem, ns, "attributeGroup", ((XmlSchemaAttributeGroup)o).Name, details);
}
else if (o is XmlSchemaAttribute)
{
XmlSchemaAttribute a = ((XmlSchemaAttribute)o);
if (a.Name == null || a.Name.Length == 0)
{
XmlQualifiedName parentName = XmlSchemas.GetParentName(o);
// Attribure reference '{0}' declared in schema type '{1}' from namespace '{2}'
return SR.Format(SR.XmlSchemaAttributeReference, a.RefName.ToString(), parentName.Name, parentName.Namespace);
}
else
{
item = SR.Format(SR.XmlSchemaNamedItem, ns, "attribute", a.Name, details);
}
}
else if (o is XmlSchemaContent)
{
XmlQualifiedName parentName = XmlSchemas.GetParentName(o);
// Check content definition of schema type '{0}' from namespace '{1}'. {2}
item = SR.Format(SR.XmlSchemaContentDef, parentName.Name, parentName.Namespace, null);
}
else if (o is XmlSchemaExternal)
{
string itemType = o is XmlSchemaImport ? "import" : o is XmlSchemaInclude ? "include" : o is XmlSchemaRedefine ? "redefine" : o.GetType().Name;
item = SR.Format(SR.XmlSchemaItem, ns, itemType, details);
}
else if (o is XmlSchema)
{
item = SR.Format(SR.XmlSchema, ns, details);
}
else
{
item = SR.Format(SR.XmlSchemaNamedItem, ns, o.GetType().Name, null, details);
}
return item;
}
private static string Dump(XmlSchemaObject o)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Indent = true;
XmlSerializer s = new XmlSerializer(o.GetType());
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
XmlWriter xmlWriter = XmlWriter.Create(sw, settings);
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("xs", XmlSchema.Namespace);
s.Serialize(xmlWriter, o, ns);
return sw.ToString();
}
private static string MergeFailedMessage(XmlSchemaObject src, XmlSchemaObject dest, string ns)
{
string err = SR.Format(SR.XmlSerializableMergeItem, ns, GetSchemaItem(src, ns, null));
err += "\r\n" + Dump(src);
err += "\r\n" + Dump(dest);
return err;
}
internal XmlSchemaObject Find(XmlSchemaObject o, IList originals)
{
string name = ItemName(o);
if (name == null)
return null;
Type type = o.GetType();
foreach (XmlSchema s in originals)
{
foreach (XmlSchemaObject item in s.Items)
{
if (item.GetType() == type && name == ItemName(item))
{
return item;
}
}
}
return null;
}
public bool IsCompiled
{
get { return _isCompiled; }
}
public void Compile(ValidationEventHandler handler, bool fullCompile)
{
if (_isCompiled)
return;
foreach (XmlSchema s in delayedSchemas.Values)
Merge(s);
delayedSchemas.Clear();
if (fullCompile)
{
_schemaSet = new XmlSchemaSet();
_schemaSet.XmlResolver = null;
_schemaSet.ValidationEventHandler += handler;
foreach (XmlSchema s in References.Values)
_schemaSet.Add(s);
int schemaCount = _schemaSet.Count;
foreach (XmlSchema s in List)
{
if (!SchemaSet.Contains(s))
{
_schemaSet.Add(s);
schemaCount++;
}
}
if (!SchemaSet.Contains(XmlSchema.Namespace))
{
AddReference(XsdSchema);
_schemaSet.Add(XsdSchema);
schemaCount++;
}
if (!SchemaSet.Contains(XmlReservedNs.NsXml))
{
AddReference(XmlSchema);
_schemaSet.Add(XmlSchema);
schemaCount++;
}
_schemaSet.Compile();
_schemaSet.ValidationEventHandler -= handler;
_isCompiled = _schemaSet.IsCompiled && schemaCount == _schemaSet.Count;
}
else
{
try
{
XmlNameTable nameTable = new System.Xml.NameTable();
Preprocessor prep = new Preprocessor(nameTable, new SchemaNames(nameTable), null);
prep.XmlResolver = null;
prep.SchemaLocations = new Hashtable();
prep.ChameleonSchemas = new Hashtable();
foreach (XmlSchema schema in SchemaSet.Schemas())
{
prep.Execute(schema, schema.TargetNamespace, true);
}
}
catch (XmlSchemaException e)
{
throw CreateValidationException(e, e.Message);
}
}
}
internal static Exception CreateValidationException(XmlSchemaException exception, string message)
{
XmlSchemaObject source = exception.SourceSchemaObject;
if (exception.LineNumber == 0 && exception.LinePosition == 0)
{
throw new InvalidOperationException(GetSchemaItem(source, null, message), exception);
}
else
{
string ns = null;
if (source != null)
{
while (source.Parent != null)
{
source = source.Parent;
}
if (source is XmlSchema)
{
ns = ((XmlSchema)source).TargetNamespace;
}
}
throw new InvalidOperationException(SR.Format(SR.XmlSchemaSyntaxErrorDetails, ns, message, exception.LineNumber, exception.LinePosition), exception);
}
}
internal static void IgnoreCompileErrors(object sender, ValidationEventArgs args)
{
return;
}
internal static XmlSchema XsdSchema
{
get
{
if (s_xsd == null)
{
s_xsd = CreateFakeXsdSchema(XmlSchema.Namespace, "schema");
}
return s_xsd;
}
}
internal static XmlSchema XmlSchema
{
get
{
if (s_xml == null)
{
s_xml = XmlSchema.Read(new StringReader(xmlSchema), null);
}
return s_xml;
}
}
private static XmlSchema CreateFakeXsdSchema(string ns, string name)
{
/* Create fake xsd schema to fool the XmlSchema.Compiler
<xsd:schema targetNamespace="http://www.w3.org/2001/XMLSchema" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="schema">
<xsd:complexType />
</xsd:element>
</xsd:schema>
*/
XmlSchema schema = new XmlSchema();
schema.TargetNamespace = ns;
XmlSchemaElement element = new XmlSchemaElement();
element.Name = name;
XmlSchemaComplexType type = new XmlSchemaComplexType();
element.SchemaType = type;
schema.Items.Add(element);
return schema;
}
internal void SetCache(SchemaObjectCache cache, bool shareTypes)
{
_shareTypes = shareTypes;
_cache = cache;
if (shareTypes)
{
cache.GenerateSchemaGraph(this);
}
}
internal bool IsReference(XmlSchemaObject type)
{
XmlSchemaObject parent = type;
while (parent.Parent != null)
{
parent = parent.Parent;
}
return References.Contains(parent);
}
internal const string xmlSchema = @"<?xml version='1.0' encoding='UTF-8' ?>
<xs:schema targetNamespace='http://www.w3.org/XML/1998/namespace' xmlns:xs='http://www.w3.org/2001/XMLSchema' xml:lang='en'>
<xs:attribute name='lang' type='xs:language'/>
<xs:attribute name='space'>
<xs:simpleType>
<xs:restriction base='xs:NCName'>
<xs:enumeration value='default'/>
<xs:enumeration value='preserve'/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name='base' type='xs:anyURI'/>
<xs:attribute name='id' type='xs:ID' />
<xs:attributeGroup name='specialAttrs'>
<xs:attribute ref='xml:base'/>
<xs:attribute ref='xml:lang'/>
<xs:attribute ref='xml:space'/>
</xs:attributeGroup>
</xs:schema>";
}
public class XmlSchemaEnumerator : IEnumerator<XmlSchema>, System.Collections.IEnumerator
{
private readonly XmlSchemas _list;
private int _idx;
private readonly int _end;
public XmlSchemaEnumerator(XmlSchemas list)
{
_list = list;
_idx = -1;
_end = list.Count - 1;
}
public void Dispose()
{
}
public bool MoveNext()
{
if (_idx >= _end)
return false;
_idx++;
return true;
}
public XmlSchema Current
{
get { return _list[_idx]; }
}
object System.Collections.IEnumerator.Current
{
get { return _list[_idx]; }
}
void System.Collections.IEnumerator.Reset()
{
_idx = -1;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace Massive {
public static class ObjectExtensions {
/// <summary>
/// Extension method for adding a bunch of parameters
/// </summary>
public static void AddParams(this DbCommand cmd, params object[] args) {
foreach (var item in args) {
AddParam(cmd, item);
}
}
/// <summary>
/// Extension for adding a single parameter
/// </summary>
public static void AddParam(this DbCommand cmd, object item) {
var p = cmd.CreateParameter();
p.ParameterName = string.Format("@{0}", cmd.Parameters.Count);
if (item == null) {
p.Value = DBNull.Value;
} else {
if (item is Guid) {
p.Value = item.ToString();
p.DbType = DbType.String;
p.Size = 4000;
} else if (item is ExpandoObject) {
var d = (IDictionary<string, object>)item;
p.Value = d.Values.FirstOrDefault();
} else {
p.Value = item;
}
if (item is string)
p.Size = ((string)item).Length > 4000 ? -1 : 4000;
}
cmd.Parameters.Add(p);
}
/// <summary>
/// Turns an IDataReader into a dynamic list of expando objects
/// </summary>
public static List<dynamic> ToExpandoList(this IDataReader rdr) {
var result = new List<dynamic>();
while (rdr.Read()) {
result.Add(rdr.RecordToExpando());
}
return result;
}
public static dynamic RecordToExpando(this IDataReader rdr) {
dynamic e = new ExpandoObject();
var d = e as IDictionary<string, object>;
for (var i = 0; i < rdr.FieldCount; i++)
d.Add(rdr.GetName(i), DBNull.Value.Equals(rdr[i]) ? null : rdr[i]);
return e;
}
/// <summary>
/// Turns an object into an ExpandoObject
/// </summary>
public static dynamic ToExpando(this object o) {
var result = new ExpandoObject();
var properties = result as IDictionary<string, object>;
if (o is ExpandoObject)
return o; //shouldn't have to... but just in case
if (o.GetType() == typeof(NameValueCollection) || o.GetType().IsSubclassOf(typeof(NameValueCollection))) {
var nv = (NameValueCollection)o;
nv.Cast<string>().Select(key => new KeyValuePair<string, object>(key, nv[key])).ToList().ForEach(properties.Add);
} else {
var props = o.GetType().GetProperties();
foreach (var item in props) {
properties.Add(item.Name, item.GetValue(o, null));
}
}
return result;
}
/// <summary>
/// Turns an object into a Dictionary
/// </summary>
public static IDictionary<string, object> ToDictionary(this object thingy) {
return (IDictionary<string, object>)thingy.ToExpando();
}
}
/// <summary>
/// A class that wraps your database table in Dynamic Funtime
/// </summary>
public class DynamicModel : DynamicObject {
const string ProviderName = "MySql.Data.MySqlClient";
private readonly DbProviderFactory _factory;
private readonly string _connectionString;
public static DynamicModel Open(string connectionStringName) {
dynamic dm = new DynamicModel(connectionStringName);
return dm;
}
/// <summary>
/// Create a dynamic model
/// </summary>
/// <param name="connectionStringName">the connection string name or the connection stirng itself</param>
/// <param name="tableName">the table name</param>
/// <param name="primaryKeyField">the primary key field name</param>
public DynamicModel(string connectionStringName, string tableName = "", string primaryKeyField = "") {
TableName = string.IsNullOrEmpty(tableName) ? GetType().Name : tableName;
PrimaryKeyField = string.IsNullOrEmpty(primaryKeyField) ? "ID" : primaryKeyField;
try
{
_factory = DbProviderFactories.GetFactory(ProviderName);
} catch(FileLoadException ex)
{
throw new MassiveException(string.Format("Could not load the specified provider: {0}. Have you added a reference to the correct assembly?", ProviderName), ex);
}
var conString = ConfigurationManager.ConnectionStrings[connectionStringName];
_connectionString = conString != null ? conString.ConnectionString : connectionStringName;
}
/// <summary>
/// Creates a new Expando from a Form POST - white listed against the columns in the DB
/// </summary>
public dynamic CreateFrom(NameValueCollection coll) {
dynamic result = new ExpandoObject();
var dc = (IDictionary<string, object>)result;
var schema = Schema;
foreach (var item in coll.Keys) {
var exists = schema.Any(x => x.COLUMN_NAME.ToLower() == item.ToString().ToLower());
if (exists) {
var key = item.ToString();
var val = coll[key];
if (!String.IsNullOrEmpty(val)) {
//what to do here? If it's empty... set it to NULL?
//if it's a string value - let it go through if it's NULLABLE?
//Empty? WTF?
dc.Add(key, val);
}
}
}
return result;
}
/// <summary>
/// Gets a default value for the column
/// </summary>
public dynamic DefaultValue(dynamic column) {
dynamic result;
var defaultValue = column.COLUMN_DEFAULT;
if (string.IsNullOrEmpty(defaultValue)) {
result = null;
} else if (defaultValue == "getdate()" || defaultValue == "(getdate())") {
result = DateTime.Now.ToShortDateString();
} else if (defaultValue == "newid()") {
result = Guid.NewGuid().ToString();
} else {
result = defaultValue.Replace("(", "").Replace(")", "");
}
return result;
}
/// <summary>
/// Creates an empty Expando set with defaults from the DB
/// </summary>
public dynamic Prototype {
get {
dynamic result = new ExpandoObject();
var schema = Schema;
foreach (var column in schema) {
var dc = (IDictionary<string, object>)result;
dc.Add(column.COLUMN_NAME, DefaultValue(column));
}
result._Table = this;
return result;
}
}
/// <summary>
/// List out all the schema bits for use with ... whatever
/// </summary>
IEnumerable<dynamic> _schema;
public IEnumerable<dynamic> Schema {
get {
return _schema ??
(_schema = Query("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @0", TableName));
}
}
/// <summary>
/// Enumerates the reader yielding the result - thanks to Jeroen Haegebaert
/// </summary>
public virtual object QueryScalar(string sql, params object[] args) {
using (var conn = OpenConnection()) {
var rdr = CreateCommand(sql, conn, args).ExecuteScalar();
return rdr;
}
}
/// <summary>
/// Enumerates the reader yielding the result - thanks to Jeroen Haegebaert
/// </summary>
public virtual IEnumerable<dynamic> Query(string sql, params object[] args) {
using (var conn = OpenConnection()) {
var rdr = CreateCommand(sql, conn, args).ExecuteReader();
while (rdr.Read()) {
yield return rdr.RecordToExpando();
}
}
}
/// <summary>
/// Executes the reader using SQL async API - thanks to Damian Edwards
/// </summary>
public void QueryAsync(string sql, Action<List<dynamic>> callback, params object[] args) {
using (var conn = new SqlConnection(_connectionString)) {
var cmd = new SqlCommand(sql, conn);
cmd.AddParams(args);
conn.Open();
var task = Task.Factory.FromAsync<IDataReader>(cmd.BeginExecuteReader, cmd.EndExecuteReader, null);
task.ContinueWith(x => callback.Invoke(x.Result.ToExpandoList()));
}
}
public virtual IEnumerable<dynamic> Query(string sql, DbConnection connection, params object[] args) {
using (var rdr = CreateCommand(sql, connection, args).ExecuteReader()) {
while (rdr.Read()) {
yield return rdr.RecordToExpando();
}
}
}
/// <summary>
/// Returns a single result
/// </summary>
public virtual object Scalar(string sql, params object[] args) {
object result;
using (var conn = OpenConnection()) {
result = CreateCommand(sql, conn, args).ExecuteScalar();
}
return result;
}
/// <summary>
/// Creates a DBCommand that you can use for loving your database.
/// </summary>
private DbCommand CreateCommand(string sql, DbConnection conn, params object[] args) {
using(var result = _factory.CreateCommand())
{
result.Connection = conn;
result.CommandText = sql;
if (args.Length > 0)
result.AddParams(args);
return result;
}
}
/// <summary>
/// Returns and OpenConnection
/// </summary>
public virtual DbConnection OpenConnection() {
var result = _factory.CreateConnection();
result.ConnectionString = _connectionString;
result.Open();
return result;
}
/// <summary>
/// Builds a set of Insert and Update commands based on the passed-on objects.
/// These objects can be POCOs, Anonymous, NameValueCollections, or Expandos. Objects
/// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs
/// </summary>
public virtual List<DbCommand> BuildCommands(params object[] things) {
var commands = new List<DbCommand>();
foreach (var item in things) {
if (HasPrimaryKey(item)) {
commands.Add(CreateUpdateCommand(item, GetPrimaryKey(item)));
} else {
commands.Add(CreateInsertCommand(item));
}
}
return commands;
}
/// <summary>
/// Executes a set of objects as Insert or Update commands based on their property settings, within a transaction.
/// These objects can be POCOs, Anonymous, NameValueCollections, or Expandos. Objects
/// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs
/// </summary>
public virtual int Save(params object[] things) {
var commands = BuildCommands(things);
return Execute(commands);
}
/// <summary>
/// Execute a single command
/// </summary>
public virtual int Execute(DbCommand command) {
return Execute(new[] { command });
}
public virtual int Execute(string sql, params object[] args) {
return Execute(CreateCommand(sql, null, args));
}
/// <summary>
/// Executes a series of DBCommands in a transaction
/// </summary>
public virtual int Execute(IEnumerable<DbCommand> commands) {
var result = 0;
using (var conn = OpenConnection()) {
using (var tx = conn.BeginTransaction()) {
foreach (var cmd in commands) {
cmd.Connection = conn;
cmd.Transaction = tx;
result += cmd.ExecuteNonQuery();
}
tx.Commit();
}
}
return result;
}
public virtual string PrimaryKeyField { get; set; }
/// <summary>
/// Conventionally introspects the object passed in for a field that
/// looks like a PK. If you've named your PrimaryKeyField, this becomes easy
/// </summary>
public virtual bool HasPrimaryKey(object o) {
return o.ToDictionary().ContainsKey(PrimaryKeyField);
}
/// <summary>
/// If the object passed in has a property with the same name as your PrimaryKeyField
/// it is returned here.
/// </summary>
public virtual object GetPrimaryKey(object o) {
object result;
o.ToDictionary().TryGetValue(PrimaryKeyField, out result);
return result;
}
public virtual string TableName { get; set; }
/// <summary>
/// Creates a command for use with transactions - internal stuff mostly, but here for you to play with
/// </summary>
public virtual DbCommand CreateInsertCommand(object o) {
var expando = o.ToExpando();
var settings = (IDictionary<string, object>)expando;
var sbKeys = new StringBuilder();
var sbVals = new StringBuilder();
var stub = "INSERT INTO {0} ({1}) \r\n VALUES ({2})";
var result = CreateCommand(stub, null);
var counter = 0;
foreach (var item in settings) {
sbKeys.AppendFormat("{0},", item.Key);
sbVals.AppendFormat("@{0},", counter);
result.AddParam(item.Value);
counter++;
}
if (counter > 0) {
var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 1);
var values = sbVals.ToString().Substring(0, sbVals.Length - 1);
var sql = string.Format(stub, TableName, keys, values);
result.CommandText = sql;
} else {
throw new InvalidOperationException("Can't parse this object to the database - there are no properties set");
}
return result;
}
/// <summary>
/// Creates a command for use with transactions - internal stuff mostly, but here for you to play with
/// </summary>
public virtual DbCommand CreateUpdateCommand(object o, object key) {
var expando = o.ToExpando();
var settings = (IDictionary<string, object>)expando;
var sbKeys = new StringBuilder();
var stub = "UPDATE {0} SET {1} WHERE {2} = @{3}";
var result = CreateCommand(stub, null);
var counter = 0;
foreach (var item in settings) {
var val = item.Value;
if (!item.Key.Equals(PrimaryKeyField, StringComparison.CurrentCultureIgnoreCase) && item.Value != null) {
result.AddParam(val);
sbKeys.AppendFormat("{0} = @{1}, \r\n", item.Key, counter);
counter++;
}
}
if (counter > 0) {
result.AddParam(key);
var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 4);//strip the last commas
result.CommandText = string.Format(stub, TableName, keys, PrimaryKeyField, counter);
} else {
throw new InvalidOperationException("No parsable object was sent in - could not divine any name/value pairs");
}
return result;
}
/// <summary>
/// Removes one or more records from the DB according to the passed-in WHERE
/// </summary>
public virtual DbCommand CreateDeleteCommand(string where = "", object key = null, params object[] args) {
var sql = string.Format("DELETE FROM {0} ", TableName);
if (key != null) {
sql += string.Format("WHERE {0}=@0", PrimaryKeyField);
args = new[] { key };
} else if (!string.IsNullOrEmpty(where)) {
sql += where.Trim().StartsWith("where", StringComparison.CurrentCultureIgnoreCase) ? where : "WHERE " + where;
}
return CreateCommand(sql, null, args);
}
/// <summary>
/// Adds a record to the database. You can pass in an Anonymous object, an ExpandoObject,
/// A regular old POCO, or a NameValueColletion from a Request.Form or Request.QueryString
/// </summary>
public virtual object Insert(object o) {
dynamic result = 0;
using (var conn = OpenConnection()) {
var cmd = CreateInsertCommand(o);
cmd.Connection = conn;
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT @@IDENTITY as newID";
result = cmd.ExecuteScalar();
}
return result;
}
/// <summary>
/// Updates a record in the database. You can pass in an Anonymous object, an ExpandoObject,
/// A regular old POCO, or a NameValueCollection from a Request.Form or Request.QueryString
/// </summary>
public virtual int Update(object o, object key) {
return Execute(CreateUpdateCommand(o, key));
}
/// <summary>
/// Removes one or more records from the DB according to the passed-in WHERE
/// </summary>
public int Delete(object key = null, string where = "", params object[] args) {
return Execute(CreateDeleteCommand(where: where, key: key, args: args));
}
/// <summary>
/// Returns all records complying with the passed-in WHERE clause and arguments,
/// ordered as specified, limited (TOP) by limit.
/// </summary>
public virtual IEnumerable<dynamic> All(string where = "", string orderBy = "", int limit = 0, string columns = "*", params object[] args) {
string sql = BuildSelect(where, orderBy, limit);
return Query(string.Format(sql, columns, TableName), args);
}
/// <summary>
/// Returns the count from this table, using optional where statement
/// </summary>
/// <param name="where">query parameters (eg: "id>=100")</param>
/// <param name="args"></param>
/// <returns></returns>
public int Count(string where = "", params object[] args)
{
var sql = BuildCount(where);
var ob = QueryScalar(string.Format(sql, TableName), args);
return int.Parse(ob.ToString());
}
private static string BuildCount(string where)
{
var sql = "SELECT Count(*) FROM {0} " ;
if (!string.IsNullOrEmpty(where))
sql += where.Trim().StartsWith("where", StringComparison.CurrentCultureIgnoreCase) ? where : "WHERE " + where;
return sql;
}
private static string BuildSelect(string where, string orderBy, int limit) {
var sql = "SELECT {0} FROM {1} ";
if (!string.IsNullOrEmpty(where))
sql += where.Trim().StartsWith("where", StringComparison.CurrentCultureIgnoreCase) ? where : "WHERE " + where;
if (!string.IsNullOrEmpty(orderBy))
sql += orderBy.Trim().StartsWith("order by", StringComparison.CurrentCultureIgnoreCase) ? orderBy : " ORDER BY " + orderBy;
if (limit > 0)
sql += " LIMIT " + limit;
return sql;
}
/// <summary>
/// Returns all records complying with the passed-in WHERE clause and arguments,
/// ordered as specified, limited (TOP) by limit.
/// </summary>
public virtual void AllAsync(Action<List<dynamic>> callback, string where = "", string orderBy = "", int limit = 0, string columns = "*", params object[] args) {
var sql = BuildSelect(where, orderBy, limit);
QueryAsync(string.Format(sql, columns, TableName), callback, args);
}
/// <summary>
/// Returns a dynamic PagedResult. Result properties are Items, TotalPages, and TotalRecords.
/// </summary>
public virtual dynamic Paged(string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args) {
dynamic result = new ExpandoObject();
var countQuery = string.Format("SELECT COUNT({0}) FROM {1}", PrimaryKeyField, TableName);
if (string.IsNullOrEmpty(orderBy))
orderBy = PrimaryKeyField;
if (!string.IsNullOrEmpty(where)) {
if (!where.Trim().StartsWith("where", StringComparison.CurrentCultureIgnoreCase)) {
where = "WHERE " + where;
}
}
var sql = string.Format("SELECT {0} FROM (SELECT ROW_NUMBER() OVER (ORDER BY {2}) AS Row, {0} FROM {3} {4}) AS Paged ", columns, pageSize, orderBy, TableName, where);
var pageStart = (currentPage - 1) * pageSize;
sql += string.Format(" WHERE Row > {0} AND Row <={1}", pageStart, (pageStart + pageSize));
countQuery += where;
result.TotalRecords = Scalar(countQuery, args);
result.TotalPages = result.TotalRecords / pageSize;
if (result.TotalRecords % pageSize > 0)
result.TotalPages += 1;
result.Items = Query(string.Format(sql, columns, TableName), args);
return result;
}
/// <summary>
/// Returns a single row from the database
/// </summary>
public virtual dynamic Single(string where, params object[] args) {
var sql = string.Format("SELECT * FROM {0} WHERE {1}", TableName, where);
return Query(sql, args).FirstOrDefault();
}
/// <summary>
/// Returns a single row from the database
/// </summary>
public virtual dynamic Single(object key, string columns = "*") {
var sql = string.Format("SELECT {0} FROM {1} WHERE {2} = @0", columns, TableName, PrimaryKeyField);
return Query(sql, key).FirstOrDefault();
}
/// <summary>
/// A helpful query tool
/// </summary>
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) {
//parse the method
var constraints = new List<string>();
var counter = 0;
var info = binder.CallInfo;
// accepting named args only... SKEET!
if (info.ArgumentNames.Count != args.Length) {
throw new InvalidOperationException("Please use named arguments for this type of query - the column name, orderby, columns, etc");
}
//first should be "FindBy, Last, Single, First"
var op = binder.Name;
var columns = " * ";
var orderBy = string.Format(" ORDER BY {0}", PrimaryKeyField);
var where = "";
var whereArgs = new List<object>();
//loop the named args - see if we have order, columns and constraints
if (info.ArgumentNames.Count > 0) {
for (var i = 0; i < args.Length; i++) {
var name = info.ArgumentNames[i].ToLower();
switch (name) {
case "orderby":
orderBy = " ORDER BY " + args[i];
break;
case "columns":
columns = args[i].ToString();
break;
default:
constraints.Add(string.Format(" {0} = @{1}", name, counter));
whereArgs.Add(args[i]);
counter++;
break;
}
}
}
if (constraints.Count > 0) {
where = " WHERE " + string.Join(" AND ", constraints.ToArray());
}
var sql = "SELECT TOP 1 " + columns + " FROM " + TableName + where;
var singleResult = op.StartsWith("First") || op.StartsWith("Last") || op.StartsWith("Get");
//Be sure to sort by DESC on the PK (PK Sort is the default)
if (op.StartsWith("Last")) {
orderBy = orderBy + " DESC ";
} else {
//default to multiple
sql = "SELECT " + columns + " FROM " + TableName + where;
}
result = singleResult ? Query(sql + orderBy, whereArgs.ToArray()).FirstOrDefault() :
Query(sql + orderBy, whereArgs.ToArray());
return true;
}
internal class MassiveException : Exception
{
public MassiveException(string message, Exception innerException = null) : base(message, innerException)
{
}
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.IO;
using Mono.Cecil.Metadata;
using RVA = System.UInt32;
namespace Mono.Cecil.PE {
sealed class ImageReader : BinaryStreamReader {
readonly Image image;
DataDirectory cli;
DataDirectory metadata;
uint table_heap_offset;
public ImageReader (Disposable<Stream> stream, string file_name)
: base (stream.value)
{
image = new Image ();
image.Stream = stream;
image.FileName = file_name;
}
void MoveTo (DataDirectory directory)
{
BaseStream.Position = image.ResolveVirtualAddress (directory.VirtualAddress);
}
void ReadImage ()
{
if (BaseStream.Length < 128)
throw new BadImageFormatException ();
// - DOSHeader
// PE 2
// Start 58
// Lfanew 4
// End 64
if (ReadUInt16 () != 0x5a4d)
throw new BadImageFormatException ();
Advance (58);
MoveTo (ReadUInt32 ());
if (ReadUInt32 () != 0x00004550)
throw new BadImageFormatException ();
// - PEFileHeader
// Machine 2
image.Architecture = ReadArchitecture ();
// NumberOfSections 2
ushort sections = ReadUInt16 ();
// TimeDateStamp 4
// PointerToSymbolTable 4
// NumberOfSymbols 4
// OptionalHeaderSize 2
Advance (14);
// Characteristics 2
ushort characteristics = ReadUInt16 ();
ushort subsystem, dll_characteristics;
ReadOptionalHeaders (out subsystem, out dll_characteristics);
ReadSections (sections);
ReadCLIHeader ();
ReadMetadata ();
image.Kind = GetModuleKind (characteristics, subsystem);
image.Characteristics = (ModuleCharacteristics) dll_characteristics;
}
TargetArchitecture ReadArchitecture ()
{
var machine = ReadUInt16 ();
switch (machine) {
case 0x014c:
return TargetArchitecture.I386;
case 0x8664:
return TargetArchitecture.AMD64;
case 0x0200:
return TargetArchitecture.IA64;
case 0x01c4:
return TargetArchitecture.ARMv7;
}
throw new NotSupportedException ();
}
static ModuleKind GetModuleKind (ushort characteristics, ushort subsystem)
{
if ((characteristics & 0x2000) != 0) // ImageCharacteristics.Dll
return ModuleKind.Dll;
if (subsystem == 0x2 || subsystem == 0x9) // SubSystem.WindowsGui || SubSystem.WindowsCeGui
return ModuleKind.Windows;
return ModuleKind.Console;
}
void ReadOptionalHeaders (out ushort subsystem, out ushort dll_characteristics)
{
// - PEOptionalHeader
// - StandardFieldsHeader
// Magic 2
bool pe64 = ReadUInt16 () == 0x20b;
// pe32 || pe64
// LMajor 1
// LMinor 1
// CodeSize 4
// InitializedDataSize 4
// UninitializedDataSize4
// EntryPointRVA 4
// BaseOfCode 4
// BaseOfData 4 || 0
// - NTSpecificFieldsHeader
// ImageBase 4 || 8
// SectionAlignment 4
// FileAlignement 4
// OSMajor 2
// OSMinor 2
// UserMajor 2
// UserMinor 2
// SubSysMajor 2
// SubSysMinor 2
// Reserved 4
// ImageSize 4
// HeaderSize 4
// FileChecksum 4
Advance (66);
// SubSystem 2
subsystem = ReadUInt16 ();
// DLLFlags 2
dll_characteristics = ReadUInt16 ();
// StackReserveSize 4 || 8
// StackCommitSize 4 || 8
// HeapReserveSize 4 || 8
// HeapCommitSize 4 || 8
// LoaderFlags 4
// NumberOfDataDir 4
// - DataDirectoriesHeader
// ExportTable 8
// ImportTable 8
// ResourceTable 8
// ExceptionTable 8
// CertificateTable 8
// BaseRelocationTable 8
Advance (pe64 ? 88 : 72);
// Debug 8
image.Debug = ReadDataDirectory ();
// Copyright 8
// GlobalPtr 8
// TLSTable 8
// LoadConfigTable 8
// BoundImport 8
// IAT 8
// DelayImportDescriptor8
Advance (56);
// CLIHeader 8
cli = ReadDataDirectory ();
if (cli.IsZero)
throw new BadImageFormatException ();
// Reserved 8
Advance (8);
}
string ReadAlignedString (int length)
{
int read = 0;
var buffer = new char [length];
while (read < length) {
var current = ReadByte ();
if (current == 0)
break;
buffer [read++] = (char) current;
}
Advance (-1 + ((read + 4) & ~3) - read);
return new string (buffer, 0, read);
}
string ReadZeroTerminatedString (int length)
{
int read = 0;
var buffer = new char [length];
var bytes = ReadBytes (length);
while (read < length) {
var current = bytes [read];
if (current == 0)
break;
buffer [read++] = (char) current;
}
return new string (buffer, 0, read);
}
void ReadSections (ushort count)
{
var sections = new Section [count];
for (int i = 0; i < count; i++) {
var section = new Section ();
// Name
section.Name = ReadZeroTerminatedString (8);
// VirtualSize 4
Advance (4);
// VirtualAddress 4
section.VirtualAddress = ReadUInt32 ();
// SizeOfRawData 4
section.SizeOfRawData = ReadUInt32 ();
// PointerToRawData 4
section.PointerToRawData = ReadUInt32 ();
// PointerToRelocations 4
// PointerToLineNumbers 4
// NumberOfRelocations 2
// NumberOfLineNumbers 2
// Characteristics 4
Advance (16);
sections [i] = section;
}
image.Sections = sections;
}
void ReadCLIHeader ()
{
MoveTo (cli);
// - CLIHeader
// Cb 4
// MajorRuntimeVersion 2
// MinorRuntimeVersion 2
Advance (8);
// Metadata 8
metadata = ReadDataDirectory ();
// Flags 4
image.Attributes = (ModuleAttributes) ReadUInt32 ();
// EntryPointToken 4
image.EntryPointToken = ReadUInt32 ();
// Resources 8
image.Resources = ReadDataDirectory ();
// StrongNameSignature 8
image.StrongName = ReadDataDirectory ();
// CodeManagerTable 8
// VTableFixups 8
// ExportAddressTableJumps 8
// ManagedNativeHeader 8
}
void ReadMetadata ()
{
MoveTo (metadata);
if (ReadUInt32 () != 0x424a5342)
throw new BadImageFormatException ();
// MajorVersion 2
// MinorVersion 2
// Reserved 4
Advance (8);
image.RuntimeVersion = ReadZeroTerminatedString (ReadInt32 ());
// Flags 2
Advance (2);
var streams = ReadUInt16 ();
var section = image.GetSectionAtVirtualAddress (metadata.VirtualAddress);
if (section == null)
throw new BadImageFormatException ();
image.MetadataSection = section;
for (int i = 0; i < streams; i++)
ReadMetadataStream (section);
if (image.TableHeap != null)
ReadTableHeap ();
if (image.PdbHeap != null)
ReadPdbHeap ();
}
void ReadMetadataStream (Section section)
{
// Offset 4
uint offset = metadata.VirtualAddress - section.VirtualAddress + ReadUInt32 (); // relative to the section start
// Size 4
uint size = ReadUInt32 ();
var data = ReadHeapData (offset, size);
var name = ReadAlignedString (16);
switch (name) {
case "#~":
case "#-":
image.TableHeap = new TableHeap (data);
table_heap_offset = offset;
break;
case "#Strings":
image.StringHeap = new StringHeap (data);
break;
case "#Blob":
image.BlobHeap = new BlobHeap (data);
break;
case "#GUID":
image.GuidHeap = new GuidHeap (data);
break;
case "#US":
image.UserStringHeap = new UserStringHeap (data);
break;
case "#Pdb":
image.PdbHeap = new PdbHeap (data);
break;
}
}
byte [] ReadHeapData (uint offset, uint size)
{
var position = BaseStream.Position;
MoveTo (offset + image.MetadataSection.PointerToRawData);
var data = ReadBytes ((int) size);
BaseStream.Position = position;
return data;
}
void ReadTableHeap ()
{
var heap = image.TableHeap;
MoveTo (table_heap_offset + image.MetadataSection.PointerToRawData);
// Reserved 4
// MajorVersion 1
// MinorVersion 1
Advance (6);
// HeapSizes 1
var sizes = ReadByte ();
// Reserved2 1
Advance (1);
// Valid 8
heap.Valid = ReadInt64 ();
// Sorted 8
heap.Sorted = ReadInt64 ();
for (int i = 0; i < Mixin.TableCount; i++) {
if (!heap.HasTable ((Table) i))
continue;
heap.Tables [i].Length = ReadUInt32 ();
}
SetIndexSize (image.StringHeap, sizes, 0x1);
SetIndexSize (image.GuidHeap, sizes, 0x2);
SetIndexSize (image.BlobHeap, sizes, 0x4);
ComputeTableInformations ();
}
static void SetIndexSize (Heap heap, uint sizes, byte flag)
{
if (heap == null)
return;
heap.IndexSize = (sizes & flag) > 0 ? 4 : 2;
}
int GetTableIndexSize (Table table)
{
return image.GetTableIndexSize (table);
}
int GetCodedIndexSize (CodedIndex index)
{
return image.GetCodedIndexSize (index);
}
void ComputeTableInformations ()
{
uint offset = (uint) BaseStream.Position - table_heap_offset - image.MetadataSection.PointerToRawData; // header
int stridx_size = image.StringHeap.IndexSize;
int guididx_size = image.GuidHeap.IndexSize;
int blobidx_size = image.BlobHeap != null ? image.BlobHeap.IndexSize : 2;
var heap = image.TableHeap;
var tables = heap.Tables;
for (int i = 0; i < Mixin.TableCount; i++) {
var table = (Table) i;
if (!heap.HasTable (table))
continue;
int size;
switch (table) {
case Table.Module:
size = 2 // Generation
+ stridx_size // Name
+ (guididx_size * 3); // Mvid, EncId, EncBaseId
break;
case Table.TypeRef:
size = GetCodedIndexSize (CodedIndex.ResolutionScope) // ResolutionScope
+ (stridx_size * 2); // Name, Namespace
break;
case Table.TypeDef:
size = 4 // Flags
+ (stridx_size * 2) // Name, Namespace
+ GetCodedIndexSize (CodedIndex.TypeDefOrRef) // BaseType
+ GetTableIndexSize (Table.Field) // FieldList
+ GetTableIndexSize (Table.Method); // MethodList
break;
case Table.FieldPtr:
size = GetTableIndexSize (Table.Field); // Field
break;
case Table.Field:
size = 2 // Flags
+ stridx_size // Name
+ blobidx_size; // Signature
break;
case Table.MethodPtr:
size = GetTableIndexSize (Table.Method); // Method
break;
case Table.Method:
size = 8 // Rva 4, ImplFlags 2, Flags 2
+ stridx_size // Name
+ blobidx_size // Signature
+ GetTableIndexSize (Table.Param); // ParamList
break;
case Table.ParamPtr:
size = GetTableIndexSize (Table.Param); // Param
break;
case Table.Param:
size = 4 // Flags 2, Sequence 2
+ stridx_size; // Name
break;
case Table.InterfaceImpl:
size = GetTableIndexSize (Table.TypeDef) // Class
+ GetCodedIndexSize (CodedIndex.TypeDefOrRef); // Interface
break;
case Table.MemberRef:
size = GetCodedIndexSize (CodedIndex.MemberRefParent) // Class
+ stridx_size // Name
+ blobidx_size; // Signature
break;
case Table.Constant:
size = 2 // Type
+ GetCodedIndexSize (CodedIndex.HasConstant) // Parent
+ blobidx_size; // Value
break;
case Table.CustomAttribute:
size = GetCodedIndexSize (CodedIndex.HasCustomAttribute) // Parent
+ GetCodedIndexSize (CodedIndex.CustomAttributeType) // Type
+ blobidx_size; // Value
break;
case Table.FieldMarshal:
size = GetCodedIndexSize (CodedIndex.HasFieldMarshal) // Parent
+ blobidx_size; // NativeType
break;
case Table.DeclSecurity:
size = 2 // Action
+ GetCodedIndexSize (CodedIndex.HasDeclSecurity) // Parent
+ blobidx_size; // PermissionSet
break;
case Table.ClassLayout:
size = 6 // PackingSize 2, ClassSize 4
+ GetTableIndexSize (Table.TypeDef); // Parent
break;
case Table.FieldLayout:
size = 4 // Offset
+ GetTableIndexSize (Table.Field); // Field
break;
case Table.StandAloneSig:
size = blobidx_size; // Signature
break;
case Table.EventMap:
size = GetTableIndexSize (Table.TypeDef) // Parent
+ GetTableIndexSize (Table.Event); // EventList
break;
case Table.EventPtr:
size = GetTableIndexSize (Table.Event); // Event
break;
case Table.Event:
size = 2 // Flags
+ stridx_size // Name
+ GetCodedIndexSize (CodedIndex.TypeDefOrRef); // EventType
break;
case Table.PropertyMap:
size = GetTableIndexSize (Table.TypeDef) // Parent
+ GetTableIndexSize (Table.Property); // PropertyList
break;
case Table.PropertyPtr:
size = GetTableIndexSize (Table.Property); // Property
break;
case Table.Property:
size = 2 // Flags
+ stridx_size // Name
+ blobidx_size; // Type
break;
case Table.MethodSemantics:
size = 2 // Semantics
+ GetTableIndexSize (Table.Method) // Method
+ GetCodedIndexSize (CodedIndex.HasSemantics); // Association
break;
case Table.MethodImpl:
size = GetTableIndexSize (Table.TypeDef) // Class
+ GetCodedIndexSize (CodedIndex.MethodDefOrRef) // MethodBody
+ GetCodedIndexSize (CodedIndex.MethodDefOrRef); // MethodDeclaration
break;
case Table.ModuleRef:
size = stridx_size; // Name
break;
case Table.TypeSpec:
size = blobidx_size; // Signature
break;
case Table.ImplMap:
size = 2 // MappingFlags
+ GetCodedIndexSize (CodedIndex.MemberForwarded) // MemberForwarded
+ stridx_size // ImportName
+ GetTableIndexSize (Table.ModuleRef); // ImportScope
break;
case Table.FieldRVA:
size = 4 // RVA
+ GetTableIndexSize (Table.Field); // Field
break;
case Table.EncLog:
size = 8;
break;
case Table.EncMap:
size = 4;
break;
case Table.Assembly:
size = 16 // HashAlgId 4, Version 4 * 2, Flags 4
+ blobidx_size // PublicKey
+ (stridx_size * 2); // Name, Culture
break;
case Table.AssemblyProcessor:
size = 4; // Processor
break;
case Table.AssemblyOS:
size = 12; // Platform 4, Version 2 * 4
break;
case Table.AssemblyRef:
size = 12 // Version 2 * 4 + Flags 4
+ (blobidx_size * 2) // PublicKeyOrToken, HashValue
+ (stridx_size * 2); // Name, Culture
break;
case Table.AssemblyRefProcessor:
size = 4 // Processor
+ GetTableIndexSize (Table.AssemblyRef); // AssemblyRef
break;
case Table.AssemblyRefOS:
size = 12 // Platform 4, Version 2 * 4
+ GetTableIndexSize (Table.AssemblyRef); // AssemblyRef
break;
case Table.File:
size = 4 // Flags
+ stridx_size // Name
+ blobidx_size; // HashValue
break;
case Table.ExportedType:
size = 8 // Flags 4, TypeDefId 4
+ (stridx_size * 2) // Name, Namespace
+ GetCodedIndexSize (CodedIndex.Implementation); // Implementation
break;
case Table.ManifestResource:
size = 8 // Offset, Flags
+ stridx_size // Name
+ GetCodedIndexSize (CodedIndex.Implementation); // Implementation
break;
case Table.NestedClass:
size = GetTableIndexSize (Table.TypeDef) // NestedClass
+ GetTableIndexSize (Table.TypeDef); // EnclosingClass
break;
case Table.GenericParam:
size = 4 // Number, Flags
+ GetCodedIndexSize (CodedIndex.TypeOrMethodDef) // Owner
+ stridx_size; // Name
break;
case Table.MethodSpec:
size = GetCodedIndexSize (CodedIndex.MethodDefOrRef) // Method
+ blobidx_size; // Instantiation
break;
case Table.GenericParamConstraint:
size = GetTableIndexSize (Table.GenericParam) // Owner
+ GetCodedIndexSize (CodedIndex.TypeDefOrRef); // Constraint
break;
case Table.Document:
size = blobidx_size // Name
+ guididx_size // HashAlgorithm
+ blobidx_size // Hash
+ guididx_size; // Language
break;
case Table.MethodDebugInformation:
size = GetTableIndexSize (Table.Document) // Document
+ blobidx_size; // SequencePoints
break;
case Table.LocalScope:
size = GetTableIndexSize (Table.Method) // Method
+ GetTableIndexSize (Table.ImportScope) // ImportScope
+ GetTableIndexSize (Table.LocalVariable) // VariableList
+ GetTableIndexSize (Table.LocalConstant) // ConstantList
+ 4 * 2; // StartOffset, Length
break;
case Table.LocalVariable:
size = 2 // Attributes
+ 2 // Index
+ stridx_size; // Name
break;
case Table.LocalConstant:
size = stridx_size // Name
+ blobidx_size; // Signature
break;
case Table.ImportScope:
size = GetTableIndexSize (Table.ImportScope) // Parent
+ blobidx_size;
break;
case Table.StateMachineMethod:
size = GetTableIndexSize (Table.Method) // MoveNextMethod
+ GetTableIndexSize (Table.Method); // KickOffMethod
break;
case Table.CustomDebugInformation:
size = GetCodedIndexSize (CodedIndex.HasCustomDebugInformation) // Parent
+ guididx_size // Kind
+ blobidx_size; // Value
break;
default:
throw new NotSupportedException ();
}
tables [i].RowSize = (uint) size;
tables [i].Offset = offset;
offset += (uint) size * tables [i].Length;
}
}
void ReadPdbHeap ()
{
var heap = image.PdbHeap;
var buffer = new ByteBuffer (heap.data);
heap.Id = buffer.ReadBytes (20);
heap.EntryPoint = buffer.ReadUInt32 ();
heap.TypeSystemTables = buffer.ReadInt64 ();
heap.TypeSystemTableRows = new uint [Mixin.TableCount];
for (int i = 0; i < Mixin.TableCount; i++) {
var table = (Table) i;
if (!heap.HasTable (table))
continue;
heap.TypeSystemTableRows [i] = buffer.ReadUInt32 ();
}
}
public static Image ReadImage (Disposable<Stream> stream, string file_name)
{
try {
var reader = new ImageReader (stream, file_name);
reader.ReadImage ();
return reader.image;
} catch (EndOfStreamException e) {
throw new BadImageFormatException (stream.value.GetFileName (), e);
}
}
public static Image ReadPortablePdb (Disposable<Stream> stream, string file_name)
{
try {
var reader = new ImageReader (stream, file_name);
var length = (uint) stream.value.Length;
reader.image.Sections = new[] {
new Section {
PointerToRawData = 0,
SizeOfRawData = length,
VirtualAddress = 0,
VirtualSize = length,
}
};
reader.metadata = new DataDirectory (0, length);
reader.ReadMetadata ();
return reader.image;
} catch (EndOfStreamException e) {
throw new BadImageFormatException (stream.value.GetFileName (), e);
}
}
}
}
| |
// 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.
// ----------------------------------------------------------------------------------
// Interop library code
//
// Contains McgModule and various data that describes interop information for types
// seen by MCG. These data will be used at runtime for MCG to make runtime decisions
// during marshalling.
//
// NOTE:
// These source code are being published to InternalAPIs and consumed by RH builds
// Use PublishInteropAPI.bat to keep the InternalAPI copies in sync
// ---------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Text;
using System.Runtime;
using System.Diagnostics.Contracts;
using Internal.NativeFormat;
using Internal.Runtime.CompilerServices;
namespace System.Runtime.InteropServices
{
/// <summary>
/// Module-level operations such as looking up strongly-typed RCWs
/// NOTE: This interface is not CLS compliant but it is only used in Mcg output which is C#
/// </summary>
[CLSCompliant(false)]
public unsafe abstract partial class McgModule
{
int m_mcgDataModulePriority; // access priority for this module in McgModuleManager
StringPool m_stringPool; // Compressed strings
/// <summary>
/// NOTE: Managed debugger depends on field name: "m_interfaceData" and field type must be McgInterfaceData[]
/// Update managed debugger whenever field name/field type is changed.
/// See CordbObjectValue::WalkTypeInfo in debug\dbi\values.cpp
/// </summary>
McgInterfaceData[] m_interfaceData;
CCWTemplateData[] m_ccwTemplateData; // All CCWTemplateData is saved here
RuntimeTypeHandle[] m_supportedInterfaceList; // List of supported interfaces type handle
// CCWTemplateData
McgClassData[] m_classData; // Used for TypeName marshalling and for CreateComObject.
// Contains entries for WinRT classes and for interfaces
// projected as value types (i.e. Nullable<T>/KeyValuePair<K,V>)
McgBoxingData[] m_boxingData;
McgAdditionalClassData[] m_additionalClassData; // Additional class data that captures parent
// child relationship
McgCollectionData[] m_collectionData; // Maps from an ICollection or IReadOnlyCollection type to
// the corresponding entries in m_interfaceTypeInfo for IList,
// IDictionary, IReadOnlyList, IReadOnlyDictionary
McgPInvokeDelegateData[] m_pinvokeDelegateData; // List of pinvoke delegates
McgCCWFactoryInfoEntry[] m_ccwFactories; // List of CCW factories provided to native via DllGetActivationFactory
McgStructMarshalData[] m_structMarshalData; // List of struct marshalling data for Marshal APIs
McgUnsafeStructFieldOffsetData[] m_unsafeStructOffsetData;
McgGenericArgumentMarshalInfo[] m_genericArgumentMarshalInfo; // Array of generic argument marshal information for shared CCW
McgHashcodeVerifyEntry[] m_hashcodeVerifyData;
#if CORECLR
private object m_DictionaryLock = new object();
Dictionary<RuntimeTypeHandle, int> m_interfaceTypeInfo_Hashtable;
Dictionary<RuntimeTypeHandle, int> m_ccwTemplateData_Hashtable;
Dictionary<RuntimeTypeHandle, int> m_classData_Hashtable;
Dictionary<RuntimeTypeHandle, int> m_collectionData_Hashtable;
Dictionary<RuntimeTypeHandle, int> m_typeNameMarshalingData_Hashtable;
Dictionary<RuntimeTypeHandle, int> m_boxingData_Hashtable;
#else
NativeReader m_interfaceTypeInfo_Hashtable;
NativeReader m_ccwTemplateData_Hashtable;
NativeReader m_classData_Hashtable;
NativeReader m_collectionData_Hashtable;
NativeReader m_boxingData_Hashtable;
#endif
#if DEBUG
bool m_hashcodesVerified;
#endif // DEBUG
FixedHashTable m_guidMap;
#if CORECLR
Dictionary<RuntimeTypeHandle, int> InitializeLookupHashTable(Func<int, RuntimeTypeHandle> getEntryTypeHandle,
Func<int> getTableSize)
{
int tableSize = getTableSize();
Dictionary<RuntimeTypeHandle, int> hashtable = new Dictionary<RuntimeTypeHandle, int>(tableSize);
for (int tableIndex = 0; tableIndex < tableSize; tableIndex++)
{
RuntimeTypeHandle handle = getEntryTypeHandle(tableIndex);
hashtable[handle] = tableIndex;
}
return hashtable;
}
// Build the lookup hashtable on the go since MCG can't generate table index lookup hashtable for CoreCLR.
// We aggressively cache everything on first lookup
int LookupTypeHandleInHashtable(
RuntimeTypeHandle typeHandle,
ref Dictionary<RuntimeTypeHandle, int> hashtable,
Func<int, RuntimeTypeHandle> getEntryTypeHandle,
Func<int> getTableSize)
{
if (hashtable == null)
{
Dictionary<RuntimeTypeHandle, int> lookupTable = InitializeLookupHashTable(getEntryTypeHandle, getTableSize);
if (Interlocked.CompareExchange(ref hashtable, lookupTable, null) != null)
{
// Another thread beat us to it , use the one from that thread
lookupTable = null;
}
}
int tableIndex;
if (hashtable.TryGetValue(typeHandle, out tableIndex))
return tableIndex;
// should never get here
return -1;
}
#else
// The hashtables generated by MCG map from a RuntimeTypeHandle hashcode to a bucket of table indexes.
// These indexes are used to lookup an entry in a corresponding MCG-generated table. The table entry
// must also contain a RuntimeTypeHandle that uniquely identifies it. The getEntryTypeHandle delegate
// is used to perform this lookup for the specific MCG-generated table.
unsafe int LookupTypeHandleInHashtable(
RuntimeTypeHandle typeHandle,
ref NativeReader hashtable,
Func<int, RuntimeTypeHandle> getEntryTypeHandle,
Func<int> getTableSize)
{
#if DEBUG
if (!m_hashcodesVerified)
{
bool allVerified = this.VerifyHashCodes();
Debug.Assert(allVerified);
m_hashcodesVerified = true;
}
#endif // DEBUG
// Not all McgModules provide all hashtables. A notable exception is the 'internal' module.
// However, one could imagine if a particular compilation unit didn't have any entries in a table
// it could also have a null hashtable (instead of an empty hashtable).
if (hashtable == null)
return -1;
var htParser = new NativeParser(hashtable, 0);
var ht = new NativeHashtable(htParser);
NativeParser entryParser;
var enumBucket = ht.Lookup(typeHandle.GetHashCode());
while (!(entryParser = enumBucket.GetNext()).IsNull)
{
int tableIndex = (int)entryParser.GetUnsigned();
if (getEntryTypeHandle(tableIndex).Equals(typeHandle))
{
return tableIndex;
}
}
return -1;
}
#endif
/// <summary>
/// Interface lookup on m_interfaceTypeInfo array using on-demand generated hash table(if available)
/// Derived McgModule can overide this method to implement its own way to Look up RuntimeTypeHandle in m_interfaceData
/// </summary>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
internal int InterfaceDataLookup(RuntimeTypeHandle typeHandle)
{
#if CORECLR
return LookupTypeHandleInHashtable(
typeHandle,
ref m_interfaceTypeInfo_Hashtable,
m_interfaceDataLookup_GetEntryTypeHandleCallback,
m_interfaceDataLookup_GetTableSizeCallback);
#else
if (m_interfaceTypeInfo_Hashtable != null)
{
return LookupTypeHandleInHashtable(
typeHandle,
ref m_interfaceTypeInfo_Hashtable,
m_interfaceDataLookup_GetEntryTypeHandleCallback,
m_interfaceDataLookup_GetTableSizeCallback);
}
else
{
// InternalModule doesn't provide HashTable
Debug.Assert(this is InternalModule);
for (int i = 0; i < m_interfaceData.Length; i++)
{
if (m_interfaceData[i].ItfType.Equals(typeHandle))
return i;
}
return -1;
}
#endif
}
private Func<int, RuntimeTypeHandle> m_interfaceDataLookup_GetEntryTypeHandleCallback;
private Func<int> m_interfaceDataLookup_GetTableSizeCallback;
RuntimeTypeHandle InterfaceDataLookup_GetEntryTypeHandle(int index)
{
return m_interfaceData[index].ItfType;
}
int InterfaceDataLookup_GetTableSize()
{
return m_interfaceData.Length;
}
int CollectionDataLookup(RuntimeTypeHandle typeHandle)
{
return LookupTypeHandleInHashtable(
typeHandle,
ref m_collectionData_Hashtable,
m_collectionDataLookup_GetEntryTypeHandleCallback,
m_collectionDataLookup_GetTableSizeCallback);
}
private Func<int, RuntimeTypeHandle> m_collectionDataLookup_GetEntryTypeHandleCallback;
private Func<int> m_collectionDataLookup_GetTableSizeCallback;
RuntimeTypeHandle CollectionDataLookup_GetEntryTypeHandle(int index)
{
return m_collectionData[index].CollectionType;
}
int CollectionDataLookup_GetTableSize()
{
return m_collectionData.Length;
}
int ClassDataLookup(RuntimeTypeHandle typeHandle)
{
return LookupTypeHandleInHashtable(
typeHandle,
ref m_classData_Hashtable,
m_classData_GetEntryTypeHandleCallback,
m_classData_GetTableSizeCallback);
}
private Func<int, RuntimeTypeHandle> m_classData_GetEntryTypeHandleCallback;
private Func<int> m_classData_GetTableSizeCallback;
RuntimeTypeHandle ClassDataLookup_GetEntryTypeHandle(int index)
{
return m_classData[index].ClassType;
}
int ClassDataLookup_GetTableSize()
{
return m_classData == null ? 0 : m_classData.Length;
}
int BoxingDataLookup(RuntimeTypeHandle typeHandle)
{
return LookupTypeHandleInHashtable(
typeHandle,
ref m_boxingData_Hashtable,
m_boxingDataLookup_GetEntryTypeHandleCallback,
m_boxingDataLookup_GetTableSizeCallback);
}
private Func<int, RuntimeTypeHandle> m_boxingDataLookup_GetEntryTypeHandleCallback;
private Func<int> m_boxingDataLookup_GetTableSizeCallback;
RuntimeTypeHandle BoxingDataLookup_GetEntryTypeHandle(int index)
{
return m_boxingData[index].ManagedClassType;
}
int BoxingDataLookup_GetTableSize()
{
return m_boxingData.Length;
}
/// <summary>
/// Returns the corresponding CCW template index for the specified type
/// </summary>
/// <returns>index if the type is found. -1 if it is not a known type in current module</returns>
internal int CCWTemplateDataLookup(RuntimeTypeHandle typeHandle)
{
return LookupTypeHandleInHashtable(
typeHandle,
ref m_ccwTemplateData_Hashtable,
m_CCWTemplateDataLookup_GetEntryTypeHandleCallback,
m_CCWTemplateDataLookup_GetTableSizeCallback);
}
private Func<int, RuntimeTypeHandle> m_CCWTemplateDataLookup_GetEntryTypeHandleCallback;
private Func<int> m_CCWTemplateDataLookup_GetTableSizeCallback;
RuntimeTypeHandle CCWTemplateDataLookup_GetEntryTypeHandle(int index)
{
return m_ccwTemplateData[index].ClassType;
}
int CCWTemplateDataLookup_GetTableSize()
{
return m_ccwTemplateData == null ? 0 : m_ccwTemplateData.Length;
}
public static readonly RuntimeTypeHandle s_DependencyReductionTypeRemovedTypeHandle =
typeof(DependencyReductionTypeRemoved).TypeHandle;
/// <summary>
/// Construct McgModule
/// </summary>
public unsafe McgModule(
int mcgDataModulePriority,
McgInterfaceData[] interfaceData,
CCWTemplateData[] ccwTemplateData,
FixupRuntimeTypeHandle[] supportedInterfaceList,
McgClassData[] classData,
McgBoxingData[] boxingData,
McgAdditionalClassData[] additionalClassData,
McgCollectionData[] collectionData,
McgPInvokeDelegateData[] pinvokeDelegateData,
McgCCWFactoryInfoEntry[] ccwFactories,
McgStructMarshalData[] structMarshalData,
McgUnsafeStructFieldOffsetData[] unsafeStructFieldOffsetData,
McgGenericArgumentMarshalInfo[] genericArgumentMarshalInfo,
McgHashcodeVerifyEntry[] hashcodeVerifyData,
byte[] interfaceTypeInfo_Hashtable,
byte[] ccwTemplateData_Hashtable,
byte[] classData_Hashtable,
byte[] collectionData_Hashtable,
byte[] boxingData_Hashtable)
{
m_mcgDataModulePriority = mcgDataModulePriority;
m_interfaceData = interfaceData;
m_classData = classData;
m_boxingData = boxingData;
m_collectionData = collectionData;
m_pinvokeDelegateData = pinvokeDelegateData;
m_additionalClassData = additionalClassData;
m_ccwFactories = ccwFactories;
m_structMarshalData = structMarshalData;
m_unsafeStructOffsetData = unsafeStructFieldOffsetData;
m_genericArgumentMarshalInfo = genericArgumentMarshalInfo;
m_ccwTemplateData = ccwTemplateData;
// Following code is disabled due to lazy static constructor dependency from McgModule which is
// static eager constructor. Undo this when McgCurrentModule is using ModuleConstructorAttribute
#if EAGER_CTOR_WORKAROUND
Debug.Assert(m_interfaceTypeInfo != null);
#endif
if (supportedInterfaceList != null)
{
m_supportedInterfaceList = new RuntimeTypeHandle[supportedInterfaceList.Length];
for (int i = 0; i < supportedInterfaceList.Length; i++)
{
m_supportedInterfaceList[i] = supportedInterfaceList[i].RuntimeTypeHandle;
}
}
else
{
m_supportedInterfaceList = null;
}
m_hashcodeVerifyData = hashcodeVerifyData;
#if CORECLR
// Will be Lazy intialized
m_interfaceTypeInfo_Hashtable = null;
m_ccwTemplateData_Hashtable = null;
m_classData_Hashtable = null;
m_collectionData_Hashtable = null;
m_typeNameMarshalingData_Hashtable = null;
m_boxingData_Hashtable = null;
#else
m_interfaceTypeInfo_Hashtable = NewHashtableReader(interfaceTypeInfo_Hashtable);
m_ccwTemplateData_Hashtable = NewHashtableReader(ccwTemplateData_Hashtable);
m_classData_Hashtable = NewHashtableReader(classData_Hashtable);
m_collectionData_Hashtable = NewHashtableReader(collectionData_Hashtable);
m_boxingData_Hashtable = NewHashtableReader(boxingData_Hashtable);
#endif
//
// Initialize cached instance delegates (we won't get that if you use lambda even though we only
// use instance member variables inside the lambda).
//
m_interfaceDataLookup_GetEntryTypeHandleCallback =
new Func<int, RuntimeTypeHandle>(this.InterfaceDataLookup_GetEntryTypeHandle);
m_interfaceDataLookup_GetTableSizeCallback =
new Func<int>(this.InterfaceDataLookup_GetTableSize);
m_collectionDataLookup_GetEntryTypeHandleCallback =
new Func<int, RuntimeTypeHandle>(this.CollectionDataLookup_GetEntryTypeHandle);
m_collectionDataLookup_GetTableSizeCallback =
new Func<int>(this.CollectionDataLookup_GetTableSize);
m_classData_GetEntryTypeHandleCallback =
new Func<int, RuntimeTypeHandle>(this.ClassDataLookup_GetEntryTypeHandle);
m_classData_GetTableSizeCallback =
new Func<int>(this.ClassDataLookup_GetTableSize);
m_boxingDataLookup_GetEntryTypeHandleCallback =
new Func<int, RuntimeTypeHandle>(this.BoxingDataLookup_GetEntryTypeHandle);
m_boxingDataLookup_GetTableSizeCallback =
new Func<int>(this.BoxingDataLookup_GetTableSize);
m_CCWTemplateDataLookup_GetEntryTypeHandleCallback =
new Func<int, RuntimeTypeHandle>(this.CCWTemplateDataLookup_GetEntryTypeHandle);
m_CCWTemplateDataLookup_GetTableSizeCallback =
new Func<int>(this.CCWTemplateDataLookup_GetTableSize);
#if DEBUG
// Check no duplicate RuntimeTypeHandle in hashtable
if (m_interfaceData != null)
{
System.Collections.Generic.Internal.HashSet<EquatableRuntimeTypeHandle> intfHashSet =
new System.Collections.Generic.Internal.HashSet<EquatableRuntimeTypeHandle>(m_interfaceData.Length);
foreach (McgInterfaceData item in m_interfaceData)
{
RuntimeTypeHandle typeHnd = item.ItfType;
if (!typeHnd.Equals(s_DependencyReductionTypeRemovedTypeHandle) && !typeHnd.Equals(default(RuntimeTypeHandle)))
{
if (intfHashSet.Add(new EquatableRuntimeTypeHandle(typeHnd), typeHnd.GetHashCode()))
{
Debug.Assert(false, "Duplicate RuntimeTypeHandle found in m_interfaceData");
}
}
}
}
if (m_classData != null)
{
System.Collections.Generic.Internal.HashSet<EquatableRuntimeTypeHandle> classHashSet =
new System.Collections.Generic.Internal.HashSet<EquatableRuntimeTypeHandle>(m_classData.Length);
foreach (McgClassData item in m_classData)
{
RuntimeTypeHandle typeHnd = item.ClassType;
if (!typeHnd.Equals(s_DependencyReductionTypeRemovedTypeHandle) && !typeHnd.Equals(default(RuntimeTypeHandle)))
{
if (classHashSet.Add(new EquatableRuntimeTypeHandle(typeHnd), typeHnd.GetHashCode()))
{
Debug.Assert(false, "Duplicate RuntimeTypeHandle found in m_classData");
}
}
}
}
#endif
}
public int ModulePriority
{
get
{
return m_mcgDataModulePriority;
}
}
private NativeReader NewHashtableReader(byte[] dataArray)
{
if (dataArray == null)
return null;
fixed (byte* pData = dataArray) // WARNING: must be pre-initialized and, therefore, frozen in place
{
return new NativeReader(pData, (uint)dataArray.Length);
}
}
/// <summary>
/// Set thunk function for interface using shared ccwVtable (generic AddrOf not supported by initdata transform + NUTC)
/// </summary>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public void SetThunk(int index, IntPtr thunk)
{
m_interfaceData[index].CcwVtable = thunk;
}
/// <summary>
/// Set data for compressed strings
/// </summary>
public void SetStringPool(byte[] dictionary, byte[] strings, ushort[] index)
{
m_stringPool = new StringPool(dictionary, strings, index);
}
StringMap m_interfaceNameMap;
StringMap m_classNameMap;
StringMap m_additionalClassNameMap;
StringMap m_ccwTemplateDataNameMap;
StringMap m_ccwFactoriesNameMap;
StringMap m_boxingDataNameMap;
StringMap m_typeNameMarshalingDataNameMap;
StringMap m_unsafeStructFieldNameMap;
// There are two sets of functions here: one for 16-bit indices, good for 64k characters, the other for 32-bit indices for bigger applications
// MCG will generate the right calls for the right width.
// Functions not called will be trimmed away by DR
public void SetinterfaceDataNameIndices(UInt16[] nameIndices)
{
m_interfaceNameMap = new StringMap16(m_stringPool, nameIndices);
}
public void SetclassDataNameIndices(UInt16[] nameIndices)
{
m_classNameMap = new StringMap16(m_stringPool, nameIndices);
}
public void SetadditionalClassDataNameIndices(UInt16[] nameIndices)
{
m_additionalClassNameMap = new StringMap16(m_stringPool, nameIndices);
}
public void SetccwFactoriesNameIndices(UInt16[] nameIndices)
{
m_ccwFactoriesNameMap = new StringMap16(m_stringPool, nameIndices);
}
public void SetccwTemplateDataNameIndices(UInt16[] nameIndices)
{
m_ccwTemplateDataNameMap = new StringMap16(m_stringPool, nameIndices);
}
public void SetboxingDataNameIndices(UInt16[] nameIndices)
{
m_boxingDataNameMap = new StringMap16(m_stringPool, nameIndices);
}
public void SettypeNameMarshalingDataNameIndices(UInt16[] nameIndices)
{
m_typeNameMarshalingDataNameMap = new StringMap16(m_stringPool, nameIndices);
}
public void SetinterfaceDataNameIndices(UInt32[] nameIndices)
{
m_interfaceNameMap = new StringMap32(m_stringPool, nameIndices);
}
public void SetclassDataNameIndices(UInt32[] nameIndices)
{
m_classNameMap = new StringMap32(m_stringPool, nameIndices);
}
public void SetadditionalClassDataNameIndices(UInt32[] nameIndices)
{
m_additionalClassNameMap = new StringMap32(m_stringPool, nameIndices);
}
public void SetccwFactoriesNameIndices(UInt32[] nameIndices)
{
m_ccwFactoriesNameMap = new StringMap32(m_stringPool, nameIndices);
}
public void SetccwTemplateDataNameIndices(UInt32[] nameIndices)
{
m_ccwTemplateDataNameMap = new StringMap32(m_stringPool, nameIndices);
}
public void SetboxingDataNameIndices(UInt32[] nameIndices)
{
m_boxingDataNameMap = new StringMap32(m_stringPool, nameIndices);
}
public void SettypeNameMarshalingDataNameIndices(UInt32[] nameIndices)
{
m_typeNameMarshalingDataNameMap = new StringMap32(m_stringPool, nameIndices);
}
public void SetunsafeStructFieldOffsetDataNameIndices(UInt16[] nameIndices)
{
m_unsafeStructFieldNameMap = new StringMap16(m_stringPool, nameIndices);
}
public void SetunsafeStructFieldOffsetDataNameIndices(UInt32[] nameIndices)
{
m_unsafeStructFieldNameMap = new StringMap32(m_stringPool, nameIndices);
}
internal unsafe bool TryGetCCWRuntimeClassName(RuntimeTypeHandle ccwTypeHandle, out string ccwRuntimeClassName)
{
ccwRuntimeClassName = null;
if (m_ccwTemplateDataNameMap == null)
return false;
int slot = CCWTemplateDataLookup(ccwTypeHandle);
if (slot >= 0)
{
ccwRuntimeClassName = m_ccwTemplateDataNameMap.GetString(slot);
return true;
}
return false;
}
/// <summary>
/// Try to get offset data according to McgStructMarshalData's FieldOffsetStartIndex/NumOfFields
/// </summary>
/// <param name="structMarshalData">The Struct Marshal Data</param>
/// <param name="fieldName">Name of field</param>
/// <param name="offset">offset in bytes</param>
/// <returns>if the offset value exists, return true; else return false </returns>
internal bool TryGetStructFieldOffset(McgStructMarshalData structMarshalData, string fieldName, out uint offset)
{
// Try to find its field in map
if (m_unsafeStructFieldNameMap != null)
{
int start = structMarshalData.FieldOffsetStartIndex;
int count = structMarshalData.NumOfFields;
for (int i = start; i < start + count; i++)
{
if (fieldName == m_unsafeStructFieldNameMap.GetString(i))
{
offset = m_unsafeStructOffsetData[i].Offset;
return true;
}
}
}
// Couldn't find its field
offset = 0;
return false;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
internal unsafe bool TryLookupInterfaceType(RuntimeTypeHandle typeHnd, out int interfaceIndex)
{
int tableIndex = InterfaceDataLookup(typeHnd);
if (tableIndex >= 0)
{
interfaceIndex = tableIndex;
return true;
}
interfaceIndex = -1;
return false;
}
internal unsafe bool TryLookupClassType(RuntimeTypeHandle typeHnd, out int classIndex)
{
int tableIndex = ClassDataLookup(typeHnd);
if (tableIndex >= 0)
{
classIndex = tableIndex;
return true;
}
classIndex = -1;
return false;
}
internal bool TryLookupCCWTemplateType(RuntimeTypeHandle typeHnd, out int ccwTemplateIndex)
{
int tableIndex = CCWTemplateDataLookup(typeHnd);
if (tableIndex >=0)
{
ccwTemplateIndex = tableIndex;
return true;
}
ccwTemplateIndex = -1;
return false;
}
internal unsafe bool TryLookupGenericArgumentType(RuntimeTypeHandle typeHnd, out int genericArgumentIndex)
{
int slot = InterfaceDataLookup(typeHnd);
if (slot >= 0)
{
if (m_genericArgumentMarshalInfo != null)
{
genericArgumentIndex = m_interfaceData[slot].MarshalIndex;
return true;
}
}
genericArgumentIndex = -1;
return false;
}
/// <summary>
/// Given a GUID, retrieve the corresponding RuntimeTypeHandle
/// @TODO: we should switch everything to RuntimeTypeHandle instead of relying on Guid
/// </summary>
unsafe internal RuntimeTypeHandle GetTypeFromGuid(ref Guid guid)
{
if (m_interfaceData != null)
{
if (m_guidMap == null)
{
int size = m_interfaceData.Length;
FixedHashTable map = new FixedHashTable(size);
for (int i = 0; i < size; i++)
{
map.Add(m_interfaceData[i].ItfGuid.GetHashCode(), i);
}
Interlocked.CompareExchange(ref m_guidMap, map, null);
}
int hash = guid.GetHashCode();
// Search hash table
for (int slot = m_guidMap.GetFirst(hash); slot >= 0; slot = m_guidMap.GetNext(slot))
{
if (InteropExtensions.GuidEquals(ref guid, ref m_interfaceData[slot].ItfGuid))
{
return m_interfaceData[slot].ItfType;
}
}
}
return default(RuntimeTypeHandle);
}
/// <summary>
/// Get the WinRT name of a given Type. If the type is projected, returns the projected name.
/// Sets isWinRT to true if the type definition is from a WinMD file.
/// </summary>
internal string GetTypeName(RuntimeTypeHandle type, ref bool isWinRT)
{
int slot = InterfaceDataLookup(type);
if (slot >= 0 && m_interfaceNameMap != null)
{
//
// WinRT interface or WinRT delegate
//
isWinRT = m_interfaceData[slot].IsIInspectableOrDelegate;
return m_interfaceNameMap.GetString(slot);
}
if (m_classData != null && m_classNameMap != null)
{
int i = ClassDataLookup(type);
if (i >= 0)
{
isWinRT = (m_classData[i].Flags & McgClassFlags.IsWinRT) != 0;
return m_classNameMap.GetString(i);
}
}
return null;
}
/// <summary>
/// Get a Type object representing the named type, along with a boolean indicating if the type
/// definition is from a WinMD file.
/// </summary>
internal Type GetTypeFromName(string name, ref bool isWinRT)
{
if (m_interfaceNameMap != null)
{
int i = m_interfaceNameMap.FindString(name);
if (i >= 0)
{
isWinRT = m_interfaceData[i].IsIInspectableOrDelegate;
return InteropExtensions.GetTypeFromHandle(m_interfaceData[i].ItfType);
}
}
if (m_classNameMap != null)
{
int i = m_classNameMap.FindString(name);
if (i >= 0)
{
isWinRT = (m_classData[i].Flags & McgClassFlags.IsWinRT) != 0;
return InteropExtensions.GetTypeFromHandle(m_classData[i].ClassType);
}
}
return null;
}
/// <summary>
/// Search this module's m_classData table for information on the requested type.
/// This function returns true if and only if it is able to locate a non-null RuntimeTypeHandle
/// record for the requested type.
/// </summary>
internal bool TryGetClassFromNameInClassData(string name, out RuntimeTypeHandle classType)
{
if (m_classNameMap != null)
{
//
// Search to see if we have a strong-typed RCW for this type.
//
int i = m_classNameMap.FindString(name);
if ((i >= 0) && ((m_classData[i].Flags & McgClassFlags.NotComObject) == 0))
{
//
// This module contains an m_classData row which matches the requested type. This row can
// be immediately used to compute the RuntimeTypeHandle that best describes the type.
//
classType = ComputeClosestClassForClassIndex(i);
if (!classType.Equals(default(RuntimeTypeHandle)))
return true;
}
}
classType = default(RuntimeTypeHandle);
return false;
}
/// <summary>
/// Search this module's m_additionalClassData table for information on the requested type.
/// This function returns true if and only if it is able to locate a non-null RuntimeTypeHandle
/// record for the requested type.
/// </summary>
internal bool TryGetClassFromNameInAdditionalClassData(string name, out RuntimeTypeHandle classType)
{
if (m_additionalClassNameMap != null)
{
//
// Search in additional class data for the closest match (for example, for MyButton, the
// closest match is probably Button)
//
int i = m_additionalClassNameMap.FindString(name);
if (i >= 0)
{
//
// We've found a match. The matching row points to the "next best" strongly-typed RCW
// type that we should create (in place of the original class)
// For example, if native code is passing MatrixTransform, and MCG only knows about its
// base class DependencyObject, we should hand out DependencyObject
//
int classDataIndex = m_additionalClassData[i].ClassDataIndex;
RuntimeTypeHandle typeHandle = m_additionalClassData[i].ClassType;
if (classDataIndex >= 0)
{
//
// This module's m_additionalClassData table points to a m_classData row which describes
// the nearest available base class of the requested type. This row can be immediately used
// to compute the RuntimeTypeHandle that best describes the type.
//
classType = ComputeClosestClassForClassIndex(classDataIndex);
if (!classType.Equals(default(RuntimeTypeHandle)))
return true;
}
else
{
//
// This module's m_additionalClassData table lists a RuntimeTypeHandle which describes
// the nearest available base class of the requested type. If this nearest base class was
// not reduced away, then use it to locate RuntimeTypeHandle describing this "next best" type.
//
if (!typeHandle.Equals(s_DependencyReductionTypeRemovedTypeHandle))
{
classType = typeHandle;
if (!classType.Equals(default(RuntimeTypeHandle)))
return true;
}
}
}
}
classType = default(RuntimeTypeHandle);
return false;
}
/// <summary>
/// This function computes an RuntimeTypeHandle instance that represents the best possible
/// description of the type associated with the requested row in the m_classData table.
///
/// RuntimeTypeHandle can generally be attached directly to the requested row. That said, in the
/// case where the associated type was removed by the dependency reducer, it is necessary to
/// walk the base class chain to find the nearest base type that is actually present at
/// runtime.
///
/// Note: This function can return default(RuntimeTypeHandle) if it determines that all information
/// associated with the supplied row has been reduced away.
/// </summary>
private RuntimeTypeHandle ComputeClosestClassForClassIndex(int index)
{
Debug.Assert((index >= 0) && (index < m_classData.Length));
if (!m_classData[index].ClassType.Equals(s_DependencyReductionTypeRemovedTypeHandle))
{
//
// The current row lists either an non-reduced exact type or the nearest non-reduced base
// type and is therefore the best possible description of the requested row.
//
return m_classData[index].ClassType;
}
else
{
//
// The type in the current row was reduced away. Try to proceed to the base class.
//
int baseClassIndex = m_classData[index].BaseClassIndex;
if (baseClassIndex >= 0)
{
//
// The base class is described elsewhere in this m_classData table. Make a recursive call
// to compute its associated RuntimeTypeHandle.
//
return ComputeClosestClassForClassIndex(baseClassIndex);
}
else
{
RuntimeTypeHandle baseClassTypeHandle = m_classData[index].BaseClassType;
if (baseClassTypeHandle.Equals(default(RuntimeTypeHandle)) ||
baseClassTypeHandle.Equals(s_DependencyReductionTypeRemovedTypeHandle))
{
//
// The reduced type either does not have a base class or refers to a base class that the
// dependency reducer found to be unnecessary.
//
return default(RuntimeTypeHandle);
}
else
{
return baseClassTypeHandle;
}
}
}
}
internal bool TryGetInterfaceTypeFromName(string name, out RuntimeTypeHandle interfaceType)
{
if (m_interfaceData != null && m_interfaceNameMap != null)
{
int index = m_interfaceNameMap.FindString(name);
if (index >= 0)
{
interfaceType = m_interfaceData[index].ItfType;
return true;
}
}
interfaceType = default(RuntimeTypeHandle);
return false;
}
internal McgInterfaceData GetInterfaceDataByIndex(int index)
{
Debug.Assert(index >= 0 && index < m_interfaceData.Length);
return m_interfaceData[index];
}
internal McgClassData GetClassDataByIndex(int index)
{
Debug.Assert(index >= 0 && index < m_classData.Length);
return m_classData[index];
}
internal CCWTemplateData GetCCWTemplateDataByIndex(int index)
{
Debug.Assert(index >= 0 && index < m_ccwTemplateData.Length);
return m_ccwTemplateData[index];
}
int m_boxingDataTypeSlot = -1; // Slot for System.Type in boxing data table
/// <summary>
/// Given a boxed value type, return a wrapper supports the IReference interface
/// </summary>
/// <param name="typeHandleOverride">
/// You might want to specify how to box this. For example, any object[] derived array could
/// potentially boxed as object[] if everything else fails
/// </param>
internal bool TryGetBoxingWrapperType(RuntimeTypeHandle typeHandle, bool IsSystemType,
out RuntimeTypeHandle boxingWrapperType, out int boxingPropertyType, out IntPtr boxingStub)
{
boxingWrapperType = default(RuntimeTypeHandle);
boxingPropertyType = default(int);
boxingStub = default(IntPtr);
if ((m_boxingData == null) || (m_boxingData.Length == 0))
{
return false;
}
if (m_boxingDataTypeSlot == -1)
{
m_boxingDataTypeSlot = BoxingDataLookup(typeof(System.Type).TypeHandle);
}
//
// Is this the exact type that we want? (Don't use 'is' check - it won't work well for
// arrays)
int slot = BoxingDataLookup(typeHandle);
// NOTE: For System.Type marshalling, use 'is' check instead, as the actual type would be
// some random internal type from reflection
//
if ((slot < 0) && IsSystemType)
{
slot = m_boxingDataTypeSlot;
}
if (slot >= 0)
{
boxingWrapperType = m_boxingData[slot].CLRBoxingWrapperType;
boxingPropertyType = m_boxingData[slot].PropertyType;
boxingStub = m_boxingData[slot].BoxingStub;
return true;
}
return false;
}
/// <summary>
/// Unbox the WinRT boxed IReference<T>/IReferenceArray<T> and box it into Object so that managed
/// code can unbox it later into the real T
/// </summary>
internal bool TryGetUnboxingStub(string className, out IntPtr unboxingStub)
{
unboxingStub = default(IntPtr);
if (m_boxingData == null)
{
return false;
}
Debug.Assert(!String.IsNullOrEmpty(className));
//
// Avoid searching for null/empty name. BoxingData has null name entries
//
int slot = m_boxingDataNameMap.FindString(className);
if (slot >= 0)
{
unboxingStub = m_boxingData[slot].UnboxingStub;
return true;
}
return false;
}
/// <summary>
/// Retrieves delegate data for the specified delegate handle
/// </summary>
internal bool TryGetPInvokeDelegateData(RuntimeTypeHandle typeHandle, out McgPInvokeDelegateData pinvokeDelegateData)
{
if (m_pinvokeDelegateData != null)
{
for (int i = 0; i < m_pinvokeDelegateData.Length; i++)
{
if (typeHandle.Equals(m_pinvokeDelegateData[i].Delegate))
{
pinvokeDelegateData = m_pinvokeDelegateData[i];
return true;
}
}
}
pinvokeDelegateData = default(McgPInvokeDelegateData);
return false;
}
/// <summary>
/// Finds McgStructMarshalData for a struct if it is defined in this module
/// </summary>
/// <param name="structTypeHandle">TypeHandle for the safe struct</param>
/// <param name="structMarshalData">McgStructMarshalData for the struct</param>
/// <returns>True if the struct marshal data is available in this module</returns>
internal bool TryGetStructMarshalData(RuntimeTypeHandle structTypeHandle, out McgStructMarshalData structMarshalData)
{
structMarshalData = default(McgStructMarshalData);
if (m_structMarshalData == null)
{
return false;
}
for (int i = 0; i < m_structMarshalData.Length; i++)
{
if (structTypeHandle.Equals(m_structMarshalData[i].SafeStructType))
{
if (m_structMarshalData[i].HasInvalidLayout)
throw new ArgumentException(SR.Format(SR.Argument_MustHaveLayoutOrBeBlittable, structTypeHandle.GetDisplayName()));
structMarshalData = m_structMarshalData[i];
return true;
}
}
return false;
}
internal unsafe RuntimeTypeHandle FindTypeSupportDynamic(Func<RuntimeTypeHandle, bool> predicate)
{
for (int i = 0; i < m_interfaceData.Length; i++)
{
McgInterfaceData data = m_interfaceData[i];
if (!data.DynamicAdapterClassType.IsNull() && predicate(data.ItfType))
return data.ItfType;
}
return default(RuntimeTypeHandle);
}
internal unsafe bool TryGetBaseType(RuntimeTypeHandle ccwType, out RuntimeTypeHandle baseType)
{
int ccwTemplateIndex = CCWTemplateDataLookup(ccwType);
if (ccwTemplateIndex >= 0)
{
// Field ParentCCWTemplateIndex >=0 means that its baseclass is in the same module
// Field BaseType != default(RuntimeTypeHandle) means that its baseclass isn't in the same module
int parentIndex = m_ccwTemplateData[ccwTemplateIndex].ParentCCWTemplateIndex;
RuntimeTypeHandle baseTypeHandle = m_ccwTemplateData[ccwTemplateIndex].BaseType;
if (parentIndex >= 0)
{
baseType = m_ccwTemplateData[parentIndex].ClassType;
return true;
}
else if (!baseTypeHandle.Equals(default(RuntimeTypeHandle)))
{
// DR will keep all base types if one of its derived type is used(rooted)
if (baseTypeHandle.Equals(s_DependencyReductionTypeRemovedTypeHandle))
{
#if !RHTESTCL
Environment.FailFast(String.Format("Base Type of {0} discarded.", m_ccwTemplateData[ccwTemplateIndex].ClassType.GetDisplayName()));
#else
Environment.FailFast("Base Type discarded.");
#endif
}
baseType = baseTypeHandle;
return true;
}
}
baseType = default(RuntimeTypeHandle);
return false;
}
internal bool TryGetImplementedInterfaces(int ccwTemplateIndex, out IEnumerable<RuntimeTypeHandle> interfaces)
{
if (ccwTemplateIndex >= 0)
{
interfaces = new Collections.Generic.List<RuntimeTypeHandle>();
//
// Walk the interface list
//
interfaces = new ArraySegment<RuntimeTypeHandle>(
m_supportedInterfaceList,
m_ccwTemplateData[ccwTemplateIndex].SupportedInterfaceListBeginIndex,
m_ccwTemplateData[ccwTemplateIndex].NumberOfSupportedInterface
);
return true;
}
interfaces = null;
return false;
}
internal bool TryGetImplementedInterfaces(RuntimeTypeHandle ccwType, out IEnumerable<RuntimeTypeHandle> interfaces)
{
int ccwTemplateIndex = CCWTemplateDataLookup(ccwType);
return TryGetImplementedInterfaces(ccwTemplateIndex, out interfaces);
}
internal bool TryGetIsWinRTType(RuntimeTypeHandle ccwType, out bool isWinRTType)
{
int ccwTemplateIndex = CCWTemplateDataLookup(ccwType);
if (ccwTemplateIndex >= 0)
{
isWinRTType = m_ccwTemplateData[ccwTemplateIndex].IsWinRTType;
return true;
}
isWinRTType = default(bool);
return false;
}
internal bool TryGetTypeHandleForICollecton(RuntimeTypeHandle interfaceTypeHandle, out RuntimeTypeHandle firstTypeHandle, out RuntimeTypeHandle secondTypeHandle)
{
// Loop over our I[ReadOnly]Collection<T1,T2> instantiations to find the type infos for
// I[ReadOnly]List<KeyValuePair<T1,T2>> and I[ReadOnly]Dictionary<T1,T2>
//
// Note that only one of IList/IDictionary may be present.
if (m_collectionData != null)
{
int slot = CollectionDataLookup(interfaceTypeHandle);
if (slot >= 0)
{
firstTypeHandle = m_collectionData[slot].FirstType;
secondTypeHandle = m_collectionData[slot].SecondType;
return true;
}
}
firstTypeHandle = default(RuntimeTypeHandle);
secondTypeHandle = default(RuntimeTypeHandle);
return false;
}
internal bool TryGetGenericArgumentMarshalInfo(RuntimeTypeHandle typeHandle, out McgGenericArgumentMarshalInfo mcgGenericArgumentMarshalInfo)
{
int slot = InterfaceDataLookup(typeHandle);
if (slot >= 0)
{
if (m_genericArgumentMarshalInfo != null)
{
int marshalIndex = m_interfaceData[slot].MarshalIndex;
mcgGenericArgumentMarshalInfo = m_genericArgumentMarshalInfo[marshalIndex];
return true;
}
}
mcgGenericArgumentMarshalInfo = default(McgGenericArgumentMarshalInfo);
return false;
}
#if ENABLE_WINRT
static Guid s_IID_IActivationFactory = new Guid(0x00000035, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46);
/// <summary>
/// Returns the requested interface pointer specified by itfType from the CCWActivationFactory
/// object instance. Typically the requested interface is the
/// System.Runtime.InteropServices.WindowsRuntime.IActivationFactory interface.
/// </summary>
public unsafe int GetCCWActivationFactory(HSTRING activatableClassId, RuntimeTypeHandle itfType, IntPtr* factoryOut)
{
try
{
string classId = McgMarshal.HStringToString(activatableClassId);
if (classId == null)
return Interop.COM.E_INVALIDARG;
RuntimeTypeHandle factoryTypeHandle = default(RuntimeTypeHandle);
if (m_ccwFactoriesNameMap != null)
{
int slot = m_ccwFactoriesNameMap.FindString(classId);
if (slot >= 0)
{
factoryTypeHandle = m_ccwFactories[slot].FactoryType;
}
}
if (factoryTypeHandle.IsNull())
return Interop.COM.E_NOINTERFACE;
object factory = InteropExtensions.RuntimeNewObject(factoryTypeHandle);
*factoryOut = McgMarshal.ObjectToComInterface(
factory,
itfType);
}
catch (Exception ex)
{
*factoryOut = default(IntPtr);
return McgMarshal.GetHRForExceptionWinRT(ex);
}
return Interop.COM.S_OK;
}
#endif
#if DEBUG
bool VerifyHashCodes()
{
if (m_hashcodeVerifyData == null)
return true;
bool success = true;
RuntimeTypeHandle typeRemovedType = typeof(DependencyReductionTypeRemoved).TypeHandle;
for (int i = 0; i < m_hashcodeVerifyData.Length; i++)
{
McgHashcodeVerifyEntry entry = m_hashcodeVerifyData[i];
if (entry.TypeHandle.Equals(typeRemovedType))
continue;
uint nutcHashcode = unchecked((uint)entry.TypeHandle.GetHashCode());
uint mcgHashcode = entry.HashCode;
if (nutcHashcode != mcgHashcode)
{
success = false;
Debug.WriteLine("MCG hashcode mistatch at index: " + DebugUtil.BasicToString(i)
+ " MCG: " + DebugUtil.ToHexStringUnsigned(mcgHashcode)
+ " NUTC: " + DebugUtil.ToHexStringUnsigned(nutcHashcode));
}
}
return success;
}
#endif // DEBUG
#if DEBUG
// VerifyHashCodes must not call String.Format or any of the integer formatting routines in System.Private.CoreLib because
// they will trigger the globalization code which uses WinRT interop, which call back here creating an
// infinite recursion. So we have a simple implementation for printing hex numbers.
static class DebugUtil
{
static char GetHexChar(uint u)
{
if (u < 10)
{
return unchecked((char)('0' + u));
}
if (u < 16)
{
return unchecked((char)('a' + (u - 10)));
}
return (char)0;
}
static public string ToHexStringUnsigned(uint u)
{
return ToHexStringUnsignedLong(u, true, 8);
}
static public unsafe string ToHexStringUnsignedLong(ulong u, bool zeroPrepad, int numChars)
{
char[] chars = new char[numChars];
int i = numChars - 1;
for (; i >= 0; i--)
{
chars[i] = GetHexChar((uint)(u % 16));
u = u / 16;
if ((i == 0) || (!zeroPrepad && (u == 0)))
break;
}
string str;
fixed (char* p = &chars[i])
{
str = new String(p, 0, numChars - i);
}
return str;
}
static public unsafe string BasicToString(int num)
{
char* pRevBuffer = stackalloc char[16];
char* pFwdBuffer = stackalloc char[16];
bool isNegative = (num < 0);
if (isNegative)
num = -num;
int len = 0;
while (num > 0)
{
int ch = num % 10;
num = num / 10;
pRevBuffer[len++] = (char)('0' + ch);
}
if (isNegative)
pRevBuffer[len++] = '-';
for (int i = (len - 1); i >= 0; i--)
{
pFwdBuffer[i] = pRevBuffer[(len - 1) - i];
}
return new String(pFwdBuffer, 0, len);
}
}
internal class EquatableRuntimeTypeHandle : IEquatable<EquatableRuntimeTypeHandle>
{
internal RuntimeTypeHandle TypeHand;
internal EquatableRuntimeTypeHandle(RuntimeTypeHandle typeHand)
{
TypeHand = typeHand;
}
public bool Equals(EquatableRuntimeTypeHandle other)
{
return TypeHand.Equals(other.TypeHand);
}
}
#endif // DEBUG
}
}
| |
// 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.Net;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
// The System.Net.Sockets.TcpListener class provide TCP services at a higher level of abstraction
// than the System.Net.Sockets.Socket class. System.Net.Sockets.TcpListener is used to create a
// host process that listens for connections from TCP clients.
public class TcpListener
{
private IPEndPoint _serverSocketEP;
private Socket _serverSocket;
private bool _active;
private bool _exclusiveAddressUse;
// Initializes a new instance of the TcpListener class with the specified local end point.
public TcpListener(IPEndPoint localEP)
{
if (Logging.On)
{
Logging.Enter(Logging.Sockets, this, "TcpListener", localEP);
}
if (localEP == null)
{
throw new ArgumentNullException("localEP");
}
_serverSocketEP = localEP;
_serverSocket = new Socket(_serverSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if (Logging.On)
{
Logging.Exit(Logging.Sockets, this, "TcpListener", null);
}
}
// Initializes a new instance of the TcpListener class that listens to the specified IP address
// and port.
public TcpListener(IPAddress localaddr, int port)
{
if (Logging.On)
{
Logging.Enter(Logging.Sockets, this, "TcpListener", localaddr);
}
if (localaddr == null)
{
throw new ArgumentNullException("localaddr");
}
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException("port");
}
_serverSocketEP = new IPEndPoint(localaddr, port);
_serverSocket = new Socket(_serverSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if (Logging.On)
{
Logging.Exit(Logging.Sockets, this, "TcpListener", null);
}
}
// This creates a TcpListener that listens on both IPv4 and IPv6 on the given port.
public static TcpListener Create(int port)
{
if (Logging.On)
{
Logging.Enter(Logging.Sockets, "TcpListener.Create", "Port: " + port);
}
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException("port");
}
TcpListener listener = new TcpListener(IPAddress.IPv6Any, port);
listener.Server.DualMode = true;
if (Logging.On)
{
Logging.Exit(Logging.Sockets, "TcpListener.Create", "Port: " + port);
}
return listener;
}
// Used by the class to provide the underlying network socket.
public Socket Server
{
get
{
return _serverSocket;
}
}
// Used by the class to indicate that the listener's socket has been bound to a port
// and started listening.
protected bool Active
{
get
{
return _active;
}
}
// Gets the m_Active EndPoint for the local listener socket.
public EndPoint LocalEndpoint
{
get
{
return _active ? _serverSocket.LocalEndPoint : _serverSocketEP;
}
}
public bool ExclusiveAddressUse
{
get
{
return _serverSocket.ExclusiveAddressUse;
}
set
{
if (_active)
{
throw new InvalidOperationException(SR.net_tcplistener_mustbestopped);
}
_serverSocket.ExclusiveAddressUse = value;
_exclusiveAddressUse = value;
}
}
public void AllowNatTraversal(bool allowed)
{
if (_active)
{
throw new InvalidOperationException(SR.net_tcplistener_mustbestopped);
}
if (allowed)
{
_serverSocket.SetIPProtectionLevel(IPProtectionLevel.Unrestricted);
}
else
{
_serverSocket.SetIPProtectionLevel(IPProtectionLevel.EdgeRestricted);
}
}
// Starts listening to network requests.
public void Start()
{
Start((int)SocketOptionName.MaxConnections);
}
public void Start(int backlog)
{
if (backlog > (int)SocketOptionName.MaxConnections || backlog < 0)
{
throw new ArgumentOutOfRangeException("backlog");
}
if (Logging.On)
{
Logging.Enter(Logging.Sockets, this, "Start", null);
}
GlobalLog.Print("TCPListener::Start()");
if (_serverSocket == null)
{
throw new InvalidOperationException(SR.net_InvalidSocketHandle);
}
// Already listening.
if (_active)
{
if (Logging.On)
{
Logging.Exit(Logging.Sockets, this, "Start", null);
}
return;
}
_serverSocket.Bind(_serverSocketEP);
try
{
_serverSocket.Listen(backlog);
}
catch (SocketException)
{
// When there is an exception, unwind previous actions (bind, etc).
Stop();
throw;
}
_active = true;
if (Logging.On)
{
Logging.Exit(Logging.Sockets, this, "Start", null);
}
}
// Closes the network connection.
public void Stop()
{
if (Logging.On)
{
Logging.Enter(Logging.Sockets, this, "Stop", null);
}
GlobalLog.Print("TCPListener::Stop()");
if (_serverSocket != null)
{
_serverSocket.Dispose();
_serverSocket = null;
}
_active = false;
_serverSocket = new Socket(_serverSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if (_exclusiveAddressUse)
{
_serverSocket.ExclusiveAddressUse = true;
}
if (Logging.On)
{
Logging.Exit(Logging.Sockets, this, "Stop", null);
}
}
// Determine if there are pending connection requests.
public bool Pending()
{
if (!_active)
{
throw new InvalidOperationException(SR.net_stopped);
}
return _serverSocket.Poll(0, SelectMode.SelectRead);
}
// Accepts a pending connection request.
public Socket AcceptSocket()
{
if (Logging.On)
{
Logging.Enter(Logging.Sockets, this, "AcceptSocket", null);
}
if (!_active)
{
throw new InvalidOperationException(SR.net_stopped);
}
Socket socket = _serverSocket.Accept();
if (Logging.On)
{
Logging.Exit(Logging.Sockets, this, "AcceptSocket", socket);
}
return socket;
}
public TcpClient AcceptTcpClient()
{
if (Logging.On)
{
Logging.Enter(Logging.Sockets, this, "AcceptTcpClient", null);
}
if (!_active)
{
throw new InvalidOperationException(SR.net_stopped);
}
Socket acceptedSocket = _serverSocket.Accept();
TcpClient returnValue = new TcpClient(acceptedSocket);
if (Logging.On)
{
Logging.Exit(Logging.Sockets, this, "AcceptTcpClient", returnValue);
}
return returnValue;
}
public IAsyncResult BeginAcceptSocket(AsyncCallback callback, object state)
{
if (Logging.On)
{
Logging.Enter(Logging.Sockets, this, "BeginAcceptSocket", null);
}
if (!_active)
{
throw new InvalidOperationException(SR.net_stopped);
}
IAsyncResult result = _serverSocket.BeginAccept(callback, state);
if (Logging.On)
{
Logging.Exit(Logging.Sockets, this, "BeginAcceptSocket", null);
}
return result;
}
public Socket EndAcceptSocket(IAsyncResult asyncResult)
{
if (Logging.On)
{
Logging.Enter(Logging.Sockets, this, "EndAcceptSocket", null);
}
if (asyncResult == null)
{
throw new ArgumentNullException("asyncResult");
}
LazyAsyncResult lazyResult = asyncResult as LazyAsyncResult;
Socket asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket;
if (asyncSocket == null)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, "asyncResult");
}
// This will throw ObjectDisposedException if Stop() has been called.
Socket socket = asyncSocket.EndAccept(asyncResult);
if (Logging.On)
{
Logging.Exit(Logging.Sockets, this, "EndAcceptSocket", socket);
}
return socket;
}
public IAsyncResult BeginAcceptTcpClient(AsyncCallback callback, object state)
{
if (Logging.On)
{
Logging.Enter(Logging.Sockets, this, "BeginAcceptTcpClient", null);
}
if (!_active)
{
throw new InvalidOperationException(SR.net_stopped);
}
IAsyncResult result = _serverSocket.BeginAccept(callback, state);
if (Logging.On)
{
Logging.Exit(Logging.Sockets, this, "BeginAcceptTcpClient", null);
}
return result;
}
public TcpClient EndAcceptTcpClient(IAsyncResult asyncResult)
{
if (Logging.On)
{
Logging.Enter(Logging.Sockets, this, "EndAcceptTcpClient", null);
}
if (asyncResult == null)
{
throw new ArgumentNullException("asyncResult");
}
LazyAsyncResult lazyResult = asyncResult as LazyAsyncResult;
Socket asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket;
if (asyncSocket == null)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, "asyncResult");
}
// This will throw ObjectDisposedException if Stop() has been called.
Socket socket = asyncSocket.EndAccept(asyncResult);
if (Logging.On)
{
Logging.Exit(Logging.Sockets, this, "EndAcceptTcpClient", socket);
}
return new TcpClient(socket);
}
public Task<Socket> AcceptSocketAsync()
{
return Task<Socket>.Factory.FromAsync(BeginAcceptSocket, EndAcceptSocket, null);
}
public Task<TcpClient> AcceptTcpClientAsync()
{
return Task<TcpClient>.Factory.FromAsync(BeginAcceptTcpClient, EndAcceptTcpClient, null);
}
}
}
| |
using NUnit.Framework;
using System;
using System.Management.Automation;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Collections.Generic;
using System.Collections;
using System.Xml;
namespace ReferenceTests.API
{
public class TestParent {
private string _msg;
public TestParent(string msg) { _msg = msg; }
public override int GetHashCode() { return _msg.ToLower().GetHashCode(); }
public override bool Equals(object obj)
{
var otherParent = obj as TestParent;
if (otherParent == null)
{
throw new InvalidOperationException("Wrong object type to compare to");
}
return _msg.Equals(otherParent._msg);
}
public bool EqualsIgnoreCase(TestParent other)
{
return String.Compare(_msg, other._msg, true) == 0;
}
}
public class TestChild : TestParent {
private string _msg2;
public TestChild(string msg, string msg2) : base(msg) { _msg2 = msg2; }
public override int GetHashCode() { return _msg2.GetHashCode() + base.GetHashCode(); }
public override bool Equals(object obj)
{
var otherChild = obj as TestChild;
if (otherChild == null)
{
throw new InvalidOperationException("Wrong object type to compare to");
}
return _msg2.Equals(otherChild._msg2) && base.EqualsIgnoreCase(otherChild);
}
}
[TypeConverter(typeof(CustomTypeConverter))]
public class Custom
{
public string Id { get; set; }
}
public class CustomTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
string stringValue = value as string;
return new Custom { Id = stringValue };
}
}
[TestFixture]
public class LanguagePrimitivesTests
{
[TestCase(3, typeof(int), (int) 3)]
[TestCase(3, typeof(double), (double) 3)]
[TestCase(3, typeof(string), "3")]
[TestCase(3, typeof(int[]), new int[] { (int) 3 })]
[TestCase(3, typeof(double[]), new double[] { (double) 3.0 })]
[TestCase(3, typeof(string[]), new string[] { "3" })]
[TestCase("3", typeof(string), "3")]
[TestCase("3", typeof(int), (int) 3)]
[TestCase("3", typeof(double), (double) 3.0)]
[TestCase("3", typeof(string[]), new string[] { "3" })]
[TestCase("3", typeof(int[]), new int[] { (int) 3 })]
[TestCase("3", typeof(double[]), new double[] { (double) 3.0 })]
public void ConvertToWorksWithBasicsAndArrayPacking(object obj, Type type, object expected)
{
var result = LanguagePrimitives.ConvertTo(obj, type);
Assert.AreEqual(type, result.GetType());
Assert.AreEqual(expected, result);
}
[Test]
public void ConvertToThrowsExceptionIfStringConversionFails()
{
Assert.Throws(
typeof(PSInvalidCastException),
delegate() {
LanguagePrimitives.ConvertTo("3foo", typeof(int));
}
);
}
[Test]
public void ConvertToThrowsExceptionIfNotPossibleAtAll()
{
Assert.Throws(
typeof(PSInvalidCastException),
delegate() {
LanguagePrimitives.ConvertTo(new TestParent("foo"), typeof(int));
}
);
}
[Test]
public void ConvertToThrowsExceptionIfNotPossibleToUpcast()
{
Assert.Throws(
typeof(PSInvalidCastException),
delegate() {
LanguagePrimitives.ConvertTo(new TestParent("foo"), typeof(TestChild));
}
);
}
[Test]
public void ConvertToThrowsExceptionAndShowsTypeBeingConvertedToInErrorMessage()
{
Exception ex = Assert.Throws(
typeof(PSInvalidCastException),
delegate()
{
LanguagePrimitives.ConvertTo("foo", typeof(TestChild));
}
);
Assert.That(ex.Message, Contains.Substring(typeof(TestChild).FullName));
}
[Test]
public void ConvertToWorksForUpcast()
{
var result = LanguagePrimitives.ConvertTo((TestParent) new TestChild("foo", "bar"), typeof(TestChild));
var expected = new TestChild("FOO", "bar");
Assert.AreEqual(expected.GetType(), result.GetType());
Assert.AreEqual(expected, result);
}
[Test]
public void ConvertToWorksForDowncast()
{
var result = LanguagePrimitives.ConvertTo(new TestChild("foo", "bar"), typeof(TestParent));
var expected = new TestParent("foo");
Assert.AreEqual(expected, result);
}
[TestCase(false, false)]
[TestCase(null, false)]
[TestCase(true, true)]
public void ConvertToCanHandleSwitchParameters(object value, bool expectedValue)
{
var result = LanguagePrimitives.ConvertTo(value, typeof(SwitchParameter));
var expected = new SwitchParameter(expectedValue);
Assert.AreEqual(expected.GetType(), result.GetType());
Assert.AreEqual(expected.IsPresent, ((SwitchParameter)result).IsPresent);
}
[TestCase(3)]
[TestCase(0.0)]
[TestCase(0.0)]
[TestCase(0)]
[TestCase(-1.0)]
public void ConvertToDoesntConvertFromNumericToSwitchParameter(object value)
{
Assert.Throws<PSInvalidCastException>(delegate
{
LanguagePrimitives.ConvertTo(value, typeof(SwitchParameter));
});
}
[Test]
public void ConvertToCanPackAsPSObject()
{
var result = LanguagePrimitives.ConvertTo(3, typeof(PSObject));
var expected = PSObject.AsPSObject(3);
Assert.AreEqual(expected.GetType(), result.GetType());
Assert.AreEqual(expected, result);
}
[Test]
public void ConvertToCanPackAsPSObjectArray()
{
var result = LanguagePrimitives.ConvertTo(3, typeof(PSObject[]));
var expected = new PSObject[] { PSObject.AsPSObject(3) };
Assert.AreEqual(expected.GetType(), result.GetType());
Assert.AreEqual(expected, result);
}
[Test]
public void ConvertToConvertsArrayToPSObjectArray()
{
var input = new int[] { 3, 4, 5 };
var expected = new PSObject[] { PSObject.AsPSObject(3), PSObject.AsPSObject(4), PSObject.AsPSObject(5) };
var result = LanguagePrimitives.ConvertTo(input, typeof(PSObject[]));
Assert.AreEqual(expected.GetType(), result.GetType());
Assert.AreEqual(expected, result);
}
[Test]
public void ConvertToConvertsArraysRecursivelyNumbers()
{
var input = new int[][] { new int[] { 3, 4 }, new int[] { 5, 6 } };
var expected = new double[][] { new double[] { 3.0, 4.0 }, new double[] { 5.0, 6.0 } };
var result = LanguagePrimitives.ConvertTo(input, typeof(double[][]));
Assert.AreEqual(expected.GetType(), result.GetType());
Assert.AreEqual(expected, result);
}
[Test]
public void ConvertToConvertsArraysRecursivelyStrings()
{
var input = new int[][] { new int[] { 3, 4 }, new int[] { 5, 6 } };
var expected = new string[][] { new string[] { "3", "4" }, new string[] { "5", "6" } };
var result = LanguagePrimitives.ConvertTo(input, typeof(string[][]));
Assert.AreEqual(expected.GetType(), result.GetType());
Assert.AreEqual(expected, result);
}
[Test]
public void ConvertToConvertsEnumerableToArray()
{
var input = new Collection<int> { 3, 4, 5 };
var expected = new string[] { "3", "4", "5" };
var result = LanguagePrimitives.ConvertTo(input, typeof(string[]));
Assert.AreEqual(expected.GetType(), result.GetType());
Assert.AreEqual(expected, result);
}
[Test]
public void ConvertToConvertsTypeWithTypeConverter()
{
string input = "MyId";
var result = LanguagePrimitives.ConvertTo(input, typeof(Custom));
Assert.AreEqual(typeof(Custom), result.GetType());
Assert.AreEqual("MyId", ((Custom)result).Id);
}
[Test]
public void ConvertUsingConstructor()
{
string input = "1.0";
var result = LanguagePrimitives.ConvertTo(input, typeof(Version));
Assert.That(result, Is.EqualTo(new Version(input)));
}
[Test]
public void ConvertToVoidReturnsAutomationNull()
{
var result = LanguagePrimitives.ConvertTo("foo", typeof(void));
Assert.That(result, Is.SameAs(System.Management.Automation.Internal.AutomationNull.Value));
}
[Test]
public void ConvertNullToPSObjectReturnsNull()
{
var result = LanguagePrimitives.ConvertTo(null, typeof(PSObject));
Assert.That(result, Is.Null);
}
[Test]
public void StringsAreNotEnumerated()
{
Assert.That(LanguagePrimitives.GetEnumerator("foo"), Is.Null);
}
[Test]
public void DictionariesAreNotEnumerated()
{
var testDict = new Dictionary<string, object> { { "foo", 123 } };
Assert.That(LanguagePrimitives.GetEnumerator(testDict), Is.Null);
}
[Test]
public void HashtablesAreNotEnumerated()
{
var testTable = new Hashtable { { "foo", 123 } };
Assert.That(LanguagePrimitives.GetEnumerator(testTable), Is.Null);
}
[Test]
public void XmlNodesAreNotEnumerated()
{
var xml = new XmlDocument();
xml.LoadXml("<a><b>foo</b><b>bar</b></a>");
Assert.That(LanguagePrimitives.GetEnumerator(xml), Is.Null);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.IO.Pipelines.Text.Primitives;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
namespace System.IO.Pipelines.Samples.Http
{
public class RequestHeaderDictionary : IHeaderDictionary
{
private static readonly byte[] ContentLengthKeyBytes = Encoding.ASCII.GetBytes("CONTENT-LENGTH");
private static readonly byte[] ContentTypeKeyBytes = Encoding.ASCII.GetBytes("CONTENT-TYPE");
private static readonly byte[] AcceptBytes = Encoding.ASCII.GetBytes("ACCEPT");
private static readonly byte[] AcceptLanguageBytes = Encoding.ASCII.GetBytes("ACCEPT-LANGUAGE");
private static readonly byte[] AcceptEncodingBytes = Encoding.ASCII.GetBytes("ACCEPT-ENCODING");
private static readonly byte[] HostBytes = Encoding.ASCII.GetBytes("HOST");
private static readonly byte[] ConnectionBytes = Encoding.ASCII.GetBytes("CONNECTION");
private static readonly byte[] CacheControlBytes = Encoding.ASCII.GetBytes("CACHE-CONTROL");
private static readonly byte[] UserAgentBytes = Encoding.ASCII.GetBytes("USER-AGENT");
private static readonly byte[] UpgradeInsecureRequests = Encoding.ASCII.GetBytes("UPGRADE-INSECURE-REQUESTS");
private Dictionary<string, HeaderValue> _headers = new Dictionary<string, HeaderValue>(10, StringComparer.OrdinalIgnoreCase);
public StringValues this[string key]
{
get
{
StringValues values;
TryGetValue(key, out values);
return values;
}
set
{
SetHeader(key, value);
}
}
public int Count => _headers.Count;
public bool IsReadOnly => false;
public ICollection<string> Keys => _headers.Keys;
public ICollection<StringValues> Values => _headers.Values.Select(v => v.GetValue()).ToList();
public void SetHeader(ref ReadableBuffer key, ref ReadableBuffer value)
{
string headerKey = GetHeaderKey(ref key);
_headers[headerKey] = new HeaderValue
{
Raw = value.Preserve()
};
}
public ReadableBuffer GetHeaderRaw(string key)
{
HeaderValue value;
if (_headers.TryGetValue(key, out value))
{
return value.Raw.Value.Buffer;
}
return default(ReadableBuffer);
}
private string GetHeaderKey(ref ReadableBuffer key)
{
// Uppercase the things
foreach (var memory in key)
{
var data = memory.Span;
for (int i = 0; i < memory.Length; i++)
{
var mask = IsAlpha(data[i]) ? 0xdf : 0xff;
data[i] = (byte)(data[i] & mask);
}
}
if (EqualsIgnoreCase(ref key, AcceptBytes))
{
return "Accept";
}
if (EqualsIgnoreCase(ref key, AcceptEncodingBytes))
{
return "Accept-Encoding";
}
if (EqualsIgnoreCase(ref key, AcceptLanguageBytes))
{
return "Accept-Language";
}
if (EqualsIgnoreCase(ref key, HostBytes))
{
return "Host";
}
if (EqualsIgnoreCase(ref key, UserAgentBytes))
{
return "User-Agent";
}
if (EqualsIgnoreCase(ref key, CacheControlBytes))
{
return "Cache-Control";
}
if (EqualsIgnoreCase(ref key, ConnectionBytes))
{
return "Connection";
}
if (EqualsIgnoreCase(ref key, UpgradeInsecureRequests))
{
return "Upgrade-Insecure-Requests";
}
return key.GetAsciiString();
}
private bool EqualsIgnoreCase(ref ReadableBuffer key, byte[] buffer)
{
if (key.Length != buffer.Length)
{
return false;
}
return key.EqualsTo(buffer);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsAlpha(byte b)
{
return b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z';
}
private void SetHeader(string key, StringValues value)
{
_headers[key] = new HeaderValue
{
Value = value
};
}
public void Add(KeyValuePair<string, StringValues> item)
{
SetHeader(item.Key, item.Value);
}
public void Add(string key, StringValues value)
{
SetHeader(key, value);
}
public void Clear()
{
_headers.Clear();
}
public bool Contains(KeyValuePair<string, StringValues> item)
{
return false;
}
public bool ContainsKey(string key)
{
return _headers.ContainsKey(key);
}
public void CopyTo(KeyValuePair<string, StringValues>[] array, int arrayIndex)
{
throw new NotSupportedException();
}
public void Reset()
{
foreach (var pair in _headers)
{
pair.Value.Raw?.Dispose();
}
_headers.Clear();
}
public IEnumerator<KeyValuePair<string, StringValues>> GetEnumerator()
{
return _headers.Select(h => new KeyValuePair<string, StringValues>(h.Key, h.Value.GetValue())).GetEnumerator();
}
public bool Remove(KeyValuePair<string, StringValues> item)
{
throw new NotImplementedException();
}
public bool Remove(string key)
{
return _headers.Remove(key);
}
public bool TryGetValue(string key, out StringValues value)
{
HeaderValue headerValue;
if (_headers.TryGetValue(key, out headerValue))
{
value = headerValue.GetValue();
return true;
}
return false;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private struct HeaderValue
{
public PreservedBuffer? Raw;
public StringValues? Value;
public StringValues GetValue()
{
if (!Value.HasValue)
{
if (!Raw.HasValue)
{
return StringValues.Empty;
}
Value = Raw.Value.Buffer.GetAsciiString();
}
return Value.Value;
}
}
}
}
| |
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Tests.Saga
{
using System;
using System.Threading.Tasks;
using MassTransit.Saga;
using Messages;
using Monitoring.Introspection.Contracts;
using NUnit.Framework;
using Shouldly;
using TestFramework;
[TestFixture]
public class When_an_initiating_message_for_a_saga_arrives :
InMemoryTestFixture
{
[Test]
public void Should_return_a_wonderful_breakdown_of_the_guts_inside_it()
{
ProbeResult result = Bus.GetProbeResult();
Console.WriteLine(result.ToJsonString());
}
[Test]
public async Task The_saga_should_be_created_when_an_initiating_message_is_received()
{
var message = new InitiateSimpleSaga(_sagaId);
await InputQueueSendEndpoint.Send(message);
Guid? sagaId = await _repository.ShouldContainSaga(_sagaId, TestTimeout);
sagaId.HasValue.ShouldBe(true);
}
public When_an_initiating_message_for_a_saga_arrives()
{
_repository = new InMemorySagaRepository<SimpleSaga>();
}
[TestFixtureSetUp]
public void Setup()
{
_sagaId = Guid.NewGuid();
}
protected override void ConfigureBus(IInMemoryBusFactoryConfigurator configurator)
{
base.ConfigureBus(configurator);
configurator.UseRetry(Retry.None);
}
protected override void ConfigureInputQueueEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
{
configurator.UseRetry(Retry.Immediate(2));
configurator.Saga(_repository);
}
Guid _sagaId;
InMemorySagaRepository<SimpleSaga> _repository;
}
[TestFixture]
public class When_an_initiating_message_for_an_existing_saga_arrives :
InMemoryTestFixture
{
[Test]
public async Task The_message_should_fault()
{
Task<ConsumeContext<Fault<InitiateSimpleSaga>>> faulted = SubscribeHandler<Fault<InitiateSimpleSaga>>();
var message = new InitiateSimpleSaga(_sagaId);
await InputQueueSendEndpoint.Send(message);
Guid? sagaId = await _repository.ShouldContainSaga(_sagaId, TestTimeout);
sagaId.HasValue.ShouldBe(true);
await InputQueueSendEndpoint.Send(message);
await faulted;
}
public When_an_initiating_message_for_an_existing_saga_arrives()
{
_repository = new InMemorySagaRepository<SimpleSaga>();
}
[TestFixtureSetUp]
public void Setup()
{
_sagaId = Guid.NewGuid();
}
protected override void ConfigureInputQueueEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
{
configurator.Saga(_repository);
}
Guid _sagaId;
InMemorySagaRepository<SimpleSaga> _repository;
}
[TestFixture]
public class When_an_initiating_and_orchestrated_message_for_a_saga_arrives :
InMemoryTestFixture
{
[Test]
public async Task The_saga_should_be_loaded()
{
await InputQueueSendEndpoint.Send(new InitiateSimpleSaga(_sagaId));
Guid? sagaId = await _repository.ShouldContainSaga(x => x.Initiated, TestTimeout);
await InputQueueSendEndpoint.Send(new CompleteSimpleSaga(_sagaId));
sagaId = await _repository.ShouldContainSaga(x => x.Completed, TestTimeout);
sagaId.HasValue.ShouldBe(true);
}
public When_an_initiating_and_orchestrated_message_for_a_saga_arrives()
{
_repository = new InMemorySagaRepository<SimpleSaga>();
}
[TestFixtureSetUp]
public void Setup()
{
_sagaId = Guid.NewGuid();
}
protected override void ConfigureInputQueueEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
{
configurator.Saga(_repository);
}
Guid _sagaId;
InMemorySagaRepository<SimpleSaga> _repository;
}
[TestFixture]
public class When_an_initiating_and_observed_message_for_a_saga_arrives :
InMemoryTestFixture
{
[Test]
public async Task The_saga_should_be_loaded()
{
await InputQueueSendEndpoint.Send(new InitiateSimpleSaga(_sagaId) {Name = "Chris"});
Guid? sagaId = await _repository.ShouldContainSaga(x => x.Initiated, TestTimeout);
await InputQueueSendEndpoint.Send(new ObservableSagaMessage {Name = "Chris"});
sagaId = await _repository.ShouldContainSaga(x => x.Observed, TestTimeout);
sagaId.HasValue.ShouldBe(true);
}
public When_an_initiating_and_observed_message_for_a_saga_arrives()
{
_repository = new InMemorySagaRepository<SimpleSaga>();
}
[TestFixtureSetUp]
public void Setup()
{
_sagaId = Guid.NewGuid();
}
protected override void ConfigureInputQueueEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
{
configurator.Saga(_repository);
}
Guid _sagaId;
InMemorySagaRepository<SimpleSaga> _repository;
}
[TestFixture]
public class When_an_existing_saga_receives_an_initiating_message :
InMemoryTestFixture
{
[Test]
public async Task An_exception_should_be_thrown()
{
var message = new InitiateSimpleSaga(_sagaId);
await BusSendEndpoint.Send(message);
try
{
await BusSendEndpoint.Send(message);
}
catch (SagaException sex)
{
Assert.AreEqual(sex.MessageType, typeof(InitiateSimpleSaga));
}
}
[TestFixtureSetUp]
public void SetUp()
{
_sagaId = Guid.NewGuid();
_repository = new InMemorySagaRepository<SimpleSaga>();
Bus.ConnectSaga(_repository);
}
Guid _sagaId;
InMemorySagaRepository<SimpleSaga> _repository;
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// 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 Jim Heising 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.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace Controls
{
/// <summary>
/// Summary description for ProgessBarEx.
/// </summary>
public class ProgressBarEx : System.Windows.Forms.UserControl
{
private int minValue = 0;
private int maxValue = 100;
private int upperValue = 0;
private int lowerValue = 0;
private Size rectSize = new Size(0, 0);
private Color minColor = Color.Gold;
private Color maxColor = Color.Red;
private bool allowDraw = true;
private bool drawBoxes = true;
private System.ComponentModel.Container components = null;
public ProgressBarEx()
{
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.DoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.UserPaint, true);
InitializeComponent();
this.DoubleBuffered = true;
CalculateRectSize();
}
public int MinValue
{
get
{
return minValue;
}
set
{
if(minValue > maxValue)
throw new Exception("MinValue must be less than MaxValue");
minValue = value;
this.Invalidate();
}
}
public int MaxValue
{
get
{
return maxValue;
}
set
{
if(minValue > maxValue)
throw new Exception("MaxValue must be greater than MinValue");
maxValue = value;
this.Invalidate();
}
}
public int UpperValue
{
get
{
return upperValue;
}
set
{
upperValue = value;
this.Invalidate();
}
}
public int LowerValue
{
get
{
return lowerValue;
}
set
{
lowerValue = value;
this.Invalidate();
}
}
public Color MinColor
{
get
{
return minColor;
}
set
{
minColor = value;
this.Invalidate();
}
}
public Color MaxColor
{
get
{
return maxColor;
}
set
{
maxColor = value;
this.Invalidate();
}
}
public bool DrawTicks
{
get
{
return drawBoxes;
}
set
{
drawBoxes = value;
this.Invalidate();
}
}
internal bool AllowDraw
{
get
{
return allowDraw;
}
set
{
allowDraw = value;
if(allowDraw)
this.Invalidate();
}
}
protected override void OnPaint(PaintEventArgs e)
{
if(allowDraw)
{
// Draw rects
using(Pen borderPen = new Pen(this.ForeColor, 1))
{
using(LinearGradientBrush gradientBrush = new LinearGradientBrush(this.ClientRectangle, minColor, maxColor, 0, false))
{
int range = maxValue - minValue;
int lowerAdj = lowerValue - minValue;
int upperAdj = lowerAdj + (upperValue - lowerValue);
if (drawBoxes)
{
for (int x = 0; x < this.Width - rectSize.Width; x += rectSize.Width + 2)
{
if (range > 0)
{
int lowerX = (int)((float)lowerAdj / (float)range * (float)this.Width);
int upperX = (int)((float)upperAdj / (float)range * (float)this.Width);
// Only draw the fill if it's within our range
if (upperAdj > 0 && x >= lowerX && x <= upperX - rectSize.Width)
e.Graphics.FillRectangle(gradientBrush, x, 0, rectSize.Width, rectSize.Height);
}
e.Graphics.DrawRectangle(borderPen, x, 0, rectSize.Width, rectSize.Height);
}
}
else
{
int lowerX = (int)((float)lowerAdj / (float)range * (float)this.Width);
int upperX = (int)((float)upperAdj / (float)range * (float)this.Width);
e.Graphics.FillRectangle(gradientBrush, lowerX, 0, upperX, rectSize.Height);
e.Graphics.DrawRectangle(borderPen, 0, 0, this.Width - 1, this.Height - 1);
}
}
}
}
}
private void CalculateRectSize()
{
rectSize.Height = this.Height - 1;
rectSize.Width = rectSize.Height * 2;
}
protected override void OnResize(EventArgs e)
{
base.OnResize (e);
CalculateRectSize();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
//
// ProgressBarEx
//
this.ForeColor = System.Drawing.Color.Gray;
this.Name = "ProgressBarEx";
this.Size = new System.Drawing.Size(200, 8);
}
#endregion
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
using System.Runtime.Remoting;
using System.Runtime.Serialization;
using System.Reflection;
using System.Globalization;
using System.Runtime.Versioning;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace System {
[Serializable]
// Holds classes (Empty, Null, Missing) for which we guarantee that there is only ever one instance of.
internal class UnitySerializationHolder : ISerializable, IObjectReference
{
#region Internal Constants
internal const int EmptyUnity = 0x0001;
internal const int NullUnity = 0x0002;
internal const int MissingUnity = 0x0003;
internal const int RuntimeTypeUnity = 0x0004;
internal const int ModuleUnity = 0x0005;
internal const int AssemblyUnity = 0x0006;
internal const int GenericParameterTypeUnity = 0x0007;
internal const int PartialInstantiationTypeUnity = 0x0008;
internal const int Pointer = 0x0001;
internal const int Array = 0x0002;
internal const int SzArray = 0x0003;
internal const int ByRef = 0x0004;
#endregion
#region Internal Static Members
internal static void GetUnitySerializationInfo(SerializationInfo info, Missing missing)
{
info.SetType(typeof(UnitySerializationHolder));
info.AddValue("UnityType", MissingUnity);
}
internal static RuntimeType AddElementTypes(SerializationInfo info, RuntimeType type)
{
List<int> elementTypes = new List<int>();
while(type.HasElementType)
{
if (type.IsSzArray)
{
elementTypes.Add(SzArray);
}
else if (type.IsArray)
{
elementTypes.Add(type.GetArrayRank());
elementTypes.Add(Array);
}
else if (type.IsPointer)
{
elementTypes.Add(Pointer);
}
else if (type.IsByRef)
{
elementTypes.Add(ByRef);
}
type = (RuntimeType)type.GetElementType();
}
info.AddValue("ElementTypes", elementTypes.ToArray(), typeof(int[]));
return type;
}
internal Type MakeElementTypes(Type type)
{
for (int i = m_elementTypes.Length - 1; i >= 0; i --)
{
if (m_elementTypes[i] == SzArray)
{
type = type.MakeArrayType();
}
else if (m_elementTypes[i] == Array)
{
type = type.MakeArrayType(m_elementTypes[--i]);
}
else if ((m_elementTypes[i] == Pointer))
{
type = type.MakePointerType();
}
else if ((m_elementTypes[i] == ByRef))
{
type = type.MakeByRefType();
}
}
return type;
}
internal static void GetUnitySerializationInfo(SerializationInfo info, RuntimeType type)
{
if (type.GetRootElementType().IsGenericParameter)
{
type = AddElementTypes(info, type);
info.SetType(typeof(UnitySerializationHolder));
info.AddValue("UnityType", GenericParameterTypeUnity);
info.AddValue("GenericParameterPosition", type.GenericParameterPosition);
info.AddValue("DeclaringMethod", type.DeclaringMethod, typeof(MethodBase));
info.AddValue("DeclaringType", type.DeclaringType, typeof(Type));
return;
}
int unityType = RuntimeTypeUnity;
if (!type.IsGenericTypeDefinition && type.ContainsGenericParameters)
{
// Partial instantiation
unityType = PartialInstantiationTypeUnity;
type = AddElementTypes(info, type);
info.AddValue("GenericArguments", type.GetGenericArguments(), typeof(Type[]));
type = (RuntimeType)type.GetGenericTypeDefinition();
}
GetUnitySerializationInfo(info, unityType, type.FullName, type.GetRuntimeAssembly());
}
internal static void GetUnitySerializationInfo(
SerializationInfo info, int unityType, String data, RuntimeAssembly assembly)
{
// A helper method that returns the SerializationInfo that a class utilizing
// UnitySerializationHelper should return from a call to GetObjectData. It contains
// the unityType (defined above) and any optional data (used only for the reflection
// types.)
info.SetType(typeof(UnitySerializationHolder));
info.AddValue("Data", data, typeof(String));
info.AddValue("UnityType", unityType);
String assemName;
if (assembly == null)
{
assemName = String.Empty;
}
else
{
assemName = assembly.FullName;
}
info.AddValue("AssemblyName", assemName);
}
#endregion
#region Private Data Members
private Type[] m_instantiation;
private int[] m_elementTypes;
private int m_genericParameterPosition;
private Type m_declaringType;
private MethodBase m_declaringMethod;
private String m_data;
private String m_assemblyName;
private int m_unityType;
#endregion
#region Constructor
internal UnitySerializationHolder(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
Contract.EndContractBlock();
m_unityType = info.GetInt32("UnityType");
if (m_unityType == MissingUnity)
return;
if (m_unityType == GenericParameterTypeUnity)
{
m_declaringMethod = info.GetValue("DeclaringMethod", typeof(MethodBase)) as MethodBase;
m_declaringType = info.GetValue("DeclaringType", typeof(Type)) as Type;
m_genericParameterPosition = info.GetInt32("GenericParameterPosition");
m_elementTypes = info.GetValue("ElementTypes", typeof(int[])) as int[];
return;
}
if (m_unityType == PartialInstantiationTypeUnity)
{
m_instantiation = info.GetValue("GenericArguments", typeof(Type[])) as Type[];
m_elementTypes = info.GetValue("ElementTypes", typeof(int[])) as int[];
}
m_data = info.GetString("Data");
m_assemblyName = info.GetString("AssemblyName");
}
#endregion
#region Private Methods
private void ThrowInsufficientInformation(string field)
{
throw new SerializationException(
Environment.GetResourceString("Serialization_InsufficientDeserializationState", field));
}
#endregion
#region ISerializable
[System.Security.SecurityCritical] // auto-generated
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnitySerHolder"));
}
#endregion
#region IObjectReference
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)] // The Module here was already created and theoretically scoped. There's not enough information to pass this info through to the serializer, and most serialization instances aren't using machine resources.
[ResourceConsumption(ResourceScope.Machine | ResourceScope.Assembly, ResourceScope.Machine | ResourceScope.Assembly)]
public virtual Object GetRealObject(StreamingContext context)
{
// GetRealObject uses the data we have in m_data and m_unityType to do a lookup on the correct
// object to return. We have specific code here to handle the different types which we support.
// The reflection types (Assembly, Module, and Type) have to be looked up through their static
// accessors by name.
Assembly assembly;
switch (m_unityType)
{
case EmptyUnity:
{
return Empty.Value;
}
case NullUnity:
{
return DBNull.Value;
}
case MissingUnity:
{
return Missing.Value;
}
case PartialInstantiationTypeUnity:
{
m_unityType = RuntimeTypeUnity;
Type definition = GetRealObject(context) as Type;
m_unityType = PartialInstantiationTypeUnity;
if (m_instantiation[0] == null)
return null;
return MakeElementTypes(definition.MakeGenericType(m_instantiation));
}
case GenericParameterTypeUnity:
{
if (m_declaringMethod == null && m_declaringType == null)
ThrowInsufficientInformation("DeclaringMember");
if (m_declaringMethod != null)
return m_declaringMethod.GetGenericArguments()[m_genericParameterPosition];
return MakeElementTypes(m_declaringType.GetGenericArguments()[m_genericParameterPosition]);
}
case RuntimeTypeUnity:
{
if (m_data == null || m_data.Length == 0)
ThrowInsufficientInformation("Data");
if (m_assemblyName == null)
ThrowInsufficientInformation("AssemblyName");
if (m_assemblyName.Length == 0)
return Type.GetType(m_data, true, false);
assembly = Assembly.Load(m_assemblyName);
Type t = assembly.GetType(m_data, true, false);
return t;
}
case ModuleUnity:
{
if (m_data == null || m_data.Length == 0)
ThrowInsufficientInformation("Data");
if (m_assemblyName == null)
ThrowInsufficientInformation("AssemblyName");
assembly = Assembly.Load(m_assemblyName);
Module namedModule = assembly.GetModule(m_data);
if (namedModule == null)
throw new SerializationException(
Environment.GetResourceString("Serialization_UnableToFindModule", m_data, m_assemblyName));
return namedModule;
}
case AssemblyUnity:
{
if (m_data == null || m_data.Length == 0)
ThrowInsufficientInformation("Data");
if (m_assemblyName == null)
ThrowInsufficientInformation("AssemblyName");
assembly = Assembly.Load(m_assemblyName);
return assembly;
}
default:
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidUnity"));
}
}
#endregion
}
}
| |
// Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Firebase.Sample.DynamicLinks {
using Firebase;
using Firebase.DynamicLinks;
using Firebase.Extensions;
using System;
using System.Collections;
using System.Threading.Tasks;
using UnityEngine;
// Handler for UI buttons on the scene. Also performs some
// necessary setup (initializing the firebase app, etc) on
// startup.
public class UIHandler : MonoBehaviour {
public GUISkin fb_GUISkin;
private Vector2 controlsScrollViewVector = Vector2.zero;
private Vector2 scrollViewVector = Vector2.zero;
bool UIEnabled = true;
private string logText = "";
const int kMaxLogSize = 16382;
DependencyStatus dependencyStatus = DependencyStatus.UnavailableOther;
const string kInvalidDomainUriPrefix = "THIS_IS_AN_INVALID_DOMAIN";
const string kDomainUriPrefixInvalidError =
"kDomainUriPrefix is not valid, link shortening will fail.\n" +
"To resolve this:\n" +
"* Goto the Firebase console https://firebase.google.com/console/\n" +
"* Click on the Dynamic Links tab\n" +
"* Copy the domain e.g x20yz.app.goo.gl\n" +
"* Replace the value of kDomainUriPrefix with the copied domain.\n";
public bool firebaseInitialized = false;
// IMPORTANT: You need to set this to a valid domain from the Firebase
// console (see kDomainUriPrefixInvalidError for the details).
public string kDomainUriPrefix = kInvalidDomainUriPrefix;
// When the app starts, check to make sure that we have
// the required dependencies to use Firebase, and if not,
// add them if possible.
public virtual void Start() {
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => {
dependencyStatus = task.Result;
if (dependencyStatus == DependencyStatus.Available) {
InitializeFirebase();
} else {
Debug.LogError(
"Could not resolve all Firebase dependencies: " + dependencyStatus);
}
});
}
// Exit if escape (or back, on mobile) is pressed.
public virtual void Update() {
if (Input.GetKeyDown(KeyCode.Escape)) {
Application.Quit();
}
}
// Handle initialization of the necessary firebase modules:
void InitializeFirebase() {
DynamicLinks.DynamicLinkReceived += OnDynamicLink;
firebaseInitialized = true;
}
void OnDestroy() {
DynamicLinks.DynamicLinkReceived -= OnDynamicLink;
}
// Display the dynamic link received by the application.
void OnDynamicLink(object sender, EventArgs args) {
var dynamicLinkEventArgs = args as ReceivedDynamicLinkEventArgs;
DebugLog(String.Format("Received dynamic link {0}",
dynamicLinkEventArgs.ReceivedDynamicLink.Url.OriginalString));
}
// Output text to the debug log text field, as well as the console.
public void DebugLog(string s) {
print(s);
logText += s + "\n";
while (logText.Length > kMaxLogSize) {
int index = logText.IndexOf("\n");
logText = logText.Substring(index + 1);
}
scrollViewVector.y = int.MaxValue;
}
public void DisableUI() {
UIEnabled = false;
}
public void EnableUI() {
UIEnabled = true;
}
// Render the log output in a scroll view.
void GUIDisplayLog() {
scrollViewVector = GUILayout.BeginScrollView(scrollViewVector);
GUILayout.Label(logText);
GUILayout.EndScrollView();
}
DynamicLinkComponents CreateDynamicLinkComponents() {
#if UNITY_5_6_OR_NEWER
string appIdentifier = Application.identifier;
#else
string appIdentifier = Application.bundleIdentifier;
#endif
return new DynamicLinkComponents(
// The base Link.
new System.Uri("https://google.com/abc"),
// The dynamic link domain.
kDomainUriPrefix) {
GoogleAnalyticsParameters = new Firebase.DynamicLinks.GoogleAnalyticsParameters() {
Source = "mysource",
Medium = "mymedium",
Campaign = "mycampaign",
Term = "myterm",
Content = "mycontent"
},
IOSParameters = new Firebase.DynamicLinks.IOSParameters(appIdentifier) {
FallbackUrl = new System.Uri("https://mysite/fallback"),
CustomScheme = "mycustomscheme",
MinimumVersion = "1.2.3",
IPadBundleId = appIdentifier,
IPadFallbackUrl = new System.Uri("https://mysite/fallbackipad")
},
ITunesConnectAnalyticsParameters =
new Firebase.DynamicLinks.ITunesConnectAnalyticsParameters() {
AffiliateToken = "abcdefg",
CampaignToken = "hijklmno",
ProviderToken = "pq-rstuv"
},
AndroidParameters = new Firebase.DynamicLinks.AndroidParameters(appIdentifier) {
FallbackUrl = new System.Uri("https://mysite/fallback"),
MinimumVersion = 12
},
SocialMetaTagParameters = new Firebase.DynamicLinks.SocialMetaTagParameters() {
Title = "My App!",
Description = "My app is awesome!",
ImageUrl = new System.Uri("https://mysite.com/someimage.jpg")
},
};
}
public Uri CreateAndDisplayLongLink() {
var longLink = CreateDynamicLinkComponents().LongDynamicLink;
DebugLog(String.Format("Long dynamic link {0}", longLink));
return longLink;
}
public Task<ShortDynamicLink> CreateAndDisplayShortLinkAsync() {
return CreateAndDisplayShortLinkAsync(new DynamicLinkOptions());
}
public Task<ShortDynamicLink> CreateAndDisplayUnguessableShortLinkAsync() {
return CreateAndDisplayShortLinkAsync(new DynamicLinkOptions {
PathLength = DynamicLinkPathLength.Unguessable
});
}
private Task<ShortDynamicLink> CreateAndDisplayShortLinkAsync(DynamicLinkOptions options) {
if (kDomainUriPrefix == kInvalidDomainUriPrefix) {
DebugLog(kDomainUriPrefixInvalidError);
var source = new TaskCompletionSource<ShortDynamicLink>();
source.TrySetException(new Exception(kDomainUriPrefixInvalidError));
return source.Task;
}
var components = CreateDynamicLinkComponents();
return DynamicLinks.GetShortLinkAsync(components, options)
.ContinueWithOnMainThread((task) => {
if (task.IsCanceled) {
DebugLog("Short link creation canceled");
} else if (task.IsFaulted) {
DebugLog(String.Format("Short link creation failed {0}", task.Exception.ToString()));
} else {
ShortDynamicLink link = task.Result;
DebugLog(String.Format("Generated short link {0}", link.Url));
var warnings = new System.Collections.Generic.List<string>(link.Warnings);
if (warnings.Count > 0) {
DebugLog("Warnings:");
foreach (var warning in warnings) {
DebugLog(" " + warning);
}
}
}
return task.Result;
});
}
// Render the buttons and other controls.
void GUIDisplayControls() {
if (UIEnabled) {
controlsScrollViewVector =
GUILayout.BeginScrollView(controlsScrollViewVector);
GUILayout.BeginVertical();
if (GUILayout.Button("Display Long Link")) {
CreateAndDisplayLongLink();
}
if (GUILayout.Button("Create Short Link")) {
CreateAndDisplayShortLinkAsync();
}
if (GUILayout.Button("Create Unguessable Short Link")) {
CreateAndDisplayUnguessableShortLinkAsync();
}
GUILayout.EndVertical();
GUILayout.EndScrollView();
}
}
// Render the GUI:
void OnGUI() {
GUI.skin = fb_GUISkin;
if (dependencyStatus != DependencyStatus.Available) {
GUILayout.Label("One or more Firebase dependencies are not present.");
GUILayout.Label("Current dependency status: " + dependencyStatus.ToString());
return;
}
Rect logArea, controlArea;
if (Screen.width < Screen.height) {
// Portrait mode
controlArea = new Rect(0.0f, 0.0f, Screen.width, Screen.height * 0.5f);
logArea = new Rect(0.0f, Screen.height * 0.5f, Screen.width, Screen.height * 0.5f);
} else {
// Landscape mode
controlArea = new Rect(0.0f, 0.0f, Screen.width * 0.5f, Screen.height);
logArea = new Rect(Screen.width * 0.5f, 0.0f, Screen.width * 0.5f, Screen.height);
}
GUILayout.BeginArea(logArea);
GUIDisplayLog();
GUILayout.EndArea();
GUILayout.BeginArea(controlArea);
GUIDisplayControls();
GUILayout.EndArea();
}
}
}
| |
/*
* 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.IO;
using System.IO.Compression;
using System.Reflection;
using System.Threading;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Serialization;
using OpenSim.Framework.Serialization.External;
using OpenSim.Region.CoreModules.World.Archiver;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
{
public class InventoryArchiveReadRequest
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// The maximum major version of archive that we can read. Minor versions shouldn't need a max number since version
/// bumps here should be compatible.
/// </summary>
public static int MAX_MAJOR_VERSION = 1;
protected TarArchiveReader archive;
private UserAccount m_userInfo;
private string m_invPath;
/// <summary>
/// Do we want to merge this load with existing inventory?
/// </summary>
protected bool m_merge;
protected IInventoryService m_InventoryService;
protected IAssetService m_AssetService;
protected IUserAccountService m_UserAccountService;
/// <value>
/// The stream from which the inventory archive will be loaded.
/// </value>
private Stream m_loadStream;
/// <summary>
/// Has the control file been loaded for this archive?
/// </summary>
public bool ControlFileLoaded { get; private set; }
/// <summary>
/// Do we want to enforce the check. IAR versions before 0.2 and 1.1 do not guarantee this order, so we can't
/// enforce.
/// </summary>
public bool EnforceControlFileCheck { get; private set; }
protected bool m_assetsLoaded;
protected bool m_inventoryNodesLoaded;
protected int m_successfulAssetRestores;
protected int m_failedAssetRestores;
protected int m_successfulItemRestores;
/// <summary>
/// Root destination folder for the IAR load.
/// </summary>
protected InventoryFolderBase m_rootDestinationFolder;
/// <summary>
/// Inventory nodes loaded from the iar.
/// </summary>
protected HashSet<InventoryNodeBase> m_loadedNodes = new HashSet<InventoryNodeBase>();
/// <summary>
/// In order to load identically named folders, we need to keep track of the folders that we have already
/// resolved.
/// </summary>
Dictionary <string, InventoryFolderBase> m_resolvedFolders = new Dictionary<string, InventoryFolderBase>();
/// <summary>
/// Record the creator id that should be associated with an asset. This is used to adjust asset creator ids
/// after OSP resolution (since OSP creators are only stored in the item
/// </summary>
protected Dictionary<UUID, UUID> m_creatorIdForAssetId = new Dictionary<UUID, UUID>();
public InventoryArchiveReadRequest(
IInventoryService inv, IAssetService assets, IUserAccountService uacc, UserAccount userInfo, string invPath, string loadPath, bool merge)
: this(
inv,
assets,
uacc,
userInfo,
invPath,
new GZipStream(ArchiveHelpers.GetStream(loadPath), CompressionMode.Decompress),
merge)
{
}
public InventoryArchiveReadRequest(
IInventoryService inv, IAssetService assets, IUserAccountService uacc, UserAccount userInfo, string invPath, Stream loadStream, bool merge)
{
m_InventoryService = inv;
m_AssetService = assets;
m_UserAccountService = uacc;
m_merge = merge;
m_userInfo = userInfo;
m_invPath = invPath;
m_loadStream = loadStream;
// FIXME: Do not perform this check since older versions of OpenSim do save the control file after other things
// (I thought they weren't). We will need to bump the version number and perform this check on all
// subsequent IAR versions only
ControlFileLoaded = true;
}
/// <summary>
/// Execute the request
/// </summary>
/// <remarks>
/// Only call this once. To load another IAR, construct another request object.
/// </remarks>
/// <returns>
/// A list of the inventory nodes loaded. If folders were loaded then only the root folders are
/// returned
/// </returns>
/// <exception cref="System.Exception">Thrown if load fails.</exception>
public HashSet<InventoryNodeBase> Execute()
{
try
{
string filePath = "ERROR";
List<InventoryFolderBase> folderCandidates
= InventoryArchiveUtils.FindFoldersByPath(
m_InventoryService, m_userInfo.PrincipalID, m_invPath);
if (folderCandidates.Count == 0)
{
// Possibly provide an option later on to automatically create this folder if it does not exist
m_log.ErrorFormat("[INVENTORY ARCHIVER]: Inventory path {0} does not exist", m_invPath);
return m_loadedNodes;
}
m_rootDestinationFolder = folderCandidates[0];
archive = new TarArchiveReader(m_loadStream);
byte[] data;
TarArchiveReader.TarEntryType entryType;
while ((data = archive.ReadEntry(out filePath, out entryType)) != null)
{
if (filePath == ArchiveConstants.CONTROL_FILE_PATH)
{
LoadControlFile(filePath, data);
}
else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH))
{
LoadAssetFile(filePath, data);
}
else if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH))
{
LoadInventoryFile(filePath, entryType, data);
}
}
archive.Close();
m_log.DebugFormat(
"[INVENTORY ARCHIVER]: Successfully loaded {0} assets with {1} failures",
m_successfulAssetRestores, m_failedAssetRestores);
m_log.InfoFormat("[INVENTORY ARCHIVER]: Successfully loaded {0} items", m_successfulItemRestores);
return m_loadedNodes;
}
finally
{
m_loadStream.Close();
}
}
public void Close()
{
if (m_loadStream != null)
m_loadStream.Close();
}
/// <summary>
/// Replicate the inventory paths in the archive to the user's inventory as necessary.
/// </summary>
/// <param name="iarPath">The item archive path to replicate</param>
/// <param name="rootDestinationFolder">The root folder for the inventory load</param>
/// <param name="resolvedFolders">
/// The folders that we have resolved so far for a given archive path.
/// This method will add more folders if necessary
/// </param>
/// <param name="loadedNodes">
/// Track the inventory nodes created.
/// </param>
/// <returns>The last user inventory folder created or found for the archive path</returns>
public InventoryFolderBase ReplicateArchivePathToUserInventory(
string iarPath,
InventoryFolderBase rootDestFolder,
Dictionary <string, InventoryFolderBase> resolvedFolders,
HashSet<InventoryNodeBase> loadedNodes)
{
string iarPathExisting = iarPath;
// m_log.DebugFormat(
// "[INVENTORY ARCHIVER]: Loading folder {0} {1}", rootDestFolder.Name, rootDestFolder.ID);
InventoryFolderBase destFolder
= ResolveDestinationFolder(rootDestFolder, ref iarPathExisting, resolvedFolders);
// m_log.DebugFormat(
// "[INVENTORY ARCHIVER]: originalArchivePath [{0}], section already loaded [{1}]",
// iarPath, iarPathExisting);
string iarPathToCreate = iarPath.Substring(iarPathExisting.Length);
CreateFoldersForPath(destFolder, iarPathExisting, iarPathToCreate, resolvedFolders, loadedNodes);
return destFolder;
}
/// <summary>
/// Resolve a destination folder
/// </summary>
///
/// We require here a root destination folder (usually the root of the user's inventory) and the archive
/// path. We also pass in a list of previously resolved folders in case we've found this one previously.
///
/// <param name="archivePath">
/// The item archive path to resolve. The portion of the path passed back is that
/// which corresponds to the resolved desintation folder.
/// <param name="rootDestinationFolder">
/// The root folder for the inventory load
/// </param>
/// <param name="resolvedFolders">
/// The folders that we have resolved so far for a given archive path.
/// </param>
/// <returns>
/// The folder in the user's inventory that matches best the archive path given. If no such folder was found
/// then the passed in root destination folder is returned.
/// </returns>
protected InventoryFolderBase ResolveDestinationFolder(
InventoryFolderBase rootDestFolder,
ref string archivePath,
Dictionary <string, InventoryFolderBase> resolvedFolders)
{
// string originalArchivePath = archivePath;
while (archivePath.Length > 0)
{
// m_log.DebugFormat("[INVENTORY ARCHIVER]: Trying to resolve destination folder {0}", archivePath);
if (resolvedFolders.ContainsKey(archivePath))
{
// m_log.DebugFormat(
// "[INVENTORY ARCHIVER]: Found previously created folder from archive path {0}", archivePath);
return resolvedFolders[archivePath];
}
else
{
if (m_merge)
{
// TODO: Using m_invPath is totally wrong - what we need to do is strip the uuid from the
// iar name and try to find that instead.
string plainPath = ArchiveConstants.ExtractPlainPathFromIarPath(archivePath);
List<InventoryFolderBase> folderCandidates
= InventoryArchiveUtils.FindFoldersByPath(
m_InventoryService, m_userInfo.PrincipalID, plainPath);
if (folderCandidates.Count != 0)
{
InventoryFolderBase destFolder = folderCandidates[0];
resolvedFolders[archivePath] = destFolder;
return destFolder;
}
}
// Don't include the last slash so find the penultimate one
int penultimateSlashIndex = archivePath.LastIndexOf("/", archivePath.Length - 2);
if (penultimateSlashIndex >= 0)
{
// Remove the last section of path so that we can see if we've already resolved the parent
archivePath = archivePath.Remove(penultimateSlashIndex + 1);
}
else
{
// m_log.DebugFormat(
// "[INVENTORY ARCHIVER]: Found no previously created folder for archive path {0}",
// originalArchivePath);
archivePath = string.Empty;
return rootDestFolder;
}
}
}
return rootDestFolder;
}
/// <summary>
/// Create a set of folders for the given path.
/// </summary>
/// <param name="destFolder">
/// The root folder from which the creation will take place.
/// </param>
/// <param name="iarPathExisting">
/// the part of the iar path that already exists
/// </param>
/// <param name="iarPathToReplicate">
/// The path to replicate in the user's inventory from iar
/// </param>
/// <param name="resolvedFolders">
/// The folders that we have resolved so far for a given archive path.
/// </param>
/// <param name="loadedNodes">
/// Track the inventory nodes created.
/// </param>
protected void CreateFoldersForPath(
InventoryFolderBase destFolder,
string iarPathExisting,
string iarPathToReplicate,
Dictionary <string, InventoryFolderBase> resolvedFolders,
HashSet<InventoryNodeBase> loadedNodes)
{
string[] rawDirsToCreate = iarPathToReplicate.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < rawDirsToCreate.Length; i++)
{
// m_log.DebugFormat("[INVENTORY ARCHIVER]: Creating folder {0} from IAR", rawDirsToCreate[i]);
if (!rawDirsToCreate[i].Contains(ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR))
continue;
int identicalNameIdentifierIndex
= rawDirsToCreate[i].LastIndexOf(
ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR);
string newFolderName = rawDirsToCreate[i].Remove(identicalNameIdentifierIndex);
newFolderName = InventoryArchiveUtils.UnescapeArchivePath(newFolderName);
UUID newFolderId = UUID.Random();
// Asset type has to be Unknown here rather than Folder, otherwise the created folder can't be
// deleted once the client has relogged.
// The root folder appears to be labelled AssetType.Folder (shows up as "Category" in the client)
// even though there is a AssetType.RootCategory
destFolder
= new InventoryFolderBase(
newFolderId, newFolderName, m_userInfo.PrincipalID,
(short)AssetType.Unknown, destFolder.ID, 1);
m_InventoryService.AddFolder(destFolder);
// Record that we have now created this folder
iarPathExisting += rawDirsToCreate[i] + "/";
m_log.DebugFormat("[INVENTORY ARCHIVER]: Created folder {0} from IAR", iarPathExisting);
resolvedFolders[iarPathExisting] = destFolder;
if (0 == i)
loadedNodes.Add(destFolder);
}
}
/// <summary>
/// Load an item from the archive
/// </summary>
/// <param name="filePath">The archive path for the item</param>
/// <param name="data">The raw item data</param>
/// <param name="rootDestinationFolder">The root destination folder for loaded items</param>
/// <param name="nodesLoaded">All the inventory nodes (items and folders) loaded so far</param>
protected InventoryItemBase LoadItem(byte[] data, InventoryFolderBase loadFolder)
{
InventoryItemBase item = UserInventoryItemSerializer.Deserialize(data);
// Don't use the item ID that's in the file
item.ID = UUID.Random();
UUID ospResolvedId = OspResolver.ResolveOspa(item.CreatorId, m_UserAccountService);
if (UUID.Zero != ospResolvedId) // The user exists in this grid
{
// m_log.DebugFormat("[INVENTORY ARCHIVER]: Found creator {0} via OSPA resolution", ospResolvedId);
// item.CreatorIdAsUuid = ospResolvedId;
// Don't preserve the OSPA in the creator id (which actually gets persisted to the
// database). Instead, replace with the UUID that we found.
item.CreatorId = ospResolvedId.ToString();
item.CreatorData = string.Empty;
}
else if (string.IsNullOrEmpty(item.CreatorData))
{
item.CreatorId = m_userInfo.PrincipalID.ToString();
// item.CreatorIdAsUuid = new UUID(item.CreatorId);
}
item.Owner = m_userInfo.PrincipalID;
// Reset folder ID to the one in which we want to load it
item.Folder = loadFolder.ID;
// Record the creator id for the item's asset so that we can use it later, if necessary, when the asset
// is loaded.
// FIXME: This relies on the items coming before the assets in the TAR file. Need to create stronger
// checks for this, and maybe even an external tool for creating OARs which enforces this, rather than
// relying on native tar tools.
m_creatorIdForAssetId[item.AssetID] = item.CreatorIdAsUuid;
if (!m_InventoryService.AddItem(item))
m_log.WarnFormat("[INVENTORY ARCHIVER]: Unable to save item {0} in folder {1}", item.Name, item.Folder);
return item;
}
/// <summary>
/// Load an asset
/// </summary>
/// <param name="assetFilename"></param>
/// <param name="data"></param>
/// <returns>true if asset was successfully loaded, false otherwise</returns>
private bool LoadAsset(string assetPath, byte[] data)
{
//IRegionSerialiser serialiser = scene.RequestModuleInterface<IRegionSerialiser>();
// Right now we're nastily obtaining the UUID from the filename
string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);
int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
if (i == -1)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping",
assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
return false;
}
string extension = filename.Substring(i);
string rawUuid = filename.Remove(filename.Length - extension.Length);
UUID assetId = new UUID(rawUuid);
if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension))
{
sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension];
if (assetType == (sbyte)AssetType.Unknown)
{
m_log.WarnFormat("[INVENTORY ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, assetId);
}
else if (assetType == (sbyte)AssetType.Object)
{
if (m_creatorIdForAssetId.ContainsKey(assetId))
{
data = SceneObjectSerializer.ModifySerializedObject(assetId, data,
sog => {
bool modified = false;
foreach (SceneObjectPart sop in sog.Parts)
{
if (string.IsNullOrEmpty(sop.CreatorData))
{
sop.CreatorID = m_creatorIdForAssetId[assetId];
modified = true;
}
}
return modified;
});
if (data == null)
return false;
}
}
//m_log.DebugFormat("[INVENTORY ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType);
AssetBase asset = new AssetBase(assetId, "From IAR", assetType, UUID.Zero.ToString());
asset.Data = data;
m_AssetService.Store(asset);
return true;
}
else
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}",
assetPath, extension);
return false;
}
}
/// <summary>
/// Load control file
/// </summary>
/// <param name="path"></param>
/// <param name="data"></param>
public void LoadControlFile(string path, byte[] data)
{
XDocument doc = XDocument.Parse(Encoding.ASCII.GetString(data));
XElement archiveElement = doc.Element("archive");
int majorVersion = int.Parse(archiveElement.Attribute("major_version").Value);
int minorVersion = int.Parse(archiveElement.Attribute("minor_version").Value);
string version = string.Format("{0}.{1}", majorVersion, minorVersion);
if (majorVersion > MAX_MAJOR_VERSION)
{
throw new Exception(
string.Format(
"The IAR you are trying to load has major version number of {0} but this version of OpenSim can only load IARs with major version number {1} and below",
majorVersion, MAX_MAJOR_VERSION));
}
ControlFileLoaded = true;
m_log.InfoFormat("[INVENTORY ARCHIVER]: Loading IAR with version {0}", version);
}
/// <summary>
/// Load inventory file
/// </summary>
/// <param name="path"></param>
/// <param name="entryType"></param>
/// <param name="data"></param>
protected void LoadInventoryFile(string path, TarArchiveReader.TarEntryType entryType, byte[] data)
{
if (!ControlFileLoaded)
throw new Exception(
string.Format(
"The IAR you are trying to load does not list {0} before {1}. Aborting load",
ArchiveConstants.CONTROL_FILE_PATH, ArchiveConstants.INVENTORY_PATH));
if (m_assetsLoaded)
throw new Exception(
string.Format(
"The IAR you are trying to load does not list all {0} before {1}. Aborting load",
ArchiveConstants.INVENTORY_PATH, ArchiveConstants.ASSETS_PATH));
path = path.Substring(ArchiveConstants.INVENTORY_PATH.Length);
// Trim off the file portion if we aren't already dealing with a directory path
if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY != entryType)
path = path.Remove(path.LastIndexOf("/") + 1);
InventoryFolderBase foundFolder
= ReplicateArchivePathToUserInventory(
path, m_rootDestinationFolder, m_resolvedFolders, m_loadedNodes);
if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY != entryType)
{
InventoryItemBase item = LoadItem(data, foundFolder);
if (item != null)
{
m_successfulItemRestores++;
// If we aren't loading the folder containing the item then well need to update the
// viewer separately for that item.
if (!m_loadedNodes.Contains(foundFolder))
m_loadedNodes.Add(item);
}
}
m_inventoryNodesLoaded = true;
}
/// <summary>
/// Load asset file
/// </summary>
/// <param name="path"></param>
/// <param name="data"></param>
protected void LoadAssetFile(string path, byte[] data)
{
if (!ControlFileLoaded)
throw new Exception(
string.Format(
"The IAR you are trying to load does not list {0} before {1}. Aborting load",
ArchiveConstants.CONTROL_FILE_PATH, ArchiveConstants.ASSETS_PATH));
if (!m_inventoryNodesLoaded)
throw new Exception(
string.Format(
"The IAR you are trying to load does not list all {0} before {1}. Aborting load",
ArchiveConstants.INVENTORY_PATH, ArchiveConstants.ASSETS_PATH));
if (LoadAsset(path, data))
m_successfulAssetRestores++;
else
m_failedAssetRestores++;
if ((m_successfulAssetRestores) % 50 == 0)
m_log.DebugFormat(
"[INVENTORY ARCHIVER]: Loaded {0} assets...",
m_successfulAssetRestores);
m_assetsLoaded = true;
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Data.MultiBinding.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Data
{
public partial class MultiBinding : BindingBase, System.Windows.Markup.IAddChild
{
#region Methods and constructors
public MultiBinding()
{
}
public bool ShouldSerializeBindings()
{
return default(bool);
}
public bool ShouldSerializeValidationRules()
{
return default(bool);
}
void System.Windows.Markup.IAddChild.AddChild(Object value)
{
}
void System.Windows.Markup.IAddChild.AddText(string text)
{
}
#endregion
#region Properties and indexers
public System.Collections.ObjectModel.Collection<BindingBase> Bindings
{
get
{
Contract.Ensures(Contract.Result<Collection<BindingBase>>() != null);
return default(System.Collections.ObjectModel.Collection<BindingBase>);
}
}
public IMultiValueConverter Converter
{
get
{
return default(IMultiValueConverter);
}
set
{
}
}
public System.Globalization.CultureInfo ConverterCulture
{
get
{
return default(System.Globalization.CultureInfo);
}
set
{
}
}
public Object ConverterParameter
{
get
{
return default(Object);
}
set
{
}
}
public BindingMode Mode
{
get
{
Contract.Ensures(((System.Windows.Data.BindingMode)(0)) <= Contract.Result<System.Windows.Data.BindingMode>());
Contract.Ensures(Contract.Result<System.Windows.Data.BindingMode>() <= ((System.Windows.Data.BindingMode)(4)));
return default(BindingMode);
}
set
{
}
}
public bool NotifyOnSourceUpdated
{
get
{
return default(bool);
}
set
{
}
}
public bool NotifyOnTargetUpdated
{
get
{
return default(bool);
}
set
{
}
}
public bool NotifyOnValidationError
{
get
{
return default(bool);
}
set
{
}
}
public UpdateSourceExceptionFilterCallback UpdateSourceExceptionFilter
{
get
{
return default(UpdateSourceExceptionFilterCallback);
}
set
{
}
}
public UpdateSourceTrigger UpdateSourceTrigger
{
get
{
Contract.Ensures(((System.Windows.Data.UpdateSourceTrigger)(0)) <= Contract.Result<System.Windows.Data.UpdateSourceTrigger>());
Contract.Ensures(Contract.Result<System.Windows.Data.UpdateSourceTrigger>() <= ((System.Windows.Data.UpdateSourceTrigger)(3)));
return default(UpdateSourceTrigger);
}
set
{
}
}
public bool ValidatesOnDataErrors
{
get
{
return default(bool);
}
set
{
}
}
public bool ValidatesOnExceptions
{
get
{
return default(bool);
}
set
{
}
}
public System.Collections.ObjectModel.Collection<System.Windows.Controls.ValidationRule> ValidationRules
{
get
{
Contract.Ensures(Contract.Result<System.Collections.ObjectModel.Collection<System.Windows.Controls.ValidationRule>>() != null);
return default(System.Collections.ObjectModel.Collection<System.Windows.Controls.ValidationRule>);
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace Internal.Cryptography.Pal
{
internal partial class FindPal
{
private const int NamedKeyUsageFlagsCount = 9;
private static readonly Dictionary<string, X509KeyUsageFlags> s_keyUsages =
new Dictionary<string, X509KeyUsageFlags>(NamedKeyUsageFlagsCount, StringComparer.OrdinalIgnoreCase)
{
{ "DigitalSignature", X509KeyUsageFlags.DigitalSignature },
{ "NonRepudiation", X509KeyUsageFlags.NonRepudiation },
{ "KeyEncipherment", X509KeyUsageFlags.KeyEncipherment },
{ "DataEncipherment", X509KeyUsageFlags.DataEncipherment },
{ "KeyAgreement", X509KeyUsageFlags.KeyAgreement },
{ "KeyCertSign", X509KeyUsageFlags.KeyCertSign },
{ "CrlSign", X509KeyUsageFlags.CrlSign },
{ "EncipherOnly", X509KeyUsageFlags.EncipherOnly },
{ "DecipherOnly", X509KeyUsageFlags.DecipherOnly },
};
#if DEBUG
static FindPal()
{
Debug.Assert(s_keyUsages.Count == NamedKeyUsageFlagsCount);
}
#endif
public static X509Certificate2Collection FindFromCollection(
X509Certificate2Collection coll,
X509FindType findType,
object findValue,
bool validOnly)
{
X509Certificate2Collection results = new X509Certificate2Collection();
using (IFindPal findPal = OpenPal(coll, results, validOnly))
{
switch (findType)
{
case X509FindType.FindByThumbprint:
{
byte[] thumbPrint = ConfirmedCast<string>(findValue).DecodeHexString();
findPal.FindByThumbprint(thumbPrint);
break;
}
case X509FindType.FindBySubjectName:
{
string subjectName = ConfirmedCast<string>(findValue);
findPal.FindBySubjectName(subjectName);
break;
}
case X509FindType.FindBySubjectDistinguishedName:
{
string subjectDistinguishedName = ConfirmedCast<string>(findValue);
findPal.FindBySubjectDistinguishedName(subjectDistinguishedName);
break;
}
case X509FindType.FindByIssuerName:
{
string issuerName = ConfirmedCast<string>(findValue);
findPal.FindByIssuerName(issuerName);
break;
}
case X509FindType.FindByIssuerDistinguishedName:
{
string issuerDistinguishedName = ConfirmedCast<string>(findValue);
findPal.FindByIssuerDistinguishedName(issuerDistinguishedName);
break;
}
case X509FindType.FindBySerialNumber:
{
string decimalOrHexString = ConfirmedCast<string>(findValue);
// FindBySerialNumber allows the input format to be either in
// hex or decimal. Since we can't know which one was intended,
// it compares against both interpretations and treats a match
// of either as a successful find.
// string is big-endian, BigInteger constructor requires little-endian.
byte[] hexBytes = decimalOrHexString.DecodeHexString();
Array.Reverse(hexBytes);
BigInteger hexValue = PositiveBigIntegerFromByteArray(hexBytes);
BigInteger decimalValue = LaxParseDecimalBigInteger(decimalOrHexString);
findPal.FindBySerialNumber(hexValue, decimalValue);
break;
}
case X509FindType.FindByTimeValid:
{
DateTime dateTime = ConfirmedCast<DateTime>(findValue);
findPal.FindByTimeValid(dateTime);
break;
}
case X509FindType.FindByTimeNotYetValid:
{
DateTime dateTime = ConfirmedCast<DateTime>(findValue);
findPal.FindByTimeNotYetValid(dateTime);
break;
}
case X509FindType.FindByTimeExpired:
{
DateTime dateTime = ConfirmedCast<DateTime>(findValue);
findPal.FindByTimeExpired(dateTime);
break;
}
case X509FindType.FindByTemplateName:
{
string expected = ConfirmedCast<string>(findValue);
findPal.FindByTemplateName(expected);
break;
}
case X509FindType.FindByApplicationPolicy:
{
string oidValue = ConfirmedOidValue(findPal, findValue, OidGroup.Policy);
findPal.FindByApplicationPolicy(oidValue);
break;
}
case X509FindType.FindByCertificatePolicy:
{
string oidValue = ConfirmedOidValue(findPal, findValue, OidGroup.Policy);
findPal.FindByCertificatePolicy(oidValue);
break;
}
case X509FindType.FindByExtension:
{
string oidValue = ConfirmedOidValue(findPal, findValue, OidGroup.ExtensionOrAttribute);
findPal.FindByExtension(oidValue);
break;
}
case X509FindType.FindByKeyUsage:
{
X509KeyUsageFlags keyUsage = ConfirmedX509KeyUsage(findValue);
findPal.FindByKeyUsage(keyUsage);
break;
}
case X509FindType.FindBySubjectKeyIdentifier:
{
byte[] keyIdentifier = ConfirmedCast<string>(findValue).DecodeHexString();
findPal.FindBySubjectKeyIdentifier(keyIdentifier);
break;
}
default:
throw new CryptographicException(SR.Cryptography_X509_InvalidFindType);
}
}
return results;
}
private static T ConfirmedCast<T>(object findValue)
{
Debug.Assert(findValue != null);
if (findValue.GetType() != typeof(T))
throw new CryptographicException(SR.Cryptography_X509_InvalidFindValue);
return (T)findValue;
}
private static string ConfirmedOidValue(IFindPal findPal, object findValue, OidGroup oidGroup)
{
string maybeOid = ConfirmedCast<string>(findValue);
if (maybeOid.Length == 0)
{
throw new ArgumentException(SR.Argument_InvalidOidValue);
}
return findPal.NormalizeOid(maybeOid, oidGroup);
}
private static X509KeyUsageFlags ConfirmedX509KeyUsage(object findValue)
{
if (findValue is X509KeyUsageFlags)
return (X509KeyUsageFlags)findValue;
if (findValue is int)
return (X509KeyUsageFlags)(int)findValue;
if (findValue is uint)
return (X509KeyUsageFlags)(uint)findValue;
string findValueString = findValue as string;
if (findValueString != null)
{
X509KeyUsageFlags usageFlags;
if (s_keyUsages.TryGetValue(findValueString, out usageFlags))
{
return usageFlags;
}
}
throw new CryptographicException(SR.Cryptography_X509_InvalidFindValue);
}
//
// verify the passed keyValue is valid as per X.208
//
// The first number must be 0, 1 or 2.
// Enforce all characters are digits and dots.
// Enforce that no dot starts or ends the Oid, and disallow double dots.
// Enforce there is at least one dot separator.
//
internal static void ValidateOidValue(string keyValue)
{
if (keyValue == null)
throw new ArgumentNullException("keyValue");
int len = keyValue.Length;
if (len < 2)
throw new ArgumentException(SR.Argument_InvalidOidValue);
// should not start with a dot. The first digit must be 0, 1 or 2.
char c = keyValue[0];
if (c != '0' && c != '1' && c != '2')
throw new ArgumentException(SR.Argument_InvalidOidValue);
if (keyValue[1] != '.' || keyValue[len - 1] == '.') // should not end in a dot
throw new ArgumentException(SR.Argument_InvalidOidValue);
// While characters 0 and 1 were both validated, start at character 1 to validate
// that there aren't two dots in a row.
for (int i = 1; i < len; i++)
{
// ensure every character is either a digit or a dot
if (char.IsDigit(keyValue[i]))
continue;
if (keyValue[i] != '.' || keyValue[i + 1] == '.') // disallow double dots
throw new ArgumentException(SR.Argument_InvalidOidValue);
}
}
internal static BigInteger PositiveBigIntegerFromByteArray(byte[] bytes)
{
// To prevent the big integer from misinterpreted as a negative number,
// add a "leading 0" to the byte array if it would considered negative.
//
// Since BigInteger(bytes[]) requires a little-endian byte array,
// the "leading 0" actually goes at the end of the array.
// An empty array is 0 (non-negative), so no over-allocation is required.
//
// If the last indexed value doesn't have the sign bit set (0x00-0x7F) then
// the number would be positive anyways, so no over-allocation is required.
if (bytes.Length == 0 || bytes[bytes.Length - 1] < 0x80)
{
return new BigInteger(bytes);
}
// Since the sign bit is set, put a new 0x00 on the end to move that bit from
// the sign bit to a data bit.
byte[] newBytes = new byte[bytes.Length + 1];
Array.Copy(bytes, 0, newBytes, 0, bytes.Length);
return new BigInteger(newBytes);
}
private static BigInteger LaxParseDecimalBigInteger(string decimalString)
{
BigInteger ten = new BigInteger(10);
BigInteger accum = BigInteger.Zero;
foreach (char c in decimalString)
{
if (c >= '0' && c <= '9')
{
accum = BigInteger.Multiply(accum, ten);
accum = BigInteger.Add(accum, c - '0');
}
}
return accum;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.Reflection;
using System.Linq.Expressions;
using Signum.Utilities;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Collections.Specialized;
using Signum.Utilities.Reflection;
using Signum.Entities.Reflection;
using System.Collections;
using Signum.Utilities.ExpressionTrees;
using System.Runtime.CompilerServices;
using System.Collections.Concurrent;
using System.Diagnostics;
namespace Signum.Entities
{
public interface IModifiableEntity : INotifyPropertyChanged, IDataErrorInfo
{
}
[Serializable, DescriptionOptions(DescriptionOptions.Members | DescriptionOptions.Description), InTypeScript(false)]
public abstract class ModifiableEntity : Modifiable, IModifiableEntity, ICloneable
{
static Func<bool>? isRetrievingFunc = null;
static public bool IsRetrieving
{
get { return isRetrievingFunc != null && isRetrievingFunc(); }
}
internal static void SetIsRetrievingFunc(Func<bool> isRetrievingFunc)
{
ModifiableEntity.isRetrievingFunc = isRetrievingFunc;
}
protected internal const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
protected virtual T Get<T>(T fieldValue, [CallerMemberName]string? automaticPropertyName = null)
{
return fieldValue;
}
protected virtual bool Set<T>(ref T field, T value, [CallerMemberName]string? automaticPropertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value))
return false;
PropertyInfo pi = GetPropertyInfo(automaticPropertyName!);
if (pi == null)
throw new ArgumentException("No PropertyInfo with name {0} found in {1} or any implemented interface".FormatWith(automaticPropertyName, this.GetType().TypeName()));
if (value is IMListPrivate && !((IMListPrivate)value).IsNew && !object.ReferenceEquals(value, field))
throw new InvalidOperationException("Only MList<T> with IsNew = true can be assigned to an entity");
if (field is INotifyCollectionChanged colb)
{
if (AttributeManager<NotifyCollectionChangedAttribute>.FieldContainsAttribute(GetType(), pi))
colb.CollectionChanged -= ChildCollectionChanged;
if (AttributeManager<NotifyChildPropertyAttribute>.FieldContainsAttribute(GetType(), pi))
foreach (var item in (IEnumerable<IModifiableEntity>)colb!)
((ModifiableEntity)item).ClearParentEntity(this);
}
if (field is ModifiableEntity modb)
{
if (AttributeManager<NotifyChildPropertyAttribute>.FieldContainsAttribute(GetType(), pi))
modb.ClearParentEntity(this);
}
SetSelfModified();
field = value;
if (field is INotifyCollectionChanged cola)
{
if (AttributeManager<NotifyCollectionChangedAttribute>.FieldContainsAttribute(GetType(), pi))
cola.CollectionChanged += ChildCollectionChanged;
if (AttributeManager<NotifyChildPropertyAttribute>.FieldContainsAttribute(GetType(), pi))
foreach (var item in (IEnumerable<IModifiableEntity>)cola!)
((ModifiableEntity)item).SetParentEntity(this);
}
if (field is ModifiableEntity moda)
{
if (AttributeManager<NotifyChildPropertyAttribute>.FieldContainsAttribute(GetType(), pi))
moda.SetParentEntity(this);
}
NotifyPrivate(pi.Name);
NotifyPrivate("Error");
NotifyToString();
ClearTemporalError(pi.Name);
return true;
}
struct PropertyKey : IEquatable<PropertyKey>
{
public PropertyKey(Type type, string propertyName)
{
this.Type = type;
this.PropertyName = propertyName;
}
public Type Type;
public string PropertyName;
public bool Equals(PropertyKey other) => other.Type == Type && other.PropertyName == PropertyName;
public override bool Equals(object? obj) => obj is PropertyKey pk && Equals(pk);
public override int GetHashCode() => Type.GetHashCode() ^ PropertyName.GetHashCode();
}
static readonly ConcurrentDictionary<PropertyKey, PropertyInfo> PropertyCache = new ConcurrentDictionary<PropertyKey, PropertyInfo>();
protected PropertyInfo GetPropertyInfo(string propertyName)
{
return PropertyCache.GetOrAdd(new PropertyKey(this.GetType(), propertyName), key =>
key.Type.GetProperty(propertyName, flags) ??
key.Type.GetInterfaces().Select(i => i.GetProperty(key.PropertyName, flags)).NotNull().FirstOrDefault());
}
static Expression<Func<ModifiableEntity, string>> ToStringPropertyExpression = m => m.ToString()!;
[HiddenProperty, ExpressionField("ToStringPropertyExpression")]
public string ToStringProperty
{
get
{
string? str = ToString();
return str.HasText() ? str : this.GetType().NiceName();
}
}
#region Collection Events
protected internal override void PostRetrieving(PostRetrievingContext ctx)
{
RebindEvents();
}
protected virtual void RebindEvents()
{
foreach (INotifyCollectionChanged? notify in AttributeManager<NotifyCollectionChangedAttribute>.FieldsWithAttribute(this))
{
if (notify == null)
continue;
notify.CollectionChanged += ChildCollectionChanged;
}
foreach (object? field in AttributeManager<NotifyChildPropertyAttribute>.FieldsWithAttribute(this))
{
if (field == null)
continue;
if (field is ModifiableEntity entity)
entity.SetParentEntity(this);
else
{
foreach (var item in (IEnumerable<IModifiableEntity>)field!)
((ModifiableEntity)item).SetParentEntity(this);
}
}
}
//[OnDeserialized]
//private void OnDeserialized(StreamingContext context)
//{
// RebindEvents();
//}
protected virtual void ChildCollectionChanged(object sender, NotifyCollectionChangedEventArgs args)
{
string? propertyName = AttributeManager<NotifyCollectionChangedAttribute>.FindPropertyName(this, sender);
if (propertyName != null)
NotifyPrivate(propertyName);
if (AttributeManager<NotifyChildPropertyAttribute>.FieldsWithAttribute(this).Contains(sender))
{
if (args.NewItems != null)
{
foreach (var p in args.NewItems.Cast<ModifiableEntity>())
p.SetParentEntity(this);
}
if (args.OldItems != null)
{
foreach (var p in args.OldItems.Cast<ModifiableEntity>())
p.SetParentEntity(this);
}
}
}
protected virtual void ChildPropertyChanged(object sender, PropertyChangedEventArgs e)
{
}
protected virtual string? ChildPropertyValidation(ModifiableEntity sender, PropertyInfo pi)
{
return null;
}
#endregion
[field: NonSerialized, Ignore]
public event PropertyChangedEventHandler? PropertyChanged;
[NonSerialized, Ignore]
ModifiableEntity? parentEntity;
public virtual T? TryGetParentEntity<T>()
where T: class, IModifiableEntity
{
return ((IModifiableEntity?)parentEntity) as T;
}
public virtual T GetParentEntity<T>()
where T : IModifiableEntity
{
if (parentEntity == null)
throw new InvalidOperationException("parentEntity is null");
return (T)(IModifiableEntity)parentEntity;
}
protected virtual void SetParentEntity(ModifiableEntity p)
{
if (p != null && this.parentEntity != null && this.parentEntity != p)
throw new InvalidOperationException($"'{nameof(parentEntity)}' of '{this}'({this.GetType().TypeName()}) is still connected to '{parentEntity}'({parentEntity.GetType().TypeName()}), then can not be set to '{p}'({p.GetType().TypeName()})");
this.parentEntity = p;
}
protected virtual void ClearParentEntity(ModifiableEntity p)
{
if (p == this.parentEntity)
this.parentEntity = null;
}
internal string? OnParentChildPropertyValidation(PropertyInfo pi)
{
if (parentEntity == null)
return null;
return parentEntity.ChildPropertyValidation(this, pi);
}
public void Notify<T>(Expression<Func<T>> property)
{
NotifyPrivate(ReflectionTools.BasePropertyInfo(property).Name);
NotifyError();
}
public void NotifyError()
{
NotifyPrivate("Error");
}
public void NotifyToString()
{
NotifyPrivate("ToStringProperty");
}
void NotifyPrivate(string propertyName)
{
var parent = this.parentEntity;
if (parent != null)
parent.ChildPropertyChanged(this, new PropertyChangedEventArgs(propertyName));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#region Temporal ID
[Ignore]
internal Guid temporalId = Guid.NewGuid();
public override int GetHashCode()
{
return GetType().FullName!.GetHashCode() ^ temporalId.GetHashCode();
}
#endregion
#region IDataErrorInfo Members
[HiddenProperty]
public string? Error
{
get { return IntegrityCheck()?.Errors.Values.ToString("\r\n"); }
}
public IntegrityCheck? IntegrityCheck()
{
using (var log = HeavyProfiler.LogNoStackTrace("IntegrityCheck"))
{
var validators = Validator.GetPropertyValidators(GetType());
Dictionary<string, string>? dic = null;
foreach (var pv in validators.Values)
{
var error = pv.PropertyCheck(this);
if (error != null)
{
if (dic == null)
dic = new Dictionary<string, string>();
dic.Add(pv.PropertyInfo.Name, error);
}
}
if (dic == null)
return null;
return new Entities.IntegrityCheck(this, dic);
}
}
//override for per-property checks
[HiddenProperty]
string? IDataErrorInfo.this[string columnName]
{
get
{
if (columnName == null)
return ((IDataErrorInfo)this).Error;
else
return PropertyCheck(columnName);
}
}
public string? PropertyCheck(Expression<Func<object?>> property)
{
return PropertyCheck(ReflectionTools.GetPropertyInfo(property).Name);
}
public string? PropertyCheck(string propertyName)
{
IPropertyValidator? pp = Validator.TryGetPropertyValidator(GetType(), propertyName);
if (pp == null)
return null; //Hidden properties
return pp.PropertyCheck(this);
}
protected internal virtual string? PropertyValidation(PropertyInfo pi)
{
return null;
}
public bool IsPropertyReadonly(string propertyName)
{
IPropertyValidator? pp = Validator.TryGetPropertyValidator(GetType(), propertyName);
if (pp == null)
return false; //Hidden properties
return pp.IsPropertyReadonly(this);
}
protected internal virtual bool IsPropertyReadonly(PropertyInfo pi)
{
return false;
}
protected static void Validate<T>(Expression<Func<T, object?>> property, Func<T, PropertyInfo, string?> validate) where T : ModifiableEntity
{
Validator.PropertyValidator(property).StaticPropertyValidation += validate;
}
public Dictionary<Guid, IntegrityCheck>? FullIntegrityCheck()
{
var graph = GraphExplorer.FromRoot(this);
return GraphExplorer.FullIntegrityCheck(graph);
}
[ForceEagerEvaluation]
protected static string NicePropertyName<R>(Expression<Func<R>> property)
{
return ReflectionTools.GetPropertyInfo(property).NiceName();
}
[ForceEagerEvaluation]
protected static string NicePropertyName<E, R>(Expression<Func<E, R>> property)
{
return ReflectionTools.GetPropertyInfo(property).NiceName();
}
#endregion
#region ICloneable Members
object ICloneable.Clone()
{
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream stream = new MemoryStream())
{
bf.Serialize(stream, this);
stream.Seek(0, SeekOrigin.Begin);
return bf.Deserialize(stream);
}
}
#endregion
[Ignore]
internal Dictionary<string, string>? temporalErrors;
internal void SetTemporalErrors(Dictionary<string, string>? errors)
{
NotifyTemporalErrors();
this.temporalErrors = errors;
NotifyTemporalErrors();
}
void NotifyTemporalErrors()
{
if (temporalErrors != null)
{
foreach (var e in temporalErrors.Keys)
NotifyPrivate(e);
NotifyError();
}
}
void ClearTemporalError(string propertyName)
{
if (this.temporalErrors == null)
return;
this.temporalErrors.Remove(propertyName);
NotifyPrivate(propertyName);
NotifyError();
}
public void SetTemporalError(PropertyInfo pi, string? error)
{
if (error == null)
{
if (this.temporalErrors != null)
{
this.temporalErrors.Remove(pi.Name);
if (this.temporalErrors.Count == 0)
this.temporalErrors = null;
}
}
else
{
if (this.temporalErrors == null)
this.temporalErrors = new Dictionary<string, string>();
this.temporalErrors.Add(pi.Name, error);
}
}
internal ModifiableEntity()
{
mixin = MixinDeclarations.CreateMixins(this);
}
[Ignore, DebuggerBrowsable(DebuggerBrowsableState.Never)]
readonly MixinEntity? mixin;
public M Mixin<M>() where M : MixinEntity
{
var result = TryMixin<M>();
if (result != null)
return result;
throw new InvalidOperationException("Mixin {0} not declared for {1} in MixinDeclarations"
.FormatWith(typeof(M).TypeName(), GetType().TypeName()));
}
public M? TryMixin<M>() where M : MixinEntity
{
var current = mixin;
while (current != null)
{
if (current is M)
return (M)current;
current = current.Next;
}
return null;
}
public MixinEntity GetMixin(Type mixinType)
{
var current = mixin;
while (current != null)
{
if (current.GetType() == mixinType)
return current;
current = current.Next;
}
throw new InvalidOperationException("Mixin {0} not declared for {1} in MixinDeclarations"
.FormatWith(mixinType.TypeName(), GetType().TypeName()));
}
[HiddenProperty]
public MixinEntity this[string mixinName]
{
get
{
var current = mixin;
while (current != null)
{
if (current.GetType().Name == mixinName)
return current;
current = current.Next;
}
throw new InvalidOperationException("Mixin {0} not declared for {1} in MixinDeclarations"
.FormatWith(mixinName, GetType().TypeName()));
}
}
[HiddenProperty]
public IEnumerable<MixinEntity> Mixins
{
get
{
var current = mixin;
while (current != null)
{
yield return current;
current = current.Next;
}
}
}
}
[Serializable]
public class IntegrityCheck
{
public IntegrityCheck(ModifiableEntity me, Dictionary<string, string> errors)
{
this.TemporalId = me.temporalId;
this.Type = me.GetType();
this.Id = me is Entity e ? e.id : null;
Errors = errors ?? throw new ArgumentNullException(nameof(errors));
}
public Guid TemporalId { get; private set; }
public Type Type { get; private set; }
public PrimaryKey? Id { get; private set; }
public Dictionary<string, string> Errors { get; private set; }
public override string ToString()
{
return $"{Errors.Count} errors in {" ".Combine(Type.Name, Id)}\r\n"
+ Errors.ToString(kvp => " {0}: {1}".FormatWith(kvp.Key, kvp.Value), "\r\n");
}
}
public class IntegrityCheckWithEntity
{
public IntegrityCheckWithEntity(IntegrityCheck integrityCheck, ModifiableEntity entity)
{
this.IntegrityCheck = integrityCheck;
this.Entity = entity;
}
public IntegrityCheck IntegrityCheck {get; private set;}
public ModifiableEntity Entity {get; set;}
public override string ToString()
{
var validators = Validator.GetPropertyValidators(Entity.GetType());
return $"{IntegrityCheck.Errors.Count} errors in {" ".Combine(IntegrityCheck.Type.Name, IntegrityCheck.Id)}\r\n"
+ IntegrityCheck.Errors.ToString(kvp => " {0} ({1}): {2}".FormatWith(
kvp.Key,
validators.GetOrThrow(kvp.Key).GetValueUntyped(Entity) ?? "null",
kvp.Value),
"\r\n");
}
}
}
| |
/*
Copyright 2014 Google Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using DriveProxy.Utils;
using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;
namespace DriveProxy.API
{
partial class DriveService
{
public class CopyStream : Stream
{
protected string _ParentId = null;
protected long TotalFiles
{
get { return _TotalBytes; }
set { _TotalBytes = value; }
}
protected long FilesProcessed
{
get { return _BytesProcessed; }
set { _BytesProcessed = value; }
}
public string ParentId
{
get { return _ParentId; }
}
public override StreamType Type
{
get { return StreamType.Copy; }
}
public void Init(string parentId, FileInfo fileInfo)
{
try
{
if (Status == StatusType.Queued)
{
throw new Exception("Stream has already been queued.");
}
if (Status != StatusType.NotStarted)
{
throw new Exception("Stream has already been started.");
}
if (String.IsNullOrEmpty(parentId))
{
parentId = API.DriveService.GetFileId(parentId);
}
if (String.IsNullOrEmpty(parentId))
{
throw new Exception("ParentId is blank.");
}
if (fileInfo == null)
{
throw new Exception("File is null.");
}
if (fileInfo.IsRoot)
{
throw new Exception("Cannot copy root folder.");
}
if (fileInfo.Id == parentId)
{
throw new Exception("Cannot copy file to itself.");
}
_FileId = fileInfo.Id;
_ParentId = parentId;
_FileInfo = fileInfo;
base.Init();
}
catch (Exception exception)
{
Log.Error(exception);
}
}
protected override void Start()
{
try
{
if (Status != StatusType.Queued)
{
throw new Exception("Stream has not been queued.");
}
base.Start();
_FileInfo = _DriveService.GetFile(FileId);
if (_FileInfo == null)
{
throw new Exception("File '" + FileId + "' no longer exists.");
}
Lock();
TotalFiles = 1;
FilesProcessed = 0;
if (FileInfo.IsFolder)
{
GetFiles(ref _FileInfo);
_FileInfo = CopyFolder(_ParentId, _FileInfo);
}
else
{
_FileInfo = CopyFile(_ParentId, _FileInfo);
}
DriveService_ProgressChanged(StatusType.Completed, null);
}
catch (Exception exception)
{
try
{
_Status = IsCancellationRequested ? StatusType.Cancelled : StatusType.Failed;
_ExceptionMessage = exception.Message;
DriveService_ProgressChanged(_Status, exception);
}
catch
{
Debugger.Break();
}
Log.Error(exception);
}
}
protected override void Dispose()
{
try
{
base.Dispose();
}
catch (Exception exception)
{
Log.Error(exception, false);
}
}
protected void DriveService_ProgressChanged(StatusType status, Exception processException)
{
try
{
UpdateProgress(status, BytesProcessed, TotalBytes, processException);
InvokeOnProgressEvent();
}
catch (Exception exception)
{
Log.Error(exception, false);
}
}
protected void GetFiles(ref FileInfo fileInfo)
{
try
{
IEnumerable<FileInfo> children = _DriveService.GetFiles(fileInfo.Id);
fileInfo.Files.AddRange(children);
TotalFiles += children.Count();
for (int i = 0; i < children.Count(); i++)
{
if (IsCancellationRequested)
{
DriveService_ProgressChanged(StatusType.Cancelled, null);
return;
}
FileInfo child = children.ElementAt(i);
if (child.IsFolder)
{
GetFiles(ref child);
}
}
}
catch (Exception exception)
{
Log.Error(exception);
}
}
protected FileInfo CopyFolder(string parentId, FileInfo fileInfo)
{
try
{
FileInfo folder = CreateFolder(parentId, fileInfo);
FilesProcessed++;
foreach (FileInfo childInfo in fileInfo.Files)
{
if (IsCancellationRequested)
{
throw new Exception("Process cancelled by user.");
}
if (childInfo.IsFolder)
{
CopyFolder(folder.Id, childInfo);
}
else
{
var copyStream = new CopyStream();
copyStream.Init(folder.Id, childInfo);
copyStream.Visible = false;
_DriveService.CopyFile(copyStream);
while (!copyStream.Processed)
{
if (IsCancellationRequested)
{
copyStream.Cancel();
}
System.Threading.Thread.Sleep(250);
}
if (IsCancellationRequested)
{
throw new Exception("Process cancelled by user.");
}
if (!copyStream.Completed)
{
throw new Exception("Could not create new folder");
}
FilesProcessed++;
}
}
return folder;
}
catch (Exception exception)
{
Log.Error(exception);
return null;
}
}
protected FileInfo CreateFolder(string parentId, FileInfo fileInfo)
{
try
{
var insertStream = new InsertStream();
insertStream.Init(parentId, fileInfo.Title, API.DriveService.MimeType.Folder);
insertStream.Visible = false;
_DriveService.InsertFile(insertStream);
while (!insertStream.Finished)
{
if (IsCancellationRequested)
{
insertStream.Cancel();
}
System.Threading.Thread.Sleep(250);
}
if (IsCancellationRequested)
{
throw new Exception("Process cancelled by user.");
}
if (!insertStream.Completed)
{
throw new Exception("Could not create new folder");
}
FileInfo folder = insertStream.FileInfo;
return folder;
}
catch (Exception exception)
{
Log.Error(exception);
return null;
}
}
protected FileInfo CopyFile(string parentId, FileInfo fileInfo)
{
try
{
FileInfoStatus currentStatus = API.DriveService.GetFileInfoStatus(fileInfo);
File file = fileInfo._file;
if (file.Parents.Count > 0)
{
file.Parents.RemoveAt(0);
}
var parentReference = new ParentReference {Id = parentId};
if (file.Parents == null)
{
file.Parents = new List<ParentReference>();
}
file.Parents.Insert(0, parentReference);
using (API.DriveService.Connection connection = API.DriveService.Connection.Create())
{
FilesResource.CopyRequest request = connection.Service.Files.Copy(file, file.Id);
request.Fields = API.DriveService.RequestFields.FileFields;
_CancellationTokenSource = new System.Threading.CancellationTokenSource();
file = request.Execute();
fileInfo = GetFileInfo(file);
FileInfoStatus newStatus = API.DriveService.GetFileInfoStatus(fileInfo);
if (currentStatus == FileInfoStatus.OnDisk)
{
DateTime modifiedDate = API.DriveService.GetDateTime(file.ModifiedDate);
try
{
API.DriveService.SetFileLastWriteTime(fileInfo.FilePath, modifiedDate);
}
catch
{
}
fileInfo = GetFileInfo(file);
newStatus = API.DriveService.GetFileInfoStatus(fileInfo);
}
return fileInfo;
}
}
catch (Exception exception)
{
Log.Error(exception);
return null;
}
}
}
}
}
| |
//
// 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 CreateVirtualMachineScaleSetDeallocateDynamicParameters()
{
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 = false
});
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 ExecuteVirtualMachineScaleSetDeallocateMethod(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();
}
var result = VirtualMachineScaleSetsClient.Deallocate(resourceGroupName, vmScaleSetName, instanceIds);
WriteObject(result);
}
}
public partial class NewAzureComputeArgumentListCmdlet : ComputeAutomationBaseCmdlet
{
protected PSArgument[] CreateVirtualMachineScaleSetDeallocateParameters()
{
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(VerbsLifecycle.Stop, "AzureRmVmss", DefaultParameterSetName = "InvokeByDynamicParameters", SupportsShouldProcess = true)]
public partial class StopAzureRmVmss : InvokeAzureComputeMethodCmdlet
{
public override string MethodName { get; set; }
protected override void ProcessRecord()
{
if (this.ParameterSetName == "InvokeByDynamicParameters")
{
this.MethodName = "VirtualMachineScaleSetDeallocate";
}
else
{
this.MethodName = "VirtualMachineScaleSetPowerOff";
}
if (ShouldProcess(this.dynamicParameters["ResourceGroupName"].Value.ToString(), VerbsLifecycle.Stop)
&& (this.dynamicParameters["Force"].IsSet ||
this.ShouldContinue(Properties.Resources.ResourceStoppingConfirmation,
"Stop-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 ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParametersForFriendMethod",
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 ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParametersForFriendMethod",
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 ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParametersForFriendMethod",
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 ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParametersForFriendMethod",
Position = 4,
Mandatory = false
});
pForce.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("Force", pForce);
var pStayProvisioned = new RuntimeDefinedParameter();
pStayProvisioned.Name = "StayProvisioned";
pStayProvisioned.ParameterType = typeof(SwitchParameter);
pStayProvisioned.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParametersForFriendMethod",
Position = 5,
Mandatory = true
});
pStayProvisioned.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("StayProvisioned", pStayProvisioned);
return dynamicParameters;
}
}
}
| |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FireSharp.EventStreaming
{
internal sealed class TemporaryCache : IDisposable
{
private readonly LinkedList<SimpleCacheItem> _pathFromRootList = new LinkedList<SimpleCacheItem>();
private readonly char[] _seperator = {'/'};
private readonly object _treeLock = new object();
public object Context = null;
public TemporaryCache()
{
Root.Name = string.Empty;
Root.Created = false;
Root.Parent = null;
Root.Name = null;
}
~TemporaryCache()
{
Dispose(false);
}
internal SimpleCacheItem Root { get; } = new SimpleCacheItem();
public void Replace(string path, JsonReader data)
{
lock (_treeLock)
{
var root = FindRoot(path);
Replace(root, data);
}
}
public void Update(string path, JsonReader data)
{
lock (_treeLock)
{
var root = FindRoot(path);
UpdateChildren(root, data);
}
}
private SimpleCacheItem FindRoot(string path)
{
var segments = path.Split(_seperator, StringSplitOptions.RemoveEmptyEntries);
return segments.Aggregate(Root, GetNamedChild);
}
private static SimpleCacheItem GetNamedChild(SimpleCacheItem root, string segment)
{
var newRoot = root.Children.FirstOrDefault(c => c.Name == segment);
if (newRoot == null)
{
newRoot = new SimpleCacheItem {Name = segment, Parent = root, Created = true};
root.Children.Add(newRoot);
}
return newRoot;
}
private void Replace(SimpleCacheItem root, JsonReader reader)
{
UpdateChildren(root, reader, true);
}
private void UpdateChildren(SimpleCacheItem root, JsonReader reader, bool replace = false)
{
if (replace)
{
DeleteChild(root);
root.Parent?.Children.Add(root);
}
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
UpdateChildren(GetNamedChild(root, reader.Value.ToString()), reader);
break;
case JsonToken.Boolean:
case JsonToken.Bytes:
case JsonToken.Date:
case JsonToken.Float:
case JsonToken.Integer:
case JsonToken.String:
if (root.Created)
{
root.Value = reader.Value.ToString();
OnAdded(new ValueAddedEventArgs(PathFromRoot(root), reader.Value.ToString()));
root.Created = false;
}
else
{
var oldData = root.Value;
root.Value = reader.Value.ToString();
OnUpdated(new ValueChangedEventArgs(PathFromRoot(root), root.Value, oldData));
}
return;
case JsonToken.Null:
DeleteChild(root);
return;
}
}
}
private void DeleteChild(SimpleCacheItem root)
{
if (root.Parent != null)
{
if (RemoveChildFromParent(root))
{
OnRemoved(new ValueRemovedEventArgs(PathFromRoot(root)));
}
}
else
{
foreach (var child in root.Children.ToArray())
{
RemoveChildFromParent(child);
OnRemoved(new ValueRemovedEventArgs(PathFromRoot(child)));
}
}
}
private bool RemoveChildFromParent(SimpleCacheItem child)
{
if (child.Parent != null)
{
return child.Parent.Children.Remove(child);
}
return false;
}
private string PathFromRoot(SimpleCacheItem root)
{
var size = 1;
while (root.Name != null)
{
size += root.Name.Length + 1;
_pathFromRootList.AddFirst(root);
root = root.Parent;
}
if (_pathFromRootList.Count == 0)
{
return "/";
}
var sb = new StringBuilder(size);
foreach (var d in _pathFromRootList)
{
sb.Append($"/{d.Name}");
}
_pathFromRootList.Clear();
return sb.ToString();
}
private void OnAdded(ValueAddedEventArgs args)
{
Added?.Invoke(this, args, Context);
}
private void OnUpdated(ValueChangedEventArgs args)
{
Changed?.Invoke(this, args, Context);
}
private void OnRemoved(ValueRemovedEventArgs args)
{
Removed?.Invoke(this, args, Context);
}
public event ValueAddedEventHandler Added;
public event ValueChangedEventHandler Changed;
public event ValueRemovedEventHandler Removed;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing)
{
Added = null;
Changed = null;
Removed = null;
}
}
}
}
| |
// Copyright 2016 Applied Geographics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
using GeoAPI.Geometries;
using NetTopologySuite.Geometries;
using AppGeo.Clients;
using AppGeo.Clients.Transform;
public class PdfMap
{
private const float PointsPerInch = 72;
private const float PixelsPerInch = 96;
private AppState _appState;
private string _templateId;
private List<String> _input;
private PreserveMode _preserveMode;
private double _originalWidth;
private double _pixelSize = -1;
public PdfMap(AppState appState, string templateId, List<String> input, PreserveMode preserveMode, double originalWidth)
{
_appState = appState;
_templateId = templateId;
_input = input;
_preserveMode = preserveMode;
_originalWidth = originalWidth;
}
private void CreatePdfBox(PdfContentByte content, Configuration.PrintTemplateContentRow row)
{
CreatePdfBox(content, row, true);
}
private void CreatePdfBox(PdfContentByte content, Configuration.PrintTemplateContentRow row, bool allowFill)
{
if (row.IsFillColorNull() && row.IsOutlineWidthNull() && row.IsOutlineColorNull())
{
return;
}
bool hasFill = false;
bool hasStroke = false;
content.SetLineWidth((1 / PixelsPerInch) * PointsPerInch);
if (!row.IsFillColorNull() && allowFill)
{
System.Drawing.Color c = System.Drawing.ColorTranslator.FromHtml(row.FillColor);
content.SetRGBColorFill(c.R, c.G, c.B);
hasFill = true;
}
if (!row.IsOutlineWidthNull())
{
content.SetLineWidth((Convert.ToSingle(row.OutlineWidth) / PixelsPerInch) * PointsPerInch);
hasStroke = true;
}
if (!row.IsOutlineColorNull())
{
System.Drawing.Color c = System.Drawing.ColorTranslator.FromHtml(row.OutlineColor);
content.SetRGBColorStroke(c.R, c.G, c.B);
hasStroke = true;
}
float originX = Convert.ToSingle(row.OriginX) * PointsPerInch;
float originY = Convert.ToSingle(row.OriginY) * PointsPerInch;
float width = Convert.ToSingle(row.Width) * PointsPerInch;
float height = Convert.ToSingle(row.Height) * PointsPerInch;
if (hasFill)
{
content.Rectangle(originX, originY, width, height);
content.Fill();
}
if (hasStroke)
{
content.Rectangle(originX, originY, width, height);
content.Stroke();
}
}
private void CreatePdfImage(PdfContentByte content, Configuration.PrintTemplateContentRow row)
{
float originX = Convert.ToSingle(row.OriginX) * PointsPerInch;
float originY = Convert.ToSingle(row.OriginY) * PointsPerInch;
float width = Convert.ToSingle(row.Width) * PointsPerInch;
float height = Convert.ToSingle(row.Height) * PointsPerInch;
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("Images/Print") + "\\" + row.FileName);
image.SetAbsolutePosition(originX, originY);
image.ScaleAbsolute(width, height);
content.AddImage(image);
CreatePdfBox(content, row, false);
}
private bool CreateLayerInLegend(PdfContentByte content, Configuration.MapTabRow mapTab, List<CommonLayer> layerList, LegendProperties properties, CommonLayer layer, float indent)
{
if (!layerList.Contains(layer))
{
return false;
}
float layerHeight = GetLayerHeightInLegend(layerList, properties, layer);
if (properties.CurrentY < properties.Height && properties.CurrentY - layerHeight < 0)
{
if (properties.CurrentColumn == properties.NumColumns)
{
return true;
}
properties.CurrentX += properties.ColumnWidth + properties.ColumnSpacing;
properties.CurrentY = properties.Height;
properties.CurrentColumn += 1;
}
int numClasses = GetNumClasses(layer);
Configuration.LayerRow configLayer = mapTab.GetMapTabLayerRows().Where(o => String.Compare(o.LayerRow.LayerName, layer.Name, true) == 0).Select(o => o.LayerRow).FirstOrDefault();
string layerName = configLayer != null && !configLayer.IsDisplayNameNull() ? configLayer.DisplayName : layer.Name;
// write the layer name
if (layer.Type == CommonLayerType.Group || numClasses > 1)
{
properties.CurrentY -= properties.FontSize;
string name = layerName;
try
{
while (content.GetEffectiveStringWidth(name, false) > properties.ColumnWidth - indent)
{
name = name.Substring(0, name.Length - 1);
}
}
catch { }
content.BeginText();
content.SetFontAndSize(properties.BaseFont, properties.FontSize);
content.SetRGBColorFill(0, 0, 0);
content.ShowTextAligned(PdfContentByte.ALIGN_LEFT, name, properties.OriginX + properties.CurrentX + indent, properties.OriginY + properties.CurrentY + (properties.SwatchHeight - properties.FontSize) / 2, 0);
content.EndText();
}
if (layer.Type == CommonLayerType.Group)
{
properties.CurrentY -= properties.LayerSpacing;
foreach (CommonLayer childLayer in layer.Children)
{
CreateLayerInLegend(content, mapTab, layerList, properties, childLayer, indent + 1.5f * properties.FontSize);
}
}
else
{
properties.CurrentY -= properties.ClassSpacing;
foreach (CommonLegendGroup legendGroup in layer.Legend.Groups)
{
foreach (CommonLegendClass legendClass in legendGroup.Classes)
{
if (!legendClass.ImageIsTransparent)
{
properties.CurrentY -= properties.SwatchHeight;
MemoryStream stream = new MemoryStream(legendClass.Image);
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(stream);
float w = properties.SwatchHeight * bitmap.Width / bitmap.Height;
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(legendClass.Image);
image.SetAbsolutePosition(properties.OriginX + properties.CurrentX + indent, properties.OriginY + properties.CurrentY - properties.SwatchHeight * 0.1f);
image.ScaleAbsolute(w, properties.SwatchHeight);
content.AddImage(image);
string label = numClasses > 1 ? legendClass.Label : layerName;
try
{
while (content.GetEffectiveStringWidth(label, false) > properties.ColumnWidth - properties.SwatchWidth - properties.ClassSpacing)
{
label = label.Substring(0, label.Length - 1);
}
}
catch { }
content.BeginText();
content.SetFontAndSize(properties.BaseFont, properties.FontSize);
content.SetRGBColorFill(0, 0, 0);
content.ShowTextAligned(PdfContentByte.ALIGN_LEFT, label, properties.OriginX + properties.CurrentX + indent + properties.SwatchWidth + properties.ClassSpacing, properties.OriginY + properties.CurrentY + (properties.SwatchHeight - properties.FontSize) / 2, 0);
content.EndText();
properties.CurrentY -= properties.ClassSpacing;
}
}
}
properties.CurrentY -= properties.LayerSpacing - properties.ClassSpacing;
}
return false;
}
private void CreatePdfLegend(PdfContentByte content, Configuration.PrintTemplateContentRow row)
{
CreatePdfBox(content, row);
LegendProperties properties = new LegendProperties(row);
if (properties.NumColumns == 0)
{
return;
}
List<CommonLayer> layerList = GetLegendLayers();
if (layerList.Count == 0)
{
return;
}
Configuration config = AppContext.GetConfiguration();
Configuration.MapTabRow mapTab = config.MapTab.FindByMapTabID(_appState.MapTab);
CommonDataFrame dataFrame = AppContext.GetDataFrame(mapTab);
List<CommonLayer> topLayers = dataFrame.TopLevelLayers;
properties.CurrentX = 0;
properties.CurrentY = properties.Height;
properties.CurrentColumn = 1;
bool full = false;
for (int i = 0; i < topLayers.Count && !full; ++i)
{
full = CreateLayerInLegend(content, mapTab, layerList, properties, topLayers[i], 0);
}
}
private void CreatePdfMap(PdfContentByte content, Configuration.PrintTemplateContentRow row)
{
int pixelWidth = Convert.ToInt32(row.Width * PixelsPerInch);
int pixelHeight = Convert.ToInt32(row.Height * PixelsPerInch);
MapMaker mapMaker = new MapMaker(_appState, pixelWidth, pixelHeight, 2);
byte[] mapImage = mapMaker.GetTileCompositeImage().Image;
float originX = Convert.ToSingle(row.OriginX) * PointsPerInch;
float originY = Convert.ToSingle(row.OriginY) * PointsPerInch;
float width = Convert.ToSingle(row.Width) * PointsPerInch;
float height = Convert.ToSingle(row.Height) * PointsPerInch;
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(mapImage);
image.SetAbsolutePosition(originX, originY);
image.ScaleAbsolute(width, height);
content.AddImage(image);
CreatePdfBox(content, row, false);
}
private void CreatePdfOverviewMap(PdfContentByte content, Configuration.PrintTemplateContentRow row)
{
AppState appState = new AppState();
appState.Application = _appState.Application;
Configuration.ApplicationRow application = AppContext.GetConfiguration().Application.First(o => o.ApplicationID == appState.Application);
appState.MapTab = application.OverviewMapID;
appState.Extent = application.GetFullExtentEnvelope();
int pixelWidth = Convert.ToInt32(row.Width * PixelsPerInch);
int pixelHeight = Convert.ToInt32(row.Height * PixelsPerInch);
MapMaker mapMaker = new MapMaker(appState, pixelWidth, pixelHeight, 2);
MapImageData mapImageData = mapMaker.GetImage();
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(new MemoryStream(mapImageData.Image));
Transformation trans = new AffineTransformation(pixelWidth * 2, pixelHeight * 2, appState.Extent);
MapGraphics mapGraphics = MapGraphics.FromImage(bitmap, trans);
double minSize = (trans.Transform(new Coordinate(1, 0)).X - trans.Transform(new Coordinate(0, 0)).X) * 12;
Envelope extent = new Envelope(new Coordinate(_appState.Extent.MinX, _appState.Extent.MinY), new Coordinate(_appState.Extent.MaxX, _appState.Extent.MaxY));
if (extent.Width < minSize)
{
extent = new Envelope(new Coordinate(extent.Centre.X - minSize * 0.5, extent.MinY), new Coordinate(extent.Centre.X + minSize * 0.5, extent.MaxY));
}
if (extent.Height < minSize)
{
extent = new Envelope(new Coordinate(extent.MinX, extent.Centre.Y - minSize * 0.5), new Coordinate(extent.MaxX, extent.Centre.Y + minSize * 0.5));
}
System.Drawing.Brush brush = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(64, System.Drawing.Color.Red));
System.Drawing.Pen pen = new System.Drawing.Pen(System.Drawing.Color.Red, 4);
mapGraphics.FillEnvelope(brush, extent);
mapGraphics.DrawEnvelope(pen, extent);
MemoryStream stream = new MemoryStream();
bitmap.Save(stream, mapImageData.Type == CommonImageType.Png ? System.Drawing.Imaging.ImageFormat.Png : System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] mapImage = stream.ToArray();
float originX = Convert.ToSingle(row.OriginX) * PointsPerInch;
float originY = Convert.ToSingle(row.OriginY) * PointsPerInch;
float width = Convert.ToSingle(row.Width) * PointsPerInch;
float height = Convert.ToSingle(row.Height) * PointsPerInch;
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(mapImage);
image.SetAbsolutePosition(originX, originY);
image.ScaleAbsolute(width, height);
content.AddImage(image);
CreatePdfBox(content, row, false);
}
private void CreatePdfTabData(PdfContentByte content, Configuration.PrintTemplateContentRow row)
{
CreatePdfBox(content, row);
float originX = Convert.ToSingle(row.OriginX) * PointsPerInch;
float originY = Convert.ToSingle(row.OriginY) * PointsPerInch;
float width = Convert.ToSingle(row.Width) * PointsPerInch;
float height = Convert.ToSingle(row.Height) * PointsPerInch;
string fontFamily = row.IsFontFamilyNull() ? "Helvetica" : row.FontFamily;
float fontSize = row.IsFontSizeNull() ? 12 : Convert.ToSingle(row.FontSize);
BaseFont normalFont = BaseFont.CreateFont(fontFamily, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
BaseFont boldFont = BaseFont.CreateFont(fontFamily + "-Bold", BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
}
private void CreatePdfText(PdfContentByte content, Configuration.PrintTemplateContentRow row, string text)
{
CreatePdfBox(content, row);
float originX = Convert.ToSingle(row.OriginX) * PointsPerInch;
float originY = Convert.ToSingle(row.OriginY) * PointsPerInch;
float width = Convert.ToSingle(row.Width) * PointsPerInch;
float height = Convert.ToSingle(row.Height) * PointsPerInch;
string fontFamily = "Helvetica";
int textAlign = PdfContentByte.ALIGN_CENTER;
float fontSize = 12;
int textStyle = iTextSharp.text.Font.NORMAL;
bool textWrap = false;
int columnAlign = Element.ALIGN_CENTER;
if (!row.IsTextWrapNull())
{
textWrap = row.TextWrap == 1;
}
if (!row.IsFontFamilyNull())
{
fontFamily = row.FontFamily;
}
if (!row.IsFontBoldNull())
{
if (row.FontBold == 1)
{
if (textWrap)
{
textStyle = Font.BOLD;
}
else
{
fontFamily += "-Bold";
}
}
}
if (!row.IsFontSizeNull())
{
fontSize = Convert.ToSingle(row.FontSize);
}
BaseFont baseFont = BaseFont.CreateFont(fontFamily, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
if (textWrap)
{
if (!row.IsTextAlignNull())
{
switch (row.TextAlign)
{
case "left":
columnAlign = Element.ALIGN_LEFT;
break;
case "right":
columnAlign = Element.ALIGN_RIGHT;
break;
}
}
Font font = new Font(baseFont, fontSize, textStyle);
content.SetRGBColorFill(0, 0, 0);
float leading = fontSize * 1.2f;
ColumnText column = new ColumnText(content);
column.SetSimpleColumn(originX, originY, originX + width, originY + height, leading, columnAlign);
column.AddText(new Phrase(leading, text, font));
column.Go();
}
else
{
originX += width / 2;
if (!row.IsTextAlignNull())
{
switch (row.TextAlign)
{
case "left":
textAlign = PdfContentByte.ALIGN_LEFT;
originX -= width / 2;
break;
case "right":
textAlign = PdfContentByte.ALIGN_RIGHT;
originX += width / 2;
break;
}
}
content.BeginText();
content.SetFontAndSize(baseFont, fontSize);
content.SetRGBColorFill(0, 0, 0);
content.ShowTextAligned(textAlign, text, originX, originY, 0);
content.EndText();
}
}
private float GetLayerHeightInLegend(List<CommonLayer> layerList, LegendProperties properties, CommonLayer layer)
{
float height = 0;
if (layer.Type == CommonLayerType.Group)
{
height = properties.FontSize + properties.LayerSpacing;
foreach (CommonLayer childLayer in layer.Children)
{
if (layerList.Contains(childLayer))
{
height += GetLayerHeightInLegend(layerList, properties, childLayer);
break;
}
}
}
else
{
int numClasses = GetNumClasses(layer);
if (numClasses > 1)
{
height = properties.FontSize + properties.ClassSpacing;
}
height += numClasses * (properties.SwatchHeight + properties.ClassSpacing) - properties.ClassSpacing;
}
return height;
}
private List<CommonLayer> GetLegendLayers()
{
StringCollection visibleLayers = null;
if (_pixelSize > 0 && _appState.VisibleLayers.ContainsKey(_appState.MapTab))
{
visibleLayers = _appState.VisibleLayers[_appState.MapTab];
}
Configuration config = AppContext.GetConfiguration();
Configuration.MapTabRow mapTab = config.MapTab.FindByMapTabID(_appState.MapTab);
CommonDataFrame dataFrame = AppContext.GetDataFrame(mapTab);
List<CommonLayer> layerList = new List<CommonLayer>();
List<String> mapTabLayerIds = new List<String>();
foreach (Configuration.MapTabLayerRow mapTabLayer in mapTab.GetMapTabLayerRows())
{
Configuration.LayerRow layer = mapTabLayer.LayerRow;
mapTabLayerIds.Add(layer.LayerID);
CommonLayer commonLayer = dataFrame.Layers.FirstOrDefault(lyr => String.Compare(lyr.Name, layer.LayerName, true) == 0);
if (commonLayer.Type == CommonLayerType.Feature && !layerList.Contains(commonLayer))
{
bool hasClasses = GetNumClasses(commonLayer) > 0;
bool visibleAtScale = _pixelSize <= 0 || commonLayer.IsWithinScaleThresholds(_pixelSize);
bool shownInLegend = !mapTabLayer.IsShowInLegendNull() && mapTabLayer.ShowInLegend == 1;
bool checkedInLegend = mapTabLayer.IsCheckInLegendNull() || mapTabLayer.CheckInLegend < 0 || visibleLayers == null || visibleLayers.Contains(layer.LayerID);
bool shownInPrintLegend = !(!mapTabLayer.IsShowInPrintLegendNull() && mapTabLayer.ShowInPrintLegend == 0);
if (hasClasses && visibleAtScale && shownInLegend && checkedInLegend && shownInPrintLegend)
{
layerList.Add(commonLayer);
while (commonLayer.Parent != null)
{
commonLayer = commonLayer.Parent;
if (!layerList.Contains(commonLayer))
{
layerList.Add(commonLayer);
}
}
}
}
}
return layerList;
}
private int GetNumClasses(CommonLayer layer)
{
int numClasses = 0;
CommonLegend legend = layer.Legend;
if (legend != null)
{
for (int g = 0; g < legend.Groups.Count; ++g)
{
for (int c = 0; c < legend.Groups[g].Classes.Count; ++c)
{
if (!legend.Groups[g].Classes[c].ImageIsTransparent)
{
++numClasses;
}
}
}
}
return numClasses;
}
public void Write(HttpResponse response)
{
Write(response, true);
}
public void Write(HttpResponse response, bool inline)
{
response.Clear();
response.ContentType = "application/pdf";
response.AddHeader("Content-Disposition", (inline ? "inline" : "attachment") + "; filename=Map.pdf");
// create the PDF document
Configuration config = AppContext.GetConfiguration();
Configuration.PrintTemplateRow printTemplate = config.PrintTemplate.First(o => o.TemplateID == _templateId);
float pageWidth = Convert.ToSingle(printTemplate.PageWidth * PointsPerInch);
float pageHeight = Convert.ToSingle(printTemplate.PageHeight * PointsPerInch);
Rectangle pageSize = new Rectangle(pageWidth, pageHeight);
pageSize.BackgroundColor = new Color(System.Drawing.Color.White);
Document document = new Document(pageSize);
PdfWriter writer = PdfWriter.GetInstance(document, response.OutputStream);
document.Open();
PdfContentByte content = writer.DirectContent;
// get the extent of the main map and fit it to the proportions of
// the map box on the page
double mapScale = 0;
Configuration.PrintTemplateContentRow mapElement = printTemplate.GetPrintTemplateContentRows().FirstOrDefault(o => o.ContentType == "map");
if (mapElement != null)
{
if (_preserveMode == PreserveMode.Extent)
{
_appState.Extent.Reaspect(mapElement.Width, mapElement.Height);
}
else
{
IPoint c = new Point(_appState.Extent.Centre);
double dx;
double dy;
if (_preserveMode == PreserveMode.Scale)
{
double ratio = _appState.Extent.Width * 96 / _originalWidth;
dx = mapElement.Width * ratio * 0.5;
dy = mapElement.Height * ratio * 0.5;
}
else
{
dx = _appState.Extent.Width * 0.5;
dy = dx * mapElement.Height / mapElement.Width;
}
_appState.Extent = new Envelope(new Coordinate(c.Coordinate.X - dx, c.Coordinate.Y - dy), new Coordinate(c.Coordinate.X + dx, c.Coordinate.Y + dy));
}
double conversion = AppContext.AppSettings.MapUnits == "feet" ? 1 : Constants.FeetPerMeter;
mapScale = _appState.Extent.Width * conversion / mapElement.Width;
_pixelSize = _appState.Extent.Width / (mapElement.Width * PixelsPerInch);
}
int inputIndex = 0;
// get the page template elements and draw each one to the page
foreach (Configuration.PrintTemplateContentRow element in printTemplate.GetPrintTemplateContentRows())
{
switch (element.ContentType)
{
case "box":
CreatePdfBox(content, element);
break;
case "date":
CreatePdfText(content, element, DateTime.Now.ToString("MMMM d, yyyy"));
break;
case "image":
CreatePdfImage(content, element);
break;
case "legend":
CreatePdfLegend(content, element);
break;
case "map":
CreatePdfMap(content, element);
break;
case "overviewmap":
CreatePdfOverviewMap(content, element);
break;
case "scale":
if (mapScale > 0)
{
CreatePdfText(content, element, "1\" = " + mapScale.ToString("0") + " ft");
}
break;
case "scalefeet":
if (mapScale > 0)
{
CreatePdfText(content, element, mapScale.ToString("0") + " ft");
}
break;
case "tabdata":
CreatePdfTabData(content, element);
break;
case "text":
if (!element.IsTextNull())
{
CreatePdfText(content, element, element.Text);
}
else if (!element.IsFileNameNull())
{
string fileName = HttpContext.Current.Server.MapPath("Text/Print") + "\\" + element.FileName;
if (File.Exists(fileName))
{
string text = File.ReadAllText(fileName);
CreatePdfText(content, element, text);
}
}
break;
case "input":
if (inputIndex < _input.Count)
{
CreatePdfText(content, element, _input[inputIndex]);
++inputIndex;
}
break;
}
}
document.Close();
response.End();
}
private class LegendProperties
{
public float OriginX;
public float OriginY;
public float Width;
public float Height;
public float FontSize;
public BaseFont BaseFont;
public float SwatchHeight;
public float SwatchWidth;
public float LayerSpacing;
public float ClassSpacing;
public float ColumnSpacing;
public float ColumnWidth;
public int NumColumns;
public float CurrentX;
public float CurrentY;
public float CurrentColumn;
public LegendProperties(Configuration.PrintTemplateContentRow row)
{
OriginX = Convert.ToSingle(row.OriginX) * PointsPerInch;
OriginY = Convert.ToSingle(row.OriginY) * PointsPerInch;
Width = Convert.ToSingle(row.Width) * PointsPerInch;
Height = Convert.ToSingle(row.Height) * PointsPerInch;
string fontFamily = row.IsFontFamilyNull() ? "Helvetica" : row.FontFamily;
FontSize = row.IsFontSizeNull() ? 12 : Convert.ToSingle(row.FontSize);
if (!row.IsFontBoldNull() && row.FontBold == 1)
{
fontFamily += "-Bold";
}
BaseFont = BaseFont.CreateFont(fontFamily, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
SwatchHeight = FontSize;
SwatchWidth = FontSize * 1.4f;
LayerSpacing = FontSize * 0.5f;
ClassSpacing = FontSize * 0.15f;
ColumnSpacing = FontSize * 1.4f;
ColumnWidth = !row.IsLegendColumnWidthNull() ? Convert.ToSingle(row.LegendColumnWidth) * PointsPerInch :
FontSize * 12 + SwatchWidth;
NumColumns = Convert.ToInt32(Math.Floor((Width + ColumnSpacing) / (ColumnWidth + ColumnSpacing)));
}
}
}
public enum PreserveMode
{
Extent = 0,
Scale = 1,
Width = 2
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ExitActions.cs" company="Appccelerate">
// Copyright (c) 2008-2019 Appccelerate
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Appccelerate.StateMachine.Specs.Sync
{
using System;
using System.Collections.Generic;
using FluentAssertions;
using Machine;
using Xbehave;
public class ExitActions
{
private const int State = 1;
private const int AnotherState = 2;
private const int Event = 2;
[Scenario]
public void ExitAction(
PassiveStateMachine<int, int> machine,
bool exitActionExecuted)
{
"establish a state machine with exit action on a state".x(() =>
{
var stateMachineDefinitionBuilder = new StateMachineDefinitionBuilder<int, int>();
stateMachineDefinitionBuilder
.In(State)
.ExecuteOnExit(() => exitActionExecuted = true)
.On(Event).Goto(AnotherState);
machine = stateMachineDefinitionBuilder
.WithInitialState(State)
.Build()
.CreatePassiveStateMachine();
});
"when leaving the state".x(() =>
{
machine.Start();
machine.Fire(Event);
});
"it should execute the exit action".x(() =>
exitActionExecuted.Should().BeTrue());
}
[Scenario]
public void ExitActionWithParameter(
PassiveStateMachine<int, int> machine,
string parameter)
{
const string Parameter = "parameter";
"establish a state machine with exit action with parameter on a state".x(() =>
{
var stateMachineDefinitionBuilder = new StateMachineDefinitionBuilder<int, int>();
stateMachineDefinitionBuilder
.In(State)
.ExecuteOnExitParametrized(p => parameter = p, Parameter)
.On(Event).Goto(AnotherState);
machine = stateMachineDefinitionBuilder
.WithInitialState(State)
.Build()
.CreatePassiveStateMachine();
});
"when leaving the state".x(() =>
{
machine.Start();
machine.Fire(Event);
});
"it should execute the exit action".x(() =>
parameter.Should().NotBeNull());
"it should pass parameter to the exit action".x(() =>
parameter.Should().Be(Parameter));
}
[Scenario]
public void MultipleExitActions(
PassiveStateMachine<int, int> machine,
bool exitAction1Executed,
bool exitAction2Executed)
{
"establish a state machine with several exit actions on a state".x(() =>
{
var stateMachineDefinitionBuilder = new StateMachineDefinitionBuilder<int, int>();
stateMachineDefinitionBuilder
.In(State)
.ExecuteOnExit(() => exitAction1Executed = true)
.ExecuteOnExit(() => exitAction2Executed = true)
.On(Event).Goto(AnotherState);
machine = stateMachineDefinitionBuilder
.WithInitialState(State)
.Build()
.CreatePassiveStateMachine();
});
"when leaving the state".x(() =>
{
machine.Start();
machine.Fire(Event);
});
"It should execute all exit actions".x(() =>
{
exitAction1Executed
.Should().BeTrue("first action should be executed");
exitAction2Executed
.Should().BeTrue("second action should be executed");
});
}
[Scenario]
public void ExceptionHandling(
PassiveStateMachine<int, int> machine,
bool exitAction1Executed,
bool exitAction2Executed,
bool exitAction3Executed)
{
var exception2 = new Exception();
var exception3 = new Exception();
var receivedExceptions = new List<Exception>();
"establish a state machine with several exit actions on a state and some of them throw an exception".x(() =>
{
var stateMachineDefinitionBuilder = new StateMachineDefinitionBuilder<int, int>();
stateMachineDefinitionBuilder
.In(State)
.ExecuteOnExit(() => exitAction1Executed = true)
.ExecuteOnExit(() =>
{
exitAction2Executed = true;
throw exception2;
})
.ExecuteOnExit(() =>
{
exitAction3Executed = true;
throw exception3;
})
.On(Event).Goto(AnotherState);
machine = stateMachineDefinitionBuilder
.WithInitialState(State)
.Build()
.CreatePassiveStateMachine();
machine.TransitionExceptionThrown += (s, e) => receivedExceptions.Add(e.Exception);
});
"when entering the state".x(() =>
{
machine.Start();
machine.Fire(Event);
});
"it should execute all entry actions on entry".x(() =>
{
exitAction1Executed
.Should().BeTrue("action 1 should be executed");
exitAction2Executed
.Should().BeTrue("action 2 should be executed");
exitAction3Executed
.Should().BeTrue("action 3 should be executed");
});
"it should handle all exceptions of all throwing entry actions by firing the TransitionExceptionThrown event".x(() =>
receivedExceptions
.Should()
.HaveCount(2)
.And
.Contain(exception2)
.And
.Contain(exception3));
}
[Scenario]
public void EventArgument(
PassiveStateMachine<int, int> machine,
int passedArgument)
{
const int Argument = 17;
"establish a state machine with an exit action taking an event argument".x(() =>
{
var stateMachineDefinitionBuilder = new StateMachineDefinitionBuilder<int, int>();
stateMachineDefinitionBuilder
.In(State)
.ExecuteOnExit((int argument) => passedArgument = argument)
.On(Event).Goto(AnotherState);
stateMachineDefinitionBuilder
.In(AnotherState)
.ExecuteOnEntry((int argument) => passedArgument = argument);
machine = stateMachineDefinitionBuilder
.WithInitialState(State)
.Build()
.CreatePassiveStateMachine();
});
"when leaving the state".x(() =>
{
machine.Start();
machine.Fire(Event, Argument);
});
"it should pass event argument to exit action".x(() =>
passedArgument.Should().Be(Argument));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using PS.Build.Extensions;
using PS.Build.Services;
using PS.Build.Tasks.Extensions;
using PS.Build.Tasks.Services;
using PS.Build.Types;
namespace PS.Build.Tasks
{
class SandboxClient : MarshalByRefObject
{
#region Static members
private static IEnumerable<AdaptationUsage> Sort(IList<AdaptationUsage> usages)
{
var subsets = new List<AdaptationUsage>();
subsets.AddRange(usages.Where(u => u.AttributeTargets == AttributeTargets.Assembly));
subsets.AddRange(usages.Where(u => u.AttributeTargets == AttributeTargets.Field));
var fieldEvents = usages.Where(u =>
{
if (u.AttributeTargets != AttributeTargets.Event) return false;
return u.AssociatedSyntaxNode.Parent.Parent is BaseFieldDeclarationSyntax;
}).ToList();
subsets.AddRange(fieldEvents);
subsets.AddRange(usages.Where(u => u.AttributeTargets == AttributeTargets.Parameter));
subsets.AddRange(usages.Where(u => u.AttributeTargets == AttributeTargets.ReturnValue));
var methodTemplates = usages.Where(u =>
{
if (u.AttributeTargets != AttributeTargets.GenericParameter) return false;
return u.AssociatedSyntaxNode.Parent.Parent is BaseMethodDeclarationSyntax;
}).ToList();
subsets.AddRange(methodTemplates);
subsets.AddRange(usages.Where(u => u.AttributeTargets == AttributeTargets.Constructor));
subsets.AddRange(usages.Where(u => u.AttributeTargets == AttributeTargets.Method));
subsets.AddRange(usages.Except(fieldEvents).Where(u => u.AttributeTargets == AttributeTargets.Event));
subsets.AddRange(usages.Where(u => u.AttributeTargets == AttributeTargets.Property));
subsets.AddRange(usages.Except(methodTemplates).Where(u => u.AttributeTargets == AttributeTargets.GenericParameter));
subsets.AddRange(usages.Where(u => u.AttributeTargets == AttributeTargets.Interface));
subsets.AddRange(usages.Where(u => u.AttributeTargets == AttributeTargets.Enum));
subsets.AddRange(usages.Where(u => u.AttributeTargets == AttributeTargets.Class));
subsets.AddRange(usages.Where(u => u.AttributeTargets == AttributeTargets.Struct));
subsets.AddRange(usages.Where(u => u.AttributeTargets == AttributeTargets.Delegate));
subsets.AddRange(usages.Where(u => u.AttributeTargets == AttributeTargets.Module));
return subsets;
}
#endregion
private readonly DomainAssemblyResolver _assemblyResolver;
private readonly IDynamicVault _dynamicVault;
private readonly IExplorer _explorer;
private readonly MacroResolver _macroResolver;
private readonly NugetExplorer _nugetExplorer;
private CSharpCompilation _compilation;
private List<AdaptationUsage> _usages;
#region Constructors
public SandboxClient(DomainAssemblyResolver assemblyResolver, IExplorer explorer)
{
if (assemblyResolver == null) throw new ArgumentNullException(nameof(assemblyResolver));
if (explorer == null) throw new ArgumentNullException(nameof(explorer));
_assemblyResolver = assemblyResolver;
_explorer = explorer;
_dynamicVault = new DynamicVault();
_nugetExplorer = new NugetExplorer(_explorer.Directories[BuildDirectory.Solution]);
_macroResolver = new MacroResolver();
_macroResolver.Register(new ExplorerMacroHandler(_explorer));
_macroResolver.Register(new NugetExplorerMacroHandler(_nugetExplorer));
_macroResolver.Register(new EnvironmentMacroHandler());
_macroResolver.Register(new TimeMacroHandler());
_macroResolver.Register(new UidMacroHandler());
_macroResolver.Register(new SpecialDirectoryMacroHandler());
}
#endregion
#region Members
public void ExecutePostBuildAdaptations(ILogger logger)
{
if (_usages != null) ExecutePostBuildAdaptations(logger, _usages);
}
public SerializableArtifact[] ExecutePreBuildAdaptations(ILogger logger)
{
return ExecutePreBuildAdaptationsInternal(logger);
}
public CompileItemReplacement[] ReplaceCompileItems(ILogger logger)
{
var result = new List<CompileItemReplacement>();
logger.Debug("------------");
logger.Info("Replacing source code files which contains adaptation usages");
var intermediateDirectory = _explorer.Directories[BuildDirectory.Intermediate];
var groupedUsages = _usages.Enumerate().ToLookup(u => u.SyntaxTree.FilePath, u => u);
logger.Info($"{groupedUsages.Count(g => g.Any(u => !u.Escaped))} files will be replaced");
var pattern = @"\[(assembly:)?(module:)?\s*\]";
var options = RegexOptions.IgnorePatternWhitespace;
var regex = new Regex(pattern, options);
foreach (var group in groupedUsages)
{
var sourceFile = group.Key;
if (group.All(u => u.Escaped))
{
logger.Info($"All adaptation are isolated in {sourceFile} file");
continue;
}
if (group.Any(u => u.Escaped))
{
var warnMessage = $"Mixed isolation detected in {sourceFile} file. Unescaped adaptations:" + Environment.NewLine;
foreach (var unescapedSyntax in group.Where(u => !u.Escaped))
{
var location = unescapedSyntax.SyntaxTree
.GetMappedLineSpan(unescapedSyntax.AttributeData.ApplicationSyntaxReference.Span)
.Span;
warnMessage += $" Position {location}: {unescapedSyntax.AttributeData}{Environment.NewLine}";
}
logger.Warn(warnMessage);
}
var replacedFile = Path.Combine(intermediateDirectory, "__replacements", sourceFile.GetMD5Hash() + ".cs");
logger.Debug("+ Replacement");
logger.Debug(" Removed: " + sourceFile);
logger.Debug(" Added: " + replacedFile);
try
{
var visitor = new CompileItemRewriterVisitor(group);
var syntaxTree = group.FirstOrDefault()?.SyntaxTree;
if (syntaxTree == null) continue;
var rewrittenItem = visitor.Visit(syntaxTree.GetRoot());
Path.GetDirectoryName(replacedFile)?.EnsureDirectoryExist();
var replacedFileContent = rewrittenItem.ToFullString();
replacedFileContent = regex.Replace(replacedFileContent, string.Empty);
File.WriteAllText(replacedFile, replacedFileContent);
var replacement = new CompileItemReplacement
{
Source = sourceFile,
Target = replacedFile
};
result.Add(replacement);
}
catch (Exception e)
{
logger.Warn($"File '{sourceFile}' could not be replaced. Details: " + e.GetBaseException().Message);
}
}
return result.ToArray();
}
private List<AdaptationUsage> AnalyzeSemanticForAdaptationUsages(SuspiciousAttributeSyntaxes suspiciousAttributeSyntaxes,
CSharpCompilation compilation,
ILogger logger)
{
logger.Debug("------------");
logger.Info("Analyzing semantic");
var suspiciousSyntaxTrees = suspiciousAttributeSyntaxes.ToLookup(pair => pair.Syntax.SyntaxTree, pair => pair);
var usages = new List<AdaptationUsage>();
foreach (var group in suspiciousSyntaxTrees)
{
var semanticModel = compilation.GetSemanticModel(group.Key, true);
foreach (var syntax in group)
{
try
{
var attributeInfo = semanticModel.GetSymbolInfo(syntax.Syntax);
var symbol = attributeInfo.Symbol ?? attributeInfo.CandidateSymbols.FirstOrDefault();
if (symbol == null) continue;
var resolvedType = syntax.PossibleTypes.FirstOrDefault(t => symbol.ResolveType() == t);
var attributeData = syntax.Syntax.ResolveAttributeData(semanticModel);
if (resolvedType == null) throw new InvalidDataException($"Could not resolve '{syntax.Syntax}' type");
if (attributeData?.Item2 == null) throw new InvalidDataException("Could not resolve attribute semantic");
if (attributeData.Item1 == AttributeTargets.All)
throw new InvalidOperationException("Unexpected AttributeTargets in resolved attribute data");
usages.Add(new AdaptationUsage(semanticModel,
group.Key,
syntax.Syntax.Parent.Parent,
attributeData.Item2,
attributeData.Item1,
resolvedType,
syntax.Escaped));
}
catch (NotSupportedException e)
{
logger.Debug($"Not supported feature. Details: {e.GetBaseException().Message}");
}
catch (Exception e)
{
logger.Warn($"Unexpected internal error. Details: {e.GetBaseException().Message}");
}
}
}
logger.Info($"Found {usages.Count} adaptation attribute usages");
foreach (var usage in usages)
{
logger.Debug($"+ Usage: {usage}");
}
return usages;
}
private SuspiciousAttributeSyntaxes AnalyzeSyntaxForAdaptationUsages(IEnumerable<Type> adaptationTypes,
IEnumerable<Tuple<SyntaxTree, SyntaxTree>> syntaxTrees,
ILogger logger)
{
logger.Debug("------------");
logger.Info("Analyzing syntax");
var visitor = new SuspiciousAttributeVisitor(adaptationTypes);
foreach (var syntaxTree in syntaxTrees)
{
visitor.IsChanged.Reset();
visitor.Visit(syntaxTree.Item2.GetRoot());
if (visitor.IsChanged.WaitOne(0))
{
logger.Debug("Suspicious attributes isolation test");
visitor.Visit(syntaxTree.Item1.GetRoot());
}
}
var suspiciousAttributeSyntaxes = visitor.SuspiciousAttributeSyntaxes;
logger.Info($"Found {suspiciousAttributeSyntaxes.Count} suspicious attributes");
foreach (var syntax in suspiciousAttributeSyntaxes)
{
logger.Debug($"+ Syntax: {syntax.Syntax}");
using (logger.IndentMessages())
{
logger.Debug($"Escaped: {syntax.Escaped}");
logger.Debug($"Location: {syntax.Syntax.GetLocation()}");
foreach (var type in syntax.PossibleTypes)
{
using (logger.IndentMessages())
logger.Debug($"* Could be: {type.FullName}");
}
}
}
return suspiciousAttributeSyntaxes;
}
private CSharpCompilation CreateCompilation(IEnumerable<SyntaxTree> syntaxTrees, ILogger logger)
{
logger.Debug("------------");
logger.Info("Creating Roslyn compilation");
var references = _explorer.References.Select(r => MetadataReference.CreateFromFile(r.FullPath));
return CSharpCompilation.Create(Guid.NewGuid().ToString("N"), syntaxTrees, references);
}
private List<Tuple<SyntaxTree, SyntaxTree>> CreateSyntaxTrees()
{
var syntaxTrees = _explorer.Items[BuildItem.Compile].Select(r =>
{
var text = File.ReadAllText(r.FullPath);
var symbols = GetBuildConstants().ToList();
var treeWithoutEscapes = CSharpSyntaxTree.ParseText(text,
path: r.FullPath,
options: new CSharpParseOptions(preprocessorSymbols: symbols));
symbols.Add("ADAPTATION");
var treeWithEscapes = CSharpSyntaxTree.ParseText(text,
path: r.FullPath,
options: new CSharpParseOptions(preprocessorSymbols: symbols));
return new Tuple<SyntaxTree, SyntaxTree>(treeWithoutEscapes, treeWithEscapes);
}).ToList();
return syntaxTrees;
}
private void ExecutePostBuildAdaptations(ILogger logger, List<AdaptationUsage> usages)
{
if (usages.All(u => u.PostBuildMethod == null))
{
logger.Info("There is no discovered adaptations with post build instructions");
return;
}
logger.Info("Executing discovered adaptations with post build instructions");
foreach (var usage in Sort(usages))
{
var method = usage.PostBuildMethod;
if (method == null)
{
logger.Debug("Adaptation does not contain void PostBuild(IServiceProvider provider) method. Skipping...");
continue;
}
var attribute = usage.Attribute;
if (attribute == null)
{
try
{
attribute = usage.AttributeData.CreateAttribute();
}
catch (Exception e)
{
logger.Warn($"Could not create adaptation attribute. Details: {e.GetBaseException().Message}.");
continue;
}
}
try
{
logger.Info("------------");
logger.Info($"Adaptation: {usage.AttributeData}");
var serviceProvider = new ServiceProvider();
serviceProvider.AddService(typeof(CSharpCompilation), _compilation);
serviceProvider.AddService(typeof(SyntaxNode), usage.AssociatedSyntaxNode);
serviceProvider.AddService(typeof(SyntaxTree), usage.SyntaxTree);
serviceProvider.AddService(typeof(SemanticModel), usage.SemanticModel);
serviceProvider.AddService(typeof(ILogger), new ScopeLogger(logger));
serviceProvider.AddService(typeof(IExplorer), _explorer);
serviceProvider.AddService(typeof(INugetExplorer), _nugetExplorer);
serviceProvider.AddService(typeof(IDynamicVault), _dynamicVault);
serviceProvider.AddService(typeof(IMacroResolver), _macroResolver);
method.Invoke(attribute, new object[] { serviceProvider });
}
catch (Exception e)
{
logger.Error($"Adaptation failed. Details: {e.GetBaseException().Message}.");
}
}
}
private List<Artifact> ExecutePreBuildAdaptations(List<AdaptationUsage> usages,
ILogger logger)
{
var result = new List<Artifact>();
if (usages.All(u => u.PreBuildMethod == null))
{
logger.Info("There is no discovered adaptations with pre build instructions");
return result;
}
logger.Info("Executing discovered adaptations with pre build instructions");
foreach (var usage in Sort(usages))
{
var method = usage.PreBuildMethod;
if (method == null)
{
logger.Debug("Adaptation does not contain void PreBuild(IServiceProvider provider) method. Skipping...");
continue;
}
Attribute attribute;
try
{
attribute = usage.AttributeData.CreateAttribute();
usage.Attribute = attribute;
}
catch (Exception e)
{
logger.Warn($"Could not create adaptation attribute. Details: {e.GetBaseException().Message}.");
continue;
}
try
{
logger.Info("------------");
logger.Info($"Adaptation: {usage.AttributeData}");
var artifactory = new Artifactory();
var serviceProvider = new ServiceProvider();
serviceProvider.AddService(typeof(CSharpCompilation), _compilation);
serviceProvider.AddService(typeof(SyntaxNode), usage.AssociatedSyntaxNode);
serviceProvider.AddService(typeof(SyntaxTree), usage.SyntaxTree);
serviceProvider.AddService(typeof(SemanticModel), usage.SemanticModel);
serviceProvider.AddService(typeof(ILogger), new ScopeLogger(logger));
serviceProvider.AddService(typeof(IExplorer), _explorer);
serviceProvider.AddService(typeof(IArtifactory), artifactory);
serviceProvider.AddService(typeof(INugetExplorer), _nugetExplorer);
serviceProvider.AddService(typeof(IDynamicVault), _dynamicVault);
serviceProvider.AddService(typeof(IMacroResolver), _macroResolver);
method.Invoke(attribute, new object[] { serviceProvider });
result.AddRange(artifactory.Artifacts);
}
catch (Exception e)
{
logger.Error($"Adaptation failed. Details: {e.GetBaseException().Message}.");
}
}
return result;
}
private SerializableArtifact[] ExecutePreBuildAdaptationsInternal(ILogger logger)
{
var result = new List<SerializableArtifact>();
var adaptationTypes = SearchCompiledAdaptations(logger);
if (!adaptationTypes.Any())
{
logger.Info("Assembly references do not contains adaptation attributes.");
return result.ToArray();
}
var syntaxTrees = CreateSyntaxTrees();
var suspiciousAttributeSyntaxes = AnalyzeSyntaxForAdaptationUsages(adaptationTypes, syntaxTrees, logger);
if (!suspiciousAttributeSyntaxes.Any())
{
logger.Info("Assembly does not use any defined adaptation attribute.");
return result.ToArray();
}
_compilation = CreateCompilation(syntaxTrees.Select(t => t.Item2), logger);
if (_compilation == null) throw new Exception("Can not create compilation");
_usages = AnalyzeSemanticForAdaptationUsages(suspiciousAttributeSyntaxes, _compilation, logger);
if (!_usages.Any())
{
logger.Info("Assembly does not use any defined adaptation attribute.");
return result.ToArray();
}
var setupMethods = new List<MethodInfo>();
foreach (var usage in Sort(_usages))
{
setupMethods.AddRange(usage.SetupMethods);
}
if (setupMethods.Any())
{
logger.Info("Setup adaptations");
var calledMethods = new List<MethodInfo>();
foreach (var method in setupMethods)
{
if (calledMethods.Contains(method)) continue;
calledMethods.Add(method);
logger.Info("------------");
logger.Info($"Setup: {method.DeclaringType?.Name} type");
var serviceProvider = new ServiceProvider();
serviceProvider.AddService(typeof(ILogger), new ScopeLogger(logger));
serviceProvider.AddService(typeof(IExplorer), _explorer);
serviceProvider.AddService(typeof(INugetExplorer), _nugetExplorer);
serviceProvider.AddService(typeof(IDynamicVault), _dynamicVault);
serviceProvider.AddService(typeof(IMacroResolver), _macroResolver);
method.Invoke(null, new object[] { serviceProvider });
}
}
var artifacts = new List<Artifact>();
artifacts.AddRange(ExecutePreBuildAdaptations(_usages, logger));
using (var cacheManager = new CacheManager<ArtifactCache>(_explorer.Directories[BuildDirectory.Intermediate], logger))
{
HandleArtifactsContent(artifacts, cacheManager, logger);
artifacts.Add(new Artifact(cacheManager.GetCachePath(), BuildItem.Internal));
}
result.AddRange(artifacts.Select(a => a.Serialize()));
return result.ToArray();
}
private string[] GetBuildConstants()
{
var constants = _explorer.Properties[BuildProperty.DefineConstants] ?? string.Empty;
return constants.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
}
private void HandleArtifactsContent(List<Artifact> artifacts, CacheManager<ArtifactCache> cacheManager, ILogger logger)
{
var artifactsWithContentGenerators = artifacts.Where(a => a.ContentFactory != null).ToList();
if (!artifactsWithContentGenerators.Any()) return;
logger.Debug("------------");
logger.Info("Processing adaptation artifacts content");
foreach (var artifact in artifactsWithContentGenerators)
{
try
{
var currentHashCodes = artifact.Dependencies.GetDependenciesHashCodes().ToArray();
var cache = cacheManager.GetCached(artifact.Path);
if (cache == null || !File.Exists(artifact.Path) || !currentHashCodes.Any())
{
cacheManager.Cache(artifact.Path,
new ArtifactCache
{
HashCodes = currentHashCodes
});
}
else if (cache.HashCodes.SequenceEqual(currentHashCodes))
{
logger.Info($"+ {artifact}: Content is up to date");
continue;
}
var content = artifact.ContentFactory();
if (content != null)
{
Path.GetDirectoryName(artifact.Path).EnsureDirectoryExist();
File.WriteAllBytes(artifact.Path, content);
}
logger.Info($"+ {artifact}: Content generated");
}
catch (Exception e)
{
logger.Error($"Adaptation content generation failed. Details: {e.GetBaseException().Message}.");
}
}
}
private List<Type> SearchCompiledAdaptations(ILogger logger)
{
var references = _explorer.References.Select(i => i.FullPath).ToList();
var adaptationDefinitionTypes = new List<Type>();
logger.Debug("------------");
logger.Info("Searching for compiled adaptation attributes");
var pathBanns = new List<string>
{
@"Reference Assemblies\Microsoft\Framework\.NETFramework"
};
foreach (var reference in references)
{
if (pathBanns.Any(p => reference.Contains(p))) continue;
try
{
var assembly = _assemblyResolver.LoadAssembly(reference);
var foundTypes = assembly.GetTypesSafely()
.Where(t => typeof(Attribute).IsAssignableFrom(t))
.Where(t => t.GetCustomAttribute<DesignerAttribute>()?.DesignerTypeName == "PS.Build.Adaptation")
.ToList();
adaptationDefinitionTypes.AddRange(foundTypes);
}
catch (Exception e)
{
logger.Warn($"Could not load reference assembly '{reference}'. Details: {e.GetBaseException().Message}");
}
}
//Recheck attributes for inheritance from adaptation types
var adaptationTypes = AppDomain.CurrentDomain
.GetAssemblies()
.Where(a => pathBanns.Any(p => a.Location.Contains(p) != true))
.SelectMany(
a => a.GetTypesSafely().Where(t => adaptationDefinitionTypes.Any(adf => adf.IsAssignableFrom(t))))
.Where(t => !t.IsAbstract)
.ToList();
//Check attribute usage inheritance option
var attributesWithWrongInheritance = adaptationTypes.Where(t =>
{
var usageAttribute = t.GetCustomAttribute<AttributeUsageAttribute>() ??
new AttributeUsageAttribute(AttributeTargets.All);
if (usageAttribute.ValidOn.HasFlag(AttributeTargets.Method) ||
usageAttribute.ValidOn.HasFlag(AttributeTargets.Class)) return usageAttribute.Inherited;
return false;
}).ToList();
attributesWithWrongInheritance.ForEach(type => logger.Warn($"{type.FullName} has invalid inheritance attribute. Skipping..."));
adaptationTypes = adaptationTypes.Except(attributesWithWrongInheritance).ToList();
//Check attributes with out key methods
var emptyAttributes = adaptationTypes.Where(t => AdaptationUsage.GetPreBuildMethod(t) == null &&
AdaptationUsage.GetPostBuildMethod(t) == null &&
!AdaptationUsage.GetSetupMethods(t).Any())
.ToList();
emptyAttributes.ForEach(type => logger.Warn($"{type.FullName} has no Setup, PreBuid or PostBuild entries. Skipping..."));
adaptationTypes = adaptationTypes.Except(emptyAttributes).ToList();
logger.Info($"Found {adaptationTypes.Count} adaptation attribute definitions");
foreach (var t in adaptationTypes)
{
logger.Debug($"+ Definition: {t.FullName} in {t.Assembly.GetName().Name}");
}
return adaptationTypes;
}
#endregion
}
}
| |
using System;
using NBitcoin.BouncyCastle.Crypto.Parameters;
using NBitcoin.BouncyCastle.Crypto.Utilities;
namespace NBitcoin.BouncyCastle.Crypto.Engines
{
/**
* A Noekeon engine, using direct-key mode.
*/
public class NoekeonEngine
: IBlockCipher
{
private const int GenericSize = 16; // Block and key size, as well as the amount of rounds.
private static readonly uint[] nullVector =
{
0x00, 0x00, 0x00, 0x00 // Used in decryption
};
private static readonly uint[] roundConstants =
{
0x80, 0x1b, 0x36, 0x6c,
0xd8, 0xab, 0x4d, 0x9a,
0x2f, 0x5e, 0xbc, 0x63,
0xc6, 0x97, 0x35, 0x6a,
0xd4
};
private uint[] state = new uint[4], // a
subKeys = new uint[4], // k
decryptKeys = new uint[4];
private bool _initialised, _forEncryption;
/**
* Create an instance of the Noekeon encryption algorithm
* and set some defaults
*/
public NoekeonEngine()
{
_initialised = false;
}
public string AlgorithmName
{
get { return "Noekeon"; }
}
public bool IsPartialBlockOkay
{
get { return false; }
}
public int GetBlockSize()
{
return GenericSize;
}
/**
* initialise
*
* @param forEncryption whether or not we are for encryption.
* @param params the parameters required to set up the cipher.
* @exception ArgumentException if the params argument is
* inappropriate.
*/
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
if (!(parameters is KeyParameter))
throw new ArgumentException("Invalid parameters passed to Noekeon init - " + parameters.GetType().Name, "parameters");
_forEncryption = forEncryption;
_initialised = true;
KeyParameter p = (KeyParameter) parameters;
setKey(p.GetKey());
}
public int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
if (!_initialised)
throw new InvalidOperationException(AlgorithmName + " not initialised");
if ((inOff + GenericSize) > input.Length)
throw new DataLengthException("input buffer too short");
if ((outOff + GenericSize) > output.Length)
throw new DataLengthException("output buffer too short");
return _forEncryption
? encryptBlock(input, inOff, output, outOff)
: decryptBlock(input, inOff, output, outOff);
}
public void Reset()
{
// TODO This should do something in case the encryption is aborted
}
/**
* Re-key the cipher.
*
* @param key the key to be used
*/
private void setKey(byte[] key)
{
subKeys[0] = Pack.BE_To_UInt32(key, 0);
subKeys[1] = Pack.BE_To_UInt32(key, 4);
subKeys[2] = Pack.BE_To_UInt32(key, 8);
subKeys[3] = Pack.BE_To_UInt32(key, 12);
}
private int encryptBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
state[0] = Pack.BE_To_UInt32(input, inOff);
state[1] = Pack.BE_To_UInt32(input, inOff+4);
state[2] = Pack.BE_To_UInt32(input, inOff+8);
state[3] = Pack.BE_To_UInt32(input, inOff+12);
int i;
for (i = 0; i < GenericSize; i++)
{
state[0] ^= roundConstants[i];
theta(state, subKeys);
pi1(state);
gamma(state);
pi2(state);
}
state[0] ^= roundConstants[i];
theta(state, subKeys);
Pack.UInt32_To_BE(state[0], output, outOff);
Pack.UInt32_To_BE(state[1], output, outOff+4);
Pack.UInt32_To_BE(state[2], output, outOff+8);
Pack.UInt32_To_BE(state[3], output, outOff+12);
return GenericSize;
}
private int decryptBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
state[0] = Pack.BE_To_UInt32(input, inOff);
state[1] = Pack.BE_To_UInt32(input, inOff+4);
state[2] = Pack.BE_To_UInt32(input, inOff+8);
state[3] = Pack.BE_To_UInt32(input, inOff+12);
Array.Copy(subKeys, 0, decryptKeys, 0, subKeys.Length);
theta(decryptKeys, nullVector);
int i;
for (i = GenericSize; i > 0; i--)
{
theta(state, decryptKeys);
state[0] ^= roundConstants[i];
pi1(state);
gamma(state);
pi2(state);
}
theta(state, decryptKeys);
state[0] ^= roundConstants[i];
Pack.UInt32_To_BE(state[0], output, outOff);
Pack.UInt32_To_BE(state[1], output, outOff+4);
Pack.UInt32_To_BE(state[2], output, outOff+8);
Pack.UInt32_To_BE(state[3], output, outOff+12);
return GenericSize;
}
private void gamma(uint[] a)
{
a[1] ^= ~a[3] & ~a[2];
a[0] ^= a[2] & a[1];
uint tmp = a[3];
a[3] = a[0];
a[0] = tmp;
a[2] ^= a[0]^a[1]^a[3];
a[1] ^= ~a[3] & ~a[2];
a[0] ^= a[2] & a[1];
}
private void theta(uint[] a, uint[] k)
{
uint tmp;
tmp = a[0]^a[2];
tmp ^= rotl(tmp,8)^rotl(tmp,24);
a[1] ^= tmp;
a[3] ^= tmp;
for (int i = 0; i < 4; i++)
{
a[i] ^= k[i];
}
tmp = a[1]^a[3];
tmp ^= rotl(tmp,8)^rotl(tmp,24);
a[0] ^= tmp;
a[2] ^= tmp;
}
private void pi1(uint[] a)
{
a[1] = rotl(a[1], 1);
a[2] = rotl(a[2], 5);
a[3] = rotl(a[3], 2);
}
private void pi2(uint[] a)
{
a[1] = rotl(a[1], 31);
a[2] = rotl(a[2], 27);
a[3] = rotl(a[3], 30);
}
// Helpers
private uint rotl(uint x, int y)
{
return (x << y) | (x >> (32-y));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using AgentRalph.Visitors;
using ICSharpCode.NRefactory.Ast;
using ICSharpCode.NRefactory.Visitors;
using SharpRefactoring;
namespace AgentRalph.CloneCandidateDetection
{
public class LiteralToParameterExpansion : IRefactoringExpansion
{
public IEnumerable<CloneDesc> FindCandidatesViaRefactoringPermutations(TargetInfo left, CloneDesc refactoredPermy)
{
MethodDeclaration right = refactoredPermy.PermutatedMethod;
// HEURISTIC: This refactoring will not change the node count, so don't bother if they don't already match.
if(right.Body.CountNodes() != left.Target.Body.CountNodes())
// if(!right.MatchesIgnorePrimitives(left.Target))
yield break;
// HEURISTIC: No point in adding any more parameters than the target method has.
int parms_to_add = left.Target.Parameters.Count - right.Parameters.Count;
if (parms_to_add > 0)
{
var md = FindCandidates(right, parms_to_add);
foreach (var h in md)
{
yield return new CloneDesc(h.md, refactoredPermy, new QuickFixInfo(refactoredPermy.ReplacementInvocationInfo, refactoredPermy.ReplacementInvocationInfo.LiteralParams.Concat(h.parameters).ToList()))
{
ReplacementInvocation = AddParms(refactoredPermy.ReplacementInvocation, h.parameters)
};
}
}
}
private AbstractNode AddParms(AbstractNode invocation, IList<object> parameters)
{
if (invocation == null)
{
throw new ArgumentNullException("invocation");
}
var m = invocation as Statement;
if (m != null)
invocation = m.DeepCopy();
else
{
var q = invocation as Expression;
if (q != null)
{
invocation = q.DeepCopy();
}
else
{
throw new Exception("Found a " + invocation.GetType());
}
}
InvocationExpression ie = FirstInvocationExpression(invocation);
foreach (var o in parameters)
{
ie.AddArg(o);
}
return invocation;
}
private InvocationExpression FirstInvocationExpression(AbstractNode invocation)
{
var v = new FindInvocationExpressionVisitor();
invocation.AcceptVisitor(v, null);
return v.Expr;
}
private class FindInvocationExpressionVisitor : AbstractAstVisitor
{
public override object VisitInvocationExpression(InvocationExpression invocationExpression, object d)
{
Expr = invocationExpression;
return null;
}
public InvocationExpression Expr { get; private set; }
}
/// <summary>
/// Shows that the other two parameters are not necessary to this object. Exposed for testing.
/// </summary>
/// <param name="right"></param>
/// <returns></returns>
public IEnumerable<CloneDesc> FindCandidatesViaRefactoringPermutations(MethodDeclaration right)
{
var md = FindCandidates(right, -1);
foreach (Holder h in md)
{
yield return new CloneDesc(h.md, Window.Null, new List<INode>());
}
}
private IEnumerable<Holder> FindCandidates(MethodDeclaration right, int count)
{
var rights_primitives = right.AllPrimitiveExpressions();
// Find all PrimitiveExpressions except the keyword 'null'
IEnumerable<PrimitiveExpression> primitives = rights_primitives.Where(x => x.ValueType != null);
// find the position of each primitive
var prims_with_position = from p in primitives
select new {p.Value, p.ValueType, Index = rights_primitives.IndexOf(p)};
// Group them together by literal value. The groups then are candidates for replacement by a single param.
var prim_groups = from p in prims_with_position
group p by new {p.Value, p.ValueType}
into g select new PrimExpSet {Value = g.Key.Value, ValueType = g.Key.ValueType, Positions = g.Select(x => x.Index)};
// The powerset of the primitive positions is all the possible ways a single primitive value can be converted to a param.
var all_param_possibles = from pes in prim_groups
let expanded = from positions in Sets<int>.PowerSet(pes.Positions.ToArray())
select new PrimExpSet {Value = pes.Value, ValueType = pes.ValueType, Positions = positions}
select expanded;
foreach (var e1 in Sets<PrimExpSet>.CartesianProduct(all_param_possibles, count))
{
// If count is neg, let anything through.
if (count < 0 || e1.Count() == count)
{
var md = MakePermutation(right, e1);
const string QUOTE = "\"";
var parameters = e1.Select(x => x.ValueType == typeof (string) ? QUOTE + x.Value + QUOTE : x.Value).ToList();
yield return new Holder {md = md, parameters = parameters};
}
}
}
private class Holder
{
public MethodDeclaration md;
public IList<object> parameters;
}
private MethodDeclaration MakePermutation(MethodDeclaration right, IEnumerable<PrimExpSet> prim_groups)
{
ResetNameCount();
right = right.DeepCopy();
var rights_primitives = right.AllPrimitiveExpressions();
foreach (var prim_grp in prim_groups)
{
var param_name = NextName();
var typeRef = new TypeReference(prim_grp.ValueType.FullName);
right.Parameters.Add(new ParameterDeclarationExpression(typeRef, param_name));
var replacer = new PrimitiveReplacer();
foreach (var pos in prim_grp.Positions)
{
replacer.AddReplacement(rights_primitives[pos], new IdentifierExpression(param_name));
}
right.AcceptVisitor(replacer, null);
}
return right;
}
private void ResetNameCount()
{
nameCounter = 0;
}
private int nameCounter;
private string NextName()
{
var name = "i" + (nameCounter != 0 ? nameCounter.ToString() : "");
nameCounter++;
return name;
}
private class PrimitiveReplacer : AbstractAstTransformer
{
private readonly IList<ReplacePair> Replacements = new List<ReplacePair>();
public override object VisitPrimitiveExpression(PrimitiveExpression primitiveExpression, object data)
{
foreach (var r in Replacements)
{
if (ReferenceEquals(primitiveExpression, r.Target))
{
ReplaceCurrentNode(r.Replacement);
}
}
return base.VisitPrimitiveExpression(primitiveExpression, data);
}
public void AddReplacement(INode target, INode replacement)
{
Replacements.Add(new ReplacePair(target, replacement));
}
}
private class ReplacePair
{
public readonly INode Target;
public readonly INode Replacement;
public ReplacePair(INode target, INode replacement)
{
Target = target;
Replacement = replacement;
}
}
private class PrimExpSet
{
public object Value;
public IEnumerable<int> Positions;
public Type ValueType { get; set; }
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
namespace Microsoft.Live.UnitTests
{
using System;
using System.IO;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
#elif WINDOWS_PHONE || DESKTOP || WEB
using Microsoft.VisualStudio.TestTools.UnitTesting;
#else
#error This platform needs to be handled.
#endif
using Microsoft.Live.Serialization;
[TestClass]
public class IndentedTextWriterTest
{
[TestMethod]
public void TestWriteString()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.Write("foo");
indentedTextWriter.Indent = 1;
indentedTextWriter.Write("bar");
Assert.AreEqual("foobar", stringWriter.ToString());
}
[TestMethod]
public void TestWriteBoolean()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.Write(true);
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(false);
Assert.AreEqual("TrueFalse", stringWriter.ToString());
}
[TestMethod]
public void TestWriteChar()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.Write('f');
indentedTextWriter.Indent = 1;
indentedTextWriter.Write('b');
Assert.AreEqual("fb", stringWriter.ToString());
}
[TestMethod]
public void TestWriteCharArray()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.Write(new char[]{'f', 'o', 'o'});
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(new char[]{'b', 'a', 'r'});
Assert.AreEqual("foobar", stringWriter.ToString());
}
[TestMethod]
public void TestWriteCharArrayIndexed()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.Write(new char[]{'f', 'o', 'o', 'b', 'a', 'r'}, 0, 3);
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(new char[]{'f', 'o', 'o', 'b', 'a', 'r'}, 3, 3);
Assert.AreEqual("foobar", stringWriter.ToString());
}
[TestMethod]
public void TestWriteDouble()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.Write(0.5d);
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(-0.5d);
Assert.AreEqual("0.5-0.5", stringWriter.ToString());
}
[TestMethod]
public void TestWriteFloat()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.Write(0.5f);
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(-0.5f);
Assert.AreEqual("0.5-0.5", stringWriter.ToString());
}
[TestMethod]
public void TestWriteInt()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.Write(10);
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(-10);
Assert.AreEqual("10-10", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLong()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.Write(10L);
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(-10L);
Assert.AreEqual("10-10", stringWriter.ToString());
}
[TestMethod]
public void TestWriteObject()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.Write((object)"foo");
indentedTextWriter.Indent = 1;
indentedTextWriter.Write((object)"bar");
Assert.AreEqual("foobar", stringWriter.ToString());
}
[TestMethod]
public void TestWriteFormatString()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.Write("foo {0}", "bar");
indentedTextWriter.Indent = 1;
indentedTextWriter.Write("foo {0}", "bar");
Assert.AreEqual("foo barfoo bar", stringWriter.ToString());
}
[TestMethod]
public void TestWriteUnsignedInt()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.Write(10u);
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(10u);
Assert.AreEqual("1010", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineNoTabs()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, false);
indentedTextWriter.WriteLineNoTabs("foo");
indentedTextWriter.Indent = 1;
indentedTextWriter.WriteLineNoTabs("bar");
Assert.AreEqual("foo\rbar\r", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineNoTabsMinimized()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.WriteLineNoTabs("foo");
indentedTextWriter.Indent = 1;
indentedTextWriter.WriteLineNoTabs("bar");
Assert.AreEqual("foobar", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineString()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, false);
indentedTextWriter.WriteLine("foo");
indentedTextWriter.Indent = 1;
indentedTextWriter.Write("bar");
Assert.AreEqual("foo\r bar", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineStringMinimized()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.WriteLine("foo");
indentedTextWriter.Indent = 1;
indentedTextWriter.Write("bar");
Assert.AreEqual("foobar", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineBoolean()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, false);
indentedTextWriter.WriteLine(true);
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(false);
Assert.AreEqual("True\r False", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineBooleanMinimized()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.WriteLine(true);
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(false);
Assert.AreEqual("TrueFalse", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineChar()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, false);
indentedTextWriter.WriteLine('f');
indentedTextWriter.Indent = 1;
indentedTextWriter.Write('b');
Assert.AreEqual("f\r b", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineCharMinimized()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.WriteLine('f');
indentedTextWriter.Indent = 1;
indentedTextWriter.Write('b');
Assert.AreEqual("fb", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineCharBuffer()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, false);
indentedTextWriter.WriteLine(new char[]{'f', 'o', 'o'});
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(new char[] {'b', 'a', 'r'});
Assert.AreEqual("foo\r bar", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineCharBufferMinimized()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.WriteLine(new char[]{'f', 'o', 'o'});
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(new char[] {'b', 'a', 'r'});
Assert.AreEqual("foobar", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineCharBufferIndexed()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, false);
indentedTextWriter.WriteLine(new char[]{'f', 'o', 'o', 'b', 'a', 'r'}, 0, 3);
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(new char[] {'f', 'o', 'o', 'b', 'a', 'r'}, 3, 3);
Assert.AreEqual("foo\r bar", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineCharBufferIndexedMinimized()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.WriteLine(new char[]{'f', 'o', 'o', 'b', 'a', 'r'}, 0, 3);
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(new char[] {'f', 'o', 'o', 'b', 'a', 'r'}, 3, 3);
Assert.AreEqual("foobar", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineDouble()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, false);
indentedTextWriter.WriteLine(0.5d);
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(-0.5d);
Assert.AreEqual("0.5\r -0.5", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineDoubleMinimized()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.WriteLine(0.5d);
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(-0.5d);
Assert.AreEqual("0.5-0.5", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineFloat()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, false);
indentedTextWriter.WriteLine(0.5f);
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(-0.5f);
Assert.AreEqual("0.5\r -0.5", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineFloatMinimized()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.WriteLine(0.5f);
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(-0.5f);
Assert.AreEqual("0.5-0.5", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineInt()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, false);
indentedTextWriter.WriteLine(10);
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(-10);
Assert.AreEqual("10\r -10", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineIntMinimized()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.WriteLine(10);
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(-10);
Assert.AreEqual("10-10", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineLong()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, false);
indentedTextWriter.WriteLine(10L);
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(-10L);
Assert.AreEqual("10\r -10", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineLongMinimized()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.WriteLine(10L);
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(-10L);
Assert.AreEqual("10-10", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineObject()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, false);
indentedTextWriter.WriteLine((object) "foo");
indentedTextWriter.Indent = 1;
indentedTextWriter.Write((object) "bar");
Assert.AreEqual("foo\r bar", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineObjectMinimized()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.WriteLine((object) "foo");
indentedTextWriter.Indent = 1;
indentedTextWriter.Write((object) "bar");
Assert.AreEqual("foobar", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineStringFormat()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, false);
indentedTextWriter.WriteLine("foo {0}", "bar");
indentedTextWriter.Indent = 1;
indentedTextWriter.Write("{0} bar", "foo");
Assert.AreEqual("foo bar\r foo bar", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineStringFormatMinimized()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.WriteLine("foo {0}", "bar");
indentedTextWriter.Indent = 1;
indentedTextWriter.Write("{0} bar", "foo");
Assert.AreEqual("foo barfoo bar", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineUnsignedInt()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, false);
indentedTextWriter.WriteLine(10u);
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(10u);
Assert.AreEqual("10\r 10", stringWriter.ToString());
}
[TestMethod]
public void TestWriteLineUnsignedIntMinimized()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.WriteLine(10u);
indentedTextWriter.Indent = 1;
indentedTextWriter.Write(10u);
Assert.AreEqual("1010", stringWriter.ToString());
}
[TestMethod]
public void TestWriteTrimmed()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, false);
indentedTextWriter.WriteTrimmed(" foo ");
Assert.AreEqual(" foo ", stringWriter.ToString());
}
[TestMethod]
public void TestWriteTrimmedMinimized()
{
var stringWriter = new StringWriter();
var indentedTextWriter = new IndentedTextWriter(stringWriter, true);
indentedTextWriter.WriteTrimmed(" foo ");
Assert.AreEqual("foo", stringWriter.ToString());
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Framework.InterfaceCommander;
using OpenSim.Region.CoreModules.World.Terrain.FileLoaders;
using OpenSim.Region.CoreModules.World.Terrain.FloodBrushes;
using OpenSim.Region.CoreModules.World.Terrain.PaintBrushes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Interfaces;
namespace OpenSim.Region.CoreModules.World.Terrain
{
public class TerrainModule : INonSharedRegionModule, ICommandableModule, ITerrainModule
{
#region StandardTerrainEffects enum
/// <summary>
/// A standard set of terrain brushes and effects recognised by viewers
/// </summary>
public enum StandardTerrainEffects : byte
{
Flatten = 0,
Raise = 1,
Lower = 2,
Smooth = 3,
Noise = 4,
Revert = 5,
// Extended brushes
Erode = 255,
Weather = 254,
Olsen = 253
}
#endregion
public const float MinParcelResolution = 4.0f; // smallest parcel is 4m x 4m = 16sqm
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly Commander m_commander = new Commander("terrain");
private readonly Dictionary<StandardTerrainEffects, ITerrainFloodEffect> m_floodeffects =
new Dictionary<StandardTerrainEffects, ITerrainFloodEffect>();
private readonly Dictionary<string, ITerrainLoader> m_loaders = new Dictionary<string, ITerrainLoader>();
private readonly Dictionary<StandardTerrainEffects, ITerrainPaintableEffect> m_painteffects =
new Dictionary<StandardTerrainEffects, ITerrainPaintableEffect>();
private ITerrainChannel m_channel;
private Dictionary<string, ITerrainEffect> m_plugineffects;
private ITerrainChannel m_revert;
private Scene m_scene;
private volatile bool m_tainted;
#region ICommandableModule Members
public ICommander CommandInterface
{
get { return m_commander; }
}
#endregion
#region INonSharedRegionModule Members
/// <summary>
/// Creates and initializes a terrain module for a region
/// </summary>
/// <param name="scene">Region initializing</param>
/// <param name="config">Config for the region</param>
public void Initialize(IConfigSource config)
{
}
public void AddRegion(Scene scene)
{
m_scene = scene;
// Install terrain module in the simulator
lock (m_scene)
{
if (m_scene.Heightmap == null)
{
m_channel = new TerrainChannel();
m_scene.Heightmap = m_channel;
m_revert = new TerrainChannel();
UpdateRevertMap();
}
else
{
m_channel = m_scene.Heightmap;
m_revert = new TerrainChannel();
UpdateRevertMap();
}
m_scene.RegisterModuleInterface<ITerrainModule>(this);
m_scene.EventManager.OnNewClient += EventManager_OnNewClient;
m_scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole;
m_scene.EventManager.OnTerrainTick += EventManager_OnTerrainTick;
InstallInterfaces();
}
InstallDefaultEffects();
LoadPlugins();
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
lock (m_scene)
{
// remove the commands
m_scene.UnregisterModuleCommander(m_commander.Name);
// remove the event-handlers
m_scene.EventManager.OnTerrainTick -= EventManager_OnTerrainTick;
m_scene.EventManager.OnPluginConsole -= EventManager_OnPluginConsole;
m_scene.EventManager.OnNewClient -= EventManager_OnNewClient;
// remove the interface
m_scene.UnregisterModuleInterface<ITerrainModule>(this);
}
}
public void Close()
{
}
public string Name
{
get { return "TerrainModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
#region ITerrainModule Members
/// <summary>
/// Loads a terrain file from disk and installs it in the scene.
/// </summary>
/// <param name="filename">Filename to terrain file. Type is determined by extension.</param>
public void LoadFromFile(string filename)
{
foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
{
if (filename.EndsWith(loader.Key))
{
lock (m_scene)
{
try
{
ITerrainChannel channel = loader.Value.LoadFile(filename);
if (channel.Width != Constants.RegionSize || channel.Height != Constants.RegionSize)
{
// TerrainChannel expects a RegionSize x RegionSize map, currently
throw new ArgumentException(String.Format("wrong size, use a file with size {0} x {1}",
Constants.RegionSize, Constants.RegionSize));
}
m_log.DebugFormat("[TERRAIN]: Loaded terrain, wd/ht: {0}/{1}", channel.Width, channel.Height);
m_scene.Heightmap = channel;
m_channel = channel;
UpdateRevertMap();
}
catch (NotImplementedException)
{
m_log.Error("[TERRAIN]: Unable to load heightmap, the " + loader.Value +
" parser does not support file loading. (May be save only)");
throw new TerrainException(String.Format("unable to load heightmap: parser {0} does not support loading", loader.Value));
}
catch (FileNotFoundException)
{
m_log.Error(
"[TERRAIN]: Unable to load heightmap, file not found. (A directory permissions error may also cause this)");
throw new TerrainException(
String.Format("unable to load heightmap: file {0} not found (or permissions do not allow access", filename));
}
catch (ArgumentException e)
{
m_log.ErrorFormat("[TERRAIN]: Unable to load heightmap: {0}", e.Message);
throw new TerrainException(
String.Format("Unable to load heightmap: {0}", e.Message));
}
}
CheckForTerrainUpdates();
m_log.Info("[TERRAIN]: File (" + filename + ") loaded successfully");
return;
}
}
m_log.Error("[TERRAIN]: Unable to load heightmap, no file loader available for that format.");
throw new TerrainException(String.Format("unable to load heightmap from file {0}: no loader available for that format", filename));
}
/// <summary>
/// Saves the current heightmap to a specified file.
/// </summary>
/// <param name="filename">The destination filename</param>
public void SaveToFile(string filename)
{
try
{
foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
{
if (filename.EndsWith(loader.Key))
{
loader.Value.SaveFile(filename, m_channel);
return;
}
}
}
catch (NotImplementedException)
{
m_log.Error("Unable to save to " + filename + ", saving of this file format has not been implemented.");
throw new TerrainException(String.Format("Unable to save heightmap: saving of this file format not implemented"));
}
catch (IOException ioe)
{
m_log.Error(String.Format("[TERRAIN]: Unable to save to {0}, {1}", filename, ioe.Message));
throw new TerrainException(String.Format("Unable to save heightmap: {0}", ioe.Message));
}
}
/// <summary>
/// Loads a terrain file from a stream and installs it in the scene.
/// </summary>
/// <param name="filename">Filename to terrain file. Type is determined by extension.</param>
/// <param name="stream"></param>
public void LoadFromStream(string filename, Stream stream)
{
foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
{
if (@filename.EndsWith(loader.Key))
{
lock (m_scene)
{
try
{
ITerrainChannel channel = loader.Value.LoadStream(stream);
m_scene.Heightmap = channel;
m_channel = channel;
UpdateRevertMap();
}
catch (NotImplementedException)
{
m_log.Error("[TERRAIN]: Unable to load heightmap, the " + loader.Value +
" parser does not support file loading. (May be save only)");
throw new TerrainException(String.Format("unable to load heightmap: parser {0} does not support loading", loader.Value));
}
}
CheckForTerrainUpdates();
m_log.Info("[TERRAIN]: File (" + filename + ") loaded successfully");
return;
}
}
m_log.Error("[TERRAIN]: Unable to load heightmap, no file loader available for that format.");
throw new TerrainException(String.Format("unable to load heightmap from file {0}: no loader available for that format", filename));
}
/// <summary>
/// Modify Land
/// </summary>
/// <param name="pos">Land-position (X,Y,0)</param>
/// <param name="size">The size of the brush (0=small, 1=medium, 2=large)</param>
/// <param name="action">0=LAND_LEVEL, 1=LAND_RAISE, 2=LAND_LOWER, 3=LAND_SMOOTH, 4=LAND_NOISE, 5=LAND_REVERT</param>
/// <param name="agentId">UUID of script-owner</param>
public void ModifyTerrain(UUID user, Vector3 pos, byte size, byte action, UUID agentId)
{
float duration = 0.25f;
if (action == 0)
duration = 4.0f;
client_OnModifyTerrain(user, (float)pos.Z, duration, size, action, pos.Y, pos.X, pos.Y, pos.X, -1, agentId, size);
}
/// <summary>
/// Saves the current heightmap to a specified stream.
/// </summary>
/// <param name="filename">The destination filename. Used here only to identify the image type</param>
/// <param name="stream"></param>
public void SaveToStream(string filename, Stream stream)
{
try
{
foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
{
if (filename.EndsWith(loader.Key))
{
loader.Value.SaveStream(stream, m_channel);
return;
}
}
}
catch (NotImplementedException)
{
m_log.Error("Unable to save to " + filename + ", saving of this file format has not been implemented.");
throw new TerrainException(String.Format("Unable to save heightmap: saving of this file format not implemented"));
}
}
public void TaintTerrain ()
{
CheckForTerrainUpdates();
}
#region Plugin Loading Methods
private void LoadPlugins()
{
m_plugineffects = new Dictionary<string, ITerrainEffect>();
// Load the files in the Terrain/ dir
string[] files = Directory.GetFiles("Terrain");
foreach (string file in files)
{
m_log.Info("Loading effects in " + file);
try
{
Assembly library = Assembly.LoadFrom(file);
foreach (Type pluginType in library.GetTypes())
{
try
{
if (pluginType.IsAbstract || pluginType.IsNotPublic)
continue;
string typeName = pluginType.Name;
if (typeof(ITerrainEffect).IsAssignableFrom(pluginType))
{
ITerrainEffect terEffect = (ITerrainEffect) Activator.CreateInstance(library.GetType(pluginType.ToString()));
InstallPlugin(typeName, terEffect);
}
else if (typeof(ITerrainLoader).IsAssignableFrom(pluginType))
{
ITerrainLoader terLoader = (ITerrainLoader) Activator.CreateInstance(library.GetType(pluginType.ToString()));
m_loaders[terLoader.FileExtension] = terLoader;
m_log.Info("L ... " + typeName);
}
}
catch (AmbiguousMatchException)
{
}
}
}
catch (BadImageFormatException)
{
}
}
}
public void InstallPlugin(string pluginName, ITerrainEffect effect)
{
lock (m_plugineffects)
{
if (!m_plugineffects.ContainsKey(pluginName))
{
m_plugineffects.Add(pluginName, effect);
m_log.Info("E ... " + pluginName);
}
else
{
m_plugineffects[pluginName] = effect;
m_log.Warn("E ... " + pluginName + " (Replaced)");
}
}
}
#endregion
#endregion
/// <summary>
/// Installs into terrain module the standard suite of brushes
/// </summary>
private void InstallDefaultEffects()
{
// Draggable Paint Brush Effects
m_painteffects[StandardTerrainEffects.Raise] = new RaiseSphere();
m_painteffects[StandardTerrainEffects.Lower] = new LowerSphere();
m_painteffects[StandardTerrainEffects.Smooth] = new SmoothSphere();
m_painteffects[StandardTerrainEffects.Noise] = new NoiseSphere();
m_painteffects[StandardTerrainEffects.Flatten] = new FlattenSphere();
m_painteffects[StandardTerrainEffects.Revert] = new RevertSphere(m_revert);
m_painteffects[StandardTerrainEffects.Erode] = new ErodeSphere();
m_painteffects[StandardTerrainEffects.Weather] = new WeatherSphere();
m_painteffects[StandardTerrainEffects.Olsen] = new OlsenSphere();
// Area of effect selection effects
m_floodeffects[StandardTerrainEffects.Raise] = new RaiseArea();
m_floodeffects[StandardTerrainEffects.Lower] = new LowerArea();
m_floodeffects[StandardTerrainEffects.Smooth] = new SmoothArea();
m_floodeffects[StandardTerrainEffects.Noise] = new NoiseArea();
m_floodeffects[StandardTerrainEffects.Flatten] = new FlattenArea();
m_floodeffects[StandardTerrainEffects.Revert] = new RevertArea(m_revert);
// Filesystem load/save loaders
m_loaders[".r32"] = new RAW32();
m_loaders[".f32"] = m_loaders[".r32"];
m_loaders[".ter"] = new Terragen();
m_loaders[".raw"] = new LLRAW();
m_loaders[".jpg"] = new JPEG();
m_loaders[".jpeg"] = m_loaders[".jpg"];
m_loaders[".bmp"] = new BMP();
m_loaders[".png"] = new PNG();
m_loaders[".gif"] = new GIF();
m_loaders[".tif"] = new TIFF();
m_loaders[".tiff"] = m_loaders[".tif"];
}
/// <summary>
/// Saves the current state of the region into the revert map buffer.
/// </summary>
public void UpdateRevertMap()
{
int x;
for (x = 0; x < m_channel.Width; x++)
{
int y;
for (y = 0; y < m_channel.Height; y++)
{
m_revert[x, y] = m_channel[x, y];
}
}
}
/// <summary>
/// Loads a tile from a larger terrain file and installs it into the region.
/// </summary>
/// <param name="filename">The terrain file to load</param>
/// <param name="fileWidth">The width of the file in units</param>
/// <param name="fileHeight">The height of the file in units</param>
/// <param name="fileStartX">Where to begin our slice</param>
/// <param name="fileStartY">Where to begin our slice</param>
public void LoadFromFile(string filename, int fileWidth, int fileHeight, int fileStartX, int fileStartY)
{
int offsetX = (int) m_scene.RegionInfo.RegionLocX - fileStartX;
int offsetY = (int) m_scene.RegionInfo.RegionLocY - fileStartY;
if (offsetX >= 0 && offsetX < fileWidth && offsetY >= 0 && offsetY < fileHeight)
{
// this region is included in the tile request
foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
{
if (filename.EndsWith(loader.Key))
{
lock (m_scene)
{
ITerrainChannel channel = loader.Value.LoadFile(filename, offsetX, offsetY,
fileWidth, fileHeight,
(int) Constants.RegionSize,
(int) Constants.RegionSize);
m_scene.Heightmap = channel;
m_channel = channel;
UpdateRevertMap();
}
return;
}
}
}
}
/// <summary>
/// Performs updates to the region periodically, synchronising physics and other heightmap aware sections
/// </summary>
private void EventManager_OnTerrainTick()
{
if (m_tainted)
{
m_tainted = false;
m_scene.PhysicsScene.SetTerrain(m_channel.GetFloatsSerialized(), m_channel.IncrementRevisionNumber());
m_scene.SaveTerrain();
// Clients who look at the map will never see changes after they looked at the map, so i've commented this out.
//m_scene.CreateTerrainTexture(true);
}
}
/// <summary>
/// Processes commandline input. Do not call directly.
/// </summary>
/// <param name="args">Commandline arguments</param>
private void EventManager_OnPluginConsole(string[] args)
{
if (args[0] == "terrain")
{
if (args.Length == 1)
{
m_commander.ProcessConsoleCommand("help", new string[0]);
return;
}
string[] tmpArgs = new string[args.Length - 2];
int i;
for (i = 2; i < args.Length; i++)
tmpArgs[i - 2] = args[i];
m_commander.ProcessConsoleCommand(args[1], tmpArgs);
}
}
/// <summary>
/// Installs terrain brush hook to IClientAPI
/// </summary>
/// <param name="client"></param>
private void EventManager_OnNewClient(IClientAPI client)
{
client.OnModifyTerrain += client_OnModifyTerrain;
client.OnBakeTerrain += client_OnBakeTerrain;
}
/// <summary>
/// Checks to see if the terrain has been modified since last check
/// but won't attempt to limit those changes to the limits specified in the estate settings
/// currently invoked by the command line operations in the region server only
/// </summary>
private void CheckForTerrainUpdates()
{
CheckForTerrainUpdates(false);
}
/// <summary>
/// Checks to see if the terrain has been modified since last check.
/// If it has been modified, every all the terrain patches are sent to the client.
/// If the call is asked to respect the estate settings for terrain_raise_limit and
/// terrain_lower_limit, it will clamp terrain updates between these values
/// currently invoked by client_OnModifyTerrain only and not the Commander interfaces
/// <param name="respectEstateSettings">should height map deltas be limited to the estate settings limits</param>
/// </summary>
private void CheckForTerrainUpdates(bool respectEstateSettings)
{
bool shouldTaint = false;
float[] serialized = m_channel.GetFloatsSerialized();
int x;
for (x = 0; x < m_channel.Width; x += Constants.TerrainPatchSize)
{
int y;
for (y = 0; y < m_channel.Height; y += Constants.TerrainPatchSize)
{
if (m_channel.Tainted(x, y))
{
// if we should respect the estate settings then
// fixup and height deltas that don't respect them
if (respectEstateSettings && LimitChannelChanges(x, y))
{
// this has been vetoed, so update
// what we are going to send to the client
serialized = m_channel.GetFloatsSerialized();
}
UpdateClientsSceneView(serialized, x, y);
shouldTaint = true;
}
}
}
if (shouldTaint)
{
m_tainted = true;
}
}
/// <summary>
/// Checks to see height deltas in the tainted terrain patch at xStart ,yStart
/// are all within the current estate limits
/// <returns>true if changes were limited, false otherwise</returns>
/// </summary>
private bool LimitChannelChanges(int xStart, int yStart)
{
bool changesLimited = false;
double minDelta = m_scene.RegionInfo.RegionSettings.TerrainLowerLimit;
double maxDelta = m_scene.RegionInfo.RegionSettings.TerrainRaiseLimit;
// loop through the height map for this patch and compare it against
// the revert map
for (int x = xStart; x < xStart + Constants.TerrainPatchSize; x++)
{
for (int y = yStart; y < yStart + Constants.TerrainPatchSize; y++)
{
double requestedHeight = m_channel[x, y];
double bakedHeight = m_revert[x, y];
double requestedDelta = requestedHeight - bakedHeight;
if (requestedDelta > maxDelta)
{
m_channel[x, y] = bakedHeight + maxDelta;
changesLimited = true;
}
else if (requestedDelta < minDelta)
{
m_channel[x, y] = bakedHeight + minDelta; //as lower is a -ve delta
changesLimited = true;
}
}
}
return changesLimited;
}
private void UpdateClientsSceneView(float[] serialized, int regionx, int regiony)
{
m_scene.ForEachScenePresence(
delegate(ScenePresence presence)
{
if (presence.SceneView != null)
presence.SceneView.TerrainPatchUpdated(serialized,
regionx / Constants.TerrainPatchSize,
regiony / Constants.TerrainPatchSize);
});
}
public bool SetTerrain(UUID userID, int x1, int y1, int x2, int y2, float height)
{
bool rc = false;
// Sanity check.
if ((height < 0.0f) || (height > 1024.0f))
return false;
int temp;
if (x1 > x2) { temp = x1; x1 = x2; x2 = temp; }
if (y1 > y2) { temp = y1; y1 = y2; y2 = temp; }
if ((x1 < 0) || (y1 < 0) || (x2 >= Constants.RegionSize) || (y2 >= Constants.RegionSize))
return false;
bool god = m_scene.Permissions.IsGod(userID);
for (int x = x1; x <= x2; x++)
{
for (int y = y1; y <= y2; y++)
{
if (god || m_scene.Permissions.CanTerraformLand(userID, new Vector3(x, y, 0)))
{
m_channel[x, y] = height;
rc = true;
}
}
}
if (rc)
CheckForTerrainUpdates(!god); //revert changes outside estate limits
return rc;
}
private void client_OnModifyTerrain(UUID user, float height, float seconds, byte size, byte action,
float north, float west, float south, float east, int parcelId, UUID agentId,
float BrushSize)
{
bool god = m_scene.Permissions.IsGod(user);
bool allowed = false;
if (north == south && east == west)
{
if (m_painteffects.ContainsKey((StandardTerrainEffects) action))
{
m_painteffects[(StandardTerrainEffects)action].PaintEffect(
m_channel, user, west, south, height, size, seconds, BrushSize, m_scene);
//revert changes outside estate limits
CheckForTerrainUpdates(!god);
}
else
{
m_log.Debug("Unknown terrain brush type " + action);
}
}
else
{
if (m_floodeffects.ContainsKey((StandardTerrainEffects) action))
{
bool[,] fillArea = new bool[m_channel.Width,m_channel.Height];
fillArea.Initialize();
if (parcelId != -1)
{
// If a parcel ID is specified, the viewer sends the bottom left of each 4sqm block,
// i.e. bottom left, not top right for north and east.
// We need to add 4m to each of these to find the top and right boundaries.
north += MinParcelResolution;
east += MinParcelResolution;
// If the parcelId == -1, it means the viewer has already done this for us.
}
int x;
for (x = 0; x < m_channel.Width; x++)
{
int y;
for (y = 0; y < m_channel.Height; y++)
{
if ((x <= east) && x >= west)
{
if ((y <= north) && y >= south)
{
if (m_scene.Permissions.CanTerraformLand(agentId, new Vector3(x,y,0)))
{
fillArea[x, y] = true;
allowed = true;
}
}
}
}
}
if (allowed)
{
m_floodeffects[(StandardTerrainEffects) action].FloodEffect(
m_channel, fillArea, size);
CheckForTerrainUpdates(!god); //revert changes outside estate limits
}
}
else
{
m_log.Debug("Unknown terrain flood type " + action);
}
}
}
private void client_OnBakeTerrain(IClientAPI remoteClient)
{
// Not a good permissions check (see client_OnModifyTerrain above), need to check the entire area.
// for now check a point in the centre of the region
if (m_scene.Permissions.CanIssueEstateCommand(remoteClient.AgentId, true))
{
InterfaceBakeTerrain(null); //bake terrain does not use the passed in parameter
}
}
#region Console Commands
private void InterfaceLoadFile(Object[] args)
{
LoadFromFile((string) args[0]);
CheckForTerrainUpdates();
}
private void InterfaceLoadTileFile(Object[] args)
{
LoadFromFile((string) args[0],
(int) args[1],
(int) args[2],
(int) args[3],
(int) args[4]);
CheckForTerrainUpdates();
}
private void InterfaceSaveFile(Object[] args)
{
SaveToFile((string) args[0]);
}
private void InterfaceBakeTerrain(Object[] args)
{
UpdateRevertMap();
}
private void InterfaceRevertTerrain(Object[] args)
{
int x, y;
for (x = 0; x < m_channel.Width; x++)
for (y = 0; y < m_channel.Height; y++)
m_channel[x, y] = m_revert[x, y];
CheckForTerrainUpdates();
}
private void InterfaceFlipTerrain(Object[] args)
{
String direction = (String)args[0];
if (direction.ToLower().StartsWith("y"))
{
for (int x = 0; x < Constants.RegionSize; x++)
{
for (int y = 0; y < Constants.RegionSize / 2; y++)
{
double height = m_channel[x, y];
double flippedHeight = m_channel[x, (int)Constants.RegionSize - 1 - y];
m_channel[x, y] = flippedHeight;
m_channel[x, (int)Constants.RegionSize - 1 - y] = height;
}
}
}
else if (direction.ToLower().StartsWith("x"))
{
for (int y = 0; y < Constants.RegionSize; y++)
{
for (int x = 0; x < Constants.RegionSize / 2; x++)
{
double height = m_channel[x, y];
double flippedHeight = m_channel[(int)Constants.RegionSize - 1 - x, y];
m_channel[x, y] = flippedHeight;
m_channel[(int)Constants.RegionSize - 1 - x, y] = height;
}
}
}
else
{
m_log.Error("Unrecognised direction - need x or y");
}
CheckForTerrainUpdates();
}
private void InterfaceRescaleTerrain(Object[] args)
{
double desiredMin = (double)args[0];
double desiredMax = (double)args[1];
// determine desired scaling factor
double desiredRange = desiredMax - desiredMin;
//m_log.InfoFormat("Desired {0}, {1} = {2}", new Object[] { desiredMin, desiredMax, desiredRange });
if (desiredRange == 0d)
{
// delta is zero so flatten at requested height
InterfaceFillTerrain(new Object[] { args[1] });
}
else
{
//work out current heightmap range
double currMin = double.MaxValue;
double currMax = double.MinValue;
int width = m_channel.Width;
int height = m_channel.Height;
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
double currHeight = m_channel[x, y];
if (currHeight < currMin)
{
currMin = currHeight;
}
else if (currHeight > currMax)
{
currMax = currHeight;
}
}
}
double currRange = currMax - currMin;
double scale = desiredRange / currRange;
//m_log.InfoFormat("Current {0}, {1} = {2}", new Object[] { currMin, currMax, currRange });
//m_log.InfoFormat("Scale = {0}", scale);
// scale the heightmap accordingly
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
double currHeight = m_channel[x, y] - currMin;
m_channel[x, y] = desiredMin + (currHeight * scale);
}
}
CheckForTerrainUpdates();
}
}
private void InterfaceElevateTerrain(Object[] args)
{
int x, y;
for (x = 0; x < m_channel.Width; x++)
for (y = 0; y < m_channel.Height; y++)
m_channel[x, y] += (double) args[0];
CheckForTerrainUpdates();
}
private void InterfaceMultiplyTerrain(Object[] args)
{
int x, y;
for (x = 0; x < m_channel.Width; x++)
for (y = 0; y < m_channel.Height; y++)
m_channel[x, y] *= (double) args[0];
CheckForTerrainUpdates();
}
private void InterfaceLowerTerrain(Object[] args)
{
int x, y;
for (x = 0; x < m_channel.Width; x++)
for (y = 0; y < m_channel.Height; y++)
m_channel[x, y] -= (double) args[0];
CheckForTerrainUpdates();
}
private void InterfaceFillTerrain(Object[] args)
{
int x, y;
for (x = 0; x < m_channel.Width; x++)
for (y = 0; y < m_channel.Height; y++)
m_channel[x, y] = (double) args[0];
CheckForTerrainUpdates();
}
private void InterfaceShowDebugStats(Object[] args)
{
double max = Double.MinValue;
double min = double.MaxValue;
double sum = 0;
int x;
for (x = 0; x < m_channel.Width; x++)
{
int y;
for (y = 0; y < m_channel.Height; y++)
{
sum += m_channel[x, y];
if (max < m_channel[x, y])
max = m_channel[x, y];
if (min > m_channel[x, y])
min = m_channel[x, y];
}
}
double avg = sum / (m_channel.Height * m_channel.Width);
m_log.Info("Channel " + m_channel.Width + "x" + m_channel.Height);
m_log.Info("max/min/avg/sum: " + max + "/" + min + "/" + avg + "/" + sum);
}
private void InterfaceEnableExperimentalBrushes(Object[] args)
{
if ((bool) args[0])
{
m_painteffects[StandardTerrainEffects.Revert] = new WeatherSphere();
m_painteffects[StandardTerrainEffects.Flatten] = new OlsenSphere();
m_painteffects[StandardTerrainEffects.Smooth] = new ErodeSphere();
}
else
{
InstallDefaultEffects();
}
}
private void InterfaceRunPluginEffect(Object[] args)
{
if ((string) args[0] == "list")
{
m_log.Info("List of loaded plugins");
foreach (KeyValuePair<string, ITerrainEffect> kvp in m_plugineffects)
{
m_log.Info(kvp.Key);
}
return;
}
if ((string) args[0] == "reload")
{
LoadPlugins();
return;
}
if (m_plugineffects.ContainsKey((string) args[0]))
{
m_plugineffects[(string) args[0]].RunEffect(m_channel);
CheckForTerrainUpdates();
}
else
{
m_log.Warn("No such plugin effect loaded.");
}
}
private void InstallInterfaces()
{
// Load / Save
string supportedFileExtensions = String.Empty;
foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
supportedFileExtensions += " " + loader.Key + " (" + loader.Value + ")";
Command loadFromFileCommand =
new Command("load", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLoadFile, "Loads a terrain from a specified file.");
loadFromFileCommand.AddArgument("filename",
"The file you wish to load from, the file extension determines the loader to be used. Supported extensions include: " +
supportedFileExtensions, "String");
Command saveToFileCommand =
new Command("save", CommandIntentions.COMMAND_NON_HAZARDOUS, InterfaceSaveFile, "Saves the current heightmap to a specified file.");
saveToFileCommand.AddArgument("filename",
"The destination filename for your heightmap, the file extension determines the format to save in. Supported extensions include: " +
supportedFileExtensions, "String");
Command loadFromTileCommand =
new Command("load-tile", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLoadTileFile, "Loads a terrain from a section of a larger file.");
loadFromTileCommand.AddArgument("filename",
"The file you wish to load from, the file extension determines the loader to be used. Supported extensions include: " +
supportedFileExtensions, "String");
loadFromTileCommand.AddArgument("file width", "The width of the file in tiles", "Integer");
loadFromTileCommand.AddArgument("file height", "The height of the file in tiles", "Integer");
loadFromTileCommand.AddArgument("minimum X tile", "The X region coordinate of the first section on the file",
"Integer");
loadFromTileCommand.AddArgument("minimum Y tile", "The Y region coordinate of the first section on the file",
"Integer");
// Terrain adjustments
Command fillRegionCommand =
new Command("fill", CommandIntentions.COMMAND_HAZARDOUS, InterfaceFillTerrain, "Fills the current heightmap with a specified value.");
fillRegionCommand.AddArgument("value", "The numeric value of the height you wish to set your region to.",
"Double");
Command elevateCommand =
new Command("elevate", CommandIntentions.COMMAND_HAZARDOUS, InterfaceElevateTerrain, "Raises the current heightmap by the specified amount.");
elevateCommand.AddArgument("amount", "The amount of height to add to the terrain in meters.", "Double");
Command lowerCommand =
new Command("lower", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLowerTerrain, "Lowers the current heightmap by the specified amount.");
lowerCommand.AddArgument("amount", "The amount of height to remove from the terrain in meters.", "Double");
Command multiplyCommand =
new Command("multiply", CommandIntentions.COMMAND_HAZARDOUS, InterfaceMultiplyTerrain, "Multiplies the heightmap by the value specified.");
multiplyCommand.AddArgument("value", "The value to multiply the heightmap by.", "Double");
Command bakeRegionCommand =
new Command("bake", CommandIntentions.COMMAND_HAZARDOUS, InterfaceBakeTerrain, "Saves the current terrain into the regions revert map.");
Command revertRegionCommand =
new Command("revert", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRevertTerrain, "Loads the revert map terrain into the regions heightmap.");
Command flipCommand =
new Command("flip", CommandIntentions.COMMAND_HAZARDOUS, InterfaceFlipTerrain, "Flips the current terrain about the X or Y axis");
flipCommand.AddArgument("direction", "[x|y] the direction to flip the terrain in", "String");
Command rescaleCommand =
new Command("rescale", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRescaleTerrain, "Rescales the current terrain to fit between the given min and max heights");
rescaleCommand.AddArgument("min", "min terrain height after rescaling", "Double");
rescaleCommand.AddArgument("max", "max terrain height after rescaling", "Double");
// Debug
Command showDebugStatsCommand =
new Command("stats", CommandIntentions.COMMAND_STATISTICAL, InterfaceShowDebugStats,
"Shows some information about the regions heightmap for debugging purposes.");
Command experimentalBrushesCommand =
new Command("newbrushes", CommandIntentions.COMMAND_HAZARDOUS, InterfaceEnableExperimentalBrushes,
"Enables experimental brushes which replace the standard terrain brushes. WARNING: This is a debug setting and may be removed at any time.");
experimentalBrushesCommand.AddArgument("Enabled?", "true / false - Enable new brushes", "Boolean");
//Plugins
Command pluginRunCommand =
new Command("effect", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRunPluginEffect, "Runs a specified plugin effect");
pluginRunCommand.AddArgument("name", "The plugin effect you wish to run, or 'list' to see all plugins", "String");
m_commander.RegisterCommand("load", loadFromFileCommand);
m_commander.RegisterCommand("load-tile", loadFromTileCommand);
m_commander.RegisterCommand("save", saveToFileCommand);
m_commander.RegisterCommand("fill", fillRegionCommand);
m_commander.RegisterCommand("elevate", elevateCommand);
m_commander.RegisterCommand("lower", lowerCommand);
m_commander.RegisterCommand("multiply", multiplyCommand);
m_commander.RegisterCommand("bake", bakeRegionCommand);
m_commander.RegisterCommand("revert", revertRegionCommand);
m_commander.RegisterCommand("newbrushes", experimentalBrushesCommand);
m_commander.RegisterCommand("stats", showDebugStatsCommand);
m_commander.RegisterCommand("effect", pluginRunCommand);
m_commander.RegisterCommand("flip", flipCommand);
m_commander.RegisterCommand("rescale", rescaleCommand);
// Add this to our scene so scripts can call these functions
m_scene.RegisterModuleCommander(m_commander);
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Services.Connectors.SimianGrid
{
/// <summary>
/// Connects region registration and neighbor lookups to the SimianGrid
/// backend
/// </summary>
public class SimianGridServiceConnector : IGridService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string m_ServerURI = String.Empty;
// private bool m_Enabled = false;
public SimianGridServiceConnector() { }
public SimianGridServiceConnector(string serverURI)
{
m_ServerURI = serverURI.TrimEnd('/');
}
public SimianGridServiceConnector(IConfigSource source)
{
CommonInit(source);
}
public void Initialise(IConfigSource source)
{
CommonInit(source);
}
private void CommonInit(IConfigSource source)
{
IConfig gridConfig = source.Configs["GridService"];
if (gridConfig == null)
{
m_log.Error("[SIMIAN GRID CONNECTOR]: GridService missing from OpenSim.ini");
throw new Exception("Grid connector init error");
}
string serviceUrl = gridConfig.GetString("GridServerURI");
if (String.IsNullOrEmpty(serviceUrl))
{
m_log.Error("[SIMIAN GRID CONNECTOR]: No Server URI named in section GridService");
throw new Exception("Grid connector init error");
}
if (!serviceUrl.EndsWith("/") && !serviceUrl.EndsWith("="))
serviceUrl = serviceUrl + '/';
m_ServerURI = serviceUrl;
// m_Enabled = true;
}
#region IGridService
public string RegisterRegion(UUID scopeID, GridRegion regionInfo)
{
Vector3d minPosition = new Vector3d(regionInfo.RegionLocX, regionInfo.RegionLocY, 0.0);
Vector3d maxPosition = minPosition + new Vector3d(regionInfo.RegionSizeX, regionInfo.RegionSizeY, Constants.RegionHeight);
OSDMap extraData = new OSDMap
{
{ "ServerURI", OSD.FromString(regionInfo.ServerURI) },
{ "InternalAddress", OSD.FromString(regionInfo.InternalEndPoint.Address.ToString()) },
{ "InternalPort", OSD.FromInteger(regionInfo.InternalEndPoint.Port) },
{ "ExternalAddress", OSD.FromString(regionInfo.ExternalEndPoint.Address.ToString()) },
{ "ExternalPort", OSD.FromInteger(regionInfo.ExternalEndPoint.Port) },
{ "MapTexture", OSD.FromUUID(regionInfo.TerrainImage) },
{ "Access", OSD.FromInteger(regionInfo.Access) },
{ "RegionSecret", OSD.FromString(regionInfo.RegionSecret) },
{ "EstateOwner", OSD.FromUUID(regionInfo.EstateOwner) },
{ "Token", OSD.FromString(regionInfo.Token) }
};
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddScene" },
{ "SceneID", regionInfo.RegionID.ToString() },
{ "Name", regionInfo.RegionName },
{ "MinPosition", minPosition.ToString() },
{ "MaxPosition", maxPosition.ToString() },
{ "Address", regionInfo.ServerURI },
{ "Enabled", "1" },
{ "ExtraData", OSDParser.SerializeJsonString(extraData) }
};
OSDMap response = SimianGrid.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
return String.Empty;
else
return "Region registration for " + regionInfo.RegionName + " failed: " + response["Message"].AsString();
}
public bool DeregisterRegion(UUID regionID)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddScene" },
{ "SceneID", regionID.ToString() },
{ "Enabled", "0" }
};
OSDMap response = SimianGrid.PostToService(m_ServerURI, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN GRID CONNECTOR]: Region deregistration for " + regionID + " failed: " + response["Message"].AsString());
return success;
}
public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{
GridRegion region = GetRegionByUUID(scopeID, regionID);
int NEIGHBOR_RADIUS = Math.Max(region.RegionSizeX, region.RegionSizeY) / 2;
if (region != null)
{
List<GridRegion> regions = GetRegionRange(scopeID,
region.RegionLocX - NEIGHBOR_RADIUS, region.RegionLocX + region.RegionSizeX + NEIGHBOR_RADIUS,
region.RegionLocY - NEIGHBOR_RADIUS, region.RegionLocY + region.RegionSizeY + NEIGHBOR_RADIUS);
for (int i = 0; i < regions.Count; i++)
{
if (regions[i].RegionID == regionID)
{
regions.RemoveAt(i);
break;
}
}
// m_log.Debug("[SIMIAN GRID CONNECTOR]: Found " + regions.Count + " neighbors for region " + regionID);
return regions;
}
return new List<GridRegion>(0);
}
public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScene" },
{ "SceneID", regionID.ToString() }
};
// m_log.DebugFormat("[SIMIAN GRID CONNECTOR] request region with uuid {0}",regionID.ToString());
OSDMap response = SimianGrid.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
{
// m_log.DebugFormat("[SIMIAN GRID CONNECTOR] uuid request successful {0}",response["Name"].AsString());
return ResponseToGridRegion(response);
}
else
{
m_log.Warn("[SIMIAN GRID CONNECTOR]: Grid service did not find a match for region " + regionID);
return null;
}
}
public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{
// Go one meter in from the requested x/y coords to avoid requesting a position
// that falls on the border of two sims
Vector3d position = new Vector3d(x + 1, y + 1, 0.0);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScene" },
{ "Position", position.ToString() },
{ "Enabled", "1" }
};
// m_log.DebugFormat("[SIMIAN GRID CONNECTOR] request grid at {0}",position.ToString());
OSDMap response = SimianGrid.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
{
// m_log.DebugFormat("[SIMIAN GRID CONNECTOR] position request successful {0}",response["Name"].AsString());
return ResponseToGridRegion(response);
}
else
{
// m_log.InfoFormat("[SIMIAN GRID CONNECTOR]: Grid service did not find a match for region at {0},{1}",
// Util.WorldToRegionLoc(x), Util.WorldToRegionLoc(y));
return null;
}
}
public GridRegion GetRegionByName(UUID scopeID, string regionName)
{
List<GridRegion> regions = GetRegionsByName(scopeID, regionName, 1);
m_log.Debug("[SIMIAN GRID CONNECTOR]: Got " + regions.Count + " matches for region name " + regionName);
if (regions.Count > 0)
return regions[0];
return null;
}
public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
{
List<GridRegion> foundRegions = new List<GridRegion>();
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScenes" },
{ "NameQuery", name },
{ "Enabled", "1" }
};
if (maxNumber > 0)
requestArgs["MaxNumber"] = maxNumber.ToString();
// m_log.DebugFormat("[SIMIAN GRID CONNECTOR] request regions with name {0}",name);
OSDMap response = SimianGrid.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
{
// m_log.DebugFormat("[SIMIAN GRID CONNECTOR] found regions with name {0}",name);
OSDArray array = response["Scenes"] as OSDArray;
if (array != null)
{
for (int i = 0; i < array.Count; i++)
{
GridRegion region = ResponseToGridRegion(array[i] as OSDMap);
if (region != null)
foundRegions.Add(region);
}
}
}
return foundRegions;
}
public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
{
List<GridRegion> foundRegions = new List<GridRegion>();
Vector3d minPosition = new Vector3d(xmin, ymin, 0.0);
Vector3d maxPosition = new Vector3d(xmax, ymax, Constants.RegionHeight);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScenes" },
{ "MinPosition", minPosition.ToString() },
{ "MaxPosition", maxPosition.ToString() },
{ "Enabled", "1" }
};
//m_log.DebugFormat("[SIMIAN GRID CONNECTOR] request regions by range {0} to {1}",minPosition.ToString(),maxPosition.ToString());
OSDMap response = SimianGrid.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
{
OSDArray array = response["Scenes"] as OSDArray;
if (array != null)
{
for (int i = 0; i < array.Count; i++)
{
GridRegion region = ResponseToGridRegion(array[i] as OSDMap);
if (region != null)
foundRegions.Add(region);
}
}
}
return foundRegions;
}
public List<GridRegion> GetDefaultRegions(UUID scopeID)
{
// TODO: Allow specifying the default grid location
const int DEFAULT_X = 1000 * 256;
const int DEFAULT_Y = 1000 * 256;
GridRegion defRegion = GetNearestRegion(new Vector3d(DEFAULT_X, DEFAULT_Y, 0.0), true);
if (defRegion != null)
return new List<GridRegion>(1) { defRegion };
else
return new List<GridRegion>(0);
}
public List<GridRegion> GetDefaultHypergridRegions(UUID scopeID)
{
// TODO: Allow specifying the default grid location
return GetDefaultRegions(scopeID);
}
public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
{
GridRegion defRegion = GetNearestRegion(new Vector3d(x, y, 0.0), true);
if (defRegion != null)
return new List<GridRegion>(1) { defRegion };
else
return new List<GridRegion>(0);
}
public List<GridRegion> GetHyperlinks(UUID scopeID)
{
List<GridRegion> foundRegions = new List<GridRegion>();
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScenes" },
{ "HyperGrid", "true" },
{ "Enabled", "1" }
};
OSDMap response = SimianGrid.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
{
// m_log.DebugFormat("[SIMIAN GRID CONNECTOR] found regions with name {0}",name);
OSDArray array = response["Scenes"] as OSDArray;
if (array != null)
{
for (int i = 0; i < array.Count; i++)
{
GridRegion region = ResponseToGridRegion(array[i] as OSDMap);
if (region != null)
foundRegions.Add(region);
}
}
}
return foundRegions;
}
public int GetRegionFlags(UUID scopeID, UUID regionID)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScene" },
{ "SceneID", regionID.ToString() }
};
m_log.DebugFormat("[SIMIAN GRID CONNECTOR] request region flags for {0}",regionID.ToString());
OSDMap response = SimianGrid.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
{
OSDMap extraData = response["ExtraData"] as OSDMap;
int enabled = response["Enabled"].AsBoolean() ? (int)OpenSim.Framework.RegionFlags.RegionOnline : 0;
int hypergrid = extraData["HyperGrid"].AsBoolean() ? (int)OpenSim.Framework.RegionFlags.Hyperlink : 0;
int flags = enabled | hypergrid;
m_log.DebugFormat("[SGGC] enabled - {0} hg - {1} flags - {2}", enabled, hypergrid, flags);
return flags;
}
else
{
m_log.Warn("[SIMIAN GRID CONNECTOR]: Grid service did not find a match for region " + regionID + " during region flags check");
return -1;
}
}
#endregion IGridService
private GridRegion GetNearestRegion(Vector3d position, bool onlyEnabled)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScene" },
{ "Position", position.ToString() },
{ "FindClosest", "1" }
};
if (onlyEnabled)
requestArgs["Enabled"] = "1";
OSDMap response = SimianGrid.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
{
return ResponseToGridRegion(response);
}
else
{
m_log.Warn("[SIMIAN GRID CONNECTOR]: Grid service did not find a match for region at " + position);
return null;
}
}
private GridRegion ResponseToGridRegion(OSDMap response)
{
if (response == null)
return null;
OSDMap extraData = response["ExtraData"] as OSDMap;
if (extraData == null)
return null;
GridRegion region = new GridRegion();
region.RegionID = response["SceneID"].AsUUID();
region.RegionName = response["Name"].AsString();
Vector3d minPosition = response["MinPosition"].AsVector3d();
Vector3d maxPosition = response["MaxPosition"].AsVector3d();
region.RegionLocX = (int)minPosition.X;
region.RegionLocY = (int)minPosition.Y;
region.RegionSizeX = (int)maxPosition.X - (int)minPosition.X;
region.RegionSizeY = (int)maxPosition.Y - (int)minPosition.Y;
if ( ! extraData["HyperGrid"] ) {
Uri httpAddress = response["Address"].AsUri();
region.ExternalHostName = httpAddress.Host;
region.HttpPort = (uint)httpAddress.Port;
IPAddress internalAddress;
IPAddress.TryParse(extraData["InternalAddress"].AsString(), out internalAddress);
if (internalAddress == null)
internalAddress = IPAddress.Any;
region.InternalEndPoint = new IPEndPoint(internalAddress, extraData["InternalPort"].AsInteger());
region.TerrainImage = extraData["MapTexture"].AsUUID();
region.Access = (byte)extraData["Access"].AsInteger();
region.RegionSecret = extraData["RegionSecret"].AsString();
region.EstateOwner = extraData["EstateOwner"].AsUUID();
region.Token = extraData["Token"].AsString();
region.ServerURI = extraData["ServerURI"].AsString();
} else {
region.ServerURI = response["Address"];
}
return region;
}
}
}
| |
// 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.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.NetworkInformation
{
public partial class Ping
{
private const int IcmpHeaderLengthInBytes = 8;
private const int IpHeaderLengthInBytes = 20;
private async Task<PingReply> SendPingAsyncCore(IPAddress address, byte[] buffer, int timeout, PingOptions options)
{
try
{
Task<PingReply> t = RawSocketPermissions.CanUseRawSockets() ?
SendIcmpEchoRequestOverRawSocket(address, buffer, timeout, options) :
SendWithPingUtility(address, buffer, timeout, options);
return await t.ConfigureAwait(false);
}
finally
{
Finish();
}
}
private async Task<PingReply> SendIcmpEchoRequestOverRawSocket(IPAddress address, byte[] buffer, int timeout, PingOptions options)
{
EndPoint endPoint = new IPEndPoint(address, 0);
bool isIpv4 = address.AddressFamily == AddressFamily.InterNetwork;
ProtocolType protocolType = isIpv4 ? ProtocolType.Icmp : ProtocolType.IcmpV6;
// Use the current thread's ID as the identifier.
ushort identifier = (ushort)Environment.CurrentManagedThreadId;
IcmpHeader header = new IcmpHeader()
{
Type = isIpv4 ? (byte)IcmpV4MessageType.EchoRequest : (byte)IcmpV6MessageType.EchoRequest,
Code = 0,
HeaderChecksum = 0,
Identifier = identifier,
SequenceNumber = 0,
};
byte[] sendBuffer = CreateSendMessageBuffer(header, buffer);
using (Socket socket = new Socket(address.AddressFamily, SocketType.Raw, protocolType))
{
socket.ReceiveTimeout = timeout;
socket.SendTimeout = timeout;
// Setting Socket.DontFragment and .Ttl is not supported on Unix, so ignore the PingOptions parameter.
int ipHeaderLength = isIpv4 ? IpHeaderLengthInBytes : 0;
await socket.SendToAsync(new ArraySegment<byte>(sendBuffer), SocketFlags.None, endPoint).ConfigureAwait(false);
byte[] receiveBuffer = new byte[ipHeaderLength + IcmpHeaderLengthInBytes + buffer.Length];
long elapsed;
Stopwatch sw = Stopwatch.StartNew();
// Read from the socket in a loop. We may receive messages that are not echo replies, or that are not in response
// to the echo request we just sent. We need to filter such messages out, and continue reading until our timeout.
// For example, when pinging the local host, we need to filter out our own echo requests that the socket reads.
while ((elapsed = sw.ElapsedMilliseconds) < timeout)
{
Task<SocketReceiveFromResult> receiveTask = socket.ReceiveFromAsync(
new ArraySegment<byte>(receiveBuffer),
SocketFlags.None,
endPoint);
var cts = new CancellationTokenSource();
Task finished = await Task.WhenAny(receiveTask, Task.Delay(timeout - (int)elapsed, cts.Token)).ConfigureAwait(false);
cts.Cancel();
if (finished != receiveTask)
{
sw.Stop();
return CreateTimedOutPingReply();
}
SocketReceiveFromResult receiveResult = receiveTask.GetAwaiter().GetResult();
int bytesReceived = receiveResult.ReceivedBytes;
if (bytesReceived - ipHeaderLength < IcmpHeaderLengthInBytes)
{
continue; // Not enough bytes to reconstruct IP header + ICMP header.
}
byte type, code;
unsafe
{
fixed (byte* bytesPtr = receiveBuffer)
{
int icmpHeaderOffset = ipHeaderLength;
IcmpHeader receivedHeader = *((IcmpHeader*)(bytesPtr + icmpHeaderOffset)); // Skip IP header.
type = receivedHeader.Type;
code = receivedHeader.Code;
if (identifier != receivedHeader.Identifier
|| type == (byte)IcmpV4MessageType.EchoRequest
|| type == (byte)IcmpV6MessageType.EchoRequest) // Echo Request, ignore
{
continue;
}
}
}
sw.Stop();
long roundTripTime = sw.ElapsedMilliseconds;
int dataOffset = ipHeaderLength + IcmpHeaderLengthInBytes;
// We want to return a buffer with the actual data we sent out, not including the header data.
byte[] dataBuffer = new byte[bytesReceived - dataOffset];
Buffer.BlockCopy(receiveBuffer, dataOffset, dataBuffer, 0, dataBuffer.Length);
IPStatus status = isIpv4
? IcmpV4MessageConstants.MapV4TypeToIPStatus(type, code)
: IcmpV6MessageConstants.MapV6TypeToIPStatus(type, code);
return new PingReply(address, options, status, roundTripTime, dataBuffer);
}
// We have exceeded our timeout duration, and no reply has been received.
sw.Stop();
return CreateTimedOutPingReply();
}
}
private async Task<PingReply> SendWithPingUtility(IPAddress address, byte[] buffer, int timeout, PingOptions options)
{
bool isIpv4 = address.AddressFamily == AddressFamily.InterNetwork;
string pingExecutable = isIpv4 ? UnixCommandLinePing.Ping4UtilityPath : UnixCommandLinePing.Ping6UtilityPath;
if (pingExecutable == null)
{
throw new PlatformNotSupportedException(SR.net_ping_utility_not_found);
}
string processArgs = UnixCommandLinePing.ConstructCommandLine(buffer.Length, address.ToString(), isIpv4);
ProcessStartInfo psi = new ProcessStartInfo(pingExecutable, processArgs);
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
Process p = new Process() { StartInfo = psi };
var processCompletion = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
p.EnableRaisingEvents = true;
p.Exited += (s, e) => processCompletion.SetResult(true);
p.Start();
var cts = new CancellationTokenSource();
Task timeoutTask = Task.Delay(timeout, cts.Token);
Task finished = await Task.WhenAny(processCompletion.Task, timeoutTask).ConfigureAwait(false);
if (finished == timeoutTask && !p.HasExited)
{
// Try to kill the ping process if it didn't return. If it is already in the process of exiting, a Win32Exception will be thrown.
try
{
p.Kill();
}
catch (Win32Exception) { }
return CreateTimedOutPingReply();
}
else
{
cts.Cancel();
if (p.ExitCode != 0)
{
// This means no reply was received, although transmission may have been successful.
return CreateTimedOutPingReply();
}
try
{
string output = await p.StandardOutput.ReadToEndAsync().ConfigureAwait(false);
long rtt = UnixCommandLinePing.ParseRoundTripTime(output);
return new PingReply(
address,
null, // Ping utility cannot accomodate these, return null to indicate they were ignored.
IPStatus.Success,
rtt,
Array.Empty<byte>()); // Ping utility doesn't deliver this info.
}
catch (Exception)
{
// If the standard output cannot be successfully parsed, throw a generic PingException.
throw new PingException(SR.net_ping);
}
}
}
private PingReply CreateTimedOutPingReply()
{
// Documentation indicates that you should only pay attention to the IPStatus value when
// its value is not "Success", but the rest of these values match that of the Windows implementation.
return new PingReply(new IPAddress(0), null, IPStatus.TimedOut, 0, Array.Empty<byte>());
}
#if DEBUG
static Ping()
{
Debug.Assert(Marshal.SizeOf<IcmpHeader>() == 8, "The size of an ICMP Header must be 8 bytes.");
}
#endif
// Must be 8 bytes total.
[StructLayout(LayoutKind.Sequential)]
internal struct IcmpHeader
{
public byte Type;
public byte Code;
public ushort HeaderChecksum;
public ushort Identifier;
public ushort SequenceNumber;
}
private static unsafe byte[] CreateSendMessageBuffer(IcmpHeader header, byte[] payload)
{
int headerSize = sizeof(IcmpHeader);
byte[] result = new byte[headerSize + payload.Length];
Marshal.Copy(new IntPtr(&header), result, 0, headerSize);
payload.CopyTo(result, headerSize);
ushort checksum = ComputeBufferChecksum(result);
// Jam the checksum into the buffer.
result[2] = (byte)(checksum >> 8);
result[3] = (byte)(checksum & (0xFF));
return result;
}
private static ushort ComputeBufferChecksum(byte[] buffer)
{
// This is using the "deferred carries" approach outlined in RFC 1071.
uint sum = 0;
for (int i = 0; i < buffer.Length; i += 2)
{
// Combine each pair of bytes into a 16-bit number and add it to the sum
ushort element0 = (ushort)((buffer[i] << 8) & 0xFF00);
ushort element1 = (i + 1 < buffer.Length)
? (ushort)(buffer[i + 1] & 0x00FF)
: (ushort)0; // If there's an odd number of bytes, pad by one octet of zeros.
ushort combined = (ushort)(element0 | element1);
sum += (uint)combined;
}
// Add back the "carry bits" which have risen to the upper 16 bits of the sum.
while ((sum >> 16) != 0)
{
var partialSum = sum & 0xFFFF;
var carries = sum >> 16;
sum = partialSum + carries;
}
return (ushort)~sum;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Security.Util
{
using System;
using System.Collections;
using System.Security.Permissions;
using System.Runtime.Serialization;
using System.Threading;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
#if FEATURE_SERIALIZATION
[Serializable]
#endif
internal class TokenBasedSet
{
// Following 3 fields are used only for serialization compat purposes: DO NOT USE THESE EVER!
#pragma warning disable 414
private int m_initSize = 24;
private int m_increment = 8;
#pragma warning restore 414
private Object[] m_objSet;
// END -> Serialization only fields
[OptionalField(VersionAdded = 2)]
private volatile Object m_Obj;
[OptionalField(VersionAdded = 2)]
private volatile Object[] m_Set;
private int m_cElt;
private volatile int m_maxIndex;
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
OnDeserializedInternal();
}
private void OnDeserializedInternal()
{
if (m_objSet != null) //v1.x case
{
if (m_cElt == 1)
m_Obj = m_objSet[m_maxIndex];
else
m_Set = m_objSet;
m_objSet = null;
}
// Nothing to do for the v2.0 and beyond case
}
[OnSerializing]
private void OnSerializing(StreamingContext ctx)
{
if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
{
//Nothing special for the v2 and beyond case
// for the v1.x case, we need to create m_objSet if necessary
if (m_cElt == 1)
{
m_objSet = new Object[m_maxIndex+1];
m_objSet[m_maxIndex] = m_Obj;
}
else if (m_cElt > 0)
{
// Array case:
m_objSet = m_Set;
}
}
}
[OnSerialized]
private void OnSerialized(StreamingContext ctx)
{
if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
{
m_objSet = null;
}
}
internal bool MoveNext(ref TokenBasedSetEnumerator e)
{
switch (m_cElt)
{
case 0:
return false;
case 1:
if (e.Index == -1)
{
e.Index = m_maxIndex;
e.Current = m_Obj;
return true;
}
else
{
e.Index = (short)(m_maxIndex+1);
e.Current = null;
return false;
}
default:
while (++e.Index <= m_maxIndex)
{
e.Current = Volatile.Read(ref m_Set[e.Index]);
if (e.Current != null)
return true;
}
e.Current = null;
return false;
}
}
internal TokenBasedSet()
{
Reset();
}
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
internal TokenBasedSet(TokenBasedSet tbSet)
{
if (tbSet == null)
{
Reset();
return;
}
if (tbSet.m_cElt > 1)
{
Object[] aObj = tbSet.m_Set;
int aLen = aObj.Length;
Object[] aNew = new Object[aLen];
System.Array.Copy(aObj, 0, aNew, 0, aLen);
m_Set = aNew;
}
else
{
m_Obj = tbSet.m_Obj;
}
m_cElt = tbSet.m_cElt;
m_maxIndex = tbSet.m_maxIndex;
}
internal void Reset()
{
m_Obj = null;
m_Set = null;
m_cElt = 0;
m_maxIndex = -1;
}
internal void SetItem(int index, Object item)
{
Object[] aObj = null;
if (item == null)
{
RemoveItem(index);
return;
}
switch (m_cElt)
{
case 0:
// on the first item, we don't create an array, we merely remember it's index and value
// this this the 99% case
m_cElt = 1;
m_maxIndex = (short)index;
m_Obj = item;
break;
case 1:
// we have to decide if a 2nd item has indeed been added and create the array
// if it has
if (index == m_maxIndex)
{
// replacing the one existing item
m_Obj = item;
}
else
{
// adding a second distinct permission
Object objSaved = m_Obj;
int iMax = Math.Max(m_maxIndex, index);
aObj = new Object[iMax+1];
aObj[m_maxIndex] = objSaved;
aObj[index] = item;
m_maxIndex = (short)iMax;
m_cElt = 2;
m_Set = aObj;
m_Obj = null;
}
break;
default:
// this is the general case code for when there is really an array
aObj = m_Set;
// we are now adding an item, check if we need to grow
if (index >= aObj.Length)
{
Object[] newset = new Object[index+1];
System.Array.Copy(aObj, 0, newset, 0, m_maxIndex+1);
m_maxIndex = (short)index;
newset[index] = item;
m_Set = newset;
m_cElt++;
}
else
{
if (aObj[index] == null)
m_cElt++;
aObj[index] = item;
if (index > m_maxIndex)
m_maxIndex = (short)index;
}
break;
}
}
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety")]
internal Object GetItem(int index)
{
switch (m_cElt)
{
case 0:
return null;
case 1:
if (index == m_maxIndex)
return m_Obj;
else
return null;
default:
if (index < m_Set.Length)
return Volatile.Read(ref m_Set[index]);
else
return null;
}
}
internal Object RemoveItem(int index)
{
Object ret = null;
switch (m_cElt)
{
case 0:
ret = null;
break;
case 1:
if (index != m_maxIndex)
{
// removing a permission we don't have ignore it
ret = null;
}
else
{
// removing the permission we have at the moment
ret = m_Obj;
Reset();
}
break;
default:
// this is the general case code for when there is really an array
// we are removing an item
if (index < m_Set.Length && (ret = Volatile.Read(ref m_Set[index])) != null)
{
// ok we really deleted something at this point
Volatile.Write(ref m_Set[index], null);
m_cElt--;
if (index == m_maxIndex)
ResetMaxIndex(m_Set);
// collapse the array
if (m_cElt == 1)
{
m_Obj = Volatile.Read(ref m_Set[m_maxIndex]);
m_Set = null;
}
}
break;
}
return ret;
}
private void ResetMaxIndex(Object[] aObj)
{
int i;
// Start at the end of the array, and
// scan backwards for the first non-null
// slot. That is the new maxIndex.
for (i = aObj.Length - 1; i >= 0; i--)
{
if (aObj[i] != null)
{
m_maxIndex = (short)i;
return;
}
}
m_maxIndex = -1;
}
internal int GetStartingIndex()
{
if (m_cElt <= 1)
return m_maxIndex;
return 0;
}
internal int GetCount()
{
return m_cElt;
}
internal int GetMaxUsedIndex()
{
return m_maxIndex;
}
internal bool FastIsEmpty()
{
return m_cElt == 0;
}
// Used to merge two distinct TokenBasedSets (used currently only in PermissionSet Deserialization)
internal TokenBasedSet SpecialUnion(TokenBasedSet other)
{
// This gets called from PermissionSet.OnDeserialized and it's possible that the TokenBasedSets have
// not been subjected to VTS callbacks yet
OnDeserializedInternal();
TokenBasedSet unionSet = new TokenBasedSet();
int maxMax;
if (other != null)
{
other.OnDeserializedInternal();
maxMax = this.GetMaxUsedIndex() > other.GetMaxUsedIndex() ? this.GetMaxUsedIndex() : other.GetMaxUsedIndex();
}
else
maxMax = this.GetMaxUsedIndex();
for (int i = 0; i <= maxMax; ++i)
{
Object thisObj = this.GetItem( i );
IPermission thisPerm = thisObj as IPermission;
#if FEATURE_CAS_POLICY
ISecurityElementFactory thisElem = thisObj as ISecurityElementFactory;
#endif // FEATURE_CAS_POLICY
Object otherObj = (other != null)?other.GetItem( i ):null;
IPermission otherPerm = otherObj as IPermission;
#if FEATURE_CAS_POLICY
ISecurityElementFactory otherElem = otherObj as ISecurityElementFactory;
#endif // FEATURE_CAS_POLICY
if (thisObj == null && otherObj == null)
continue;
if (thisObj == null)
{
#if FEATURE_CAS_POLICY
if (otherElem != null)
{
otherPerm = PermissionSet.CreatePerm(otherElem, false);
}
#endif // FEATURE_CAS_POLICY
PermissionToken token = PermissionToken.GetToken(otherPerm);
if (token == null)
{
throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
}
unionSet.SetItem(token.m_index, otherPerm);
}
else if (otherObj == null)
{
#if FEATURE_CAS_POLICY
if (thisElem != null)
{
thisPerm = PermissionSet.CreatePerm(thisElem, false);
}
#endif // FEATURE_CAS_POLICY
PermissionToken token = PermissionToken.GetToken(thisPerm);
if (token == null)
{
throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
}
unionSet.SetItem( token.m_index, thisPerm);
}
else
{
Contract.Assert( (thisObj == null || otherObj == null), "Permission cannot be in both TokenBasedSets" );
}
}
return unionSet;
}
internal void SpecialSplit(ref TokenBasedSet unrestrictedPermSet, ref TokenBasedSet normalPermSet, bool ignoreTypeLoadFailures)
{
int maxIndex = GetMaxUsedIndex();
for (int i = GetStartingIndex(); i <= maxIndex; ++i)
{
Object obj = GetItem( i );
if (obj != null)
{
IPermission perm = obj as IPermission;
#if FEATURE_CAS_POLICY
if (perm == null)
perm = PermissionSet.CreatePerm(obj, ignoreTypeLoadFailures);
#endif // FEATURE_CAS_POLICY
PermissionToken token = PermissionToken.GetToken(perm);
if (perm == null || token == null)
continue;
if (perm is IUnrestrictedPermission)
{
// Add to unrestrictedPermSet
if (unrestrictedPermSet == null)
unrestrictedPermSet = new TokenBasedSet();
unrestrictedPermSet.SetItem(token.m_index, perm);
}
else
{
// Add to normalPermSet
if (normalPermSet == null)
normalPermSet = new TokenBasedSet();
normalPermSet.SetItem(token.m_index, perm);
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Management;
using System.Text;
using System.Text.RegularExpressions;
namespace PerfView
{
/// <summary>
/// A code:ProcessInfo represents a process that existed at the time a snapshot was taken with
/// the code:ProcessInfo constructor. It basically is a set of read-only properties describing
/// the process.
/// </summary>
public class ProcessInfo
{
public int ProcessID { get { return processID; } }
public int ParentProcessID { get { return parentProcessID; } }
public string CommandLine
{
get
{
if (commandLine == null)
{
commandLine = (string)processObj["CommandLine"];
if (commandLine == null)
{
commandLine = ExecutablePath;
}
if (commandLine == null)
{
commandLine = "";
}
}
return commandLine;
}
}
public string ExecutablePath
{
get
{
if (executablePath == null)
{
executablePath = (string)processObj["ExecutablePath"];
}
return executablePath;
}
}
public string Name
{
get
{
if (name == null)
{
name = Path.GetFileNameWithoutExtension(ExecutablePath);
}
return name;
}
}
public DateTime CreationDate
{
get
{
if (creationDate == default(DateTime))
{
string creationDateStr = (string)processObj["CreationDate"];
if (creationDateStr != null)
{
creationDate = ToDateTime(creationDateStr);
}
}
return creationDate;
}
}
public long CpuTime100ns
{
get
{
if (cpuTime100ns == 0)
{
cpuTime100ns = (long)((ulong)processObj["KernelModeTime"] + (ulong)processObj["UserModeTime"]);
}
return cpuTime100ns;
}
}
public int PageFaults { get { return (int)(uint)processObj["PageFaults"]; } }
public long WorkingSetSize { get { return (long)(ulong)processObj["WorkingSetSize"]; } }
public IList<ProcessInfo> Children { get { return children; } }
public ProcessInfo Parent { get { return parent; } }
public override string ToString()
{
return ToString("", int.MaxValue);
}
public string ToString(string indent, int limit)
{
// Strip the EXE name from the command line
var args = Regex.Replace(CommandLine, "^((\\S+)|(\".*?\"))\\s*", "");
var shortName = Name;
if (shortName.Length > 24)
{
shortName = shortName.Substring(0, 24);
}
return string.Format("{0,-24} | Pid: {1,5} | Alive: {2,6} | Args: {3}", shortName, ProcessID,
TimeStr(DateTime.Now - CreationDate), args);
}
/// <summary>
/// Returns a time span picking good units so that it can be expressed in a small amount of
/// space (5 spaces)
/// </summary>
/// <param name="span"></param>
/// <returns></returns>
public static string TimeStr(TimeSpan span)
{
double time = span.TotalMilliseconds;
if (time < 1000)
{
return time.ToString("f0") + "ms";
}
time = time / 1000;
if (time < 60)
{
return time.ToString("f1") + "s";
}
time = time / 60;
if (time < 60)
{
return time.ToString("f1") + "m";
}
time = time / 60;
if (time < 24)
{
return time.ToString("f1") + "h";
}
time = time / 24;
if (time < 100)
{
return time.ToString("f1") + "d";
}
return time.ToString("f0") + "d";
}
#region Private
internal ProcessInfo(ManagementBaseObject processObj)
{
this.processObj = processObj;
processID = (int)(uint)processObj["ProcessID"];
parentProcessID = (int)(uint)processObj["ParentProcessID"];
children = emptyList;
}
/// <summary>
/// Given a command line, compress out uninteresting parts to show the most important part.
/// </summary>
private static string CompressCommandLine(string commandLine, int limit)
{
if (commandLine.Length > limit)
{
commandLine = Regex.Replace(commandLine, "\"([^\"]*)\"", "$1");
commandLine = Regex.Replace(commandLine, @"(\S+).exe", "$1", RegexOptions.IgnoreCase);
commandLine = Regex.Replace(commandLine, @"\S+\\", "");
commandLine = Regex.Replace(commandLine, @"\s+", " ");
if (commandLine.Length > limit)
{
commandLine = commandLine.Substring(0, limit - 1) + "...";
}
}
return commandLine;
}
// Converts a given datetime in DMTF format to System.DateTime object.
internal List<ProcessInfo> children;
internal ProcessInfo parent;
private static System.DateTime ToDateTime(string dmtfDate)
{
System.DateTime initializer = System.DateTime.MinValue;
int year = initializer.Year;
int month = initializer.Month;
int day = initializer.Day;
int hour = initializer.Hour;
int minute = initializer.Minute;
int second = initializer.Second;
long ticks = 0;
string dmtf = dmtfDate;
System.DateTime datetime = System.DateTime.MinValue;
string tempString = string.Empty;
if ((dmtf == null))
{
throw new System.ArgumentOutOfRangeException();
}
if ((dmtf.Length == 0))
{
throw new System.ArgumentOutOfRangeException();
}
if ((dmtf.Length != 25))
{
throw new System.ArgumentOutOfRangeException();
}
try
{
tempString = dmtf.Substring(0, 4);
if (("****" != tempString))
{
year = int.Parse(tempString);
}
tempString = dmtf.Substring(4, 2);
if (("**" != tempString))
{
month = int.Parse(tempString);
}
tempString = dmtf.Substring(6, 2);
if (("**" != tempString))
{
day = int.Parse(tempString);
}
tempString = dmtf.Substring(8, 2);
if (("**" != tempString))
{
hour = int.Parse(tempString);
}
tempString = dmtf.Substring(10, 2);
if (("**" != tempString))
{
minute = int.Parse(tempString);
}
tempString = dmtf.Substring(12, 2);
if (("**" != tempString))
{
second = int.Parse(tempString);
}
tempString = dmtf.Substring(15, 6);
if (("******" != tempString))
{
ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000))));
}
if ((year < 0)
|| (month < 0)
|| (day < 0)
|| (hour < 0)
|| (minute < 0)
|| (second < 0)
|| (ticks < 0))
{
throw new System.ArgumentOutOfRangeException();
}
}
catch (System.Exception e)
{
throw new System.ArgumentOutOfRangeException(null, e.Message);
}
datetime = new System.DateTime(year, month, day, hour, minute, second, 0);
datetime = datetime.AddTicks(ticks);
System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime);
int UTCOffset = 0;
int OffsetToBeAdjusted = 0;
long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute)));
tempString = dmtf.Substring(22, 3);
if ((tempString != "******"))
{
tempString = dmtf.Substring(21, 4);
try
{
UTCOffset = int.Parse(tempString);
}
catch (System.Exception e)
{
throw new System.ArgumentOutOfRangeException(null, e.Message);
}
OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset)));
datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted)));
}
return datetime;
}
private ManagementBaseObject processObj;
private int processID;
private int parentProcessID;
private string commandLine;
private string executablePath;
private string name;
private DateTime creationDate;
private long cpuTime100ns;
private static List<ProcessInfo> emptyList = new List<ProcessInfo>();
#endregion
}
/// <summary>
/// code:ProcessInfos represents the collection of all processes on the machine. When you create a
/// ProcessInfos object, a snapshot of process information is taken, which can then be traversed.
/// </summary>
public class ProcessInfos
{
/// <summary>
/// Create a new snapshot of the processes on the machine.
/// </summary>
public ProcessInfos()
{
allProcs = new Dictionary<int, ProcessInfo>();
topProcs = new List<ProcessInfo>();
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_Process");
foreach (ManagementObject processObj in searcher.Get())
{
ProcessInfo processInfo = new ProcessInfo(processObj);
// Process ID 0 is a special Peudo-process that is weird (it is its own parent)
if (processInfo.ProcessID != 0)
{
allProcs.Add(processInfo.ProcessID, processInfo);
}
}
// create the lists of children based on the parent information
foreach (ProcessInfo process in allProcs.Values)
{
ProcessInfo parentProcess;
if (allProcs.TryGetValue(process.ParentProcessID, out parentProcess))
{
// All zero element lists are shared, if we are going to add an element we need to
// do copy on write.
if (parentProcess.children.Count == 0)
{
parentProcess.children = new List<ProcessInfo>();
}
parentProcess.Children.Add(process);
process.parent = parentProcess;
}
else
{
topProcs.Add(process); // It does not have a parent.
}
}
}
/// <summary>
/// Used to enumerate all the processes that existed at the time the snapshot was taken
/// </summary>
public ICollection<ProcessInfo> Processes { get { return allProcs.Values; } }
/// <summary>
/// Look up a particular process by process ID. If it does not exist, null is returned.
/// </summary>
public ProcessInfo this[int processID]
{
get
{
ProcessInfo ret = null;
allProcs.TryGetValue(processID, out ret);
return ret;
}
}
/// <summary>
/// Return the collection of all processes that do not have a parent. This is the natural
/// starting point for traversing the processes organized by which process spawned which.
/// </summary>
public ICollection<ProcessInfo> Orphans { get { return topProcs; } }
/// <summary>
/// Returns a
/// </summary>
/// <returns></returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("-------------------------------------------------------------------------------");
sb.AppendLine(" Proc Run CPU WS Command Line (children indented after parents)");
sb.AppendLine(" ID Time Time Meg " + DateTime.Now);
sb.AppendLine("-------------------------------------------------------------------------------");
foreach (ProcessInfo process in topProcs)
{
PrintTree(process, sb, "");
}
return sb.ToString();
}
#region Private
private void PrintTree(ProcessInfo process, StringBuilder sb, string indent)
{
sb.AppendLine(process.ToString(indent, 54));
foreach (ProcessInfo child in process.Children)
{
PrintTree(child, sb, indent + " ");
}
}
private List<ProcessInfo> topProcs; // Processes with no parent (that is alive)
private Dictionary<int, ProcessInfo> allProcs;
#endregion
}
}
| |
//#define REREAD_STATE_AFTER_WRITE_FAILED
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using Orleans.Storage;
using Orleans.TestingHost;
using UnitTests.GrainInterfaces;
using UnitTests.Grains;
using Xunit;
using Xunit.Abstractions;
using TesterInternal;
using TestExtensions;
using Orleans.Hosting;
using Orleans.Internal;
using Microsoft.Extensions.DependencyInjection;
// ReSharper disable RedundantAssignment
// ReSharper disable UnusedVariable
// ReSharper disable InconsistentNaming
namespace UnitTests.StorageTests
{
/// <summary>
/// PersistenceGrainTests - Run with only local unit test silo -- no external dependency on Azure storage
/// </summary>
public class PersistenceGrainTests_Local : OrleansTestingBase, IClassFixture<PersistenceGrainTests_Local.Fixture>, IDisposable
{
public class Fixture : BaseTestClusterFixture
{
protected override void ConfigureTestCluster(TestClusterBuilder builder)
{
builder.Options.InitialSilosCount = 1;
builder.AddSiloBuilderConfigurator<SiloConfigurator>();
}
private class SiloConfigurator : ISiloConfigurator
{
public void Configure(ISiloBuilder hostBuilder)
{
hostBuilder.AddMemoryGrainStorage("MemoryStore");
hostBuilder.AddTestStorageProvider(MockStorageProviderName1, (sp, name) => ActivatorUtilities.CreateInstance<MockStorageProvider>(sp, name));
hostBuilder.AddTestStorageProvider(MockStorageProviderName2, (sp, name) => ActivatorUtilities.CreateInstance<MockStorageProvider>(sp, name));
hostBuilder.AddTestStorageProvider(MockStorageProviderNameLowerCase, (sp, name) => ActivatorUtilities.CreateInstance<MockStorageProvider>(sp, name));
hostBuilder.AddTestStorageProvider(ErrorInjectorProviderName, (sp, name) => ActivatorUtilities.CreateInstance<ErrorInjectionStorageProvider>(sp));
}
}
}
const string MockStorageProviderName1 = "test1";
const string MockStorageProviderName2 = "test2";
const string MockStorageProviderNameLowerCase = "lowercase";
const string ErrorInjectorProviderName = "ErrorInjector";
private readonly ITestOutputHelper output;
protected TestCluster HostedCluster { get; }
public PersistenceGrainTests_Local(ITestOutputHelper output, Fixture fixture)
{
this.output = output;
HostedCluster = fixture.HostedCluster;
SetErrorInjection(ErrorInjectorProviderName, ErrorInjectionPoint.None);
ResetMockStorageProvidersHistory();
}
public void Dispose()
{
SetErrorInjection(ErrorInjectorProviderName, ErrorInjectionPoint.None);
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Silo_StorageProvidersLoaded()
{
List<SiloHandle> silos = this.HostedCluster.GetActiveSilos().ToList();
foreach (var silo in silos)
{
var testHooks = this.HostedCluster.Client.GetTestHooks(silo);
ICollection<string> providers = await testHooks.GetStorageProviderNames();
Assert.NotNull(providers); // Null provider manager
Assert.True(providers.Count > 0, "Some providers loaded");
Assert.True(testHooks.HasStorageProvider(MockStorageProviderName1).Result,
$"provider {MockStorageProviderName1} on silo {silo.Name} should be registered");
Assert.True(testHooks.HasStorageProvider(MockStorageProviderName2).Result,
$"provider {MockStorageProviderName2} on silo {silo.Name} should be registered");
Assert.True(testHooks.HasStorageProvider(MockStorageProviderNameLowerCase).Result,
$"provider {MockStorageProviderNameLowerCase} on silo {silo.Name} should be registered");
Assert.True(testHooks.HasStorageProvider(ErrorInjectorProviderName).Result,
$"provider {ErrorInjectorProviderName} on silo {silo.Name} should be registered");
}
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public void Persistence_Silo_StorageProvider_Name_Missing()
{
List<SiloHandle> silos = this.HostedCluster.GetActiveSilos().ToList();
var silo = silos.First();
const string providerName = "NotPresent";
Assert.False(this.HostedCluster.Client.GetTestHooks(silo).HasStorageProvider(providerName).Result,
$"provider {providerName} on silo {silo.Name} should not be registered");
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Grain_CheckStateInit()
{
Guid id = Guid.NewGuid();
IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(id);
bool ok = await grain.CheckStateInit();
Assert.True(ok, "CheckStateInit OK");
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Grain_CheckStorageProvider()
{
Guid id = Guid.NewGuid();
IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(id);
string providerType = await grain.CheckProviderType();
Assert.Equal(typeof(MockStorageProvider).FullName, providerType); // StorageProvider provider type
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Grain_Init()
{
Guid id = Guid.NewGuid();
IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(id);
await grain.DoSomething();
//request InitCount on providers on all silos in this cluster
IManagementGrain mgmtGrain = this.HostedCluster.GrainFactory.GetGrain<IManagementGrain>(0);
object[] replies = await mgmtGrain.SendControlCommandToProvider(typeof(MockStorageProvider).FullName,
MockStorageProviderName1, (int)MockStorageProvider.Commands.InitCount, null);
Assert.Contains(1, replies); // StorageProvider #Init
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Grain_Activate_StoredValue()
{
const string providerName = MockStorageProviderName1;
string grainType = typeof(PersistenceTestGrain).FullName;
Guid guid = Guid.NewGuid();
_ = guid.ToString("N");
IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(guid);
// Store initial value in storage
int initialValue = 567;
SetStoredValue(providerName, typeof(MockStorageProvider).FullName, grainType, grain, "Field1", initialValue);
int readValue = await grain.GetValue();
Assert.Equal(initialValue, readValue); // Read previously stored value
}
[Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("Generics")]
public async Task Persistence_Grain_Activate_StoredValue_Generic()
{
const string providerName = MockStorageProviderName1;
string grainType = typeof(PersistenceTestGenericGrain<int>).FullName;
Guid guid = Guid.NewGuid();
_ = guid.ToString("N");
var grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGenericGrain<int>>(guid);
// Store initial value in storage
int initialValue = 567;
SetStoredValue(providerName, typeof(MockStorageProvider).FullName, grainType, grain, "Field1", initialValue);
int readValue = await grain.GetValue();
Assert.Equal(initialValue, readValue); // Read previously stored value
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Grain_Activate_Error()
{
const string providerName = ErrorInjectorProviderName;
string grainType = typeof(PersistenceProviderErrorGrain).FullName;
Guid guid = Guid.NewGuid();
string id = guid.ToString("N");
IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(guid);
// Store initial value in storage
int initialValue = 567;
SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", initialValue);
SetErrorInjection(providerName, ErrorInjectionPoint.BeforeRead);
await Assert.ThrowsAsync<StorageProviderInjectedError>(() =>
grain.GetValue());
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Grain_Read()
{
const string providerName = MockStorageProviderName1;
Guid id = Guid.NewGuid();
IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(id);
await grain.DoSomething();
var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName);
Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads
Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Grain_Write()
{
const string providerName = MockStorageProviderName1;
Guid id = Guid.NewGuid();
IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(id);
await grain.DoWrite(1);
var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName);
Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads
Assert.Equal(1, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes
Assert.Equal(1, providerState.LastStoredGrainState.Field1); // Store-Field1
await grain.DoWrite(2);
providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName);
Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads
Assert.Equal(2, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes
Assert.Equal(2, providerState.LastStoredGrainState.Field1); // Store-Field1
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Grain_ReRead()
{
const string providerName = MockStorageProviderName1;
string grainType = typeof(PersistenceTestGrain).FullName;
Guid guid = Guid.NewGuid();
_ = guid.ToString("N");
IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(guid);
await grain.DoSomething();
var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName);
Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads
Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes
SetStoredValue(providerName, typeof(MockStorageProvider).FullName, grainType, grain, "Field1", 42);
await grain.DoRead();
providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName);
Assert.Equal(2, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads-2
Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes-2
Assert.Equal(42, providerState.LastStoredGrainState.Field1); // Store-Field1
}
[Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("MemoryStore")]
public async Task MemoryStore_Read_Write()
{
Guid guid = Guid.NewGuid();
_ = guid.ToString("N");
IMemoryStorageTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IMemoryStorageTestGrain>(guid);
int val = await grain.GetValue();
Assert.Equal(0, val); // Initial value
await grain.DoWrite(1);
val = await grain.GetValue();
Assert.Equal(1, val); // Value after Write-1
await grain.DoWrite(2);
val = await grain.GetValue();
Assert.Equal(2, val); // Value after Write-2
val = await grain.DoRead();
Assert.Equal(2, val); // Value after Re-Read
}
[Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("MemoryStore")]
public async Task MemoryStore_Delete()
{
Guid id = Guid.NewGuid();
var grain = this.HostedCluster.GrainFactory.GetGrain<IMemoryStorageTestGrain>(id);
await grain.DoWrite(1);
await grain.DoDelete();
int val = await grain.GetValue(); // Should this throw instead?
Assert.Equal(0, val); // Value after Delete
await grain.DoWrite(2);
val = await grain.GetValue();
Assert.Equal(2, val); // Value after Delete + New Write
}
[Fact, TestCategory("Stress"), TestCategory("CorePerf"), TestCategory("Persistence"), TestCategory("MemoryStore")]
public async Task MemoryStore_Stress_Read()
{
const int numIterations = 10000;
Stopwatch sw = Stopwatch.StartNew();
Task<int>[] promises = new Task<int>[numIterations];
for (int i = 0; i < numIterations; i++)
{
IMemoryStorageTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IMemoryStorageTestGrain>(Guid.NewGuid());
int idx = i; // Capture
Func<Task<int>> asyncFunc =
async () =>
{
await grain.DoWrite(idx);
return await grain.DoRead();
};
promises[i] = Task.Run(asyncFunc);
}
await Task.WhenAll(promises);
TimeSpan elapsed = sw.Elapsed;
double tps = (numIterations * 2) / elapsed.TotalSeconds; // One Read and one Write per iteration
output.WriteLine("{0} Completed Read-Write operations in {1} at {2} TPS", numIterations, elapsed, tps);
for (int i = 0; i < numIterations; i++)
{
int expectedVal = i;
Assert.Equal(expectedVal, promises[i].Result); // "Returned value - Read @ #" + i
}
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Write()
{
const string providerName = MockStorageProviderName1;
Guid id = Guid.NewGuid();
IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(id);
await grain.DoWrite(1);
var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName);
Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads
Assert.Equal(1, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes
Assert.Equal(1, providerState.LastStoredGrainState.Field1); // Store-Field1
await grain.DoWrite(2);
providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName);
Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads
Assert.Equal(2, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes
Assert.Equal(2, providerState.LastStoredGrainState.Field1); // Store-Field1
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Delete()
{
const string providerName = MockStorageProviderName1;
Guid id = Guid.NewGuid();
IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(id);
await grain.DoWrite(1);
var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName);
int initialReadCount = providerState.ProviderStateForTest.ReadCount;
int initialWriteCount = providerState.ProviderStateForTest.WriteCount;
int initialDeleteCount = providerState.ProviderStateForTest.DeleteCount;
await grain.DoDelete();
providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName);
Assert.Equal(initialDeleteCount + 1, providerState.ProviderStateForTest.DeleteCount); // StorageProvider #Deletes
Assert.Null(providerState.LastStoredGrainState); // Store-AfterDelete-Empty
int val = await grain.GetValue(); // Returns current in-memory null data without re-read.
providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); // update state
Assert.Equal(0, val); // Value after Delete
Assert.Equal(initialReadCount, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads
await grain.DoWrite(2);
providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); // update state
Assert.Equal(initialReadCount, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads
Assert.Equal(initialWriteCount + 1, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes
Assert.Equal(2, providerState.LastStoredGrainState.Field1); // Store-Field1
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Grain_Read_Error()
{
const string providerName = MockStorageProviderName1;
Guid id = Guid.NewGuid();
IPersistenceErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceErrorGrain>(id);
_ = await grain.GetValue();
var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName);
Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads
Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes
try
{
await grain.DoReadError(true);
}
catch (ApplicationException)
{
// Expected error
}
catch (AggregateException ae)
{
Exception e = ae.GetBaseException();
if (e is ApplicationException)
{
// Expected error
}
else
{
throw e;
}
}
providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName);
Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads-2
Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes-2
try
{
await grain.DoReadError(false);
}
catch (ApplicationException)
{
// Expected error
}
catch (AggregateException ae)
{
Exception e = ae.GetBaseException();
if (e is ApplicationException)
{
// Expected error
}
else
{
throw e;
}
}
providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName);
Assert.Equal(2, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads-2
Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes-2
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Grain_Write_Error()
{
const string providerName = MockStorageProviderName1;
Guid id = Guid.NewGuid();
IPersistenceErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceErrorGrain>(id);
await grain.DoWrite(1);
var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName);
Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads
Assert.Equal(1, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes
Assert.Equal(1, providerState.LastStoredGrainState.Field1); // Store-Field1
await grain.DoWrite(2);
providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName);
Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads
Assert.Equal(2, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes
Assert.Equal(2, providerState.LastStoredGrainState.Field1); // Store-Field1
try
{
await grain.DoWriteError(3, true);
}
catch (ApplicationException)
{
// Expected error
}
catch (AggregateException ae)
{
if (ae.GetBaseException() is ApplicationException)
{
// Expected error
}
else
{
throw;
}
}
providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); // update provider state
Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads
Assert.Equal(2, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes
Assert.Equal(2, providerState.LastStoredGrainState.Field1); // Store-Field1
try
{
await grain.DoWriteError(4, false);
}
catch (ApplicationException)
{
// Expected error
}
catch (AggregateException ae)
{
if (ae.GetBaseException() is ApplicationException)
{
// Expected error
}
else
{
throw;
}
}
providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName);
Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads
Assert.Equal(3, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes
Assert.Equal(4, providerState.LastStoredGrainState.Field1); // Store-Field1
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Grain_ReRead_Error()
{
const string providerName = "test1";
string grainType = typeof(PersistenceErrorGrain).FullName;
Guid guid = Guid.NewGuid();
_ = guid.ToString("N");
IPersistenceErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceErrorGrain>(guid);
_ = await grain.GetValue();
var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName);
Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads
Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes
SetStoredValue(providerName, typeof(MockStorageProvider).FullName, grainType, grain, "Field1", 42);
await grain.DoRead();
providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName);
Assert.Equal(2, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads-2
Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes-2
Assert.Equal(42, providerState.LastStoredGrainState.Field1); // Store-Field1
await grain.DoWrite(43);
providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName);
Assert.Equal(2, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads-2
Assert.Equal(1, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes-2
Assert.Equal(43, providerState.LastStoredGrainState.Field1); // Store-Field1
try
{
await grain.DoReadError(true);
}
catch (ApplicationException)
{
// Expected error
}
catch (AggregateException ae)
{
if (ae.GetBaseException() is ApplicationException)
{
// Expected error
}
else
{
throw;
}
}
providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName);
Assert.Equal(2, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads-2
Assert.Equal(1, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes-2
Assert.Equal(43, providerState.LastStoredGrainState.Field1); // Store-Field1
try
{
await grain.DoReadError(false);
}
catch (ApplicationException)
{
// Expected error
}
catch (AggregateException ae)
{
if (ae.GetBaseException() is ApplicationException)
{
// Expected error
}
else
{
throw;
}
}
providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName);
Assert.Equal(3, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads-2
Assert.Equal(1, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes-2
Assert.Equal(43, providerState.LastStoredGrainState.Field1); // Store-Field1
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Provider_Error_BeforeRead()
{
string grainType = typeof(PersistenceProviderErrorGrain).FullName;
string providerName = ErrorInjectorProviderName;
Guid guid = Guid.NewGuid();
string id = guid.ToString("N");
IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(guid);
var val = await grain.GetValue(); // Activate grain
int expectedVal = 42;
SetErrorInjection(providerName, ErrorInjectionPoint.None);
SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal);
val = await grain.DoRead();
Assert.Equal(expectedVal, val); // Returned value
SetErrorInjection(providerName, ErrorInjectionPoint.BeforeRead);
CheckStorageProviderErrors(grain.DoRead);
SetErrorInjection(providerName, ErrorInjectionPoint.None);
val = await grain.GetValue();
Assert.Equal(expectedVal, val); // Returned value
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Provider_Error_AfterRead()
{
string grainType = typeof(PersistenceProviderErrorGrain).FullName;
string providerName = ErrorInjectorProviderName;
Guid guid = Guid.NewGuid();
string id = guid.ToString("N");
IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(guid);
var val = await grain.GetValue(); // Activate grain
int expectedVal = 52;
SetErrorInjection(providerName, ErrorInjectionPoint.None);
SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal);
val = await grain.DoRead();
Assert.Equal(expectedVal, val); // Returned value
SetErrorInjection(providerName, ErrorInjectionPoint.AfterRead);
CheckStorageProviderErrors(grain.DoRead);
val = await grain.GetValue();
Assert.Equal(expectedVal, val); // Returned value
int newVal = 53;
SetErrorInjection(providerName, ErrorInjectionPoint.None);
SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", newVal);
val = await grain.GetValue();
Assert.Equal(expectedVal, val); // Returned value
await grain.DoRead(); // Force re-read
expectedVal = newVal;
val = await grain.GetValue();
Assert.Equal(expectedVal, val); // Returned value
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Provider_Error_BeforeWrite()
{
Guid id = Guid.NewGuid();
string providerName = ErrorInjectorProviderName;
IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(id);
var val = await grain.GetValue();
int expectedVal = 62;
await grain.DoWrite(expectedVal);
var providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName);
Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1
const int attemptedVal3 = 63;
SetErrorInjection(providerName, ErrorInjectionPoint.BeforeWrite);
CheckStorageProviderErrors(() => grain.DoWrite(attemptedVal3));
// Stored value unchanged
providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName);
Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1
SetErrorInjection(providerName, ErrorInjectionPoint.None);
val = await grain.GetValue();
// Stored value unchanged
providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName);
Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1
#if REREAD_STATE_AFTER_WRITE_FAILED
Assert.Equal(expectedVal, val); // Last value written successfully
#else
Assert.Equal(attemptedVal3, val); // Last value attempted to be written is still in memory
#endif
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Provider_InconsistentStateException_DeactivatesGrain()
{
Guid id = Guid.NewGuid();
string providerName = ErrorInjectorProviderName;
IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(id);
var val = await grain.GetValue();
int expectedVal = 62;
var originalActivationId = await grain.GetActivationId();
await grain.DoWrite(expectedVal);
var providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName);
Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1
const int attemptedVal3 = 63;
SetErrorInjection(providerName, new ErrorInjectionBehavior
{
ErrorInjectionPoint = ErrorInjectionPoint.BeforeWrite,
ExceptionType = typeof(InconsistentStateException)
});
CheckStorageProviderErrors(() => grain.DoWrite(attemptedVal3), typeof(InconsistentStateException));
// Stored value unchanged
providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName);
Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1
Assert.NotEqual(originalActivationId, await grain.GetActivationId());
SetErrorInjection(providerName, ErrorInjectionPoint.None);
val = await grain.GetValue();
// Stored value unchanged
providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName);
Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1
// The value should not have changed.
Assert.Equal(expectedVal, val);
}
/// <summary>
/// Tests that deactivations caused by an <see cref="InconsistentStateException"/> only affect the grain which
/// the exception originated from.
/// </summary>
/// <returns></returns>
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Provider_InconsistentStateException_DeactivatesOnlyCurrentGrain()
{
var target = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(Guid.NewGuid());
var proxy = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorProxyGrain>(Guid.NewGuid());
// Record the original activation ids.
var targetActivationId = await target.GetActivationId();
var proxyActivationId = await proxy.GetActivationId();
// Cause an inconsistent state exception.
this.SetErrorInjection(ErrorInjectorProviderName, new ErrorInjectionBehavior
{
ErrorInjectionPoint = ErrorInjectionPoint.BeforeWrite,
ExceptionType = typeof(InconsistentStateException)
});
this.CheckStorageProviderErrors(() => proxy.DoWrite(63, target), typeof(InconsistentStateException));
// The target should have been deactivated by the exception.
Assert.NotEqual(targetActivationId, await target.GetActivationId());
// The grain which called the target grain should not have been deactivated.
Assert.Equal(proxyActivationId, await proxy.GetActivationId());
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Provider_Error_AfterWrite()
{
Guid id = Guid.NewGuid();
string providerName = ErrorInjectorProviderName;
IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(id);
var val = await grain.GetValue();
int expectedVal = 82;
await grain.DoWrite(expectedVal);
var providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName);
Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1
const int attemptedVal4 = 83;
SetErrorInjection(providerName, ErrorInjectionPoint.AfterWrite);
CheckStorageProviderErrors(() => grain.DoWrite(attemptedVal4));
// Stored value has changed
expectedVal = attemptedVal4;
providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName);
Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1
SetErrorInjection(providerName, ErrorInjectionPoint.None);
val = await grain.GetValue();
Assert.Equal(expectedVal, val); // Returned value
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Provider_Error_BeforeReRead()
{
string grainType = typeof(PersistenceProviderErrorGrain).FullName;
string providerName = ErrorInjectorProviderName;
Guid guid = Guid.NewGuid();
string id = guid.ToString("N");
IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(guid);
var val = await grain.GetValue();
int expectedVal = 72;
SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal);
val = await grain.DoRead();
Assert.Equal(expectedVal, val); // Returned value
expectedVal = 73;
await grain.DoWrite(expectedVal);
var providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName);
Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1
SetErrorInjection(providerName, ErrorInjectionPoint.BeforeRead);
CheckStorageProviderErrors(grain.DoRead);
SetErrorInjection(providerName, ErrorInjectionPoint.None);
val = await grain.GetValue();
Assert.Equal(expectedVal, val); // Returned value
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Provider_Error_AfterReRead()
{
string grainType = typeof(PersistenceProviderErrorGrain).FullName;
string providerName = ErrorInjectorProviderName;
Guid guid = Guid.NewGuid();
string id = guid.ToString("N");
IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(guid);
var val = await grain.GetValue();
int expectedVal = 92;
SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal);
val = await grain.DoRead();
Assert.Equal(expectedVal, val); // Returned value
expectedVal = 93;
await grain.DoWrite(expectedVal);
var providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName);
Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1
expectedVal = 94;
SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal);
SetErrorInjection(providerName, ErrorInjectionPoint.AfterRead);
CheckStorageProviderErrors(grain.DoRead);
SetErrorInjection(providerName, ErrorInjectionPoint.None);
val = await grain.GetValue();
Assert.Equal(expectedVal, val); // Returned value
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Error_Handled_Read()
{
string grainType = typeof(PersistenceUserHandledErrorGrain).FullName;
string providerName = ErrorInjectorProviderName;
Guid guid = Guid.NewGuid();
_ = guid.ToString("N");
IPersistenceUserHandledErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceUserHandledErrorGrain>(guid);
_ = await grain.GetValue(); // Activate grain
int expectedVal = 42;
SetErrorInjection(providerName, ErrorInjectionPoint.None);
SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal);
var val = await grain.DoRead(false);
Assert.Equal(expectedVal, val); // Returned value
int newVal = expectedVal + 1;
SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", newVal);
SetErrorInjection(providerName, ErrorInjectionPoint.BeforeRead);
val = await grain.DoRead(true);
Assert.Equal(expectedVal, val); // Returned value
SetErrorInjection(providerName, ErrorInjectionPoint.None);
expectedVal = newVal;
SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", newVal);
val = await grain.DoRead(false);
Assert.Equal(expectedVal, val); // Returned value
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Error_Handled_Write()
{
string grainType = typeof(PersistenceUserHandledErrorGrain).FullName;
string providerName = ErrorInjectorProviderName;
Guid guid = Guid.NewGuid();
_ = guid.ToString("N");
IPersistenceUserHandledErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceUserHandledErrorGrain>(guid);
_ = await grain.GetValue(); // Activate grain
int expectedVal = 42;
SetErrorInjection(providerName, ErrorInjectionPoint.None);
SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal);
var val = await grain.DoRead(false);
Assert.Equal(expectedVal, val); // Returned value
int newVal = expectedVal + 1;
SetErrorInjection(providerName, ErrorInjectionPoint.BeforeWrite);
await grain.DoWrite(newVal, true);
val = await grain.GetValue();
Assert.Equal(expectedVal, val); // Returned value
SetErrorInjection(providerName, ErrorInjectionPoint.None);
expectedVal = newVal;
await grain.DoWrite(newVal, false);
val = await grain.GetValue();
Assert.Equal(expectedVal, val); // Returned value
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Error_NotHandled_Write()
{
string grainType = typeof(PersistenceUserHandledErrorGrain).FullName;
string providerName = ErrorInjectorProviderName;
Guid guid = Guid.NewGuid();
string id = guid.ToString("N");
IPersistenceUserHandledErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceUserHandledErrorGrain>(guid);
var val = await grain.GetValue(); // Activate grain
int expectedVal = 42;
SetErrorInjection(providerName, ErrorInjectionPoint.None);
SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal);
val = await grain.DoRead(false);
Assert.Equal(expectedVal, val); // Returned value after read
int newVal = expectedVal + 1;
SetErrorInjection(providerName, ErrorInjectionPoint.BeforeWrite);
CheckStorageProviderErrors(() => grain.DoWrite(newVal, false));
val = await grain.GetValue();
// Stored value unchanged
var providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName);
Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1
#if REREAD_STATE_AFTER_WRITE_FAILED
Assert.Equal(expectedVal, val); // After failed write: Last value written successfully
#else
Assert.Equal(newVal, val); // After failed write: Last value attempted to be written is still in memory
#endif
SetErrorInjection(providerName, ErrorInjectionPoint.None);
expectedVal = newVal;
await grain.DoWrite(newVal, false);
val = await grain.GetValue();
Assert.Equal(expectedVal, val); // Returned value after good write
}
[Fact, TestCategory("Stress"), TestCategory("CorePerf"), TestCategory("Persistence")]
public async Task Persistence_Provider_Loop_Read()
{
const int numIterations = 100;
string grainType = typeof(PersistenceTestGrain).FullName;
Task<int>[] promises = new Task<int>[numIterations];
for (int i = 0; i < numIterations; i++)
{
int expectedVal = i;
IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(Guid.NewGuid());
Guid guid = grain.GetPrimaryKey();
_ = guid.ToString("N");
SetStoredValue(MockStorageProviderName1, typeof(MockStorageProvider).FullName, grainType, grain, "Field1", expectedVal); // Update state data behind grain
promises[i] = grain.DoRead();
}
await Task.WhenAll(promises);
for (int i = 0; i < numIterations; i++)
{
int expectedVal = i;
Assert.Equal(expectedVal, promises[i].Result); // "Returned value - Read @ #" + i
}
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Grain_BadProvider()
{
IBadProviderTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IBadProviderTestGrain>(Guid.NewGuid());
var oex = await Assert.ThrowsAsync<BadGrainStorageConfigException>(() => grain.DoSomething());
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public void OrleansException_BadProvider()
{
string msg1 = "BadProvider";
string msg2 = "Wrapper";
string msg3 = "Aggregate";
var bpce = new BadProviderConfigException(msg1);
var oe = new OrleansException(msg2, bpce);
var ae = new AggregateException(msg3, oe);
Assert.NotNull(ae.InnerException); // AggregateException.InnerException should not be null
Assert.IsAssignableFrom<OrleansException>(ae.InnerException);
Exception exc = ae.InnerException;
Assert.NotNull(exc.InnerException); // OrleansException.InnerException should not be null
Assert.IsAssignableFrom<BadProviderConfigException>(exc.InnerException);
exc = ae.GetBaseException();
Assert.NotNull(exc.InnerException); // BaseException.InnerException should not be null
Assert.IsAssignableFrom<BadProviderConfigException>(exc.InnerException);
Assert.StartsWith(msg3, ae.Message); // "AggregateException.Message should be '{0}'", msg3
Assert.Equal(msg2, exc.Message); // "OrleansException.Message should be '{0}'", msg2
Assert.Equal(msg1, exc.InnerException.Message); // "InnerException.Message should be '{0}'", msg1
}
[Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("MemoryStore")]
public async Task MemoryStore_UserGrain_Read_Write()
{
Guid id = Guid.NewGuid();
IUser grain = this.HostedCluster.GrainFactory.GetGrain<IUser>(id);
string name = id.ToString();
await grain.SetName(name);
string readName = await grain.GetName();
Assert.Equal(name, readName); // Read back previously set name
Guid id1 = Guid.NewGuid();
Guid id2 = Guid.NewGuid();
string name1 = id1.ToString();
string name2 = id2.ToString();
IUser friend1 = this.HostedCluster.GrainFactory.GetGrain<IUser>(id1);
IUser friend2 = this.HostedCluster.GrainFactory.GetGrain<IUser>(id2);
await friend1.SetName(name1);
await friend2.SetName(name2);
var readName1 = await friend1.GetName();
var readName2 = await friend2.GetName();
Assert.Equal(name1, readName1); // Friend #1 Name
Assert.Equal(name2, readName2); // Friend #2 Name
await grain.AddFriend(friend1);
await grain.AddFriend(friend2);
var friends = await grain.GetFriends();
Assert.Equal(2, friends.Count); // Number of friends
Assert.Equal(name1, await friends[0].GetName()); // GetFriends - Friend #1 Name
Assert.Equal(name2, await friends[1].GetName()); // GetFriends - Friend #2 Name
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Persistence_Grain_NoState()
{
const string providerName = MockStorageProviderName1;
Guid id = Guid.NewGuid();
IPersistenceNoStateTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceNoStateTestGrain>(id);
await grain.DoSomething();
Assert.True(HasStorageProvider(providerName));
}
[Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("Serialization")]
public void Serialize_GrainState_DeepCopy()
{
// NOTE: This test requires Silo to be running & Client init so that grain references can be resolved before serialization.
IUser[] grains = new IUser[3];
grains[0] = this.HostedCluster.GrainFactory.GetGrain<IUser>(Guid.NewGuid());
grains[1] = this.HostedCluster.GrainFactory.GetGrain<IUser>(Guid.NewGuid());
grains[2] = this.HostedCluster.GrainFactory.GetGrain<IUser>(Guid.NewGuid());
GrainStateContainingGrainReferences initialState = new GrainStateContainingGrainReferences();
foreach (var g in grains)
{
initialState.GrainList.Add(g);
initialState.GrainDict.Add(g.GetPrimaryKey().ToString(), g);
}
var copy = (GrainStateContainingGrainReferences)this.HostedCluster.SerializationManager.DeepCopy(initialState);
Assert.NotSame(initialState.GrainDict, copy.GrainDict); // Dictionary
Assert.NotSame(initialState.GrainList, copy.GrainList); // List
}
[Fact, TestCategory("Persistence"), TestCategory("Serialization"), TestCategory("CorePerf"), TestCategory("Stress")]
public async Task Serialize_GrainState_DeepCopy_Stress()
{
int num = 100;
int loops = num * 100;
GrainStateContainingGrainReferences[] states = new GrainStateContainingGrainReferences[num];
for (int i = 0; i < num; i++)
{
IUser grain = this.HostedCluster.GrainFactory.GetGrain<IUser>(Guid.NewGuid());
states[i] = new GrainStateContainingGrainReferences();
states[i].GrainList.Add(grain);
states[i].GrainDict.Add(grain.GetPrimaryKey().ToString(), grain);
}
List<Task> tasks = new List<Task>();
for (int i = 0; i < loops; i++)
{
int idx = random.Next(num);
tasks.Add(Task.Run(() => { var copy = this.HostedCluster.SerializationManager.DeepCopy(states[idx]); }));
tasks.Add(Task.Run(() => { var other = this.HostedCluster.SerializationManager.RoundTripSerializationForTesting(states[idx]); }));
}
await Task.WhenAll(tasks);
//Task copyTask = Task.Run(() =>
//{
// for (int i = 0; i < loops; i++)
// {
// int idx = random.Next(num);
// var copy = states[idx].DeepCopy();
// }
//});
//Task serializeTask = Task.Run(() =>
//{
// for (int i = 0; i < loops; i++)
// {
// int idx = random.Next(num);
// var other = SerializationManager.RoundTripSerializationForTesting(states[idx]);
// }
//});
//await Task.WhenAll(copyTask, serializeTask);
}
[Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("Scheduler"), TestCategory("Reentrancy")]
public async Task ReentrentGrainWithState()
{
Guid id1 = Guid.NewGuid();
Guid id2 = Guid.NewGuid();
IReentrentGrainWithState grain1 = this.HostedCluster.GrainFactory.GetGrain<IReentrentGrainWithState>(id1);
IReentrentGrainWithState grain2 = this.HostedCluster.GrainFactory.GetGrain<IReentrentGrainWithState>(id2);
await Task.WhenAll(grain1.Setup(grain2), grain2.Setup(grain1));
Task t11 = grain1.Test1();
Task t12 = grain1.Test2();
Task t21 = grain2.Test1();
Task t22 = grain2.Test2();
await Task.WhenAll(t11, t12, t21, t22);
}
[Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("Scheduler"), TestCategory("Reentrancy")]
public async Task NonReentrentStressGrainWithoutState()
{
Guid id1 = Guid.NewGuid();
INonReentrentStressGrainWithoutState grain1 = this.HostedCluster.GrainFactory.GetGrain<INonReentrentStressGrainWithoutState>(id1);
await grain1.Test1();
}
private const bool DoStart = true; // Task.Delay tests fail (Timeout) unless True
[Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("Scheduler"), TestCategory("Reentrancy")]
public async Task ReentrentGrain_Task_Delay()
{
Guid id1 = Guid.NewGuid();
IReentrentGrainWithState grain1 = this.HostedCluster.GrainFactory.GetGrain<IReentrentGrainWithState>(id1);
await grain1.Task_Delay(DoStart);
}
[Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("Scheduler"), TestCategory("Reentrancy")]
public async Task NonReentrentGrain_Task_Delay()
{
Guid id1 = Guid.NewGuid();
INonReentrentStressGrainWithoutState grain1 = this.HostedCluster.GrainFactory.GetGrain<INonReentrentStressGrainWithoutState>(id1);
await grain1.Task_Delay(DoStart);
}
[Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("Scheduler"), TestCategory("Reentrancy")]
public async Task StateInheritanceTest()
{
Guid id1 = Guid.NewGuid();
IStateInheritanceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IStateInheritanceTestGrain>(id1);
await grain.SetValue(1);
int val = await grain.GetValue();
Assert.Equal(1, val);
}
// ---------- Utility functions ----------
private void SetStoredValue(string providerName, string providerTypeFullName, string grainType, IGrain grain, string fieldName, int newValue)
{
IManagementGrain mgmtGrain = this.HostedCluster.GrainFactory.GetGrain<IManagementGrain>(0);
// set up SetVal func args
var args = new MockStorageProvider.SetValueArgs
{
Val = newValue,
Name = "Field1",
GrainType = grainType,
GrainReference = (GrainReference) grain,
StateType = typeof(PersistenceTestGrainState)
};
mgmtGrain.SendControlCommandToProvider(providerTypeFullName,
providerName, (int)MockStorageProvider.Commands.SetValue, args).Wait();
}
private void SetErrorInjection(string providerName, ErrorInjectionPoint errorInjectionPoint)
{
SetErrorInjection(providerName, new ErrorInjectionBehavior { ErrorInjectionPoint = errorInjectionPoint });
}
private void SetErrorInjection(string providerName, ErrorInjectionBehavior errorInjectionBehavior)
{
ErrorInjectionStorageProvider.SetErrorInjection(providerName, errorInjectionBehavior, this.HostedCluster.GrainFactory);
}
private void CheckStorageProviderErrors(Func<Task> taskFunc, Type expectedException = null)
{
StackTrace at = new StackTrace();
TimeSpan timeout = Debugger.IsAttached ? TimeSpan.FromMinutes(5) : TimeSpan.FromSeconds(15);
try
{
taskFunc().WithTimeout(timeout).GetAwaiter().GetResult();
if (ErrorInjectionStorageProvider.DoInjectErrors)
{
string msg = "StorageProviderInjectedError exception should have been thrown " + at;
output.WriteLine("Assertion failed: {0}", msg);
Assert.True(false, msg);
}
}
catch (Exception e)
{
output.WriteLine("Exception caught: {0}", e);
var baseException = e.GetBaseException();
if (baseException is OrleansException && baseException.InnerException != null)
{
baseException = baseException.InnerException;
}
Assert.IsAssignableFrom(expectedException ?? typeof(StorageProviderInjectedError), baseException);
//if (exc is StorageProviderInjectedError)
//{
// //Expected error
//}
//else
//{
// output.WriteLine("Unexpected exception: {0}", exc);
// Assert.True(false, exc.ToString());
//}
}
}
private bool HasStorageProvider(string providerName)
{
foreach (var siloHandle in this.HostedCluster.GetActiveSilos())
{
if (this.HostedCluster.Client.GetTestHooks(siloHandle).HasStorageProvider(providerName).Result)
{
return true;
}
}
return false;
}
private ProviderState GetStateForStorageProviderInUse(string providerName, string providerTypeFullName, bool okNull = false)
{
ProviderState providerState = new ProviderState();
IManagementGrain mgmtGrain = this.HostedCluster.GrainFactory.GetGrain<IManagementGrain>(0);
object[] replies = mgmtGrain.SendControlCommandToProvider(providerTypeFullName,
providerName, (int)MockStorageProvider.Commands.GetProvideState, null).Result;
object[] replies2 = mgmtGrain.SendControlCommandToProvider(providerTypeFullName,
providerName, (int)MockStorageProvider.Commands.GetLastState, null).Result;
for(int i = 0; i < replies.Length; i++)
{
MockStorageProvider.StateForTest state = (MockStorageProvider.StateForTest)replies[i];
PersistenceTestGrainState grainState = (PersistenceTestGrainState)replies2[i];
if (state.ReadCount > 0)
{
providerState.ProviderStateForTest = state;
providerState.LastStoredGrainState = grainState;
return providerState;
}
}
return providerState;
}
class ProviderState
{
public MockStorageProvider.StateForTest ProviderStateForTest { get; set; }
public PersistenceTestGrainState LastStoredGrainState { get; set; }
}
private void ResetMockStorageProvidersHistory()
{
var mockStorageProviders = new[] { MockStorageProviderName1, MockStorageProviderName2, MockStorageProviderNameLowerCase };
foreach (var siloHandle in this.HostedCluster.GetActiveSilos().ToList())
{
foreach (var providerName in mockStorageProviders)
{
if (!this.HostedCluster.Client.GetTestHooks(siloHandle).HasStorageProvider(providerName).Result) continue;
IManagementGrain mgmtGrain = this.HostedCluster.GrainFactory.GetGrain<IManagementGrain>(0);
_ = mgmtGrain.SendControlCommandToProvider(typeof(MockStorageProvider).FullName,
providerName, (int)MockStorageProvider.Commands.ResetHistory, null).Result;
}
}
}
}
}
// ReSharper restore RedundantAssignment
// ReSharper restore UnusedVariable
// ReSharper restore InconsistentNaming
| |
using System;
using System.Collections.Generic;
using System.Linq;
using FizzWare.NBuilder;
using FluentValidation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using NerdBudget.Core.Models;
using NerdBudget.Core.Repositories;
using NerdBudget.Core.Services;
namespace NerdBudget.Tests.Core.Services
{
[TestClass]
public class BudgetServiceTests : ServiceTestHelper<Budget, BudgetService, IBudgetRepository>
{
#region Helpers/Test Initializers
private const int CountOfCategories = 10;
private const int CountOfBudgets = 3;
[TestInitialize]
public override void TestInitialize()
{
base.TestInitialize();
}
private Account GetAccount()
{
var account = Builder<Account>.CreateNew().Build();
var categories = Builder<Category>.CreateListOfSize(CountOfCategories)
.Build();
account.Categories.AddRange(categories);
foreach (var c in account.Categories)
{
var budgets = Builder<Budget>.CreateListOfSize(CountOfBudgets).Build();
foreach (var b in budgets)
{
b.Id = c.Id + b.Id;
c.Budgets.Add(b);
}
}
return account;
}
#endregion
#region Tests - Insert
[TestMethod]
public void BudgetService_Insert_Should_Succeed()
{
// arrange
var budget = Builder<Budget>.CreateNew()
.With(x => x.Id = "")
.With(x => x.CreatedAt = DateTime.MinValue)
.Build();
var account = GetAccount();
var category = account.Categories.Last();
var po = new PrivateObject(account);
var allBudgets = po.GetProperty("Budgets") as BudgetCollection;
MockRepo.Setup(x => x.Save(budget));
MockValidator.Setup(x => x.Validate(budget)).Returns(ValidationSuccess);
// act
SubjectUnderTest.Insert(category, budget);
// assert
Assert.AreEqual(CountOfBudgets + 1, category.Budgets.Count);
Assert.AreEqual(account.Id, budget.AccountId);
Assert.AreEqual(category.Id, budget.CategoryId);
Assert.AreEqual(category.Budgets.Count * 10 - 10, budget.Sequence);
Assert.AreNotEqual(DateTime.MinValue, budget.CreatedAt);
Assert.AreNotEqual("", budget.Id);
// Since we didn't load ACCOUNT from the database, our test will
// only have the newly inserted budget for the "ALL" FK
Assert.AreEqual(1, allBudgets.Count);
MockRepo.VerifyAll();
MockValidator.VerifyAll();
}
[TestMethod, ExpectedException(typeof(ValidationException))]
public void BudgetService_Insert_Should_ThrowException()
{
// arrange
var budget = Builder<Budget>.CreateNew()
.With(x => x.Id = "")
.With(x => x.CreatedAt = DateTime.MinValue)
.Build();
var account = GetAccount();
var category = account.Categories.Last();
MockRepo.Setup(x => x.Save(budget));
MockValidator.Setup(x => x.Validate(budget)).Returns(ValidationFailure);
// act
SubjectUnderTest.Insert(category, budget);
}
#endregion
#region Tests - Update
[TestMethod]
public void BudgetService_Update_Should_Succeed()
{
// arrange
var account = GetAccount();
var category = account.Categories.Last();
var budget = category.Budgets.Last();
budget.UpdatedAt = DateTime.MinValue;
MockRepo.Setup(x => x.Save(budget));
MockValidator.Setup(x => x.Validate(budget)).Returns(ValidationSuccess);
// act
SubjectUnderTest.Update(budget);
// assert
Assert.AreNotEqual(DateTime.MinValue, budget.UpdatedAt);
MockRepo.VerifyAll();
MockValidator.VerifyAll();
}
[TestMethod]
public void BudgetService_Update_Should_Succeed_WithDifferentCategory()
{
// arrange
var account = GetAccount();
var goToCat = account.Categories.First();
var isFromCat = account.Categories.Last();
var budget = isFromCat.Budgets.Last();
budget.CategoryId = goToCat.Id;
budget.UpdatedAt = DateTime.MinValue;
MockRepo.Setup(x => x.Save(budget));
MockValidator.Setup(x => x.Validate(budget)).Returns(ValidationSuccess);
// act
SubjectUnderTest.Update(budget);
// assert
Assert.AreNotEqual(DateTime.MinValue, budget.UpdatedAt);
Assert.AreEqual(CountOfBudgets + 1, goToCat.Budgets.Count);
Assert.AreEqual(CountOfBudgets - 1, isFromCat.Budgets.Count);
MockRepo.VerifyAll();
MockValidator.VerifyAll();
}
[TestMethod, ExpectedException(typeof(ValidationException))]
public void BudgetService_Update_Should_ThrowException()
{
// arrange
var budget = Builder<Budget>.CreateNew().Build();
MockRepo.Setup(x => x.Save(budget));
MockValidator.Setup(x => x.Validate(budget)).Returns(ValidationFailure);
// act
SubjectUnderTest.Update(budget);
}
[TestMethod]
public void BudgetService_UpdateMany_Should_Succeed()
{
// arrange
var account = GetAccount();
var category = account.Categories.Last();
MockRepo.Setup(x => x.Save(category.Budgets));
MockValidator.Setup(x => x.Validate(Any.Item)).Returns(ValidationSuccess);
// act
SubjectUnderTest.Update(category.Budgets);
// assert
foreach (var b in category.Budgets)
{
Assert.AreNotEqual(DateTime.MinValue, b.UpdatedAt);
}
MockRepo.VerifyAll();
MockValidator.VerifyAll();
}
[TestMethod, ExpectedException(typeof(ValidationException))]
public void BudgetService_UpdateMany_Should_ThrowException()
{
// arrange
var budgets = Builder<Budget>.CreateListOfSize(10).Build();
MockRepo.Setup(x => x.Save(budgets));
MockValidator.Setup(x => x.Validate(It.IsAny<Budget>())).Returns(ValidationFailure);
// act
SubjectUnderTest.Update(budgets);
}
#endregion
#region Tests - Delete
[TestMethod]
public void BudgetService_Delete_Should_Succeed()
{
// arrange
var account = GetAccount();
var category = account.Categories.Last();
var budget = category.Budgets.Last();
MockRepo.Setup(x => x.Delete(budget));
// act
SubjectUnderTest.Delete(budget);
// assert
Assert.AreEqual(CountOfBudgets - 1, category.Budgets.Count);
MockRepo.VerifyAll();
}
#endregion
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using SRC = System.Runtime.CompilerServices;
namespace Microsoft.PythonTools.Analysis {
static class IdDispenser {
// The one and only comparer instance.
private static readonly IEqualityComparer<object> _comparer = new WrapperComparer();
private static Dictionary<object, object> _hashtable = new Dictionary<object, object>(_comparer);
private static readonly Object _synchObject = new Object(); // The one and only global lock instance.
// We do not need to worry about duplicates that to using long for unique Id.
// It takes more than 100 years to overflow long on year 2005 hardware.
private static long _currentId = 0; // Last unique Id we have given out.
// cleanupId and cleanupGC are used for efficient scheduling of hashtable cleanups
private static long _cleanupId; // currentId at the time of last cleanup
private static int _cleanupGC; // GC.CollectionCount(0) at the time of last cleanup
public static void Clear() {
lock (_synchObject) {
_hashtable.Clear();
_currentId = 0;
}
}
/// <summary>
/// Given an ID returns the object associated with that ID.
/// </summary>
public static object GetObject(long id) {
lock (_synchObject) {
foreach (Wrapper w in _hashtable.Keys) {
if (w.Target != null) {
if (w.Id == id) return w.Target;
}
}
return null;
}
}
/// <summary>
/// Gets a unique ID for an object if it has been assigned one.
/// </summary>
public static bool TryGetId(Object o, out long id) {
if (o == null) {
id = 0;
return true;
}
lock (_synchObject) {
// If the object exists then return its existing ID.
object res;
if (_hashtable.TryGetValue(o, out res)) {
id = ((Wrapper)res).Id;
return true;
}
}
id = 0;
return false;
}
/// <summary>
/// Gets a unique ID for an object
/// </summary>
public static long GetId(Object o) {
if (o == null)
return 0;
lock (_synchObject) {
// If the object exists then return its existing ID.
object res;
if (_hashtable.TryGetValue(o, out res)) {
return ((Wrapper)res).Id;
}
long uniqueId = checked(++_currentId);
long change = uniqueId - _cleanupId;
// Cleanup the table if it is a while since we have done it last time.
// Take the size of the table into account.
if (change > 1234 + _hashtable.Count / 2) {
// It makes sense to do the cleanup only if a GC has happened in the meantime.
// WeakReferences can become zero only during the GC.
int currentGC = GC.CollectionCount(0);
if (currentGC != _cleanupGC) {
Cleanup();
_cleanupId = uniqueId;
_cleanupGC = currentGC;
} else {
_cleanupId += 1234;
}
}
Wrapper w = new Wrapper(o, uniqueId);
_hashtable[w] = w;
return uniqueId;
}
}
/// <summary>
/// Goes over the hashtable and removes empty entries
/// </summary>
private static void Cleanup() {
int liveCount = 0;
int emptyCount = 0;
foreach (Wrapper w in _hashtable.Keys) {
if (w.Target != null)
liveCount++;
else
emptyCount++;
}
// Rehash the table if there is a significant number of empty slots
if (emptyCount > liveCount / 4) {
Dictionary<object, object> newtable = new Dictionary<object, object>(liveCount + liveCount / 4, _comparer);
foreach (Wrapper w in _hashtable.Keys) {
if (w.Target != null)
newtable[w] = w;
}
_hashtable = newtable;
}
}
/// <summary>
/// Weak-ref wrapper caches the weak reference, our hash code, and the object ID.
/// </summary>
private sealed class Wrapper {
private WeakReference _weakReference;
private int _hashCode;
private long _id;
public Wrapper(Object obj, long uniqueId) {
_weakReference = new WeakReference(obj, true);
_hashCode = (obj == null) ? 0 : SRC.RuntimeHelpers.GetHashCode(obj);
_id = uniqueId;
}
public long Id {
get {
return _id;
}
}
public Object Target {
get {
return _weakReference.Target;
}
}
public override int GetHashCode() {
return _hashCode;
}
}
/// <summary>
/// WrapperComparer treats Wrapper as transparent envelope
/// </summary>
private sealed class WrapperComparer : IEqualityComparer<object> {
bool IEqualityComparer<object>.Equals(Object x, Object y) {
Wrapper wx = x as Wrapper;
if (wx != null)
x = wx.Target;
Wrapper wy = y as Wrapper;
if (wy != null)
y = wy.Target;
return Object.ReferenceEquals(x, y);
}
int IEqualityComparer<object>.GetHashCode(Object obj) {
Wrapper wobj = obj as Wrapper;
if (wobj != null)
return wobj.GetHashCode();
return GetHashCodeWorker(obj);
}
private static int GetHashCodeWorker(object o) {
if (o == null) return 0;
return SRC.RuntimeHelpers.GetHashCode(o);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
// using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal static class FileTextLoaderOptions
{
/// <summary>
/// Hidden registry key to control maximum size of a text file we will read into memory.
/// we have this option to reduce a chance of OOM when user adds massive size files to the solution.
/// Default threshold is 100MB which came from some internal data on big files and some discussion.
///
/// User can override default value by setting DWORD value on FileLengthThreshold in
/// "[VS HIVE]\Roslyn\Internal\Performance\Text"
/// </summary>
// [ExportOption]
internal static readonly Option<long> FileLengthThreshold = new Option<long>(nameof(FileTextLoaderOptions), nameof(FileLengthThreshold), defaultValue: 100 * 1024 * 1024,
storageLocations: new LocalUserProfileStorageLocation(@"Roslyn\Internal\Performance\Text\FileLengthThreshold"));
}
[DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
public class FileTextLoader : TextLoader
{
private readonly string _path;
private readonly Encoding _defaultEncoding;
/// <summary>
/// Creates a content loader for specified file.
/// </summary>
/// <param name="path">An absolute file path.</param>
/// <param name="defaultEncoding">
/// Specifies an encoding to be used if the actual encoding can't be determined from the stream content (the stream doesn't start with Byte Order Mark).
/// If not specified auto-detect heuristics are used to determine the encoding. If these heuristics fail the decoding is assumed to be <see cref="Encoding.Default"/>.
/// Note that if the stream starts with Byte Order Mark the value of <paramref name="defaultEncoding"/> is ignored.
/// </param>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="path"/> is not an absolute path.</exception>
public FileTextLoader(string path, Encoding defaultEncoding)
{
CompilerPathUtilities.RequireAbsolutePath(path, "path");
_path = path;
_defaultEncoding = defaultEncoding;
}
/// <summary>
/// Absolute path of the file.
/// </summary>
public string Path
{
get { return _path; }
}
/// <summary>
/// Specifies an encoding to be used if the actual encoding of the file
/// can't be determined from the stream content (the stream doesn't start with Byte Order Mark).
/// If <c>null</c> auto-detect heuristics are used to determine the encoding.
/// If these heuristics fail the decoding is assumed to be <see cref="Encoding.Default"/>.
/// Note that if the stream starts with Byte Order Mark the value of <see cref="DefaultEncoding"/> is ignored.
/// </summary>
public Encoding DefaultEncoding
{
get { return _defaultEncoding; }
}
protected virtual SourceText CreateText(Stream stream, Workspace workspace)
{
var factory = workspace.Services.GetService<ITextFactoryService>();
return factory.CreateText(stream, _defaultEncoding);
}
/// <summary>
/// Load a text and a version of the document in the workspace.
/// </summary>
/// <exception cref="IOException"></exception>
/// <exception cref="InvalidDataException"></exception>
public override async Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
{
ValidateFileLength(workspace, _path);
DateTime prevLastWriteTime = FileUtilities.GetFileTimeStamp(_path);
TextAndVersion textAndVersion;
// In many .NET Framework versions (specifically the 4.5.* series, but probably much earlier
// and also later) there is this particularly interesting bit in FileStream.BeginReadAsync:
//
// // [ed: full comment clipped for brevity]
// //
// // If we did a sync read to fill the buffer, we could avoid the
// // problem, and any async read less than 64K gets turned into a
// // synchronous read by NT anyways...
// if (numBytes < _bufferSize)
// {
// if (_buffer == null) _buffer = new byte[_bufferSize];
// IAsyncResult bufferRead = BeginReadCore(_buffer, 0, _bufferSize, null, null, 0);
// _readLen = EndRead(bufferRead);
//
// In English, this means that if you do a asynchronous read for smaller than _bufferSize,
// this is implemented by the framework by starting an asynchronous read, and then
// blocking your thread until that read is completed. The comment implies this is "fine"
// because the asynchronous read will actually be synchronous and thus EndRead won't do
// any blocking -- it'll be an effective no-op. In theory, everything is fine here.
//
// In reality, this can end very poorly. That read in fact can be asynchronous, which means the
// EndRead will enter a wait and block the thread. If we are running that call to ReadAsync on a
// thread pool thread that completed a previous piece of IO, it means there has to be another
// thread available to service the completion of that request in order for our thread to make
// progress. Why is this worse than the claim about the operating system turning an
// asynchronous read into a synchronous one? If the underlying native ReadFile completes
// synchronously, that would mean just our thread is being blocked, and will be unblocked once
// the kernel gets done with our work. In this case, if the OS does do the read asynchronously
// we are now dependent on another thread being available to unblock us.
//
// So how does ths manifest itself? We have seen dumps from customers reporting hangs where
// we have over a hundred thread pool threads all blocked on EndRead() calls as we read this stream.
// In these cases, the user had just completed a build that had a bunch of XAML files, and
// this resulted in many .g.i.cs files being written and updated. As a result, Roslyn is trying to
// re-read them to provide a new compilation to the XAML language service that is asking for it.
// Inspecting these dumps and sampling some of the threads made some notable discoveries:
//
// 1. When there was a read blocked, it was the _last_ chunk that we were reading in the file in
// the file that we were reading. This leads me to believe that it isn't simply very slow IO
// (like a network drive), because in that case I'd expect to see some threads in different
// places than others.
// 2. Some stacks were starting by the continuation of a ReadAsync, and some were the first read
// of a file from the background parser. In the first case, all of those threads were if the
// files were over 4K in size. The ones with the BackgroundParser still on the stack were files
// less than 4K in size.
// 3. The "time unresponsive" in seconds correlated with roughly the number of threads we had
// blocked, which makes me think we were impacted by the once-per-second hill climbing algorithm
// used by the thread pool.
//
// So what's my analysis? When the XAML language service updated all the files, we kicked off
// background parses for all of them. If the file was over 4K the asynchronous read actually did
// happen (see point #2), but we'd eventually block the thread pool reading the last chunk.
// Point #1 confirms that it was always the last chunk. And in small file cases, we'd block on
// the first chunk. But in either case, we'd be blocking off a thread pool thread until another
// thread pool thread was available. Since we had enough requests going (over a hundred),
// sometimes the user got unlucky and all the threads got blocked. At this point, the CLR
// started slowly kicking off more threads, but each time it'd start a new thread rather than
// starting work that would be needed to unblock a thread, it just handled an IO that resulted
// in another file read hitting the end of the file and another thread would get blocked. The
// CLR then must kick off another thread, rinse, repeat. Eventually it'll make progress once
// there's no more pending IO requests, everything will complete, and life then continues.
//
// To work around this issue, we set bufferSize to 1, which means that all reads should bypass
// this logic. This is tracked by https://github.com/dotnet/corefx/issues/6007, at least in
// corefx. We also open the file for reading with FileShare mode read/write/delete so that
// we do not lock this file.
using (var stream = FileUtilities.RethrowExceptionsAsIOException(() => new FileStream(_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, bufferSize: 1, useAsync: true)))
{
var version = VersionStamp.Create(prevLastWriteTime);
// we do this so that we asynchronously read from file. and this should allocate less for IDE case.
// but probably not for command line case where it doesn't use more sophisticated services.
using (var readStream = await SerializableBytes.CreateReadableStreamAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false))
{
var text = CreateText(readStream, workspace);
textAndVersion = TextAndVersion.Create(text, version, _path);
}
}
// Check if the file was definitely modified and closed while we were reading. In this case, we know the read we got was
// probably invalid, so throw an IOException which indicates to our caller that we should automatically attempt a re-read.
// If the file hasn't been closed yet and there's another writer, we will rely on file change notifications to notify us
// and reload the file.
DateTime newLastWriteTime = FileUtilities.GetFileTimeStamp(_path);
if (!newLastWriteTime.Equals(prevLastWriteTime))
{
var message = string.Format(WorkspacesResources.File_was_externally_modified_colon_0, _path);
throw new IOException(message);
}
return textAndVersion;
}
/// <summary>
/// Load a text and a version of the document in the workspace.
/// </summary>
/// <exception cref="IOException"></exception>
/// <exception cref="InvalidDataException"></exception>
// internal
#pragma warning disable RS0016 // Add public types and members to the declared API
public override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
#pragma warning restore RS0016 // Add public types and members to the declared API
{
//base.LoadTextAndVersionAsync
ValidateFileLength(workspace, _path);
DateTime prevLastWriteTime = FileUtilities.GetFileTimeStamp(_path);
TextAndVersion textAndVersion;
// Open file for reading with FileShare mode read/write/delete so that we do not lock this file.
using (var stream = FileUtilities.RethrowExceptionsAsIOException(() => new FileStream(_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, bufferSize: 4096, useAsync: false)))
{
var version = VersionStamp.Create(prevLastWriteTime);
var text = CreateText(stream, workspace);
textAndVersion = TextAndVersion.Create(text, version, _path);
}
// Check if the file was definitely modified and closed while we were reading. In this case, we know the read we got was
// probably invalid, so throw an IOException which indicates to our caller that we should automatically attempt a re-read.
// If the file hasn't been closed yet and there's another writer, we will rely on file change notifications to notify us
// and reload the file.
DateTime newLastWriteTime = FileUtilities.GetFileTimeStamp(_path);
if (!newLastWriteTime.Equals(prevLastWriteTime))
{
var message = string.Format(WorkspacesResources.File_was_externally_modified_colon_0, _path);
throw new IOException(message);
}
return textAndVersion;
}
private string GetDebuggerDisplay()
{
return nameof(Path) + " = " + Path;
}
private static void ValidateFileLength(Workspace workspace, string path)
{
// Validate file length is under our threshold.
// Otherwise, rather than reading the content into the memory, we will throw
// InvalidDataException to caller of FileTextLoader.LoadText to deal with
// the situation.
//
// check this (http://source.roslyn.io/#Microsoft.CodeAnalysis.Workspaces/Workspace/Solution/TextDocumentState.cs,132)
// to see how workspace deal with exception from FileTextLoader. other consumer can handle the exception differently
var fileLength = FileUtilities.GetFileLength(path);
var threshold = workspace.Options.GetOption(FileTextLoaderOptions.FileLengthThreshold);
if (fileLength > threshold)
{
// log max file length which will log to VS telemetry in VS host
Logger.Log(FunctionId.FileTextLoader_FileLengthThresholdExceeded, KeyValueLogMessage.Create(m =>
{
m["FileLength"] = fileLength;
m["Ext"] = PathUtilities.GetExtension(path);
}));
var message = string.Format(WorkspacesResources.File_0_size_of_1_exceeds_maximum_allowed_size_of_2, path, fileLength, threshold);
throw new InvalidDataException(message);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using NitroNet.Common.Exceptions;
using NitroNet.ViewEngine.Config;
using NitroNet.ViewEngine.IO;
namespace NitroNet.ViewEngine
{
public class NitroTemplateRepository : ITemplateRepository, IDisposable
{
private readonly IFileSystem _fileSystem;
private readonly INitroNetConfig _configuration;
private readonly IEnumerable<Regex> _filters;
private Dictionary<string, FileTemplateInfo> _templates;
private Dictionary<string, List<FileTemplateInfo>> _templatesByName;
private IEnumerable<IDisposable> _viewSubscriptions;
private IEnumerable<IDisposable> _partialSubscriptions;
private IEnumerable<IDisposable> _componentSubscriptions;
public NitroTemplateRepository(IFileSystem fileSystem, INitroNetConfig configuration)
{
_fileSystem = fileSystem;
_configuration = configuration;
if (_configuration.Filters == null || !_configuration.Filters.Any())
{
_filters = new List<Regex>();
}
else
{
_filters = _configuration.Filters.Select(f => new Regex(f, RegexOptions.Compiled));
}
InitCache();
if (!_fileSystem.SupportsSubscribe)
return;
var componentSubscriptions = new List<IDisposable>();
foreach (var componentPath in _configuration.ComponentPaths)
{
foreach (var configurationExtension in _configuration.Extensions)
{
componentSubscriptions.Add(
_fileSystem.SubscribeDirectoryGetFilesAsync(PathInfo.Create(componentPath.ToString()),
configurationExtension, files => InitCache()));
}
}
_componentSubscriptions = componentSubscriptions;
var partialSubscriptions = new List<IDisposable>();
foreach (var partialPath in _configuration.PartialPaths)
{
foreach (var configurationExtension in _configuration.Extensions)
{
partialSubscriptions.Add(
_fileSystem.SubscribeDirectoryGetFilesAsync(PathInfo.Create(partialPath.ToString()),
configurationExtension, files => InitCache()));
}
}
_partialSubscriptions = partialSubscriptions;
var viewSubscriptions = new List<IDisposable>();
foreach (var viewPath in _configuration.ViewPaths)
{
foreach (var configurationExtension in _configuration.Extensions)
{
viewSubscriptions.Add(
_fileSystem.SubscribeDirectoryGetFilesAsync(PathInfo.Create(viewPath.ToString()),
configurationExtension, files => InitCache()));
}
}
_viewSubscriptions = viewSubscriptions;
}
private void InitCache()
{
List<FileTemplateInfo> viewTemplates = new List<FileTemplateInfo>();
foreach (var viewPath in _configuration.ViewPaths)
{
foreach (var configurationExtension in _configuration.Extensions)
{
viewTemplates.AddRange(
_fileSystem.DirectoryGetFiles(viewPath, configurationExtension).Select(f =>
{
var relativePath = GetTemplateId(f).RemoveStartSlash();
return new FileTemplateInfo(relativePath.ToString(), TemplateType.View, f, _fileSystem);
}));
}
}
List<FileTemplateInfo> partialTemplates = new List<FileTemplateInfo>();
foreach (var partialPath in _configuration.PartialPaths)
{
foreach (var configurationExtension in _configuration.Extensions)
{
partialTemplates.AddRange(
_fileSystem.DirectoryGetFiles(partialPath, configurationExtension).Select(f =>
{
var relativePath = GetTemplateId(f).RemoveStartSlash();
return new FileTemplateInfo(relativePath.ToString(), TemplateType.Partial, f, _fileSystem);
}));
}
}
List<FileTemplateInfo> componentTemplates = new List<FileTemplateInfo>();
foreach (var componentPath in _configuration.ComponentPaths)
{
foreach (var configurationExtension in _configuration.Extensions)
{
componentTemplates.AddRange(
_fileSystem.DirectoryGetFiles(componentPath, configurationExtension).Select(f =>
{
var relativePath = GetTemplateId(f).RemoveStartSlash();
return new FileTemplateInfo(relativePath.ToString(), TemplateType.Component, f, _fileSystem);
}));
}
}
var templates = componentTemplates
.Concat(partialTemplates)
.Concat(viewTemplates)
.GroupBy(p => p.Id, StringComparer.InvariantCultureIgnoreCase)
.ToDictionary(i => i.Key, i => i.First(), StringComparer.InvariantCultureIgnoreCase);
_templates = FilterTemplates(templates);
_templatesByName = new Dictionary<string, List<FileTemplateInfo>>();
foreach (var template in _templates)
{
var templateName = template.Value.Name;
if (_templatesByName.ContainsKey(templateName))
{
_templatesByName[templateName].Add(template.Value);
}
else
{
_templatesByName[templateName] = new List<FileTemplateInfo> { template.Value };
}
}
}
public Task<TemplateInfo> GetTemplateAsync(string id)
{
FileTemplateInfo templateInfo;
if (_templates.TryGetValue(id, out templateInfo))
return Task.FromResult<TemplateInfo>(templateInfo);
List<FileTemplateInfo> templateInfos;
if (_templatesByName.TryGetValue(id, out templateInfos))
{
if (templateInfos.Count > 1)
{
throw new NitroNetTemplateNotFoundException(
string.Format("Couldn't find view template. There is more than one template with id {0}. Please specify the view name including the path relative to the NitroNet root folder.", id));
}
return Task.FromResult<TemplateInfo>(templateInfos.FirstOrDefault());
}
return Task.FromResult<TemplateInfo>(null);
}
public Task<IEnumerable<TemplateInfo>> GetTemplatesByNameAsync(string name)
{
List<FileTemplateInfo> templateInfo;
if (_templatesByName.TryGetValue(name, out templateInfo))
return Task.FromResult((IEnumerable<TemplateInfo>)templateInfo);
return Task.FromResult((IEnumerable<TemplateInfo>)new List<TemplateInfo>());
}
private PathInfo GetTemplateId(PathInfo info)
{
return _fileSystem.Path.Combine(_fileSystem.Path.GetDirectoryName(info), _fileSystem.Path.GetFileNameWithoutExtension(info));
}
public IEnumerable<TemplateInfo> GetAll()
{
return _templates.Values;
}
~NitroTemplateRepository()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual Dictionary<string, FileTemplateInfo> FilterTemplates(Dictionary<string, FileTemplateInfo> templates)
{
if (!_filters.Any())
{
return templates;
}
var filteredTemplates = new Dictionary<string, FileTemplateInfo>();
foreach (var template in templates)
{
var isFiltered = false;
foreach (var filter in _filters)
{
if (filter.IsMatch(template.Value.Path.ToString()))
{
isFiltered = true;
}
}
if (!isFiltered)
{
filteredTemplates.Add(template.Key, template.Value);
}
}
return filteredTemplates;
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
foreach (var componentSubscription in _componentSubscriptions)
{
componentSubscription.Dispose();
}
foreach (var partialSubscription in _partialSubscriptions)
{
partialSubscription.Dispose();
}
foreach (var viewSubscription in _viewSubscriptions)
{
viewSubscription.Dispose();
}
}
_componentSubscriptions = null;
_partialSubscriptions = null;
_viewSubscriptions = null;
}
}
}
| |
//
// This file was generated by the BinaryNotes compiler.
// See http://bnotes.sourceforge.net
// Any modifications to this file will be lost upon recompilation of the source ASN.1.
//
using GSF.ASN1;
using GSF.ASN1.Attributes;
using GSF.ASN1.Coders;
namespace GSF.MMS.Model
{
[ASN1PreparedElement]
[ASN1Sequence(Name = "DefineAccessControlList_Request", IsSet = false)]
public class DefineAccessControlList_Request : IASN1PreparedElement
{
private static readonly IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(DefineAccessControlList_Request));
private AccessControlListElementsSequenceType accessControlListElements_;
private Identifier accessControlListName_;
[ASN1Element(Name = "accessControlListName", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)]
public Identifier AccessControlListName
{
get
{
return accessControlListName_;
}
set
{
accessControlListName_ = value;
}
}
[ASN1Element(Name = "accessControlListElements", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)]
public AccessControlListElementsSequenceType AccessControlListElements
{
get
{
return accessControlListElements_;
}
set
{
accessControlListElements_ = value;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
[ASN1PreparedElement]
[ASN1Sequence(Name = "accessControlListElements", IsSet = false)]
public class AccessControlListElementsSequenceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(AccessControlListElementsSequenceType));
private AccessCondition deleteAccessCondition_;
private bool deleteAccessCondition_present;
private AccessCondition editAccessCondition_;
private bool editAccessCondition_present;
private AccessCondition executeAccessCondition_;
private bool executeAccessCondition_present;
private AccessCondition loadAccessCondition_;
private bool loadAccessCondition_present;
private AccessCondition readAccessCondition_;
private bool readAccessCondition_present;
private AccessCondition storeAccessCondition_;
private bool storeAccessCondition_present;
private AccessCondition writeAccessCondition_;
private bool writeAccessCondition_present;
[ASN1Element(Name = "readAccessCondition", IsOptional = true, HasTag = true, Tag = 0, HasDefaultValue = false)]
public AccessCondition ReadAccessCondition
{
get
{
return readAccessCondition_;
}
set
{
readAccessCondition_ = value;
readAccessCondition_present = true;
}
}
[ASN1Element(Name = "storeAccessCondition", IsOptional = true, HasTag = true, Tag = 1, HasDefaultValue = false)]
public AccessCondition StoreAccessCondition
{
get
{
return storeAccessCondition_;
}
set
{
storeAccessCondition_ = value;
storeAccessCondition_present = true;
}
}
[ASN1Element(Name = "writeAccessCondition", IsOptional = true, HasTag = true, Tag = 2, HasDefaultValue = false)]
public AccessCondition WriteAccessCondition
{
get
{
return writeAccessCondition_;
}
set
{
writeAccessCondition_ = value;
writeAccessCondition_present = true;
}
}
[ASN1Element(Name = "loadAccessCondition", IsOptional = true, HasTag = true, Tag = 3, HasDefaultValue = false)]
public AccessCondition LoadAccessCondition
{
get
{
return loadAccessCondition_;
}
set
{
loadAccessCondition_ = value;
loadAccessCondition_present = true;
}
}
[ASN1Element(Name = "executeAccessCondition", IsOptional = true, HasTag = true, Tag = 4, HasDefaultValue = false)]
public AccessCondition ExecuteAccessCondition
{
get
{
return executeAccessCondition_;
}
set
{
executeAccessCondition_ = value;
executeAccessCondition_present = true;
}
}
[ASN1Element(Name = "deleteAccessCondition", IsOptional = true, HasTag = true, Tag = 5, HasDefaultValue = false)]
public AccessCondition DeleteAccessCondition
{
get
{
return deleteAccessCondition_;
}
set
{
deleteAccessCondition_ = value;
deleteAccessCondition_present = true;
}
}
[ASN1Element(Name = "editAccessCondition", IsOptional = true, HasTag = true, Tag = 6, HasDefaultValue = false)]
public AccessCondition EditAccessCondition
{
get
{
return editAccessCondition_;
}
set
{
editAccessCondition_ = value;
editAccessCondition_present = true;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isReadAccessConditionPresent()
{
return readAccessCondition_present;
}
public bool isStoreAccessConditionPresent()
{
return storeAccessCondition_present;
}
public bool isWriteAccessConditionPresent()
{
return writeAccessCondition_present;
}
public bool isLoadAccessConditionPresent()
{
return loadAccessCondition_present;
}
public bool isExecuteAccessConditionPresent()
{
return executeAccessCondition_present;
}
public bool isDeleteAccessConditionPresent()
{
return deleteAccessCondition_present;
}
public bool isEditAccessConditionPresent()
{
return editAccessCondition_present;
}
}
}
}
| |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2009 Oracle. All rights reserved.
*
*/
using System;
using System.Collections.Generic;
using System.Text;
using BerkeleyDB.Internal;
namespace BerkeleyDB {
/// <summary>
/// Represents errors that occur during Berkley DB operations.
/// </summary>
public class DatabaseException : Exception {
/// <summary>
/// The underlying error code from the Berkeley DB C library.
/// </summary>
public int ErrorCode;
/// <summary>
/// Throw an exception which corresponds to the specified Berkeley DB
/// error code.
/// </summary>
/// <param name="err">The Berkeley DB error code</param>
public static void ThrowException(int err) {
switch (err) {
case 0:
return;
case ErrorCodes.DB_NOTFOUND:
throw new NotFoundException();
case ErrorCodes.DB_BUFFER_SMALL:
throw new MemoryException();
case ErrorCodes.DB_FOREIGN_CONFLICT:
throw new ForeignConflictException();
case ErrorCodes.DB_KEYEMPTY:
throw new KeyEmptyException();
case ErrorCodes.DB_KEYEXIST:
throw new KeyExistException();
case ErrorCodes.DB_LOCK_DEADLOCK:
throw new DeadlockException();
case ErrorCodes.DB_LOCK_NOTGRANTED:
throw new LockNotGrantedException();
case ErrorCodes.DB_LOG_BUFFER_FULL:
throw new FullLogBufferException();
case ErrorCodes.DB_OLD_VERSION:
throw new OldVersionException();
case ErrorCodes.DB_PAGE_NOTFOUND:
throw new PageNotFoundException();
case ErrorCodes.DB_REP_DUPMASTER:
case ErrorCodes.DB_REP_HOLDELECTION:
case ErrorCodes.DB_REP_IGNORE:
case ErrorCodes.DB_REP_ISPERM:
case ErrorCodes.DB_REP_JOIN_FAILURE:
case ErrorCodes.DB_REP_NEWSITE:
case ErrorCodes.DB_REP_NOTPERM:
return;
case ErrorCodes.DB_REP_LEASE_EXPIRED:
throw new LeaseExpiredException();
case ErrorCodes.DB_RUNRECOVERY:
throw new RunRecoveryException();
case ErrorCodes.DB_SECONDARY_BAD:
throw new BadSecondaryException();
case ErrorCodes.DB_VERIFY_BAD:
throw new VerificationException();
case ErrorCodes.DB_VERSION_MISMATCH:
throw new VersionMismatchException();
default:
throw new DatabaseException(err);
}
}
/// <summary>
/// Create a new DatabaseException, encapsulating a specific error code.
/// </summary>
/// <param name="err">The error code to encapsulate.</param>
public DatabaseException(int err)
: base(libdb_csharp.db_strerror(err)) {
ErrorCode = err;
}
}
/// <summary>
/// A secondary index has been corrupted. This is likely the result of an
/// application operating on related databases without first associating
/// them.
/// </summary>
public class BadSecondaryException : DatabaseException {
/// <summary>
/// Initialize a new instance of the BadSecondaryException
/// </summary>
public BadSecondaryException() : base(ErrorCodes.DB_SECONDARY_BAD) { }
}
/// <summary>
///
/// </summary>
public class ForeignConflictException : DatabaseException {
/// <summary>
/// Initialize a new instance of the ForeignConflictException
/// </summary>
public ForeignConflictException()
: base(ErrorCodes.DB_FOREIGN_CONFLICT) { }
}
/// <summary>
/// In-memory logs are configured and no more log buffer space is available.
/// </summary>
public class FullLogBufferException : DatabaseException {
/// <summary>
/// Initialize a new instance of the FullLogBufferException
/// </summary>
public FullLogBufferException()
: base(ErrorCodes.DB_LOG_BUFFER_FULL) { }
}
/// <summary>
/// The requested key/data pair logically exists but was never explicitly
/// created by the application, or that the requested key/data pair was
/// deleted and never re-created. In addition, the Queue access method will
/// throw a KeyEmptyException for records that were created as part of a
/// transaction that was later aborted and never re-created.
/// </summary>
/// <remarks>
/// The Recno and Queue access methods will automatically create key/data
/// pairs under some circumstances.
/// </remarks>
public class KeyEmptyException : DatabaseException {
/// <summary>
/// Initialize a new instance of the KeyEmptyException
/// </summary>
public KeyEmptyException() : base(ErrorCodes.DB_KEYEMPTY) { }
}
/// <summary>
/// A key/data pair was inserted into the database using
/// <see cref="Database.PutNoOverwrite"/> and the key already
/// exists in the database, or using
/// <see cref="BTreeDatabase.PutNoDuplicate"/> or
/// <see cref="HashDatabase.PutNoDuplicate"/> and the key/data
/// pair already exists in the database.
/// </summary>
public class KeyExistException : DatabaseException {
/// <summary>
/// Initialize a new instance of the KeyExistException
/// </summary>
public KeyExistException() : base(ErrorCodes.DB_KEYEXIST) { }
}
/// <summary>
/// When multiple threads of control are modifying the database, there is
/// normally the potential for deadlock. In Berkeley DB, deadlock is
/// signified by a DeadlockException thrown from the Berkeley DB function.
/// Whenever a Berkeley DB function throws a DeadlockException, the
/// enclosing transaction should be aborted.
/// </summary>
public class DeadlockException : DatabaseException {
/// <summary>
/// Initialize a new instance of the DeadlockException
/// </summary>
public DeadlockException() : base(ErrorCodes.DB_LOCK_DEADLOCK) { }
}
/// <summary>
/// The site's replication master lease has expired.
/// </summary>
public class LeaseExpiredException : DatabaseException {
/// <summary>
/// Initialize a new instance of the LeaseExpiredException
/// </summary>
public LeaseExpiredException()
: base(ErrorCodes.DB_REP_LEASE_EXPIRED) { }
}
/// <summary>
/// If <see cref="DatabaseEnvironmentConfig.TimeNotGranted"/> is true,
/// database calls timing out based on lock or transaction timeout values
/// will throw a LockNotGrantedException, instead of a DeadlockException.
/// </summary>
public class LockNotGrantedException : DatabaseException {
/// <summary>
/// Initialize a new instance of the LockNotGrantedException
/// </summary>
public LockNotGrantedException()
: base(ErrorCodes.DB_LOCK_NOTGRANTED) { }
}
internal class MemoryException : DatabaseException {
/// <summary>
/// Initialize a new instance of the MemoryException
/// </summary>
internal MemoryException() : base(ErrorCodes.DB_BUFFER_SMALL) { }
}
/// <summary>
/// The requested key/data pair did not exist in the database or that
/// start-of- or end-of-file has been reached by a cursor.
/// </summary>
public class NotFoundException : DatabaseException {
/// <summary>
/// Initialize a new instance of the NotFoundException
/// </summary>
public NotFoundException() : base(ErrorCodes.DB_NOTFOUND) { }
}
/// <summary>
/// This version of Berkeley DB is unable to upgrade a given database.
/// </summary>
public class OldVersionException : DatabaseException {
/// <summary>
/// Initialize a new instance of the OldVersionException
/// </summary>
public OldVersionException() : base(ErrorCodes.DB_OLD_VERSION) { }
}
/// <summary>
///
/// </summary>
public class PageNotFoundException : DatabaseException {
/// <summary>
///
/// </summary>
public PageNotFoundException() : base(ErrorCodes.DB_PAGE_NOTFOUND) { }
}
/// <summary>
/// Berkeley DB has encountered an error it considers fatal to an entire
/// environment. Once a RunRecoveryException has been thrown by any
/// interface, it will be returned from all subsequent Berkeley DB calls
/// made by any threads of control participating in the environment.
/// </summary>
/// <remarks>
/// An example of this type of fatal error is a corrupted database page. The
/// only way to recover from this type of error is to have all threads of
/// control exit the Berkeley DB environment, run recovery of the
/// environment, and re-enter Berkeley DB. (It is not strictly necessary
/// that the processes exit, although that is the only way to recover system
/// resources, such as file descriptors and memory, allocated by
/// Berkeley DB.)
/// </remarks>
public class RunRecoveryException : DatabaseException {
/// <summary>
/// Initialize a new instance of the RunRecoveryException
/// </summary>
public RunRecoveryException() : base(ErrorCodes.DB_RUNRECOVERY) { }
}
/// <summary>
/// Thrown by <see cref="Database.Verify"/> if a database is
/// corrupted, and by <see cref="Database.Salvage"/> if all
/// key/data pairs in the file may not have been successfully output.
/// </summary>
public class VerificationException : DatabaseException {
/// <summary>
/// Initialize a new instance of the VerificationException
/// </summary>
public VerificationException() : base(ErrorCodes.DB_VERIFY_BAD) { }
}
/// <summary>
/// The version of the Berkeley DB library doesn't match the version that
/// created the database environment.
/// </summary>
public class VersionMismatchException : DatabaseException {
/// <summary>
/// Initialize a new instance of the VersionMismatchException
/// </summary>
public VersionMismatchException()
: base(ErrorCodes.DB_VERSION_MISMATCH) { }
}
}
| |
using UnityEngine;
using System.Collections;
public class sui_demo_ControllerBoat : MonoBehaviour {
//PUBLIC VARIABLES
public bool isActive = false;
public bool isControllable = true;
public bool isExtraZoom = false;
public bool keepAboveSurface = true;
public bool handleObjectOcclusion = true;
public Transform cameraTarget;
public bool reverseYAxis = true;
public bool reverseXAxis = false;
public Vector2 mouseSensitivity = new Vector2(4.0f,4.0f);
public float cameraFOV = 35.0f;
public Vector2 cameraOffset = new Vector2(0.0f,0.0f);
public float cameraLean = 0.0f;
public float walkSpeed = 0.02f;
public float runSpeed = 0.4f;
public Vector3 rotationLimits = new Vector3(0.0f,0.0f,-30.0f);
public float minZoomAmount = 1.25f;
public float maxZoomAmount = 8.0f;
public sui_demo_animBoat targetAnimator;
//PRIVATE VARIABLES
private Transform cameraObject;
private Vector2 axisSensitivity = new Vector2(4.0f,4.0f);
private float followDistance = 5.0f;
private float followHeight = 1.0f;
private float followLat = 0.0f;
private float camFOV = 35.0f;
private float camRotation = 0.0f;
private Vector3 camRot;
private float camHeight = 0.0f;
private bool isInWater = false;
private bool isInWaterDeep = false;
private bool isUnderWater = false;
//private bool isAtSurface = false;
//private bool isFloating = false;
//private bool isFalling = false;
private Vector3 targetPosition;
private float MouseRotationDistance = 0.0f;
private float MouseVerticalDistance = 0.0f;
private GameObject suimonoGameObject;
private Suimono.Core.SuimonoModule suimonoModuleObject;
private float followTgtDistance = 0.0f;
//private bool orbitView = false;
private Quaternion targetRotation;
private float MouseScrollDistance = 0.0f;
//private Transform playerObject;
//private float projEmitTimer = 0.0f;
//private float camVRotation = 0.0f;
//private float firingTime = 0.0f;
//private float sightingTime = 0.0f;
private float setFOV = 1.0f;
//private float targetUseLean = 0.0f;
private float useSpeed = 0.0f;
private float useSideSpeed = 0.0f;
private float moveSpeed = 0.05f;
private float moveForward = 0.0f;
private float moveSideways = 0.0f;
private bool isRunning = false;
//private bool isMouseMove = false;
//private float lastYPos = 0.0f;
//private float propSpd = 0.0f;
//private float engPos = 0.5f;
//private Transform vehiclePosition;
//private Transform vehicleExitPosition;
//private float forwardAmt = 0.0f;
//private float sidewaysAmt = 0.0f;
//private float editorSensitivity = 1.0f;
//private float button3time = 0.0f;
private Vector3 savePos;
private float oldMouseRotation;
//private float oldMouseVRotation;
private float xMove;
private float zMove;
private sui_demo_ControllerMaster MC;
private sui_demo_InputController IC;
private float waterLevel;
void Awake() {
//get Suimono Specific Objects
suimonoGameObject = GameObject.Find("SUIMONO_Module");
if (suimonoGameObject != null) suimonoModuleObject = suimonoGameObject.GetComponent<Suimono.Core.SuimonoModule>();
targetPosition = cameraTarget.position;
targetRotation = cameraTarget.rotation;
if (cameraTarget != null){
targetAnimator = cameraTarget.gameObject.GetComponent<sui_demo_animBoat>();
}
MC = this.gameObject.GetComponent<sui_demo_ControllerMaster>() as sui_demo_ControllerMaster;
IC = this.gameObject.GetComponent<sui_demo_InputController>() as sui_demo_InputController;
}
void LateUpdate() {
//clamp rotations
if (rotationLimits.x != 0.0f){
if (cameraTarget.transform.eulerAngles.x < 360.0f-rotationLimits.x && cameraTarget.transform.eulerAngles.x > rotationLimits.x+10f){
cameraTarget.transform.eulerAngles = new Vector3(
360.0f-rotationLimits.x,
cameraTarget.transform.eulerAngles.y,
cameraTarget.transform.eulerAngles.z
);
} else if (cameraTarget.transform.eulerAngles.x > rotationLimits.x && cameraTarget.transform.eulerAngles.x < 360.0f-rotationLimits.x){
cameraTarget.transform.eulerAngles = new Vector3(
rotationLimits.x,
cameraTarget.transform.eulerAngles.y,
cameraTarget.transform.eulerAngles.z
);
}
}
if (rotationLimits.y != 0.0f){
if (cameraTarget.transform.eulerAngles.y < 360.0f-rotationLimits.y && cameraTarget.transform.eulerAngles.y > rotationLimits.y+10f){
cameraTarget.transform.eulerAngles = new Vector3(
cameraTarget.transform.eulerAngles.x,
360.0f-rotationLimits.y,
cameraTarget.transform.eulerAngles.z
);
} else if (cameraTarget.transform.eulerAngles.y > rotationLimits.y && cameraTarget.transform.eulerAngles.y < 360.0f-rotationLimits.y){
cameraTarget.transform.eulerAngles = new Vector3(
cameraTarget.transform.eulerAngles.x,
rotationLimits.y,
cameraTarget.transform.eulerAngles.z
);
}
}
if (rotationLimits.z != 0.0f){
if (cameraTarget.transform.eulerAngles.z < 360.0f-rotationLimits.z && cameraTarget.transform.eulerAngles.z > rotationLimits.z+10f){
cameraTarget.transform.eulerAngles = new Vector3(
cameraTarget.transform.eulerAngles.x,
cameraTarget.transform.eulerAngles.y,
360.0f-rotationLimits.z
);
} else if (cameraTarget.transform.eulerAngles.z > rotationLimits.z && cameraTarget.transform.eulerAngles.z < 360.0f-rotationLimits.z){
cameraTarget.transform.eulerAngles = new Vector3(
cameraTarget.transform.eulerAngles.x,
cameraTarget.transform.eulerAngles.y,
rotationLimits.z
);
}
}
}
void FixedUpdate () {
if (isActive){
//------------------------------------
// GET DATA FROM MASTER CONTROLLER
//------------------------------------
cameraObject = MC.cameraObject;
//---------------------------------
// GET KEYBOARD AND MOUSE INPUTS
//---------------------------------
if (isControllable){
//"WASD" MOVEMENT KEYS
moveForward = 0.0f;
moveSideways = 0.0f;
if (IC.inputKeyW) moveForward = 1.0f;
if (IC.inputKeyS) moveForward = -1.0f;
if (IC.inputKeyA) moveSideways = -1.0f;
if (IC.inputKeyD) moveSideways = 1.0f;
//MOUSE BUTTON 0
//isMouseMove = IC.inputMouseKey0;
//MOUSE BUTTON 1
isExtraZoom = IC.inputMouseKey1;
if (isExtraZoom){
setFOV = 0.5f;
} else {
setFOV = 1.0f;
}
//SHIFT
isRunning = IC.inputKeySHIFTL;
if (moveForward == -1.0f) isRunning = false;
//SPACE
//orbitView = IC.inputKeySPACE;
}
//CHECK FOR MOUSE INPUT
targetPosition = cameraTarget.position;
oldMouseRotation = MouseRotationDistance;
//oldMouseVRotation = MouseVerticalDistance;
//GET MOUSE MOVEMENT
MouseRotationDistance = IC.inputMouseX;
MouseVerticalDistance = IC.inputMouseY;
MouseScrollDistance = IC.inputMouseWheel;
if (reverseXAxis) MouseRotationDistance = -IC.inputMouseX;
if (reverseYAxis) MouseVerticalDistance = -IC.inputMouseY;
//---------------------------------
// HANDLE CAMERA VIEWS
//---------------------------------
if (!isControllable){
//Zoom Settings used for the intro screen
camFOV = 63.2f;
followLat = Mathf.Lerp(followLat,-0.85f,Time.deltaTime*4.0f);
followHeight = Mathf.Lerp(followHeight,1.8f,Time.deltaTime*4.0f);
followDistance = Mathf.Lerp(followDistance,5.0f,Time.deltaTime*4.0f);
axisSensitivity = new Vector2(
Mathf.Lerp(axisSensitivity.x,mouseSensitivity.x,Time.deltaTime*4.0f),
Mathf.Lerp(axisSensitivity.y,mouseSensitivity.y,Time.deltaTime*4.0f)
);
cameraObject.GetComponent<Camera>().fieldOfView = camFOV;
}
//IDLE SETTINGS lerp camera back
camFOV = Mathf.Lerp(camFOV,cameraFOV*setFOV,Time.deltaTime*4.0f);
followLat = Mathf.Lerp(followLat,-0.4f,Time.deltaTime*4.0f);
followHeight = Mathf.Lerp(followHeight,1.4f,Time.deltaTime*2.0f);
axisSensitivity = new Vector2(Mathf.Lerp(axisSensitivity.x,mouseSensitivity.x,Time.deltaTime*4.0f),axisSensitivity.y);
axisSensitivity = new Vector2(axisSensitivity.x, Mathf.Lerp(axisSensitivity.y,mouseSensitivity.y,Time.deltaTime*4.0f));
//LOCK CURSOR
Cursor.lockState = CursorLockMode.None;
//---------------------------------
// SUIMONO SPECIFIC HANDLING
//---------------------------------
// we use this to get the current Suimono plane water level (if applicable) from the
// main Suimono Module object, then translate this into different walk / run speeds
// based on water depth.
//var waterLevel : float = suimonoModuleObject.GetWaterDepth(cameraTarget);
if (suimonoModuleObject != null){
waterLevel = suimonoModuleObject.SuimonoGetHeight(cameraTarget.position,"object depth");
isInWater = false;
if (waterLevel < 0.0f) waterLevel = 0.0f;
if (waterLevel > 0.0f){
isInWater = true;
isInWaterDeep = false;
isUnderWater = false;
//isFloating = false;
//isAtSurface = false;
if (waterLevel >= 0.9f && waterLevel < 1.8f) isInWaterDeep = true;
if (waterLevel >= 1.8f) isUnderWater = true;
//if (waterLevel >= 1.2f && waterLevel < 1.8f) isAtSurface = true;
//if (isInWaterDeep && waterLevel > 2.0f) isFloating = true;
}
}
//---------------------------------
// SET MOVEMENT SPEEDS
//---------------------------------
float spdLerp = 5.0f;
if (isRunning && moveForward > 0.0f) spdLerp = 2.5f;
moveSpeed = walkSpeed;
if (isInWaterDeep || isUnderWater) isRunning = false;
if (isRunning) moveSpeed = runSpeed;
if (moveForward != 0.0f && moveSideways != 0.0f) moveSpeed *= 0.75f;
if (!isInWater) moveSpeed *= 0.0f;
useSpeed = Mathf.Lerp(useSpeed, (moveSpeed * moveForward), Time.deltaTime*spdLerp);
useSideSpeed = Mathf.Lerp(useSideSpeed, (moveSpeed * moveSideways), Time.deltaTime*spdLerp);
//---------------------------------
// CHARACTER POSITIONING
//---------------------------------
if (isControllable){
//ROTATE BOAT
if (moveForward != 0.0f){
xMove = Mathf.Lerp(xMove,useSpeed,Time.deltaTime);
zMove = Mathf.Lerp(zMove,useSpeed,Time.deltaTime);
cameraTarget.eulerAngles = new Vector3(
cameraTarget.eulerAngles.x,
(cameraTarget.eulerAngles.y + Mathf.Lerp(0.0f,20.0f*moveSideways*moveForward,Time.deltaTime*(Mathf.Abs(xMove*10.0f))) ),
cameraTarget.eulerAngles.z
);
if (isInWater){
cameraTarget.eulerAngles = new Vector3(
cameraTarget.eulerAngles.x,
cameraTarget.eulerAngles.y,
(cameraTarget.eulerAngles.z + Mathf.Lerp(0.0f,-130.0f*moveSideways*moveForward,Time.deltaTime*(Mathf.Abs(zMove*5.0f))))
);
}
} else {
xMove = Mathf.Lerp(xMove,0.0f,Time.deltaTime);
}
//MOVE BOAT
if (cameraTarget.GetComponent<Rigidbody>()){
//calculate forward / backward movement
Vector3 setNewPos;
setNewPos = ((cameraTarget.transform.forward * (xMove)));
//calculate vertical while underwater
Vector3 setNewVertPos = new Vector3(0f,0f,0f);
//set final movement
cameraTarget.GetComponent<Rigidbody>().MovePosition(cameraTarget.GetComponent<Rigidbody>().position + (setNewPos + setNewVertPos));
}
//---------------------------------
// CAMERA POSITIONING
//---------------------------------
//Calculate Follow Distance
float followLerpSpeed = 2.0f;
followDistance -= (MouseScrollDistance*8.0f);
followDistance = Mathf.Clamp(followDistance,minZoomAmount,maxZoomAmount);
followTgtDistance = Mathf.Lerp(followTgtDistance,followDistance,Time.deltaTime*followLerpSpeed);
// Calculate Rotation
camRotation = Mathf.Lerp(oldMouseRotation,MouseRotationDistance*axisSensitivity.x,Time.deltaTime);
targetRotation.eulerAngles = new Vector3(targetRotation.eulerAngles.x,(targetRotation.eulerAngles.y + camRotation),targetRotation.eulerAngles.z);
cameraObject.transform.eulerAngles = new Vector3(targetRotation.eulerAngles.x,cameraObject.transform.eulerAngles.y,cameraObject.transform.eulerAngles.z);
cameraObject.transform.eulerAngles = new Vector3(cameraObject.transform.eulerAngles.x,targetRotation.eulerAngles.y,cameraObject.transform.eulerAngles.z);
camHeight = Mathf.Lerp(camHeight,camHeight+MouseVerticalDistance*axisSensitivity.y,Time.deltaTime);
if (keepAboveSurface && suimonoModuleObject != null){
camHeight = Mathf.Clamp(camHeight,waterLevel+0.25f,12.0f);
} else {
camHeight = Mathf.Clamp(camHeight,-1.0f,12.0f);
}
// SET CAMERA POSITION and ROTATIONS
cameraObject.transform.position = cameraTarget.transform.position+(-cameraObject.transform.forward*followTgtDistance);
cameraObject.transform.position = new Vector3(cameraObject.transform.position.x,(cameraObject.transform.position.y + camHeight),cameraObject.transform.position.z);
cameraObject.transform.LookAt(new Vector3(targetPosition.x,targetPosition.y + followHeight,targetPosition.z));
//CHECK CAMERA OCCLUSION and REPOSITION
if (handleObjectOcclusion){
//RaycastHit[] hits;
Vector3 testPos = cameraTarget.transform.position;
testPos = new Vector3(testPos.x,(testPos.y + followHeight),testPos.z);
RaycastHit hit = new RaycastHit();
if(Physics.Linecast(testPos,cameraObject.transform.position, out hit)) {
if (hit.transform.gameObject.layer != 4){
if (hit.transform == transform || hit.transform == cameraTarget){
//do nothing
} else {
//check for triggers
bool trigCheck = false;
if (hit.transform.GetComponent<Collider>() != null){
if (hit.transform.GetComponent<Collider>().isTrigger) trigCheck = true;
}
if (!trigCheck){
//calculate ray
//Ray dirRay = new Ray(testPos, testPos - cameraObject.transform.position);
//move camera
cameraObject.transform.position = hit.point;
}
}
}
}
}
//set camera offset
cameraObject.transform.position = new Vector3((cameraObject.transform.position.x + cameraOffset.x),cameraObject.transform.position.y,cameraObject.transform.position.z);
cameraObject.transform.position = new Vector3(cameraObject.transform.position.x, (cameraObject.transform.position.y + cameraOffset.y),cameraObject.transform.position.z);
//set camera leaning
cameraObject.transform.eulerAngles = new Vector3(
cameraObject.transform.rotation.eulerAngles.x,
cameraObject.transform.rotation.eulerAngles.y,
cameraLean);
}
//---------------------------------
// SET CAMERA SETTINGS and FX
//---------------------------------
if (isControllable){
//SET CAMERA SETTINGS
cameraObject.GetComponent<Camera>().fieldOfView = camFOV;
}
//------------------------------------
// SEND MODES TO CHARACTER ANIMATOR
//------------------------------------
if (targetAnimator != null){
//send normal animations
if (moveForward > 0.0f){
targetAnimator.behaviorIsRevving = true;
targetAnimator.behaviorIsRevvingHigh = isRunning;
targetAnimator.behaviorIsRevvingBack = false;
} else if (moveForward < 0.0f){
targetAnimator.behaviorIsRevving = false;
targetAnimator.behaviorIsRevvingHigh = false;
targetAnimator.behaviorIsRevvingBack = true;
} else if (moveForward == 0.0f){
targetAnimator.behaviorIsRevving = false;
targetAnimator.behaviorIsRevvingHigh = false;
targetAnimator.behaviorIsRevvingBack = false;
}
targetAnimator.engineRotation = moveSideways;
}
}
if (targetAnimator != null){
targetAnimator.behaviorIsOn = isActive;
}
}
}
| |
namespace FakeItEasy
{
using System;
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
/// <summary>
/// Provides validation extensions for <see cref="IArgumentConstraintManager{T}"/>.
/// </summary>
public static class ArgumentConstraintManagerExtensions
{
/// <summary>
/// Constrains an argument so that it must be null (Nothing in VB).
/// </summary>
/// <typeparam name="T">The type of the argument.</typeparam>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <returns>A dummy argument value.</returns>
public static T IsNull<T>(this IArgumentConstraintManager<T> manager) where T : class
{
Guard.AgainstNull(manager, "manager");
return manager.Matches(x => x == null, x => x.Write("NULL"));
}
/// <summary>
/// Constrains the string argument to contain the specified text.
/// </summary>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <param name="value">The string the argument string should contain.</param>
/// <returns>A dummy argument value.</returns>
public static string Contains(this IArgumentConstraintManager<string> manager, string value)
{
return manager.NullCheckedMatches(x => x.Contains(value), x => x.Write("string that contains ").WriteArgumentValue(value));
}
/// <summary>
/// Constrains the sequence so that it must contain the specified value.
/// </summary>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <param name="value">The value the collection should contain.</param>
/// <typeparam name="T">The type of sequence.</typeparam>
/// <returns>A dummy argument value.</returns>
public static T Contains<T>(this IArgumentConstraintManager<T> manager, object value) where T : IEnumerable
{
return manager.NullCheckedMatches(
x => x.Cast<object>().Contains(value),
x => x.Write("sequence that contains the value ").WriteArgumentValue(value));
}
/// <summary>
/// Constrains the string so that it must start with the specified value.
/// </summary>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <param name="value">The value the string should start with.</param>
/// <returns>A dummy argument value.</returns>
public static string StartsWith(this IArgumentConstraintManager<string> manager, string value)
{
return manager.NullCheckedMatches(x => x.StartsWith(value, StringComparison.Ordinal), x => x.Write("string that starts with ").WriteArgumentValue(value));
}
/// <summary>
/// Constrains the string so that it must end with the specified value.
/// </summary>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <param name="value">The value the string should end with.</param>
/// <returns>A dummy argument value.</returns>
public static string EndsWith(this IArgumentConstraintManager<string> manager, string value)
{
return manager.NullCheckedMatches(x => x.EndsWith(value, StringComparison.Ordinal), x => x.Write("string that ends with ").WriteArgumentValue(value));
}
/// <summary>
/// Constrains the string so that it must be null or empty.
/// </summary>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <returns>A dummy argument value.</returns>
public static string IsNullOrEmpty(this IArgumentConstraintManager<string> manager)
{
return manager.Matches(x => string.IsNullOrEmpty(x), "NULL or string.Empty");
}
/// <summary>
/// Constrains argument value so that it must be greater than the specified value.
/// </summary>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <param name="value">The value the string should start with.</param>
/// <typeparam name="T">The type of argument to constrain.</typeparam>
/// <returns>A dummy argument value.</returns>
public static T IsGreaterThan<T>(this IArgumentConstraintManager<T> manager, T value) where T : IComparable
{
Guard.AgainstNull(manager, "manager");
return manager.Matches(x => x.CompareTo(value) > 0, x => x.Write("greater than ").WriteArgumentValue(value));
}
/// <summary>
/// The tested argument collection should contain the same elements as the
/// as the specified collection.
/// </summary>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <param name="value">The sequence to test against.</param>
/// <typeparam name="T">The type of argument to constrain.</typeparam>
/// <returns>A dummy argument value.</returns>
public static T IsSameSequenceAs<T>(this IArgumentConstraintManager<T> manager, IEnumerable value) where T : IEnumerable
{
return manager.NullCheckedMatches(
x => x.Cast<object>().SequenceEqual(value.Cast<object>()),
x => x.Write("specified sequence"));
}
/// <summary>
/// Tests that the IEnumerable contains no items.
/// </summary>
/// <typeparam name="T">The type of argument.</typeparam>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <returns>A dummy argument value.</returns>
public static T IsEmpty<T>(this IArgumentConstraintManager<T> manager) where T : IEnumerable
{
return manager.NullCheckedMatches(
x => !x.Cast<object>().Any(),
x => x.Write("empty collection"));
}
/// <summary>
/// Tests that the passed in argument is equal to the specified value.
/// </summary>
/// <typeparam name="T">The type of the argument.</typeparam>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <param name="value">The value to compare to.</param>
/// <returns>A dummy argument value.</returns>
public static T IsEqualTo<T>(this IArgumentConstraintManager<T> manager, T value)
{
Guard.AgainstNull(manager, "manager");
return manager.Matches(
x => object.Equals(value, x),
x => x.Write("equal to ").WriteArgumentValue(value));
}
/// <summary>
/// Tests that the passed in argument is the same instance (reference) as the specified value.
/// </summary>
/// <typeparam name="T">The type of the argument.</typeparam>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <param name="value">The reference to compare to.</param>
/// <returns>A dummy argument value.</returns>
public static T IsSameAs<T>(this IArgumentConstraintManager<T> manager, T value)
{
Guard.AgainstNull(manager, "manager");
return manager.Matches(
x => object.ReferenceEquals(value, x),
x => x.Write("same as ").WriteArgumentValue(value));
}
/// <summary>
/// Constrains the argument to be of the specified type.
/// </summary>
/// <typeparam name="T">The type of argument in the method signature.</typeparam>
/// <param name="manager">The constraint manager.</param>
/// <param name="type">The type to constrain the argument with.</param>
/// <returns>A dummy value.</returns>
public static T IsInstanceOf<T>(this IArgumentConstraintManager<T> manager, Type type)
{
return manager.NullCheckedMatches(x => type.IsAssignableFrom(x.GetType()), x => x.Write("Instance of ").Write(type.FullName));
}
/// <summary>
/// Constrains the argument with a predicate.
/// </summary>
/// <param name="scope">
/// The constraint manager.
/// </param>
/// <param name="predicate">
/// The predicate that should constrain the argument.
/// </param>
/// <param name="description">
/// A human readable description of the constraint.
/// </param>
/// <typeparam name="T">
/// The type of argument in the method signature.
/// </typeparam>
/// <returns>
/// A dummy argument value.
/// </returns>
public static T Matches<T>(this IArgumentConstraintManager<T> scope, Func<T, bool> predicate, string description)
{
Guard.AgainstNull(scope, "scope");
return scope.Matches(predicate, x => x.Write(description));
}
/// <summary>
/// Constrains the argument with a predicate.
/// </summary>
/// <param name="manager">
/// The constraint manager.
/// </param>
/// <param name="predicate">
/// The predicate that should constrain the argument.
/// </param>
/// <param name="descriptionFormat">
/// A human readable description of the constraint format string.
/// </param>
/// <param name="args">
/// Arguments for the format string.
/// </param>
/// <typeparam name="T">
/// The type of argument in the method signature.
/// </typeparam>
/// <returns>
/// A dummy argument value.
/// </returns>
public static T Matches<T>(this IArgumentConstraintManager<T> manager, Func<T, bool> predicate, string descriptionFormat, params object[] args)
{
Guard.AgainstNull(manager, "manager");
return manager.Matches(predicate, x => x.Write(string.Format(CultureInfo.CurrentCulture, descriptionFormat, args)));
}
/// <summary>
/// Constrains the argument with a predicate.
/// </summary>
/// <param name="scope">
/// The constraint manager.
/// </param>
/// <param name="predicate">
/// The predicate that should constrain the argument.
/// </param>
/// <typeparam name="T">
/// The type of argument in the method signature.
/// </typeparam>
/// <returns>
/// A dummy argument value.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Appropriate for Linq expressions.")]
public static T Matches<T>(this IArgumentConstraintManager<T> scope, Expression<Func<T, bool>> predicate)
{
Guard.AgainstNull(predicate, "predicate");
return scope.Matches(predicate.Compile(), predicate.ToString());
}
/// <summary>
/// Constrains the argument to be not null (Nothing in VB) and to match
/// the specified predicate.
/// </summary>
/// <typeparam name="T">The type of the argument to constrain.</typeparam>
/// <param name="manager">The constraint manager.</param>
/// <param name="predicate">The predicate that constrains non null values.</param>
/// <param name="descriptionWriter">An action that writes a description of the constraint
/// to the output.</param>
/// <returns>A dummy argument value.</returns>
public static T NullCheckedMatches<T>(this IArgumentConstraintManager<T> manager, Func<T, bool> predicate, Action<IOutputWriter> descriptionWriter)
{
Guard.AgainstNull(manager, "manager");
return manager.Matches(
x => ((object)x) != null && predicate(x),
descriptionWriter);
}
}
}
| |
// This file is substantially taken from the BaseOverlay class included in Pathoschild's ChestsAnywhere mod.
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using StardewModdingAPI.Events;
using StardewValley;
using System;
using Rectangle = xTile.Dimensions.Rectangle;
namespace StardewValleyMods.CategorizeChests.Interface
{
/// <summary>An interface which supports user interaction and overlays the active menu (if any).</summary>
public abstract class InterfaceHost : IDisposable
{
/*********
** Properties
*********/
/// <summary>The last viewport bounds.</summary>
private Rectangle LastViewport;
/// <summary>Indicates whether to keep the overlay active. If <c>null</c>, the overlay is kept until explicitly disposed.</summary>
private readonly Func<bool> KeepAliveCheck;
/*********
** Public methods
*********/
/// <summary>Release all resources.</summary>
public virtual void Dispose()
{
GraphicsEvents.OnPostRenderGuiEvent -= this.OnPostRenderGuiEvent;
GameEvents.UpdateTick -= this.OnUpdateTick;
ControlEvents.KeyPressed -= this.OnKeyPressed;
ControlEvents.ControllerButtonPressed -= this.OnControllerButtonPressed;
ControlEvents.ControllerTriggerPressed -= this.OnControllerTriggerPressed;
ControlEvents.MouseChanged -= this.OnMouseChanged;
}
/*********
** Protected methods
*********/
/****
** Implementation
****/
/// <summary>Construct an instance.</summary>
/// <param name="keepAlive">Indicates whether to keep the overlay active. If <c>null</c>, the overlay is kept until explicitly disposed.</param>
protected InterfaceHost(Func<bool> keepAlive = null)
{
this.KeepAliveCheck = keepAlive;
this.LastViewport = new Rectangle(Game1.viewport.X, Game1.viewport.Y, Game1.viewport.Width,
Game1.viewport.Height);
GraphicsEvents.OnPostRenderGuiEvent += this.OnPostRenderGuiEvent;
GameEvents.UpdateTick += this.OnUpdateTick;
ControlEvents.KeyPressed += this.OnKeyPressed;
ControlEvents.ControllerButtonPressed += this.OnControllerButtonPressed;
ControlEvents.ControllerTriggerPressed += this.OnControllerTriggerPressed;
ControlEvents.MouseChanged += this.OnMouseChanged;
}
/// <summary>Draw the overlay to the screen.</summary>
/// <param name="batch">The sprite batch being drawn.</param>
protected virtual void Draw(SpriteBatch batch)
{
}
/// <summary>The method invoked when the player left-clicks.</summary>
/// <param name="x">The X-position of the cursor.</param>
/// <param name="y">The Y-position of the cursor.</param>
/// <returns>Whether the event has been handled and shouldn't be propagated further.</returns>
protected virtual bool ReceiveLeftClick(int x, int y)
{
return false;
}
/// <summary>The method invoked when the player presses a key.</summary>
/// <param name="input">The key that was pressed.</param>
/// <returns>Whether the event has been handled and shouldn't be propagated further.</returns>
protected virtual bool ReceiveKeyPress(Keys input)
{
return false;
}
/// <summary>The method invoked when the player presses a controller button.</summary>
/// <param name="input">The button that was pressed.</param>
/// <returns>Whether the event has been handled and shouldn't be propagated further.</returns>
protected virtual bool ReceiveButtonPress(Buttons input)
{
return false;
}
/// <summary>The method invoked when the player presses a controller trigger.</summary>
/// <param name="input">The trigger that was pressed.</param>
/// <returns>Whether the event has been handled and shouldn't be propagated further.</returns>
protected virtual bool ReceiveTriggerPress(Buttons input)
{
return false;
}
/// <summary>The method invoked when the player uses the mouse scroll wheel.</summary>
/// <param name="amount">The scroll amount.</param>
/// <returns>Whether the event has been handled and shouldn't be propagated further.</returns>
protected virtual bool ReceiveScrollWheelAction(int amount)
{
return false;
}
/// <summary>The method invoked when the cursor is hovered.</summary>
/// <param name="x">The cursor's X position.</param>
/// <param name="y">The cursor's Y position.</param>
/// <returns>Whether the event has been handled and shouldn't be propagated further.</returns>
protected virtual bool ReceiveCursorHover(int x, int y)
{
return false;
}
/// <summary>The method invoked when the player resizes the game windoww.</summary>
/// <param name="oldBounds">The previous game window bounds.</param>
/// <param name="newBounds">The new game window bounds.</param>
protected virtual void ReceiveGameWindowResized(Rectangle oldBounds, Rectangle newBounds)
{
}
/// <summary>Draw the mouse cursor.</summary>
/// <remarks>Derived from <see cref="StardewValley.Menus.IClickableMenu.drawMouse"/>.</remarks>
protected void DrawCursor()
{
if (Game1.options.hardwareCursor)
return;
Game1.spriteBatch.Draw(Game1.mouseCursors, new Vector2(Game1.getOldMouseX(), Game1.getOldMouseY()),
Game1.getSourceRectForStandardTileSheet(Game1.mouseCursors, 0, 16, 16), Color.White, 0.0f, Vector2.Zero,
Game1.pixelZoom + Game1.dialogueButtonScale / 150f, SpriteEffects.None, 0f);
}
/****
** Event listeners
****/
/// <summary>The method called when the game finishes drawing components to the screen.</summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The event arguments.</param>
private void OnPostRenderGuiEvent(object sender, EventArgs e)
{
this.Draw(Game1.spriteBatch);
}
/// <summary>The method called once per event tick.</summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The event arguments.</param>
private void OnUpdateTick(object sender, EventArgs e)
{
// detect end of life
if (this.KeepAliveCheck != null && !this.KeepAliveCheck())
{
this.Dispose();
return;
}
// trigger window resize event
Rectangle newViewport = Game1.viewport;
if (this.LastViewport.Width != newViewport.Width || this.LastViewport.Height != newViewport.Height)
{
newViewport = new Rectangle(newViewport.X, newViewport.Y, newViewport.Width, newViewport.Height);
this.ReceiveGameWindowResized(this.LastViewport, newViewport);
this.LastViewport = newViewport;
}
}
/// <summary>The method invoked when the player presses a key.</summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The event arguments.</param>
private void OnKeyPressed(object sender, EventArgsKeyPressed e)
{
bool handled = this.ReceiveKeyPress(e.KeyPressed);
if (handled)
Game1.oldKBState = Keyboard.GetState();
}
/// <summary>The method invoked when the player presses a controller button.</summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The event arguments.</param>
private void OnControllerButtonPressed(object sender, EventArgsControllerButtonPressed e)
{
GamePadState state = GamePad.GetState(PlayerIndex.One);
// handle controller cursor click
if (state.IsButtonDown(Buttons.A) && !Game1.oldPadState.IsButtonDown(Buttons.X))
{
bool handled = this.ReceiveLeftClick(Game1.getMouseX(), Game1.getMouseY());
if (handled)
Game1.oldPadState = GamePad.GetState(PlayerIndex.One);
}
// handle button press
else
{
bool handled = this.ReceiveButtonPress(e.ButtonPressed);
if (handled)
Game1.oldPadState = GamePad.GetState(PlayerIndex.One);
}
}
/// <summary>The method invoked when the player presses a controller trigger.</summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The event arguments.</param>
private void OnControllerTriggerPressed(object sender, EventArgsControllerTriggerPressed e)
{
bool handled = this.ReceiveTriggerPress(e.ButtonPressed);
if (handled)
Game1.oldPadState = GamePad.GetState(PlayerIndex.One);
}
/// <summary>The method invoked when the mouse state changes.</summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The event arguments.</param>
private void OnMouseChanged(object sender, EventArgsMouseStateChanged e)
{
// get data
MouseState oldState = e.PriorState;
MouseState newState = e.NewState;
Point position = e.NewPosition;
// raise events
bool hoverHandled = this.ReceiveCursorHover(position.X, position.Y);
bool leftClickHandled = oldState.LeftButton != ButtonState.Pressed &&
newState.LeftButton == ButtonState.Pressed &&
this.ReceiveLeftClick(position.X, position.Y);
bool scrollHandled = oldState.ScrollWheelValue != newState.ScrollWheelValue &&
this.ReceiveScrollWheelAction(newState.ScrollWheelValue - oldState.ScrollWheelValue);
// suppress handled input
if (hoverHandled || leftClickHandled || scrollHandled)
{
MouseState cur = Game1.oldMouseState;
Game1.oldMouseState = new MouseState(
x: cur.X,
y: cur.Y,
scrollWheel: scrollHandled ? newState.ScrollWheelValue : cur.ScrollWheelValue,
leftButton: leftClickHandled ? newState.LeftButton : cur.LeftButton,
middleButton: cur.MiddleButton,
rightButton: cur.RightButton,
xButton1: cur.XButton1,
xButton2: cur.XButton2
);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using Xunit;
namespace System.Collections.Tests
{
public partial class Dictionary_IDictionary_NonGeneric_Tests : IDictionary_NonGeneric_Tests
{
protected override IDictionary NonGenericIDictionaryFactory()
{
return new Dictionary<string, string>();
}
protected override ModifyOperation ModifyEnumeratorThrows => PlatformDetection.IsFullFramework ? base.ModifyEnumeratorThrows : ModifyOperation.Add | ModifyOperation.Insert;
protected override ModifyOperation ModifyEnumeratorAllowed => PlatformDetection.IsFullFramework ? base.ModifyEnumeratorAllowed : ModifyOperation.Remove | ModifyOperation.Clear;
/// <summary>
/// Creates an object that is dependent on the seed given. The object may be either
/// a value type or a reference type, chosen based on the value of the seed.
/// </summary>
protected override object CreateTKey(int seed)
{
int stringLength = seed % 10 + 5;
Random rand = new Random(seed);
byte[] bytes = new byte[stringLength];
rand.NextBytes(bytes);
return Convert.ToBase64String(bytes);
}
/// <summary>
/// Creates an object that is dependent on the seed given. The object may be either
/// a value type or a reference type, chosen based on the value of the seed.
/// </summary>
protected override object CreateTValue(int seed) => CreateTKey(seed);
protected override Type ICollection_NonGeneric_CopyTo_IndexLargerThanArrayCount_ThrowType => typeof(ArgumentOutOfRangeException);
#region IDictionary tests
[Fact]
public void IDictionary_NonGeneric_ItemSet_NullValueWhenDefaultValueIsNonNull()
{
IDictionary dictionary = new Dictionary<string, int>();
Assert.Throws<ArgumentNullException>(() => dictionary[GetNewKey(dictionary)] = null);
}
[Fact]
public void IDictionary_NonGeneric_ItemSet_KeyOfWrongType()
{
if (!IsReadOnly)
{
IDictionary dictionary = new Dictionary<string, string>();
AssertExtensions.Throws<ArgumentException>("key", () => dictionary[23] = CreateTValue(12345));
Assert.Empty(dictionary);
}
}
[Fact]
public void IDictionary_NonGeneric_ItemSet_ValueOfWrongType()
{
if (!IsReadOnly)
{
IDictionary dictionary = new Dictionary<string, string>();
object missingKey = GetNewKey(dictionary);
AssertExtensions.Throws<ArgumentException>("value", () => dictionary[missingKey] = 324);
Assert.Empty(dictionary);
}
}
[Fact]
public void IDictionary_NonGeneric_Add_KeyOfWrongType()
{
if (!IsReadOnly)
{
IDictionary dictionary = new Dictionary<string, string>();
object missingKey = 23;
AssertExtensions.Throws<ArgumentException>("key", () => dictionary.Add(missingKey, CreateTValue(12345)));
Assert.Empty(dictionary);
}
}
[Fact]
public void IDictionary_NonGeneric_Add_ValueOfWrongType()
{
if (!IsReadOnly)
{
IDictionary dictionary = new Dictionary<string, string>();
object missingKey = GetNewKey(dictionary);
AssertExtensions.Throws<ArgumentException>("value", () => dictionary.Add(missingKey, 324));
Assert.Empty(dictionary);
}
}
[Fact]
public void IDictionary_NonGeneric_Add_NullValueWhenDefaultTValueIsNonNull()
{
if (!IsReadOnly)
{
IDictionary dictionary = new Dictionary<string, int>();
object missingKey = GetNewKey(dictionary);
Assert.Throws<ArgumentNullException>(() => dictionary.Add(missingKey, null));
Assert.Empty(dictionary);
}
}
[Fact]
public void IDictionary_NonGeneric_Contains_KeyOfWrongType()
{
if (!IsReadOnly)
{
IDictionary dictionary = new Dictionary<string, int>();
Assert.False(dictionary.Contains(1));
}
}
[Fact]
public void Clear_OnEmptyCollection_DoesNotInvalidateEnumerator()
{
if (ModifyEnumeratorAllowed.HasFlag(ModifyOperation.Clear))
{
IDictionary dictionary = new Dictionary<string, string>();
IEnumerator valuesEnum = dictionary.GetEnumerator();
dictionary.Clear();
Assert.Empty(dictionary);
Assert.False(valuesEnum.MoveNext());
}
}
#endregion
#region ICollection tests
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_ArrayOfIncorrectKeyValuePairType(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
KeyValuePair<string, int>[] array = new KeyValuePair<string, int>[count * 3 / 2];
AssertExtensions.Throws<ArgumentException>(null, () => collection.CopyTo(array, 0));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_ArrayOfCorrectKeyValuePairType(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
KeyValuePair<string, string>[] array = new KeyValuePair<string, string>[count];
collection.CopyTo(array, 0);
int i = 0;
foreach (object obj in collection)
Assert.Equal(array[i++], obj);
}
#endregion
}
public class Dictionary_Tests
{
[Fact]
public void CopyConstructorExceptions()
{
AssertExtensions.Throws<ArgumentNullException>("dictionary", () => new Dictionary<int, int>((IDictionary<int, int>)null));
AssertExtensions.Throws<ArgumentNullException>("dictionary", () => new Dictionary<int, int>((IDictionary<int, int>)null, null));
AssertExtensions.Throws<ArgumentNullException>("dictionary", () => new Dictionary<int, int>((IDictionary<int, int>)null, EqualityComparer<int>.Default));
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Dictionary<int, int>(new NegativeCountDictionary<int, int>()));
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Dictionary<int, int>(new NegativeCountDictionary<int, int>(), null));
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Dictionary<int, int>(new NegativeCountDictionary<int, int>(), EqualityComparer<int>.Default));
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(101)]
public void ICollection_NonGeneric_CopyTo_NonContiguousDictionary(int count)
{
ICollection collection = (ICollection)CreateDictionary(count, k => k.ToString());
KeyValuePair<string, string>[] array = new KeyValuePair<string, string>[count];
collection.CopyTo(array, 0);
int i = 0;
foreach (object obj in collection)
Assert.Equal(array[i++], obj);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(101)]
public void ICollection_Generic_CopyTo_NonContiguousDictionary(int count)
{
ICollection<KeyValuePair<string, string>> collection = CreateDictionary(count, k => k.ToString());
KeyValuePair<string, string>[] array = new KeyValuePair<string, string>[count];
collection.CopyTo(array, 0);
int i = 0;
foreach (KeyValuePair<string, string> obj in collection)
Assert.Equal(array[i++], obj);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(101)]
public void IDictionary_Generic_CopyTo_NonContiguousDictionary(int count)
{
IDictionary<string, string> collection = CreateDictionary(count, k => k.ToString());
KeyValuePair<string, string>[] array = new KeyValuePair<string, string>[count];
collection.CopyTo(array, 0);
int i = 0;
foreach (KeyValuePair<string, string> obj in collection)
Assert.Equal(array[i++], obj);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(101)]
public void CopyTo_NonContiguousDictionary(int count)
{
Dictionary<string, string> collection = (Dictionary<string, string>)CreateDictionary(count, k => k.ToString());
string[] array = new string[count];
collection.Keys.CopyTo(array, 0);
int i = 0;
foreach (KeyValuePair<string, string> obj in collection)
Assert.Equal(array[i++], obj.Key);
collection.Values.CopyTo(array, 0);
i = 0;
foreach (KeyValuePair<string, string> obj in collection)
Assert.Equal(array[i++], obj.Key);
}
[Fact]
public void Remove_NonExistentEntries_DoesNotPreventEnumeration()
{
const string SubKey = "-sub-key";
var dictionary = new Dictionary<string, string>();
dictionary.Add("a", "b");
dictionary.Add("c", "d");
foreach (string key in dictionary.Keys)
{
if (dictionary.Remove(key + SubKey))
break;
}
dictionary.Add("c" + SubKey, "d");
foreach (string key in dictionary.Keys)
{
if (dictionary.Remove(key + SubKey))
break;
}
}
[Fact]
public void TryAdd_ItemAlreadyExists_DoesNotInvalidateEnumerator()
{
var dictionary = new Dictionary<string, string>();
dictionary.Add("a", "b");
IEnumerator valuesEnum = dictionary.GetEnumerator();
Assert.False(dictionary.TryAdd("a", "c"));
Assert.True(valuesEnum.MoveNext());
}
[Theory]
[MemberData(nameof(CopyConstructorInt32Data))]
public void CopyConstructorInt32(int size, Func<int, int> keyValueSelector, Func<IDictionary<int, int>, IDictionary<int, int>> dictionarySelector)
{
TestCopyConstructor(size, keyValueSelector, dictionarySelector);
}
public static IEnumerable<object[]> CopyConstructorInt32Data
{
get { return GetCopyConstructorData(i => i); }
}
[Theory]
[MemberData(nameof(CopyConstructorStringData))]
public void CopyConstructorString(int size, Func<int, string> keyValueSelector, Func<IDictionary<string, string>, IDictionary<string, string>> dictionarySelector)
{
TestCopyConstructor(size, keyValueSelector, dictionarySelector);
}
public static IEnumerable<object[]> CopyConstructorStringData
{
get { return GetCopyConstructorData(i => i.ToString()); }
}
private static void TestCopyConstructor<T>(int size, Func<int, T> keyValueSelector, Func<IDictionary<T, T>, IDictionary<T, T>> dictionarySelector)
{
IDictionary<T, T> expected = CreateDictionary(size, keyValueSelector);
IDictionary<T, T> input = dictionarySelector(CreateDictionary(size, keyValueSelector));
Assert.Equal(expected, new Dictionary<T, T>(input));
}
[Theory]
[MemberData(nameof(CopyConstructorInt32ComparerData))]
public void CopyConstructorInt32Comparer(int size, Func<int, int> keyValueSelector, Func<IDictionary<int, int>, IDictionary<int, int>> dictionarySelector, IEqualityComparer<int> comparer)
{
TestCopyConstructor(size, keyValueSelector, dictionarySelector, comparer);
}
public static IEnumerable<object[]> CopyConstructorInt32ComparerData
{
get
{
var comparers = new IEqualityComparer<int>[]
{
null,
EqualityComparer<int>.Default
};
return GetCopyConstructorData(i => i, comparers);
}
}
[Theory]
[MemberData(nameof(CopyConstructorStringComparerData))]
public void CopyConstructorStringComparer(int size, Func<int, string> keyValueSelector, Func<IDictionary<string, string>, IDictionary<string, string>> dictionarySelector, IEqualityComparer<string> comparer)
{
TestCopyConstructor(size, keyValueSelector, dictionarySelector, comparer);
}
[Fact]
public void CantAcceptDuplicateKeysFromSourceDictionary()
{
Dictionary<string, int> source = new Dictionary<string, int> { { "a", 1 }, { "A", 1 } };
AssertExtensions.Throws<ArgumentException>(null, () => new Dictionary<string, int>(source, StringComparer.OrdinalIgnoreCase));
}
public static IEnumerable<object[]> CopyConstructorStringComparerData
{
get
{
var comparers = new IEqualityComparer<string>[]
{
null,
EqualityComparer<string>.Default,
StringComparer.Ordinal,
StringComparer.OrdinalIgnoreCase
};
return GetCopyConstructorData(i => i.ToString(), comparers);
}
}
private static void TestCopyConstructor<T>(int size, Func<int, T> keyValueSelector, Func<IDictionary<T, T>, IDictionary<T, T>> dictionarySelector, IEqualityComparer<T> comparer)
{
IDictionary<T, T> expected = CreateDictionary(size, keyValueSelector, comparer);
IDictionary<T, T> input = dictionarySelector(CreateDictionary(size, keyValueSelector, comparer));
Assert.Equal(expected, new Dictionary<T, T>(input, comparer));
}
private static IEnumerable<object[]> GetCopyConstructorData<T>(Func<int, T> keyValueSelector, IEqualityComparer<T>[] comparers = null)
{
var dictionarySelectors = new Func<IDictionary<T, T>, IDictionary<T, T>>[]
{
d => d,
d => new DictionarySubclass<T, T>(d),
d => new ReadOnlyDictionary<T, T>(d)
};
var sizes = new int[] { 0, 1, 2, 3 };
foreach (Func<IDictionary<T, T>, IDictionary<T, T>> dictionarySelector in dictionarySelectors)
{
foreach (int size in sizes)
{
if (comparers != null)
{
foreach (IEqualityComparer<T> comparer in comparers)
{
yield return new object[] { size, keyValueSelector, dictionarySelector, comparer };
}
}
else
{
yield return new object[] { size, keyValueSelector, dictionarySelector };
}
}
}
}
private static IDictionary<T, T> CreateDictionary<T>(int size, Func<int, T> keyValueSelector, IEqualityComparer<T> comparer = null)
{
Dictionary<T, T> dict = Enumerable.Range(0, size + 1).ToDictionary(keyValueSelector, keyValueSelector, comparer);
// Remove first item to reduce Count to size and alter the contiguity of the dictionary
dict.Remove(keyValueSelector(0));
return dict;
}
[Fact]
public void ComparerSerialization()
{
// Strings switch between randomized and non-randomized comparers,
// however this should never be observable externally.
TestComparerSerialization(EqualityComparer<string>.Default);
// OrdinalCaseSensitiveComparer is internal and (de)serializes as OrdinalComparer
TestComparerSerialization(StringComparer.Ordinal, "System.OrdinalComparer");
// OrdinalIgnoreCaseComparer is internal and (de)serializes as OrdinalComparer
TestComparerSerialization(StringComparer.OrdinalIgnoreCase, "System.OrdinalComparer");
TestComparerSerialization(StringComparer.CurrentCulture);
TestComparerSerialization(StringComparer.CurrentCultureIgnoreCase);
TestComparerSerialization(StringComparer.InvariantCulture);
TestComparerSerialization(StringComparer.InvariantCultureIgnoreCase);
// Check other types while here, IEquatable valuetype, nullable valuetype, and non IEquatable object
TestComparerSerialization(EqualityComparer<int>.Default);
TestComparerSerialization(EqualityComparer<int?>.Default);
TestComparerSerialization(EqualityComparer<object>.Default);
}
private static void TestComparerSerialization<T>(IEqualityComparer<T> equalityComparer, string internalTypeName = null)
{
var bf = new BinaryFormatter();
var s = new MemoryStream();
var dict = new Dictionary<T, T>(equalityComparer);
Assert.Same(equalityComparer, dict.Comparer);
bf.Serialize(s, dict);
s.Position = 0;
dict = (Dictionary<T, T>)bf.Deserialize(s);
if (internalTypeName == null)
{
Assert.IsType(equalityComparer.GetType(), dict.Comparer);
}
else
{
Assert.Equal(internalTypeName, dict.Comparer.GetType().ToString());
}
Assert.True(equalityComparer.Equals(dict.Comparer));
}
private sealed class DictionarySubclass<TKey, TValue> : Dictionary<TKey, TValue>
{
public DictionarySubclass(IDictionary<TKey, TValue> dictionary)
{
foreach (var pair in dictionary)
{
Add(pair.Key, pair.Value);
}
}
}
/// <summary>
/// An incorrectly implemented dictionary that returns -1 from Count.
/// </summary>
private sealed class NegativeCountDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
public int Count { get { return -1; } }
public TValue this[TKey key] { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } }
public bool IsReadOnly { get { throw new NotImplementedException(); } }
public ICollection<TKey> Keys { get { throw new NotImplementedException(); } }
public ICollection<TValue> Values { get { throw new NotImplementedException(); } }
public void Add(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); }
public void Add(TKey key, TValue value) { throw new NotImplementedException(); }
public void Clear() { throw new NotImplementedException(); }
public bool Contains(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); }
public bool ContainsKey(TKey key) { throw new NotImplementedException(); }
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { throw new NotImplementedException(); }
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { throw new NotImplementedException(); }
public bool Remove(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); }
public bool Remove(TKey key) { throw new NotImplementedException(); }
public bool TryGetValue(TKey key, out TValue value) { throw new NotImplementedException(); }
IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); }
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
namespace Microsoft.CodeAnalysis.Differencing
{
public sealed partial class Match<TNode>
{
private const double ExactMatchDistance = 0.0;
private const double EpsilonDistance = 0.00001;
private const double MatchingDistance1 = 0.25;
private const double MatchingDistance2 = 0.5;
private const double MatchingDistance3 = 0.75;
private const double MaxDistance = 1.0;
private readonly TreeComparer<TNode> _comparer;
private readonly TNode _root1;
private readonly TNode _root2;
private readonly Dictionary<TNode, TNode> _oneToTwo;
private readonly Dictionary<TNode, TNode> _twoToOne;
internal Match(TNode root1, TNode root2, TreeComparer<TNode> comparer, IEnumerable<KeyValuePair<TNode, TNode>> knownMatches)
{
_root1 = root1;
_root2 = root2;
_comparer = comparer;
int labelCount = comparer.LabelCount;
CategorizeNodesByLabels(comparer, root1, labelCount, out var nodes1, out var count1);
CategorizeNodesByLabels(comparer, root2, labelCount, out var nodes2, out var count2);
_oneToTwo = new Dictionary<TNode, TNode>();
_twoToOne = new Dictionary<TNode, TNode>();
// Root nodes always match. Add them before adding known matches to make sure we always have root mapping.
TryAdd(root1, root2);
if (knownMatches != null)
{
foreach (var knownMatch in knownMatches)
{
if (comparer.GetLabel(knownMatch.Key) != comparer.GetLabel(knownMatch.Value))
{
throw new ArgumentException(string.Format(WorkspacesResources.Matching_nodes_0_and_1_must_have_the_same_label, knownMatch.Key, knownMatch.Value), nameof(knownMatches));
}
if (!comparer.TreesEqual(knownMatch.Key, root1))
{
throw new ArgumentException(string.Format(WorkspacesResources.Node_0_must_be_contained_in_the_old_tree, knownMatch.Key), nameof(knownMatches));
}
if (!comparer.TreesEqual(knownMatch.Value, root2))
{
throw new ArgumentException(string.Format(WorkspacesResources.Node_0_must_be_contained_in_the_new_tree, knownMatch.Value), nameof(knownMatches));
}
// skip pairs whose key or value is already mapped:
TryAdd(knownMatch.Key, knownMatch.Value);
}
}
ComputeMatch(nodes1, nodes2);
}
private static void CategorizeNodesByLabels(
TreeComparer<TNode> comparer,
TNode root,
int labelCount,
out List<TNode>[] nodes,
out int totalCount)
{
nodes = new List<TNode>[labelCount];
int count = 0;
// It is important that we add the nodes in depth-first prefix order.
// This order ensures that a node of a certain kind can have a parent of the same kind
// and we can still use tied-to-parent for that kind. That's because the parent will always
// be processed earlier than the child due to depth-first prefix ordering.
foreach (TNode node in comparer.GetDescendants(root))
{
int label = comparer.GetLabel(node);
if (label < 0 || label >= labelCount)
{
throw new InvalidOperationException(string.Format(WorkspacesResources.Label_for_node_0_is_invalid_it_must_be_within_bracket_0_1, node, labelCount));
}
var list = nodes[label];
if (list == null)
{
nodes[label] = list = new List<TNode>();
}
list.Add(node);
count++;
}
totalCount = count;
}
private void ComputeMatch(List<TNode>[] nodes1, List<TNode>[] nodes2)
{
Debug.Assert(nodes1.Length == nodes2.Length);
// --- The original FastMatch algorithm ---
//
// For each leaf label l, and then for each internal node label l do:
// a) S1 := chain T1(l)
// b) S2 := chain T2(l)
// c) lcs := LCS(S1, S2, Equal)
// d) For each pair of nodes (x,y) in lcs add (x,y) to M.
// e) Pair unmatched nodes with label l as in Algorithm Match, adding matches to M:
// For each unmatched node x in T1, if there is an unmatched node y in T2 such that equal(x,y)
// then add (x,y) to M.
//
// equal(x,y) is defined as follows:
// x, y are leafs => equal(x,y) := label(x) == label(y) && compare(value(x), value(y)) <= f
// x, y are nodes => equal(x,y) := label(x) == label(y) && |common(x,y)| / max(|x|, |y|) > t
// where f, t are constants.
//
// --- Actual implementation ---
//
// We also categorize nodes by their labels, but then we proceed differently:
//
// 1) A label may be marked "tied to parent". Let x, y have both label l and l is "tied to parent".
// Then (x,y) can be in M only if (parent(x), parent(y)) in M.
// Thus we require labels of children tied to a parent to be preceded by all their possible parent labels.
//
// 2) Rather than defining function equal in terms of constants f and t, which are hard to get right,
// we try to match multiple times with different threshold for node distance.
// The comparer defines the distance [0..1] between two nodes and it can do so by analyzing
// the node structure and value. The comparer can tune the distance specifically for each node kind.
// We first try to match nodes of the same labels to the exactly matching or almost matching counterparts.
// The we keep increasing the threshold and keep adding matches.
for (int l = 0; l < nodes1.Length; l++)
{
if (nodes1[l] != null && nodes2[l] != null)
{
ComputeMatchForLabel(l, nodes1[l], nodes2[l]);
}
}
}
private void ComputeMatchForLabel(int label, List<TNode> s1, List<TNode> s2)
{
int tiedToAncestor = _comparer.TiedToAncestor(label);
ComputeMatchForLabel(s1, s2, tiedToAncestor, EpsilonDistance); // almost exact match
ComputeMatchForLabel(s1, s2, tiedToAncestor, MatchingDistance1); // ok match
ComputeMatchForLabel(s1, s2, tiedToAncestor, MatchingDistance2); // ok match
ComputeMatchForLabel(s1, s2, tiedToAncestor, MatchingDistance3); // ok match
ComputeMatchForLabel(s1, s2, tiedToAncestor, MaxDistance); // any match
}
private void ComputeMatchForLabel(List<TNode> s1, List<TNode> s2, int tiedToAncestor, double maxAcceptableDistance)
{
// Obviously, the algorithm below is O(n^2). However, in the common case, the 2 lists will
// be sequences that exactly match. The purpose of "firstNonMatch2" is to reduce the complexity
// to O(n) in this case. Basically, the pointer is the 1st non-matched node in the list of nodes of tree2
// with the given label.
// Whenever we match to firstNonMatch2 we set firstNonMatch2 to the subsequent node.
// So in the case of totally matching sequences, we process them in O(n) -
// both node1 and firstNonMatch2 will be advanced simultaneously.
Debug.Assert(maxAcceptableDistance >= ExactMatchDistance && maxAcceptableDistance <= MaxDistance);
int count1 = s1.Count;
int count2 = s2.Count;
int firstNonMatch2 = 0;
for (int i1 = 0; i1 < count1; i1++)
{
TNode node1 = s1[i1];
// Skip this guy if it already has a partner
if (HasPartnerInTree2(node1))
{
continue;
}
// Find node2 that matches node1 the best, i.e. has minimal distance.
double bestDistance = MaxDistance * 2;
TNode bestMatch = default(TNode);
bool matched = false;
int i2;
for (i2 = firstNonMatch2; i2 < count2; i2++)
{
TNode node2 = s2[i2];
// Skip this guy if it already has a partner
if (HasPartnerInTree1(node2))
{
continue;
}
// this requires parents to be processed before their children:
if (tiedToAncestor > 0)
{
// TODO (tomat): For nodes tied to their parents,
// consider avoiding matching them to all other nodes of the same label.
// Rather we should only match them with their siblings that share the same parent.
var ancestor1 = _comparer.GetAncestor(node1, tiedToAncestor);
var ancestor2 = _comparer.GetAncestor(node2, tiedToAncestor);
// Since CategorizeNodesByLabels added nodes to the s1/s2 lists in depth-first prefix order,
// we can also accept equality in the following condition. That's because we find the partner
// of the parent node before we get to finding it for the child node of the same kind.
Debug.Assert(_comparer.GetLabel(ancestor1) <= _comparer.GetLabel(node1));
if (!Contains(ancestor1, ancestor2))
{
continue;
}
}
// We know that
// 1. (node1, node2) not in M
// 2. Both of their parents are matched to the same parent (or are not matched)
//
// Now, we have no other choice than comparing the node "values"
// and looking for the one with the smaller distance.
double distance = _comparer.GetDistance(node1, node2);
if (distance < bestDistance)
{
matched = true;
bestMatch = node2;
bestDistance = distance;
// We only stop if we've got an exact match. This is to resolve the problem
// of entities with identical names(name is often used as the "value" of a
// node) but with different "sub-values" (e.g. two locals may have the same name
// but different types. Since the type is not part of the value, we don't want
// to stop looking for the best match if we don't have an exact match).
if (distance == ExactMatchDistance)
{
break;
}
}
}
if (matched && bestDistance <= maxAcceptableDistance)
{
bool added = TryAdd(node1, bestMatch);
// We checked above that node1 doesn't have a partner.
// The map is a bijection by construction, so we should be able to add the mapping.
Debug.Assert(added);
// If we exactly matched to firstNonMatch2 we can advance it.
if (i2 == firstNonMatch2)
{
firstNonMatch2 = i2 + 1;
}
if (firstNonMatch2 == count2)
{
return;
}
}
}
}
internal bool TryAdd(TNode node1, TNode node2)
{
Debug.Assert(_comparer.TreesEqual(node1, _root1));
Debug.Assert(_comparer.TreesEqual(node2, _root2));
if (_oneToTwo.ContainsKey(node1) || _twoToOne.ContainsKey(node2))
{
return false;
}
_oneToTwo.Add(node1, node2);
_twoToOne.Add(node2, node1);
return true;
}
internal bool TryGetPartnerInTree1(TNode node2, out TNode partner1)
{
bool result = _twoToOne.TryGetValue(node2, out partner1);
Debug.Assert(_comparer.TreesEqual(node2, _root2));
Debug.Assert(!result || _comparer.TreesEqual(partner1, _root1));
return result;
}
internal bool HasPartnerInTree1(TNode node2)
{
Debug.Assert(_comparer.TreesEqual(node2, _root2));
return _twoToOne.ContainsKey(node2);
}
internal bool TryGetPartnerInTree2(TNode node1, out TNode partner2)
{
bool result = _oneToTwo.TryGetValue(node1, out partner2);
Debug.Assert(_comparer.TreesEqual(node1, _root1));
Debug.Assert(!result || _comparer.TreesEqual(partner2, _root2));
return result;
}
internal bool HasPartnerInTree2(TNode node1)
{
Debug.Assert(_comparer.TreesEqual(node1, _root1));
return _oneToTwo.ContainsKey(node1);
}
internal bool Contains(TNode node1, TNode node2)
{
Debug.Assert(_comparer.TreesEqual(node2, _root2));
return TryGetPartnerInTree2(node1, out var partner2) && node2.Equals(partner2);
}
public TreeComparer<TNode> Comparer => _comparer;
public TNode OldRoot => _root1;
public TNode NewRoot => _root2;
public IReadOnlyDictionary<TNode, TNode> Matches
{
get
{
return new ReadOnlyDictionary<TNode, TNode>(_oneToTwo);
}
}
public IReadOnlyDictionary<TNode, TNode> ReverseMatches
{
get
{
return new ReadOnlyDictionary<TNode, TNode>(_twoToOne);
}
}
public bool TryGetNewNode(TNode oldNode, out TNode newNode)
{
return _oneToTwo.TryGetValue(oldNode, out newNode);
}
public bool TryGetOldNode(TNode newNode, out TNode oldNode)
{
return _twoToOne.TryGetValue(newNode, out oldNode);
}
/// <summary>
/// Returns an edit script (a sequence of edits) that transform <see cref="OldRoot"/> subtree
/// to <see cref="NewRoot"/> subtree.
/// </summary>
public EditScript<TNode> GetTreeEdits()
{
return new EditScript<TNode>(this);
}
/// <summary>
/// Returns an edit script (a sequence of edits) that transform a sequence of nodes <paramref name="oldNodes"/>
/// to a sequence of nodes <paramref name="newNodes"/>.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="oldNodes"/> or <paramref name="newNodes"/> is a null reference.</exception>
public IEnumerable<Edit<TNode>> GetSequenceEdits(IEnumerable<TNode> oldNodes, IEnumerable<TNode> newNodes)
{
if (oldNodes == null)
{
throw new ArgumentNullException(nameof(oldNodes));
}
if (newNodes == null)
{
throw new ArgumentNullException(nameof(newNodes));
}
var oldList = (oldNodes as IReadOnlyList<TNode>) ?? oldNodes.ToList();
var newList = (newNodes as IReadOnlyList<TNode>) ?? newNodes.ToList();
return new LongestCommonSubsequence(this).GetEdits(oldList, newList);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Windows;
using System.Diagnostics;
using System.Windows.Input;
using System.Windows.Media;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using MS.Utility;
using MS.Internal;
using SR = MS.Internal.PresentationCore.SR;
using SRID = MS.Internal.PresentationCore.SRID;
namespace System.Windows.Input
{
/// <summary>
/// Represents a single sampling point from a stylus input device
/// </summary>
public struct StylusPoint : IEquatable<StylusPoint>
{
internal static readonly float DefaultPressure = 0.5f;
private double _x;
private double _y;
private float _pressureFactor;
private int[] _additionalValues;
private StylusPointDescription _stylusPointDescription;
#region Constructors
/// <summary>
/// StylusPoint
/// </summary>
/// <param name="x">x</param>
/// <param name="y">y</param>
public StylusPoint(double x, double y)
: this(x, y, DefaultPressure, null, null, false, false)
{
}
/// <summary>
/// StylusPoint
/// </summary>
/// <param name="x">x</param>
/// <param name="y">y</param>
/// <param name="pressureFactor">pressureFactor</param>
public StylusPoint(double x, double y, float pressureFactor)
: this(x, y, pressureFactor, null, null, false, true)
{
}
/// <summary>
/// StylusPoint
/// </summary>
/// <param name="x">x</param>
/// <param name="y">y</param>
/// <param name="pressureFactor">pressureFactor</param>
/// <param name="stylusPointDescription">stylusPointDescription</param>
/// <param name="additionalValues">additionalValues</param>
public StylusPoint(double x, double y, float pressureFactor, StylusPointDescription stylusPointDescription, int[] additionalValues)
: this(x, y, pressureFactor, stylusPointDescription, additionalValues, true, true)
{
}
/// <summary>
/// internal ctor
/// </summary>
internal StylusPoint(
double x,
double y,
float pressureFactor,
StylusPointDescription stylusPointDescription,
int[] additionalValues,
bool validateAdditionalData,
bool validatePressureFactor)
{
if (Double.IsNaN(x))
{
throw new ArgumentOutOfRangeException("x", SR.Get(SRID.InvalidStylusPointXYNaN));
}
if (Double.IsNaN(y))
{
throw new ArgumentOutOfRangeException("y", SR.Get(SRID.InvalidStylusPointXYNaN));
}
//we don't validate pressure when called by StylusPointDescription.Reformat
if (validatePressureFactor &&
(pressureFactor == Single.NaN || pressureFactor < 0.0f || pressureFactor > 1.0f))
{
throw new ArgumentOutOfRangeException("pressureFactor", SR.Get(SRID.InvalidPressureValue));
}
//
// only accept values between MaxXY and MinXY
// we don't throw when passed a value outside of that range, we just silently trunctate
//
_x = GetClampedXYValue(x);
_y = GetClampedXYValue(y);
_stylusPointDescription = stylusPointDescription;
_additionalValues = additionalValues;
_pressureFactor = pressureFactor;
if (validateAdditionalData)
{
//
// called from the public verbose ctor
//
if (null == stylusPointDescription)
{
throw new ArgumentNullException("stylusPointDescription");
}
//
// additionalValues can be null if PropertyCount == 3 (X, Y, P)
//
if (stylusPointDescription.PropertyCount > StylusPointDescription.RequiredCountOfProperties &&
null == additionalValues)
{
throw new ArgumentNullException("additionalValues");
}
if (additionalValues != null)
{
ReadOnlyCollection<StylusPointPropertyInfo> properties
= stylusPointDescription.GetStylusPointProperties();
int expectedAdditionalValues = properties.Count - StylusPointDescription.RequiredCountOfProperties; //for x, y, pressure
if (additionalValues.Length != expectedAdditionalValues)
{
throw new ArgumentException(SR.Get(SRID.InvalidAdditionalDataForStylusPoint), "additionalValues");
}
//
// any buttons passed in must each be in their own int. We need to
// pack them all into one int here
//
int[] newAdditionalValues =
new int[stylusPointDescription.GetExpectedAdditionalDataCount()];
_additionalValues = newAdditionalValues;
for (int i = StylusPointDescription.RequiredCountOfProperties, j = 0; i < properties.Count; i++, j++)
{
//
// use SetPropertyValue, it validates buttons, but does not copy the
// int[] on writes (since we pass the bool flag)
//
SetPropertyValue(properties[i], additionalValues[j], false/*copy on write*/);
}
}
}
}
#endregion Constructors
/// <summary>
/// The Maximum X or Y value supported for backwards compatibility with previous inking platforms
/// </summary>
public static readonly double MaxXY = 81164736.28346430d;
/// <summary>
/// The Minimum X or Y value supported for backwards compatibility with previous inking platforms
/// </summary>
public static readonly double MinXY = -81164736.32125960d;
/// <summary>
/// X
/// </summary>
public double X
{
get { return _x; }
set
{
if (Double.IsNaN(value))
{
throw new ArgumentOutOfRangeException("X", SR.Get(SRID.InvalidStylusPointXYNaN));
}
//
// only accept values between MaxXY and MinXY
// we don't throw when passed a value outside of that range, we just silently trunctate
//
_x = GetClampedXYValue(value);
}
}
/// <summary>
/// Y
/// </summary>
public double Y
{
get { return _y; }
set
{
if (Double.IsNaN(value))
{
throw new ArgumentOutOfRangeException("Y", SR.Get(SRID.InvalidStylusPointXYNaN));
}
//
// only accept values between MaxXY and MinXY
// we don't throw when passed a value outside of that range, we just silently trunctate
//
_y = GetClampedXYValue(value);
}
}
/// <summary>
/// PressureFactor. A value between 0.0 (no pressure) and 1.0 (max pressure)
/// </summary>
public float PressureFactor
{
get
{
//
// note that pressure can be stored a > 1 or < 0.
// we need to clamp if this is the case
//
if (_pressureFactor > 1.0f)
{
return 1.0f;
}
if (_pressureFactor < 0.0f)
{
return 0.0f;
}
return _pressureFactor;
}
set
{
if (value < 0.0f || value > 1.0f)
{
throw new ArgumentOutOfRangeException("PressureFactor", SR.Get(SRID.InvalidPressureValue));
}
_pressureFactor = value;
}
}
/// <summary>
/// Describes the properties this StylusPoint contains
/// </summary>
public StylusPointDescription Description
{
get
{
if (null == _stylusPointDescription)
{
// this can happen when you call new StylusPoint()
// a few of the ctor's lazy init this as well
_stylusPointDescription = new StylusPointDescription();
}
return _stylusPointDescription;
}
internal set
{
//
// called by StylusPointCollection.Add / Set
// to replace the StylusPoint.Description with the collections.
//
Debug.Assert(value != null &&
StylusPointDescription.AreCompatible(value, this.Description));
_stylusPointDescription = value;
}
}
/// <summary>
/// Returns true if this StylusPoint supports the specified property
/// </summary>
/// <param name="stylusPointProperty">The StylusPointProperty to see if this StylusPoint supports</param>
public bool HasProperty(StylusPointProperty stylusPointProperty)
{
return this.Description.HasProperty(stylusPointProperty);
}
/// <summary>
/// Provides read access to all stylus properties
/// </summary>
/// <param name="stylusPointProperty">The StylusPointPropertyIds of the property to retrieve</param>
public int GetPropertyValue(StylusPointProperty stylusPointProperty)
{
if (null == stylusPointProperty)
{
throw new ArgumentNullException("stylusPointProperty");
}
if (stylusPointProperty.Id == StylusPointPropertyIds.X)
{
return (int)_x;
}
else if (stylusPointProperty.Id == StylusPointPropertyIds.Y)
{
return (int)_y;
}
else if (stylusPointProperty.Id == StylusPointPropertyIds.NormalPressure)
{
StylusPointPropertyInfo info =
this.Description.GetPropertyInfo(StylusPointProperties.NormalPressure);
int max = info.Maximum;
return (int)(_pressureFactor * (float)max);
}
else
{
int propertyIndex = this.Description.GetPropertyIndex(stylusPointProperty.Id);
if (-1 == propertyIndex)
{
throw new ArgumentException(SR.Get(SRID.InvalidStylusPointProperty), "stylusPointProperty");
}
if (stylusPointProperty.IsButton)
{
//
// we get button data from a single int in the array
//
int buttonData = _additionalValues[_additionalValues.Length - 1];
int buttonBitPosition = this.Description.GetButtonBitPosition(stylusPointProperty);
int bit = 1 << buttonBitPosition;
if ((buttonData & bit) != 0)
{
return 1;
}
else
{
return 0;
}
}
else
{
return _additionalValues[propertyIndex - 3];
}
}
}
/// <summary>
/// Allows supported properties to be set
/// </summary>
/// <param name="stylusPointProperty">The property to set, it must exist on this StylusPoint</param>
/// <param name="value">value</param>
public void SetPropertyValue(StylusPointProperty stylusPointProperty, int value)
{
SetPropertyValue(stylusPointProperty, value, true);
}
/// <summary>
/// Optimization that lets the ctor call setvalue repeatly without causing a copy of the int[]
/// </summary>
/// <param name="stylusPointProperty">stylusPointProperty</param>
/// <param name="value">value</param>
/// <param name="copyBeforeWrite"></param>
internal void SetPropertyValue(StylusPointProperty stylusPointProperty, int value, bool copyBeforeWrite)
{
if (null == stylusPointProperty)
{
throw new ArgumentNullException("stylusPointProperty");
}
if (stylusPointProperty.Id == StylusPointPropertyIds.X)
{
double dVal = (double)value;
//
// only accept values between MaxXY and MinXY
// we don't throw when passed a value outside of that range, we just silently trunctate
//
_x = GetClampedXYValue(dVal);
}
else if (stylusPointProperty.Id == StylusPointPropertyIds.Y)
{
double dVal = (double)value;
//
// only accept values between MaxXY and MinXY
// we don't throw when passed a value outside of that range, we just silently trunctate
//
_y = GetClampedXYValue(dVal);
}
else if (stylusPointProperty.Id == StylusPointPropertyIds.NormalPressure)
{
StylusPointPropertyInfo info =
this.Description.GetPropertyInfo(StylusPointProperties.NormalPressure);
int min = info.Minimum;
int max = info.Maximum;
if (max == 0)
{
_pressureFactor = 0.0f;
}
else
{
_pressureFactor = (float)(Convert.ToSingle(min + value) / Convert.ToSingle(max));
}
}
else
{
int propertyIndex = this.Description.GetPropertyIndex(stylusPointProperty.Id);
if (-1 == propertyIndex)
{
throw new ArgumentException(SR.Get(SRID.InvalidStylusPointProperty), "propertyId");
}
if (stylusPointProperty.IsButton)
{
if (value < 0 || value > 1)
{
throw new ArgumentOutOfRangeException("value", SR.Get(SRID.InvalidMinMaxForButton));
}
if (copyBeforeWrite)
{
CopyAdditionalData();
}
//
// we get button data from a single int in the array
//
int buttonData = _additionalValues[_additionalValues.Length - 1];
int buttonBitPosition = this.Description.GetButtonBitPosition(stylusPointProperty);
int bit = 1 << buttonBitPosition;
if (value == 0)
{
//turn the bit off
buttonData &= ~bit;
}
else
{
//turn the bit on
buttonData |= bit;
}
_additionalValues[_additionalValues.Length - 1] = buttonData;
}
else
{
if (copyBeforeWrite)
{
CopyAdditionalData();
}
_additionalValues[propertyIndex - 3] = value;
}
}
}
/// <summary>
/// Explicit cast converter between StylusPoint and Point
/// </summary>
/// <param name="stylusPoint">stylusPoint</param>
public static explicit operator Point(StylusPoint stylusPoint)
{
return new Point(stylusPoint.X, stylusPoint.Y);
}
/// <summary>
/// Allows languages that don't support operator overloading
/// to convert to a point
/// </summary>
public Point ToPoint()
{
return new Point(this.X, this.Y);
}
/// <summary>
/// Compares two StylusPoint instances for exact equality.
/// Note that double values can acquire error when operated upon, such that
/// an exact comparison between two values which are logically equal may fail.
/// Furthermore, using this equality operator, Double.NaN is not equal to itself.
/// Descriptions must match for equality to succeed and additional values must match
/// </summary>
/// <returns>
/// bool - true if the two Stylus instances are exactly equal, false otherwise
/// </returns>
/// <param name='stylusPoint1'>The first StylusPoint to compare</param>
/// <param name='stylusPoint2'>The second StylusPoint to compare</param>
public static bool operator ==(StylusPoint stylusPoint1, StylusPoint stylusPoint2)
{
return StylusPoint.Equals(stylusPoint1, stylusPoint2);
}
/// <summary>
/// Compares two StylusPoint instances for exact inequality.
/// Note that double values can acquire error when operated upon, such that
/// an exact comparison between two values which are logically equal may fail.
/// Furthermore, using this equality operator, Double.NaN is not equal to itself.
/// </summary>
/// <returns>
/// bool - true if the two Stylus instances are exactly inequal, false otherwise
/// </returns>
/// <param name='stylusPoint1'>The first StylusPoint to compare</param>
/// <param name='stylusPoint2'>The second StylusPoint to compare</param>
public static bool operator !=(StylusPoint stylusPoint1, StylusPoint stylusPoint2)
{
return !StylusPoint.Equals(stylusPoint1, stylusPoint2);
}
/// <summary>
/// Compares two StylusPoint instances for exact equality.
/// Note that double values can acquire error when operated upon, such that
/// an exact comparison between two values which are logically equal may fail.
/// Furthermore, using this equality operator, Double.NaN is not equal to itself.
/// Descriptions must match for equality to succeed and additional values must match
/// </summary>
/// <returns>
/// bool - true if the two Stylus instances are exactly equal, false otherwise
/// </returns>
/// <param name='stylusPoint1'>The first StylusPoint to compare</param>
/// <param name='stylusPoint2'>The second StylusPoint to compare</param>
public static bool Equals(StylusPoint stylusPoint1, StylusPoint stylusPoint2)
{
//
// do the cheap comparison first
//
bool membersEqual =
stylusPoint1._x == stylusPoint2._x &&
stylusPoint1._y == stylusPoint2._y &&
stylusPoint1._pressureFactor == stylusPoint2._pressureFactor;
if (!membersEqual)
{
return false;
}
//
// before we go checking the descriptions... check to see if both additionalData's are null
// we can infer that the SPD's are just X,Y,P and that they are compatible.
//
if (stylusPoint1._additionalValues == null &&
stylusPoint2._additionalValues == null)
{
Debug.Assert(StylusPointDescription.AreCompatible(stylusPoint1.Description, stylusPoint2.Description));
return true;
}
//
// ok, the members are equal. compare the description and then additional data
//
if (object.ReferenceEquals(stylusPoint1.Description, stylusPoint2.Description) ||
StylusPointDescription.AreCompatible(stylusPoint1.Description, stylusPoint2.Description))
{
//
// descriptions match and there are equal numbers of additional values
// let's check the values
//
for (int x = 0; x < stylusPoint1._additionalValues.Length; x++)
{
if (stylusPoint1._additionalValues[x] != stylusPoint2._additionalValues[x])
{
return false;
}
}
//
// Ok, ok already, we're equal
//
return true;
}
return false;
}
/// <summary>
/// Compares two StylusPoint instances for exact equality.
/// Note that double values can acquire error when operated upon, such that
/// an exact comparison between two values which are logically equal may fail.
/// Furthermore, using this equality operator, Double.NaN is not equal to itself.
/// Descriptions must match for equality to succeed and additional values must match
/// </summary>
/// <returns>
/// bool - true if the object is an instance of StylusPoint and if it's equal to "this".
/// </returns>
/// <param name='o'>The object to compare to "this"</param>
public override bool Equals(object o)
{
if ((null == o) || !(o is StylusPoint))
{
return false;
}
StylusPoint value = (StylusPoint)o;
return StylusPoint.Equals(this, value);
}
/// <summary>
/// Equals - compares this StylusPoint with the passed in object. In this equality
/// Double.NaN is equal to itself, unlike in numeric equality.
/// Note that double values can acquire error when operated upon, such that
/// an exact comparison between two values which
/// are logically equal may fail.
/// </summary>
/// <returns>
/// bool - true if "value" is equal to "this".
/// </returns>
/// <param name='value'>The StylusPoint to compare to "this"</param>
public bool Equals(StylusPoint value)
{
return StylusPoint.Equals(this, value);
}
/// <summary>
/// Returns the HashCode for this StylusPoint
/// </summary>
/// <returns>
/// int - the HashCode for this StylusPoint
/// </returns>
public override int GetHashCode()
{
int hash =
_x.GetHashCode() ^
_y.GetHashCode() ^
_pressureFactor.GetHashCode();
if (_stylusPointDescription != null)
{
hash ^= _stylusPointDescription.GetHashCode();
}
if (_additionalValues != null)
{
for (int x = 0; x < _additionalValues.Length; x++)
{
hash ^= _additionalValues[x]; //don't call GetHashCode on integers, it just returns the int
}
}
return hash;
}
/// <summary>
/// Used by the StylusPointCollection.ToHimetricArray method
/// </summary>
/// <returns></returns>
internal int[] GetAdditionalData()
{
//return a direct ref
return _additionalValues;
}
/// <summary>
/// Internal helper used by SPC.Reformat to preserve the pressureFactor
/// </summary>
internal float GetUntruncatedPressureFactor()
{
return _pressureFactor;
}
/// <summary>
/// GetPacketData - returns avalon space packet data with true pressure if it exists
/// </summary>
internal int[] GetPacketData()
{
int count = 2; //x, y
if (_additionalValues != null)
{
count += _additionalValues.Length;
}
if (this.Description.ContainsTruePressure)
{
count++;
}
int[] data = new int[count];
data[0] = (int)_x;
data[1] = (int)_y;
int startIndex = 2;
if (this.Description.ContainsTruePressure)
{
startIndex = 3;
data[2] = GetPropertyValue(StylusPointProperties.NormalPressure);
}
if (_additionalValues != null)
{
for (int x = 0; x < _additionalValues.Length; x++)
{
data[x + startIndex] = _additionalValues[x];
}
}
return data;
}
/// <summary>
/// Internal helper to determine if a stroke has default pressure
/// This is used by ISF serialization to not serialize pressure
/// </summary>
internal bool HasDefaultPressure
{
get
{
return (_pressureFactor == DefaultPressure);
}
}
/// <summary>
/// Used by the SetPropertyData to make a copy of the data
/// before modifying it. This is required so that we don't
/// have two StylusPoint's sharing the same int[]
/// which can happen when you call: StylusPoint p = otherStylusPoint
/// because the CLR just does a memberwise copy
/// </summary>
/// <returns></returns>
private void CopyAdditionalData()
{
if (null != _additionalValues)
{
int[] newData = new int[_additionalValues.Length];
for (int x = 0; x < _additionalValues.Length; x++)
{
newData[x] = _additionalValues[x];
}
_additionalValues = newData;
}
}
/// <summary>
/// Private helper that returns a double clamped to MaxXY or MinXY
/// We only accept values in this range to support ISF serialization
/// </summary>
private static double GetClampedXYValue(double xyValue)
{
if (xyValue > MaxXY)
{
return MaxXY;
}
if (xyValue < MinXY)
{
return MinXY;
}
return xyValue;
}
}
}
| |
using System;
using MicrosoftResearch.Infer;
using MicrosoftResearch.Infer.Collections;
using MicrosoftResearch.Infer.Models;
using MicrosoftResearch.Infer.Distributions;
using MicrosoftResearch.Infer.Maths;
using MicrosoftResearch.Infer.Factors;
using MicrosoftResearch.Infer.Utils;
// This file contains classes related to distributions.
namespace KernelEP.Tool{
public abstract class KEPDist{
public new static IKEPDist FromMatlabStruct(MatlabStruct s){
string className = s.GetString("className");
if(className.Equals(DNormal.MATLAB_CLASS)){
return DNormal.FromMatlabStruct(s);
} else if(className.Equals(DBeta.MATLAB_CLASS)){
return DBeta.FromMatlabStruct(s);
} else{
throw new ArgumentException("unknown distribution class.");
}
}
}
// marker interface for a distribution in this kernel EP framwork
public interface IKEPDist{
// return mean as a vector. Work on univariate distributions as well.
Vector GetMeanVector();
Matrix GetCovarianceMatrix();
ISuff GetSuffStat();
}
// Interface for a distribution in kernel EP framework
// Type D parametrizes the domain of the distribution e.g., double
// Type V = type of variance. Either double or PositiveDefiniteMatrix
// public interface ParamDist<D, V> : CanGetMean<D>,
// CanGetVariance<V>, KEPDist{
//
// // Return true if this Dist is proper e.g., does not have
// // negative variance.
//// public abstract bool IsProper();
//
// // Get the dimension of the input to the distribution
//// public abstract int GetDimension();
//
// }
// univariate distribution
// This is just a wrapper. Infer.NET distributions are sealed (?).
public interface IDistUni : IKEPDist{
// Get the underlying wrapped Infer.NET distribution
IDistribution<double> GetWrappedDistribution();
double GetMean();
double GetVariance();
}
// multivariate distribution
// This is just a wrapper. Infer.NET distributions are sealed (?).
public interface IDistMulti : IKEPDist{
// Get the underlying wrapped Infer.NET distribution
IDistribution<Vector> GetWrappedDistribution();
int GetDimension();
}
// A class representing sufficient statistic.
// This is mainly used for construction of an outgoing message.
// Sufficient statistic for a univariate distribution.
// public class SuffStatUni : SuffStat<double, double>{
//
// public double GetFirstMoment(){
// return -1;
// }
//
// public double GetSecondMoment(){
// return -1;
// }
// }
public interface ISuff{
Vector GetFirstMomentAsVector();
// uncentered 2nd moment
PositiveDefiniteMatrix GetSecondMomentAsMatrix();
// Return true if this is a sufficient statistic for a univariate
// distribution i.e., first moment has one component, 2nd-moment matrix
// has 1 entry.
bool IsUnivariate();
}
public class SuffStat : ISuff{
private readonly Vector firstMoment;
private PositiveDefiniteMatrix secondMoment;
public SuffStat(Vector firstMoment, PositiveDefiniteMatrix secondMoment){
int c1 = firstMoment.Count;
if(c1 * c1 != secondMoment.Count){
throw new ArgumentException("1st & 2nd moments have incompatible dimensions.");
}
this.firstMoment = firstMoment;
this.secondMoment = secondMoment;
}
public Vector GetFirstMomentAsVector(){
return firstMoment;
}
// uncentered 2nd moment
public PositiveDefiniteMatrix GetSecondMomentAsMatrix(){
return secondMoment;
}
// Return true if this is a sufficient statistic for a univariate
// distribution i.e., first moment has one component, 2nd-moment matrix
// has 1 entry.
public bool IsUnivariate(){
return firstMoment.Count == 1;
}
}
public abstract class DistBuilderBase{
public static DistBuilderBase FromMatlabStruct(MatlabStruct s){
string className = s.GetString("className");
if(className.Equals(DNormalBuilder.MATLAB_CLASS)){
return DNormalBuilder.FromMatlabStruct(s);
} else if(className.Equals(DBetaBuilder.MATLAB_CLASS)){
return DBetaBuilder.FromMatlabStruct(s);
} else if(className.Equals(DNormalLogVarBuilder.MATLAB_CLASS)){
return DNormalLogVarBuilder.FromMatlabStruct(s);
} else if(className.Equals(DBetaLogBuilder.MATLAB_CLASS)){
return DBetaLogBuilder.FromMatlabStruct(s);
} else{
throw new ArgumentException("invalid MatlabStruct for a DistBuilder.");
}
}
}
// A builder for Dist objects from samples or list of statistics.
public abstract class DistBuilder<T> : DistBuilderBase where T : IKEPDist{
// Get the sufficient statistic for the distribution.
// For example for a 1d Gaussian, the suff stat is [x; x.^2].
// The returned suff stat s is such that fromStat(s) gives back d.
//public abstract ISuff GetStat(T d);
// Construct a distribution from the sufficient statistics s.
public abstract T FromStat(ISuff s);
// In Matlab code, sufficient statistic is represented with one vector.
// For example, for a 1d Gaussian, s = [x, x^2].
// This can be problematic for multivariate statistic as matrix needs
// to be vectorized. If possible, ISuff should be used.
public abstract T FromStat(Vector s);
// Return a representaive statistic vector of the distribution
public abstract Vector GetStat(T dist);
}
public class DNormalBuilder : DistBuilder<DNormal>{
private static DNormalBuilder instance = null;
public const string MATLAB_CLASS = "DistNormalBuilder";
public static DNormalBuilder Instance{
get{
if(instance == null){
instance = new DNormalBuilder();
}
return instance;
}
}
// singleton pattern
private DNormalBuilder(){
}
public override DNormal FromStat(ISuff s){
double mean = s.GetFirstMomentAsVector()[0];
double m2 = s.GetSecondMomentAsMatrix()[0, 0];
double variance = m2 - mean * mean;
return new DNormal(mean,variance);
}
public override DNormal FromStat(Vector s){
// assume s = [x, x^2]
if(s.Count != 2){
throw new ArgumentException("2-dim vector for containing first 2 moments expected.");
}
double mean = s[0];
double m2 = s[1];
double variance = m2 - mean * mean;
return new DNormal(mean,variance);
}
public override Vector GetStat(DNormal dist){
// return mean and uncentered 2nd moment
double mean = dist.GetMean();
double m2 = dist.GetVariance() + mean * mean;
return Vector.FromArray(new []{ mean, m2 });
}
public new static DNormalBuilder FromMatlabStruct(MatlabStruct s){
string className = s.GetString("className");
if(!className.Equals(MATLAB_CLASS)){
throw new ArgumentException("The input does not represent a " + typeof(DNormalBuilder));
}
return DNormalBuilder.Instance;
}
}
// DistBuilder which represents a normal distribution with its mean and
// log variance
public class DNormalLogVarBuilder : DistBuilder<DNormal>{
private static DNormalLogVarBuilder instance = null;
public const string MATLAB_CLASS = "DNormalLogVarBuilder";
public static DNormalLogVarBuilder Instance{
get{
if(instance == null){
instance = new DNormalLogVarBuilder();
}
return instance;
}
}
// singleton pattern
private DNormalLogVarBuilder(){
}
public override DNormal FromStat(ISuff s){
return DNormalBuilder.Instance.FromStat(s);
}
public override DNormal FromStat(Vector s){
// assume s = [mean, log variance]
if(s.Count != 2){
throw new ArgumentException("2-dim vector for containing " +
"[mean, log(variance)] expected.");
}
double mean = s[0];
double logVar = s[1];
double variance = Math.Exp(logVar);
return new DNormal(mean,variance);
}
public override Vector GetStat(DNormal dist){
double mean = dist.GetMean();
double logVar = Math.Log(dist.GetVariance());
return Vector.FromArray(new[]{ mean, logVar });
}
public new static DNormalLogVarBuilder FromMatlabStruct(MatlabStruct s){
string className = s.GetString("className");
if(!className.Equals(MATLAB_CLASS)){
throw new ArgumentException("The input does not represent a " + typeof(DNormalLogVarBuilder));
}
return DNormalLogVarBuilder.Instance;
}
}
public class DBetaBuilder : DistBuilder<DBeta>{
private static DBetaBuilder instance = null;
public const string MATLAB_CLASS = "DistBetaBuilder";
public static DBetaBuilder Instance{
get{
if(instance == null){
instance = new DBetaBuilder();
}
return instance;
}
}
// singleton pattern
private DBetaBuilder(){
}
public override DBeta FromStat(ISuff s){
double mean = s.GetFirstMomentAsVector()[0];
double m2 = s.GetSecondMomentAsMatrix()[0, 0];
double variance = m2 - mean * mean;
Beta b = Beta.FromMeanAndVariance(mean, variance);
return DBeta.FromBeta(b);
}
public override DBeta FromStat(Vector s){
if(s.Count != 2){
throw new ArgumentException("2-dim vector containing first 2 moments expected.");
}
double mean = s[0];
// hack
double epsi = 1e-3;
mean = Math.Max(Math.Min(mean, 1 - epsi), 0 + epsi);
double m2 = s[1];
double variance = m2 - mean * mean;
// hack
if(variance < 0 || variance >= mean * (1 - mean)){
variance = mean * (1 - mean) * 0.9;
}
Beta b = Beta.FromMeanAndVariance(mean, variance);
return DBeta.FromBeta(b);
}
public override Vector GetStat(DBeta dist){
// return mean and uncentered 2nd moment
double mean = dist.GetMean();
double m2 = dist.GetVariance() + mean * mean;
return Vector.FromArray(new []{ mean, m2 });
}
public new static DBetaBuilder FromMatlabStruct(MatlabStruct s){
string className = s.GetString("className");
if(!className.Equals(MATLAB_CLASS)){
throw new ArgumentException("The input does not represent a " + typeof(DBetaBuilder));
}
return DBetaBuilder.Instance;
}
}
// use log(alpha) and log(beta)
public class DBetaLogBuilder : DistBuilder<DBeta>{
private static DBetaLogBuilder instance = null;
public const string MATLAB_CLASS = "DBetaLogBuilder";
public static DBetaLogBuilder Instance{
get{
if(instance == null){
instance = new DBetaLogBuilder();
}
return instance;
}
}
// singleton pattern
private DBetaLogBuilder(){
}
public override DBeta FromStat(ISuff s){
double mean = s.GetFirstMomentAsVector()[0];
double m2 = s.GetSecondMomentAsMatrix()[0, 0];
double variance = m2 - mean * mean;
Beta b = Beta.FromMeanAndVariance(mean, variance);
return DBeta.FromBeta(b);
}
public override DBeta FromStat(Vector s){
if(s.Count != 2){
throw new ArgumentException("2-dim vector containing log(alpha), log(beta) expected.");
}
double alpha = Math.Exp(s[0]);
double beta = Math.Exp(s[1]);
Beta b = new Beta(alpha,beta);
return DBeta.FromBeta(b);
}
public override Vector GetStat(DBeta dist){
// stat = ( log(alpha), log(beta) )
double la = Math.Log(dist.GetAlpha());
double lb = Math.Log(dist.GetBeta());
return Vector.FromArray(new[]{ la, lb });
}
public new static DBetaLogBuilder FromMatlabStruct(MatlabStruct s){
string className = s.GetString("className");
if(!className.Equals(MATLAB_CLASS)){
throw new ArgumentException("The input does not represent a " + typeof(DBetaLogBuilder));
}
return DBetaLogBuilder.Instance;
}
}
/**Gamma distribution builder based on log(shape) and log(rate).
According to Ali et. al (appendix), this parameterization works the best for Gamma dists.*/
public class DGammaLogBuilder : DistBuilder<DGamma>{
public override DGamma FromStat(ISuff s){
throw new NotImplementedException();
}
public override DGamma FromStat(Vector suff){
// Expect (log(shape), log(rate))
if(suff.Count != 2){
throw new ArgumentException("Expect 2-dim vector: (log(shape), log(rate)).");
}
double shape = Math.Exp(suff[0]);
double rate = Math.Exp(suff[1]);
Gamma g = Gamma.FromShapeAndRate(shape, rate);
return new DGamma(g);
}
public override Vector GetStat(DGamma dist){
// stat = (log(shape), log(rate))
double ls = Math.Log(dist.GetShape());
double lr = Math.Log(dist.GetRate());
return Vector.FromArray(new []{ ls, lr });
}
}
public class DVectorNormal : IDistMulti{
private Vector mean;
private Matrix covariance;
public DVectorNormal(Vector mean, Matrix covariance){
this.mean = mean;
this.covariance = covariance;
}
public IDistribution<Vector> GetWrappedDistribution(){
PositiveDefiniteMatrix pos = (PositiveDefiniteMatrix)covariance;
return new VectorGaussian(mean,pos);
}
public Vector GetMeanVector(){
return mean;
}
public Matrix GetCovarianceMatrix(){
return covariance;
}
public ISuff GetSuffStat(){
throw new NotImplementedException();
}
public int GetDimension(){
return mean.Count;
}
}
public class DGamma : IDistUni{
private Gamma gam;
public DGamma(double shape, double rate){
gam = Gamma.FromShapeAndRate(shape, rate);
}
public DGamma(Gamma gam){
this.gam = gam;
}
public IDistribution<double> GetWrappedDistribution(){
return gam;
}
public double GetShape(){
return gam.Shape;
}
public double GetRate(){
return gam.Rate;
}
public double GetMean(){
return gam.GetMean();
}
public double GetVariance(){
return gam.GetVariance();
}
public Vector GetMeanVector(){
return Vector.FromArray(gam.GetMean());
}
public Matrix GetCovarianceMatrix(){
return PositiveDefiniteMatrix.IdentityScaledBy(1, gam.GetVariance());
}
public DGamma FromMeanAndVariance(double mean, double variance){
Gamma g = Gamma.FromMeanAndVariance(mean, variance);
return new DGamma(g);
}
public ISuff GetSuffStat(){
throw new NotImplementedException();
}
}
public class DNormal : IDistUni{
private double mean;
private double variance;
public static string MATLAB_CLASS = "DistNormal";
public DNormal(double mean, double variance){
this.mean = mean;
this.variance = variance;
}
public Gaussian GetDistribution(){
return new Gaussian(this.mean,this.variance);
}
public IDistribution<double> GetWrappedDistribution(){
//MicrosoftResearch.Infer.Distributions.Gaussian
return new Gaussian(this.mean,this.variance);
}
public double GetMean(){
return this.mean;
}
public double GetVariance(){
return this.variance;
}
public Vector GetMeanVector(){
return Vector.FromArray(this.mean);
}
public Matrix GetCovarianceMatrix(){
return PositiveDefiniteMatrix.IdentityScaledBy(1, this.variance);
}
public ISuff GetSuffStat(){
Vector moment1 = GetMeanVector();
double m2 = variance + mean * mean;
PositiveDefiniteMatrix moment2 = PositiveDefiniteMatrix.IdentityScaledBy(1, m2);
SuffStat s = new SuffStat(moment1,moment2);
return s;
}
// construct from Infer.NET Gaussian object
public static DNormal FromGaussian(Gaussian g){
return new DNormal(g.GetMean(),g.GetVariance());
}
public static DNormal PointMass(double mean){
// Construct a Gaussian with very small width.
return DNormal.FromGaussian(Gaussian.PointMass(mean));
}
public override string ToString(){
return String.Format("{0}(mean={1}, variance={2})", typeof(DNormal),
this.mean, this.variance);
}
public static DNormal FromMatlabStruct(MatlabStruct s){
string className = s.GetString("className");
if(!className.Equals(MATLAB_CLASS)){
throw new ArgumentException("The input does not represent a " + typeof(DNormal));
}
Vector meanVec = s.Get1DVector("mean");
if(meanVec.Count != 1){
throw new ArgumentException("mean vector is not 1 dimenion.");
}
double mean = meanVec[0];
double variance = s.GetDouble("variance");
return new DNormal(mean,variance);
}
}
public class DBeta : IDistUni{
private double alpha;
private double beta;
private readonly double mean;
private readonly double variance;
public static string MATLAB_CLASS = "DistBeta";
public DBeta(double alpha, double beta){
this.alpha = alpha;
this.beta = beta;
GetDistribution().GetMeanAndVariance(out this.mean, out this.variance);
}
public Beta GetDistribution(){
return new Beta(this.alpha,this.beta);
}
public IDistribution<double> GetWrappedDistribution(){
return GetDistribution();
}
public double GetMean(){
return this.mean;
}
public double GetVariance(){
return this.variance;
}
public double GetAlpha(){
return alpha;
}
public double GetBeta(){
return beta;
}
public Vector GetMeanVector(){
return Vector.FromArray(this.mean);
}
public Matrix GetCovarianceMatrix(){
return PositiveDefiniteMatrix.IdentityScaledBy(1, this.variance);
}
public ISuff GetSuffStat(){
Vector moment1 = GetMeanVector();
double m2 = variance + mean * mean;
PositiveDefiniteMatrix moment2 = PositiveDefiniteMatrix.IdentityScaledBy(1, m2);
SuffStat s = new SuffStat(moment1,moment2);
return s;
}
public override string ToString(){
return String.Format("{0}(mean={1}, variance={2})", typeof(DBeta),
this.mean, this.variance);
}
// construct from Infer.NET Beta object
public static DBeta FromBeta(Beta g){
return new DBeta(g.TrueCount,g.FalseCount);
}
public static DBeta PointMass(double mean){
return DBeta.FromBeta(Beta.PointMass(mean));
}
public static DBeta FromMatlabStruct(MatlabStruct s){
string className = s.GetString("className");
if(!className.Equals(MATLAB_CLASS)){
throw new ArgumentException("The input does not represent a " + typeof(DBeta));
}
double a = s.GetDouble("alpha");
double b = s.GetDouble("beta");
return new DBeta(a,b);
}
}
public class Uniform1DSampler : Sampleable<double>{
private double lowerBound;
private double upperBound;
private Random random;
public Uniform1DSampler(double lowerBound, double upperBound, Random random){
if(lowerBound > upperBound){
throw new ArgumentException("expect lowerBound <= upperBound");
}
this.random = random;
this.lowerBound = lowerBound;
this.upperBound = upperBound;
}
public Uniform1DSampler(double lowerBound, double upperBound) :
this(lowerBound, upperBound, new Random()){
}
public double Sample(){
double udraw = random.NextDouble();
return udraw * (upperBound - lowerBound) + lowerBound;
}
public double Sample(double result){
result = Sample();
return result;
}
}
// // interface for a bunch of incoming messages
// // 2 incoming messages
// public abstract class InMsgs<A, B> : IIncomingMessages
// where A : KEPDist
// where B : KEPDist{
//
// public abstract A GetMsg0();
//
// public abstract B GetMsg1();
// // preserve the order of incoming messages.
// // If the factor is of the form p(x1 | x2, x3, ..), the order is always
// // x1, x2, x3, ....
// public abstract KEPDist[] AsArray();
// }
//
// // 3 incoming messages
// public abstract class InMsgs<A, B, C> : IIncomingMessages{
//
// }
// public interface IIncomingMessages{
// // number of incoming messages
//// int IncomingCount();
//
// }
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Runtime;
namespace System.ServiceModel.Channels
{
internal delegate IAsyncResult ChainedBeginHandler(TimeSpan timeout, AsyncCallback asyncCallback, object state);
internal delegate void ChainedEndHandler(IAsyncResult result);
internal class ChainedAsyncResult : AsyncResult
{
private ChainedBeginHandler _begin2;
private ChainedEndHandler _end1;
private ChainedEndHandler _end2;
private TimeoutHelper _timeoutHelper;
private static AsyncCallback s_begin1Callback = Fx.ThunkCallback(new AsyncCallback(Begin1Callback));
private static AsyncCallback s_begin2Callback = Fx.ThunkCallback(new AsyncCallback(Begin2Callback));
protected ChainedAsyncResult(TimeSpan timeout, AsyncCallback callback, object state)
: base(callback, state)
{
_timeoutHelper = new TimeoutHelper(timeout);
}
public ChainedAsyncResult(TimeSpan timeout, AsyncCallback callback, object state, ChainedBeginHandler begin1, ChainedEndHandler end1, ChainedBeginHandler begin2, ChainedEndHandler end2)
: base(callback, state)
{
_timeoutHelper = new TimeoutHelper(timeout);
Begin(begin1, end1, begin2, end2);
}
protected void Begin(ChainedBeginHandler begin1, ChainedEndHandler end1, ChainedBeginHandler begin2, ChainedEndHandler end2)
{
_end1 = end1;
_begin2 = begin2;
_end2 = end2;
IAsyncResult result = begin1(_timeoutHelper.RemainingTime(), s_begin1Callback, this);
if (!result.CompletedSynchronously)
{
return;
}
if (Begin1Completed(result))
{
Complete(true);
}
}
private static void Begin1Callback(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
ChainedAsyncResult thisPtr = (ChainedAsyncResult)result.AsyncState;
bool completeSelf = false;
Exception completeException = null;
try
{
completeSelf = thisPtr.Begin1Completed(result);
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
completeSelf = true;
completeException = exception;
}
if (completeSelf)
{
thisPtr.Complete(false, completeException);
}
}
private bool Begin1Completed(IAsyncResult result)
{
_end1(result);
result = _begin2(_timeoutHelper.RemainingTime(), s_begin2Callback, this);
if (!result.CompletedSynchronously)
{
return false;
}
_end2(result);
return true;
}
private static void Begin2Callback(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
ChainedAsyncResult thisPtr = (ChainedAsyncResult)result.AsyncState;
Exception completeException = null;
try
{
thisPtr._end2(result);
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
completeException = exception;
}
thisPtr.Complete(false, completeException);
}
public static void End(IAsyncResult result)
{
AsyncResult.End<ChainedAsyncResult>(result);
}
}
internal class ChainedCloseAsyncResult : ChainedAsyncResult
{
private IList<ICommunicationObject> _collection;
public ChainedCloseAsyncResult(TimeSpan timeout, AsyncCallback callback, object state, ChainedBeginHandler begin1, ChainedEndHandler end1, IList<ICommunicationObject> collection)
: base(timeout, callback, state)
{
_collection = collection;
Begin(BeginClose, EndClose, begin1, end1);
}
public ChainedCloseAsyncResult(TimeSpan timeout, AsyncCallback callback, object state, ChainedBeginHandler begin1, ChainedEndHandler end1, params ICommunicationObject[] objs)
: base(timeout, callback, state)
{
_collection = new List<ICommunicationObject>();
if (objs != null)
{
for (int index = 0; index < objs.Length; index++)
{
if (objs[index] != null)
{
_collection.Add(objs[index]);
}
}
}
Begin(BeginClose, EndClose, begin1, end1);
}
private IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return new CloseCollectionAsyncResult(timeout, callback, state, _collection);
}
private void EndClose(IAsyncResult result)
{
CloseCollectionAsyncResult.End((CloseCollectionAsyncResult)result);
}
}
internal class ChainedOpenAsyncResult : ChainedAsyncResult
{
private IList<ICommunicationObject> _collection;
public ChainedOpenAsyncResult(TimeSpan timeout, AsyncCallback callback, object state, ChainedBeginHandler begin1, ChainedEndHandler end1, IList<ICommunicationObject> collection)
: base(timeout, callback, state)
{
_collection = collection;
Begin(begin1, end1, BeginOpen, EndOpen);
}
public ChainedOpenAsyncResult(TimeSpan timeout, AsyncCallback callback, object state, ChainedBeginHandler begin1, ChainedEndHandler end1, params ICommunicationObject[] objs)
: base(timeout, callback, state)
{
_collection = new List<ICommunicationObject>();
for (int index = 0; index < objs.Length; index++)
{
if (objs[index] != null)
{
_collection.Add(objs[index]);
}
}
Begin(begin1, end1, BeginOpen, EndOpen);
}
private IAsyncResult BeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return new OpenCollectionAsyncResult(timeout, callback, state, _collection);
}
private void EndOpen(IAsyncResult result)
{
OpenCollectionAsyncResult.End((OpenCollectionAsyncResult)result);
}
}
}
| |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Android.Content;
using Android.Graphics;
using Android.OS;
using Android.Util;
using Android.Views;
using Android.Widget;
using System;
namespace com.bytewild.imaging.cropper
{
public abstract class ImageViewTouchBase : ImageView
{
#region Members
// This is the base transformation which is used to show the image
// initially. The current computation for this shows the image in
// it's entirety, letterboxing as needed. One could choose to
// show the image as cropped instead.
//
// This matrix is recomputed when we go from the thumbnail image to
// the full size image.
protected Matrix baseMatrix = new Matrix();
// This is the supplementary transformation which reflects what
// the user has done in terms of zooming and panning.
//
// This matrix remains the same when we go from the thumbnail image
// to the full size image.
protected Matrix suppMatrix = new Matrix();
// This is the final matrix which is computed as the concatentation
// of the base matrix and the supplementary matrix.
private Matrix displayMatrix = new Matrix();
// Temporary buffer used for getting the values out of a matrix.
private float[] matrixValues = new float[9];
// The current bitmap being displayed.
protected RotateBitmap bitmapDisplayed = new RotateBitmap(null);
private int thisWidth = -1;
private int thisHeight = -1;
const float SCALE_RATE = 1.25F;
private float maxZoom;
private Handler handler = new Handler();
private Action onLayoutRunnable = null;
#endregion
#region Constructor
public ImageViewTouchBase(Context context)
: base(context)
{
init();
}
public ImageViewTouchBase(Context context, IAttributeSet attrs)
: base(context, attrs)
{
init();
}
#endregion
#region Private helpers
private void init()
{
SetScaleType(ImageView.ScaleType.Matrix);
}
private void setImageBitmap(Bitmap bitmap, int rotation)
{
base.SetImageBitmap(bitmap);
var d = Drawable;
if (d != null)
{
d.SetDither(true);
}
Bitmap old = bitmapDisplayed.Bitmap;
bitmapDisplayed.Bitmap = bitmap;
bitmapDisplayed.Rotation = rotation;
}
#endregion
#region Public methods
public void Clear()
{
SetImageBitmapResetBase(null, true);
}
/// <summary>
/// This function changes bitmap, reset base matrix according to the size
/// of the bitmap, and optionally reset the supplementary matrix.
/// </summary>
public void SetImageBitmapResetBase(Bitmap bitmap, bool resetSupp)
{
SetImageRotateBitmapResetBase(new RotateBitmap(bitmap), resetSupp);
}
public void SetImageRotateBitmapResetBase(RotateBitmap bitmap, bool resetSupp)
{
int viewWidth = Width;
if (viewWidth <= 0)
{
onLayoutRunnable = () =>
{
SetImageRotateBitmapResetBase(bitmap, resetSupp);
};
return;
}
if (bitmap.Bitmap != null)
{
getProperBaseMatrix(bitmap, baseMatrix);
setImageBitmap(bitmap.Bitmap, bitmap.Rotation);
}
else
{
baseMatrix.Reset();
base.SetImageBitmap(null);
}
if (resetSupp)
{
suppMatrix.Reset();
}
ImageMatrix = GetImageViewMatrix();
this.maxZoom = CalculateMaxZoom();
}
#endregion
#region Overrides
protected override void OnLayout(bool changed, int left, int top, int right, int bottom)
{
this.IvLeft = left;
this.IvRight = right;
this.IvTop = top;
this.IvBottom = bottom;
thisWidth = right - left;
thisHeight = bottom - top;
var r = onLayoutRunnable;
if (r != null)
{
onLayoutRunnable = null;
r();
}
if (bitmapDisplayed.Bitmap != null)
{
getProperBaseMatrix(bitmapDisplayed, baseMatrix);
ImageMatrix = GetImageViewMatrix();
}
}
public override bool OnKeyDown(Keycode keyCode, KeyEvent e)
{
if (keyCode == Keycode.Back && GetScale() > 1.0f)
{
// If we're zoomed in, pressing Back jumps out to show the entire
// image, otherwise Back returns the user to the gallery.
ZoomTo(1.0f);
return true;
}
return base.OnKeyDown(keyCode, e);
}
public override void SetImageBitmap(Bitmap bm)
{
setImageBitmap(bm, 0);
}
#endregion
#region Properties
public int IvLeft { get; private set; }
public int IvRight { get; private set; }
public int IvTop { get; private set; }
public int IvBottom { get; private set; }
#endregion
#region Protected methods
protected float GetValue(Matrix matrix, int whichValue)
{
matrix.GetValues(matrixValues);
return matrixValues[whichValue];
}
/// <summary>
/// Get the scale factor out of the matrix.
/// </summary>
protected float GetScale(Matrix matrix)
{
return GetValue(matrix, Matrix.MscaleX);
}
protected float GetScale()
{
return GetScale(suppMatrix);
}
/// <summary>
/// Setup the base matrix so that the image is centered and scaled properly.
/// </summary>
private void getProperBaseMatrix(RotateBitmap bitmap, Matrix matrix)
{
float viewWidth = Width;
float viewHeight = Height;
float w = bitmap.Width;
float h = bitmap.Height;
int rotation = bitmap.Rotation;
matrix.Reset();
// We limit up-scaling to 2x otherwise the result may look bad if it's
// a small icon.
float widthScale = Math.Min(viewWidth / w, 2.0f);
float heightScale = Math.Min(viewHeight / h, 2.0f);
float scale = Math.Min(widthScale, heightScale);
matrix.PostConcat(bitmap.GetRotateMatrix());
matrix.PostScale(scale, scale);
matrix.PostTranslate(
(viewWidth - w * scale) / 2F,
(viewHeight - h * scale) / 2F);
}
// Combine the base matrix and the supp matrix to make the final matrix.
protected Matrix GetImageViewMatrix()
{
// The final matrix is computed as the concatentation of the base matrix
// and the supplementary matrix.
displayMatrix.Set(baseMatrix);
displayMatrix.PostConcat(suppMatrix);
return displayMatrix;
}
// Sets the maximum zoom, which is a scale relative to the base matrix. It
// is calculated to show the image at 400% zoom regardless of screen or
// image orientation. If in the future we decode the full 3 megapixel image,
// rather than the current 1024x768, this should be changed down to 200%.
protected float CalculateMaxZoom()
{
if (bitmapDisplayed.Bitmap == null)
{
return 1F;
}
float fw = (float)bitmapDisplayed.Width / (float)thisWidth;
float fh = (float)bitmapDisplayed.Height / (float)thisHeight;
float max = Math.Max(fw, fh) * 4;
return max;
}
protected virtual void ZoomTo(float scale, float centerX, float centerY)
{
if (scale > maxZoom)
{
scale = maxZoom;
}
float oldScale = GetScale();
float deltaScale = scale / oldScale;
suppMatrix.PostScale(deltaScale, deltaScale, centerX, centerY);
ImageMatrix = GetImageViewMatrix();
Center(true, true);
}
protected void ZoomTo(float scale, float centerX,
float centerY, float durationMs)
{
float incrementPerMs = (scale - GetScale()) / durationMs;
float oldScale = GetScale();
long startTime = System.Environment.TickCount;
Action anim = null;
anim = () =>
{
long now = System.Environment.TickCount;
float currentMs = Math.Min(durationMs, now - startTime);
float target = oldScale + (incrementPerMs * currentMs);
ZoomTo(target, centerX, centerY);
if (currentMs < durationMs)
{
handler.Post(anim);
}
};
handler.Post(anim);
}
protected void ZoomTo(float scale)
{
float cx = Width / 2F;
float cy = Height / 2F;
ZoomTo(scale, cx, cy);
}
protected virtual void ZoomIn()
{
ZoomIn(SCALE_RATE);
}
protected virtual void ZoomOut()
{
ZoomOut(SCALE_RATE);
}
protected virtual void ZoomIn(float rate)
{
if (GetScale() >= maxZoom)
{
// Don't let the user zoom into the molecular level.
return;
}
if (bitmapDisplayed.Bitmap == null)
{
return;
}
float cx = Width / 2F;
float cy = Height / 2F;
suppMatrix.PostScale(rate, rate, cx, cy);
ImageMatrix = GetImageViewMatrix();
}
protected void ZoomOut(float rate)
{
if (bitmapDisplayed.Bitmap == null)
{
return;
}
float cx = Width / 2F;
float cy = Height / 2F;
// Zoom out to at most 1x.
Matrix tmp = new Matrix(suppMatrix);
tmp.PostScale(1F / rate, 1F / rate, cx, cy);
if (GetScale(tmp) < 1F)
{
suppMatrix.SetScale(1F, 1F, cx, cy);
}
else
{
suppMatrix.PostScale(1F / rate, 1F / rate, cx, cy);
}
ImageMatrix = GetImageViewMatrix();
Center(true, true);
}
protected virtual void PostTranslate(float dx, float dy)
{
suppMatrix.PostTranslate(dx, dy);
}
protected void PanBy(float dx, float dy)
{
PostTranslate(dx, dy);
ImageMatrix = GetImageViewMatrix();
}
/// <summary>
/// Center as much as possible in one or both axis. Centering is
/// defined as follows: if the image is scaled down below the
/// view's dimensions then center it (literally). If the image
/// is scaled larger than the view and is translated out of view
/// then translate it back into view (i.e. eliminate black bars).
/// </summary>
protected void Center(bool horizontal, bool vertical)
{
if (bitmapDisplayed.Bitmap == null)
{
return;
}
Matrix m = GetImageViewMatrix();
RectF rect = new RectF(0, 0,
bitmapDisplayed.Bitmap.Width,
bitmapDisplayed.Bitmap.Height);
m.MapRect(rect);
float height = rect.Height();
float width = rect.Width();
float deltaX = 0, deltaY = 0;
if (vertical)
{
int viewHeight = Height;
if (height < viewHeight)
{
deltaY = (viewHeight - height) / 2 - rect.Top;
}
else if (rect.Top > 0)
{
deltaY = -rect.Top;
}
else if (rect.Bottom < viewHeight)
{
deltaY = Height - rect.Bottom;
}
}
if (horizontal)
{
int viewWidth = Width;
if (width < viewWidth)
{
deltaX = (viewWidth - width) / 2 - rect.Left;
}
else if (rect.Left > 0)
{
deltaX = -rect.Left;
}
else if (rect.Right < viewWidth)
{
deltaX = viewWidth - rect.Right;
}
}
PostTranslate(deltaX, deltaY);
ImageMatrix = GetImageViewMatrix();
}
#endregion
}
}
| |
/* ***************************************************************************
* This file is part of SharpNEAT - Evolution of Neural Networks.
*
* Copyright 2004-2016 Colin Green (sharpneat@gmail.com)
*
* SharpNEAT is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SharpNEAT is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SharpNEAT. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using SharpNeat.Core;
using SharpNeat.Phenomes;
namespace SharpNeat.Domains.FunctionRegression
{
/// <summary>
/// Function regression task.
/// The function to be regressed is read from the config data. There is always one output.
/// </summary>
public class FunctionRegressionEvaluator : IPhenomeEvaluator<IBlackBox>
{
/// <summary>
/// The maximum error for the evaluator. The output at each sample point is in the range 0 to 1. Thus the error at each point has a maximum of 1.0.
/// The error for the evaulator as a whole is the root mean square error (RMSE) over all sample points. Thus max error is always 1.0
/// </summary>
const double MaxError = 1.0;
ulong _evalCount;
bool _stopConditionSatisfied;
ParameterSamplingInfo[] _paramSamplingInfoArr;
IFunction _fnTask;
double _samplePointCount;
double _samplePointCountReciprocal;
#region Constructor
/// <summary>
/// Construct a function regress evaluator with the provided parameter sampling info and function to regress.
/// </summary>
public FunctionRegressionEvaluator(ParameterSamplingInfo[] paramSamplingInfoArr, IFunction fnTask)
{
_paramSamplingInfoArr = paramSamplingInfoArr;
_fnTask = fnTask;
// Calculate the total numeber of sample points.
int samplePointCount = 1;
for(int i=0; i<_paramSamplingInfoArr.Length; i++) {
samplePointCount *= _paramSamplingInfoArr[i]._sampleCount;
}
_samplePointCount = samplePointCount;
_samplePointCountReciprocal = 1.0 / _samplePointCount;
}
#endregion
#region IPhenomeEvaluator<IBlackBox> Members
/// <summary>
/// Gets the total number of evaluations that have been performed.
/// </summary>
public ulong EvaluationCount
{
get { return _evalCount; }
}
/// <summary>
/// Gets a value indicating whether some goal fitness has been achieved and that
/// the the evolutionary algorithm/search should stop. This property's value can remain false
/// to allow the algorithm to run indefinitely.
/// </summary>
public bool StopConditionSatisfied
{
get { return _stopConditionSatisfied; }
}
/// <summary>
/// Evaluate the provided IBlackBox against the XOR problem domain and return its fitness score.
/// </summary>
public FitnessInfo Evaluate(IBlackBox box)
{
_evalCount++;
int paramCount = _paramSamplingInfoArr.Length;
int paramIdxBound = paramCount - 1;
int[] sampleIdxArr = new int[paramCount];
int[] sampleCountArr = new int[paramCount];
double[] paramValueArr = new double[paramCount];
double[] paramIncrArr = new double[paramCount];
for(int i=0; i<paramCount; i++)
{
sampleCountArr[i] = _paramSamplingInfoArr[i]._sampleCount;
paramValueArr[i] = _paramSamplingInfoArr[i]._min;
paramIncrArr[i] = _paramSamplingInfoArr[i]._incr;
}
// Error accumulator.
double errorAcc = 0.0;
for(;;)
{
// Reset black box internal state.
box.ResetState();
// Apply function arguments to black box inputs.
for(int i=0; i<paramCount; i++) {
box.InputSignalArray[i] = paramValueArr[i];
}
// Activate black box.
box.Activate();
// Get the black box's output value.
double response = box.OutputSignalArray[0];
// Get correct function value to compare with.
double correctVal = _fnTask.GetValue(paramValueArr);
// Accumulate squared error at each sample bpoint. Abs() not required because we are squaring.
errorAcc += (response-correctVal) * (response-correctVal);
// Determine next sample point.
for(int i=0; i<paramCount; i++)
{
sampleIdxArr[i]++;
if(sampleIdxArr[i] < sampleCountArr[i])
{ // The parameter has incremented without reaching its bound.
// We have the next valid sample point, so break out of the loop.
paramValueArr[i] += paramIncrArr[i];
break;
}
// The current parameter has reached its bound.
// If the *last* parameter has reached its bound then exit the outer loop.
if(i == paramIdxBound) {
goto exit;
}
// Reset the parameter and allow the inner loop to continue. This will
// increment the next parameter.
sampleIdxArr[i] = 0;
paramValueArr[i] = _paramSamplingInfoArr[i]._min;
}
}
exit:
double fitness = MaxError - Math.Sqrt(errorAcc * _samplePointCountReciprocal);
if(fitness < 0.5) {
fitness = 0.0;
} else {
fitness = (fitness-0.5) * 2.0;
}
// Note. This is correct. Network's response is subtracted from MaxError; if all responses are correct then fitness == MaxError.
if(fitness == MaxError) {
_stopConditionSatisfied = true;
}
return new FitnessInfo(fitness, fitness);
}
/// <summary>
/// Reset the internal state of the evaluation scheme if any exists.
/// </summary>
public void Reset()
{
}
#endregion
#region Public Static Methods
/// <summary>
/// Get an instance of the function class for the specified function type.
/// </summary>
/// <param name="fnId"></param>
/// <returns></returns>
public static IFunction GetFunction(FunctionId fnId)
{
switch(fnId)
{
case FunctionId.Abs:
return new AbsFunction();
case FunctionId.Log:
return new LogFunction();
case FunctionId.Multiplication:
return new MultiplicationFunction();
case FunctionId.Sine:
return new SineFunction();
case FunctionId.SineXSquared:
return new SineXSquaredFunction();
}
throw new ArgumentException(string.Format("Unknown FunctionId type [{0}]", fnId));
}
#endregion
}
}
| |
/*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// Represents the schema for generic items.
/// </summary>
[Schema]
public class ItemSchema : ServiceObjectSchema
{
/// <summary>
/// Field URIs for Item.
/// </summary>
private static class FieldUris
{
public const string ItemId = "item:ItemId";
public const string ParentFolderId = "item:ParentFolderId";
public const string ItemClass = "item:ItemClass";
public const string MimeContent = "item:MimeContent";
public const string MimeContentUTF8 = "item:MimeContentUTF8";
public const string Attachments = "item:Attachments";
public const string Subject = "item:Subject";
public const string DateTimeReceived = "item:DateTimeReceived";
public const string Size = "item:Size";
public const string Categories = "item:Categories";
public const string HasAttachments = "item:HasAttachments";
public const string Importance = "item:Importance";
public const string InReplyTo = "item:InReplyTo";
public const string InternetMessageHeaders = "item:InternetMessageHeaders";
public const string IsAssociated = "item:IsAssociated";
public const string IsDraft = "item:IsDraft";
public const string IsFromMe = "item:IsFromMe";
public const string IsResend = "item:IsResend";
public const string IsSubmitted = "item:IsSubmitted";
public const string IsUnmodified = "item:IsUnmodified";
public const string DateTimeSent = "item:DateTimeSent";
public const string DateTimeCreated = "item:DateTimeCreated";
public const string Body = "item:Body";
public const string ResponseObjects = "item:ResponseObjects";
public const string Sensitivity = "item:Sensitivity";
public const string ReminderDueBy = "item:ReminderDueBy";
public const string ReminderIsSet = "item:ReminderIsSet";
public const string ReminderMinutesBeforeStart = "item:ReminderMinutesBeforeStart";
public const string DisplayTo = "item:DisplayTo";
public const string DisplayCc = "item:DisplayCc";
public const string Culture = "item:Culture";
public const string EffectiveRights = "item:EffectiveRights";
public const string LastModifiedName = "item:LastModifiedName";
public const string LastModifiedTime = "item:LastModifiedTime";
public const string WebClientReadFormQueryString = "item:WebClientReadFormQueryString";
public const string WebClientEditFormQueryString = "item:WebClientEditFormQueryString";
public const string ConversationId = "item:ConversationId";
public const string UniqueBody = "item:UniqueBody";
public const string StoreEntryId = "item:StoreEntryId";
public const string InstanceKey = "item:InstanceKey";
public const string NormalizedBody = "item:NormalizedBody";
public const string EntityExtractionResult = "item:EntityExtractionResult";
public const string Flag = "item:Flag";
public const string PolicyTag = "item:PolicyTag";
public const string ArchiveTag = "item:ArchiveTag";
public const string RetentionDate = "item:RetentionDate";
public const string Preview = "item:Preview";
public const string TextBody = "item:TextBody";
public const string IconIndex = "item:IconIndex";
public const string Hashtags = "item:Hashtags";
public const string Mentions = "item:Mentions";
public const string MentionedMe = "item:MentionedMe";
}
/// <summary>
/// Defines the Id property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Id =
new ComplexPropertyDefinition<ItemId>(
XmlElementNames.ItemId,
FieldUris.ItemId,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1,
delegate() { return new ItemId(); });
/// <summary>
/// Defines the Body property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Body =
new ComplexPropertyDefinition<MessageBody>(
XmlElementNames.Body,
FieldUris.Body,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete,
ExchangeVersion.Exchange2007_SP1,
delegate() { return new MessageBody(); });
/// <summary>
/// Defines the ItemClass property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition ItemClass =
new StringPropertyDefinition(
XmlElementNames.ItemClass,
FieldUris.ItemClass,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the Subject property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Subject =
new StringPropertyDefinition(
XmlElementNames.Subject,
FieldUris.Subject,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the MimeContent property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition MimeContent =
new ComplexPropertyDefinition<MimeContent>(
XmlElementNames.MimeContent,
FieldUris.MimeContent,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.MustBeExplicitlyLoaded,
ExchangeVersion.Exchange2007_SP1,
delegate() { return new MimeContent(); });
/// <summary>
/// Defines the MimeContentUTF8 property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition MimeContentUTF8 =
new ComplexPropertyDefinition<MimeContentUTF8>(
XmlElementNames.MimeContentUTF8,
FieldUris.MimeContentUTF8,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.MustBeExplicitlyLoaded,
ExchangeVersion.Exchange2013_SP1,
delegate() { return new MimeContentUTF8(); });
/// <summary>
/// Defines the ParentFolderId property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition ParentFolderId =
new ComplexPropertyDefinition<FolderId>(
XmlElementNames.ParentFolderId,
FieldUris.ParentFolderId,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1,
delegate() { return new FolderId(); });
/// <summary>
/// Defines the Sensitivity property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Sensitivity =
new GenericPropertyDefinition<Sensitivity>(
XmlElementNames.Sensitivity,
FieldUris.Sensitivity,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the Attachments property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Attachments = new AttachmentsPropertyDefinition();
/// <summary>
/// Defines the DateTimeReceived property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition DateTimeReceived =
new DateTimePropertyDefinition(
XmlElementNames.DateTimeReceived,
FieldUris.DateTimeReceived,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the Size property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Size =
new IntPropertyDefinition(
XmlElementNames.Size,
FieldUris.Size,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the Categories property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Categories =
new ComplexPropertyDefinition<StringList>(
XmlElementNames.Categories,
FieldUris.Categories,
PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1,
delegate() { return new StringList(); });
/// <summary>
/// Defines the Importance property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Importance =
new GenericPropertyDefinition<Importance>(
XmlElementNames.Importance,
FieldUris.Importance,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the InReplyTo property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition InReplyTo =
new StringPropertyDefinition(
XmlElementNames.InReplyTo,
FieldUris.InReplyTo,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the IsSubmitted property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition IsSubmitted =
new BoolPropertyDefinition(
XmlElementNames.IsSubmitted,
FieldUris.IsSubmitted,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the IsAssociated property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition IsAssociated =
new BoolPropertyDefinition(
XmlElementNames.IsAssociated,
FieldUris.IsAssociated,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010);
/// <summary>
/// Defines the IsDraft property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition IsDraft =
new BoolPropertyDefinition(
XmlElementNames.IsDraft,
FieldUris.IsDraft,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the IsFromMe property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition IsFromMe =
new BoolPropertyDefinition(
XmlElementNames.IsFromMe,
FieldUris.IsFromMe,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the IsResend property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition IsResend =
new BoolPropertyDefinition(
XmlElementNames.IsResend,
FieldUris.IsResend,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the IsUnmodified property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition IsUnmodified =
new BoolPropertyDefinition(
XmlElementNames.IsUnmodified,
FieldUris.IsUnmodified,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the InternetMessageHeaders property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition InternetMessageHeaders =
new ComplexPropertyDefinition<InternetMessageHeaderCollection>(
XmlElementNames.InternetMessageHeaders,
FieldUris.InternetMessageHeaders,
ExchangeVersion.Exchange2007_SP1,
delegate() { return new InternetMessageHeaderCollection(); });
/// <summary>
/// Defines the DateTimeSent property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition DateTimeSent =
new DateTimePropertyDefinition(
XmlElementNames.DateTimeSent,
FieldUris.DateTimeSent,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the DateTimeCreated property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition DateTimeCreated =
new DateTimePropertyDefinition(
XmlElementNames.DateTimeCreated,
FieldUris.DateTimeCreated,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the AllowedResponseActions property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition AllowedResponseActions =
new ResponseObjectsPropertyDefinition(
XmlElementNames.ResponseObjects,
FieldUris.ResponseObjects,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the ReminderDueBy property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition ReminderDueBy =
new ScopedDateTimePropertyDefinition(
XmlElementNames.ReminderDueBy,
FieldUris.ReminderDueBy,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1,
delegate(ExchangeVersion version)
{
return AppointmentSchema.StartTimeZone;
});
/// <summary>
/// Defines the IsReminderSet property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition IsReminderSet =
new BoolPropertyDefinition(
XmlElementNames.ReminderIsSet, // Note: server-side the name is ReminderIsSet
FieldUris.ReminderIsSet,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the ReminderMinutesBeforeStart property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition ReminderMinutesBeforeStart =
new IntPropertyDefinition(
XmlElementNames.ReminderMinutesBeforeStart,
FieldUris.ReminderMinutesBeforeStart,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the DisplayCc property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition DisplayCc =
new StringPropertyDefinition(
XmlElementNames.DisplayCc,
FieldUris.DisplayCc,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the DisplayTo property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition DisplayTo =
new StringPropertyDefinition(
XmlElementNames.DisplayTo,
FieldUris.DisplayTo,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the HasAttachments property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition HasAttachments =
new BoolPropertyDefinition(
XmlElementNames.HasAttachments,
FieldUris.HasAttachments,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the Culture property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Culture =
new StringPropertyDefinition(
XmlElementNames.Culture,
FieldUris.Culture,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the EffectiveRights property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition EffectiveRights =
new EffectiveRightsPropertyDefinition(
XmlElementNames.EffectiveRights,
FieldUris.EffectiveRights,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the LastModifiedName property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition LastModifiedName =
new StringPropertyDefinition(
XmlElementNames.LastModifiedName,
FieldUris.LastModifiedName,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the LastModifiedTime property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition LastModifiedTime =
new DateTimePropertyDefinition(
XmlElementNames.LastModifiedTime,
FieldUris.LastModifiedTime,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the WebClientReadFormQueryString property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition WebClientReadFormQueryString =
new StringPropertyDefinition(
XmlElementNames.WebClientReadFormQueryString,
FieldUris.WebClientReadFormQueryString,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010);
/// <summary>
/// Defines the WebClientEditFormQueryString property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition WebClientEditFormQueryString =
new StringPropertyDefinition(
XmlElementNames.WebClientEditFormQueryString,
FieldUris.WebClientEditFormQueryString,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010);
/// <summary>
/// Defines the ConversationId property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition ConversationId =
new ComplexPropertyDefinition<ConversationId>(
XmlElementNames.ConversationId,
FieldUris.ConversationId,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010,
delegate() { return new ConversationId(); });
/// <summary>
/// Defines the UniqueBody property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition UniqueBody =
new ComplexPropertyDefinition<UniqueBody>(
XmlElementNames.UniqueBody,
FieldUris.UniqueBody,
PropertyDefinitionFlags.MustBeExplicitlyLoaded,
ExchangeVersion.Exchange2010,
delegate() { return new UniqueBody(); });
/// <summary>
/// Defines the StoreEntryId property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition StoreEntryId =
new ByteArrayPropertyDefinition(
XmlElementNames.StoreEntryId,
FieldUris.StoreEntryId,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP2);
/// <summary>
/// Defines the InstanceKey property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition InstanceKey =
new ByteArrayPropertyDefinition(
XmlElementNames.InstanceKey,
FieldUris.InstanceKey,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2013);
/// <summary>
/// Defines the NormalizedBody property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition NormalizedBody =
new ComplexPropertyDefinition<NormalizedBody>(
XmlElementNames.NormalizedBody,
FieldUris.NormalizedBody,
PropertyDefinitionFlags.MustBeExplicitlyLoaded,
ExchangeVersion.Exchange2013,
delegate() { return new NormalizedBody(); });
/// <summary>
/// Defines the EntityExtractionResult property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition EntityExtractionResult =
new ComplexPropertyDefinition<EntityExtractionResult>(
XmlElementNames.NlgEntityExtractionResult,
FieldUris.EntityExtractionResult,
PropertyDefinitionFlags.MustBeExplicitlyLoaded,
ExchangeVersion.Exchange2013,
delegate() { return new EntityExtractionResult(); });
/// <summary>
/// Defines the InternetMessageHeaders property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Flag =
new ComplexPropertyDefinition<Flag>(
XmlElementNames.Flag,
FieldUris.Flag,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2013,
delegate() { return new Flag(); });
/// <summary>
/// Defines the PolicyTag property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition PolicyTag =
new ComplexPropertyDefinition<PolicyTag>(
XmlElementNames.PolicyTag,
FieldUris.PolicyTag,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2013,
delegate() { return new PolicyTag(); });
/// <summary>
/// Defines the ArchiveTag property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition ArchiveTag =
new ComplexPropertyDefinition<ArchiveTag>(
XmlElementNames.ArchiveTag,
FieldUris.ArchiveTag,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2013,
delegate() { return new ArchiveTag(); });
/// <summary>
/// Defines the RetentionDate property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition RetentionDate =
new DateTimePropertyDefinition(
XmlElementNames.RetentionDate,
FieldUris.RetentionDate,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2013,
true);
/// <summary>
/// Defines the Preview property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Preview =
new StringPropertyDefinition(
XmlElementNames.Preview,
FieldUris.Preview,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2013);
/// <summary>
/// Defines the TextBody property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition TextBody =
new ComplexPropertyDefinition<TextBody>(
XmlElementNames.TextBody,
FieldUris.TextBody,
PropertyDefinitionFlags.MustBeExplicitlyLoaded,
ExchangeVersion.Exchange2013,
delegate() { return new TextBody(); });
/// <summary>
/// Defines the IconIndex property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition IconIndex =
new GenericPropertyDefinition<IconIndex>(
XmlElementNames.IconIndex,
FieldUris.IconIndex,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2013);
/// <summary>
/// Defines the Hashtags property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Hashtags =
new ComplexPropertyDefinition<StringList>(
XmlElementNames.Hashtags,
FieldUris.Hashtags,
PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete,
ExchangeVersion.Exchange2015,
delegate() { return new StringList(); });
/// <summary>
/// Defines the Mentions property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Mentions =
new ComplexPropertyDefinition<EmailAddressCollection>(
XmlElementNames.Mentions,
FieldUris.Mentions,
PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete,
ExchangeVersion.Exchange2015,
delegate() { return new EmailAddressCollection(); });
/// <summary>
/// Defines the MentionedMe property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition MentionedMe =
new BoolPropertyDefinition(
XmlElementNames.MentionedMe,
FieldUris.MentionedMe,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2015,
true);
// This must be declared after the property definitions
internal static readonly ItemSchema Instance = new ItemSchema();
/// <summary>
/// Registers properties.
/// </summary>
/// <remarks>
/// IMPORTANT NOTE: PROPERTIES MUST BE REGISTERED IN SCHEMA ORDER (i.e. the same order as they are defined in types.xsd)
/// </remarks>
internal override void RegisterProperties()
{
base.RegisterProperties();
this.RegisterProperty(MimeContent);
this.RegisterProperty(Id);
this.RegisterProperty(ParentFolderId);
this.RegisterProperty(ItemClass);
this.RegisterProperty(Subject);
this.RegisterProperty(Sensitivity);
this.RegisterProperty(Body);
this.RegisterProperty(Attachments);
this.RegisterProperty(DateTimeReceived);
this.RegisterProperty(Size);
this.RegisterProperty(Categories);
this.RegisterProperty(Importance);
this.RegisterProperty(InReplyTo);
this.RegisterProperty(IsSubmitted);
this.RegisterProperty(IsDraft);
this.RegisterProperty(IsFromMe);
this.RegisterProperty(IsResend);
this.RegisterProperty(IsUnmodified);
this.RegisterProperty(InternetMessageHeaders);
this.RegisterProperty(DateTimeSent);
this.RegisterProperty(DateTimeCreated);
this.RegisterProperty(AllowedResponseActions);
this.RegisterProperty(ReminderDueBy);
this.RegisterProperty(IsReminderSet);
this.RegisterProperty(ReminderMinutesBeforeStart);
this.RegisterProperty(DisplayCc);
this.RegisterProperty(DisplayTo);
this.RegisterProperty(HasAttachments);
this.RegisterProperty(ServiceObjectSchema.ExtendedProperties);
this.RegisterProperty(Culture);
this.RegisterProperty(EffectiveRights);
this.RegisterProperty(LastModifiedName);
this.RegisterProperty(LastModifiedTime);
this.RegisterProperty(IsAssociated);
this.RegisterProperty(WebClientReadFormQueryString);
this.RegisterProperty(WebClientEditFormQueryString);
this.RegisterProperty(ConversationId);
this.RegisterProperty(UniqueBody);
this.RegisterProperty(Flag);
this.RegisterProperty(StoreEntryId);
this.RegisterProperty(InstanceKey);
this.RegisterProperty(NormalizedBody);
this.RegisterProperty(EntityExtractionResult);
this.RegisterProperty(PolicyTag);
this.RegisterProperty(ArchiveTag);
this.RegisterProperty(RetentionDate);
this.RegisterProperty(Preview);
this.RegisterProperty(TextBody);
this.RegisterProperty(IconIndex);
this.RegisterProperty(MimeContentUTF8);
this.RegisterProperty(Hashtags);
this.RegisterProperty(Mentions);
this.RegisterProperty(MentionedMe);
}
/// <summary>
/// Initializes a new instance of the <see cref="ItemSchema"/> class.
/// </summary>
internal ItemSchema()
: base()
{
}
}
}
| |
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# Port port by: Lars Brubaker
// larsbrubaker@gmail.com
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
#define AA_TIPS
using Tao.OpenGl;
using System;
using System.Collections.Generic;
using AGG.Image;
using AGG.VertexSource;
using AGG.Transform;
using Tesselate;
namespace AGG
{
public abstract class VertexCachedTesselator : Tesselator
{
public abstract void AddVertex(double x, double y);
}
public class RenderToGLTesselator : VertexCachedTesselator
{
List<AddedVertex> m_Vertices = new List<AddedVertex>();
internal class AddedVertex
{
internal AddedVertex(double x, double y)
{
m_X = x;
m_Y = y;
}
internal double m_X;
internal double m_Y;
};
public RenderToGLTesselator()
{
callBegin += new Tesselator.CallBeginDelegate(BeginCallBack);
callEnd += new Tesselator.CallEndDelegate(EndCallBack);
callVertex += new Tesselator.CallVertexDelegate(VertexCallBack);
//callEdgeFlag += new Tesselator.CallEdgeFlagDelegate(EdgeFlagCallBack);
callCombine += new Tesselator.CallCombineDelegate(CombineCallBack);
}
public override void BeginPolygon()
{
m_Vertices.Clear();
base.BeginPolygon();
}
public void BeginCallBack(Tesselator.TriangleListType type)
{
switch (type)
{
case Tesselator.TriangleListType.Triangles:
Gl.glBegin(Gl.GL_TRIANGLES);
break;
case Tesselator.TriangleListType.TriangleFan:
Gl.glBegin(Gl.GL_TRIANGLE_FAN);
break;
case Tesselator.TriangleListType.TriangleStrip:
Gl.glBegin(Gl.GL_TRIANGLE_STRIP);
break;
}
}
public void EndCallBack()
{
Gl.glEnd();
}
public void VertexCallBack(int index)
{
Gl.glVertex2d(m_Vertices[index].m_X, m_Vertices[index].m_Y);
}
public void EdgeFlagCallBack(int IsEdge)
{
Gl.glEdgeFlag(IsEdge);
}
public void CombineCallBack(double[] coords3, int[] data4,
double[] weight4, out int outData)
{
outData = AddVertex(coords3[0], coords3[1], false);
}
public override void AddVertex(double x, double y)
{
AddVertex(x, y, true);
}
public int AddVertex(double x, double y, bool passOnToTesselator)
{
int index = m_Vertices.Count;
m_Vertices.Add(new AddedVertex(x, y));
double[] coords = new double[3];
coords[0] = x;
coords[1] = y;
if (passOnToTesselator)
{
AddVertex(coords, index);
}
return index;
}
};
public class CacheTriangleWithEdgeInfoTesselator : VertexCachedTesselator
{
internal class AddedVertex
{
internal AddedVertex(double x, double y)
{
m_Vertex.x = x;
m_Vertex.y = y;
}
internal Vector2D m_Vertex;
};
internal class RenderIndices
{
internal RenderIndices(int index, bool isEdge)
{
m_Index = index;
m_IsEdge = isEdge;
}
internal int m_Index;
internal bool m_IsEdge;
}
bool m_IsEdge = false;
List<AddedVertex> m_Vertices = new List<AddedVertex>();
List<RenderIndices> m_Indices = new List<RenderIndices>();
public CacheTriangleWithEdgeInfoTesselator()
{
callVertex += new Tesselator.CallVertexDelegate(VertexCallBack);
callEdgeFlag += new Tesselator.CallEdgeFlagDelegate(EdgeFlagCallBack);
callCombine += new Tesselator.CallCombineDelegate(CombineCallBack);
}
protected void DrawNonAATriangle(Vector2D p0, Vector2D p1, Vector2D p2)
{
Gl.glBegin(Gl.GL_TRIANGLES);
{
// P1
Gl.glTexCoord2d(.9, 0);
Gl.glVertex2d(p0.x, p0.y);
// P2
Gl.glTexCoord2d(.9, 1);
Gl.glVertex2d(p1.x, p1.y);
// P3
Gl.glTexCoord2d(1, .5);
Gl.glVertex2d(p2.x, p2.y);
}
Gl.glEnd();
}
protected void Draw1EdgeTriangle(Vector2D p0, Vector2D p1, Vector2D p2)
{
if(p0 == p1 || p1 == p2 || p2 == p0)
{
return;
}
Vector2D edegP0P1Vector = p1 - p0;
Vector2D edegeP0P1Normal = edegP0P1Vector;
edegeP0P1Normal.Normalize();
#if AA_TIPS
Vector2D edegP2P1Vector = p1 - p2;
Vector2D edegeP2P1Normal = edegP2P1Vector;
edegeP2P1Normal.Normalize();
Vector2D edegP2P0Vector = p0 - p2;
Vector2D edegeP2P0Normal = edegP2P0Vector;
edegeP2P0Normal.Normalize();
#endif
Vector2D Normal = edegeP0P1Normal.GetPerpendicular();
double edgeDotP3 = Normal.Dot(p2 - p0);
if (edgeDotP3 < 0)
{
edgeDotP3 = -edgeDotP3;
}
else
{
Normal.Negate();
}
Vector2D edgeP0Offset = p0 + Normal;
Vector2D edgeP1Offset = p1 + Normal;
Gl.glBegin(Gl.GL_TRIANGLE_FAN);
{
Gl.glTexCoord2d(.5, 0);
Gl.glVertex2d(p0.x, p0.y);
#if AA_TIPS
// the new point
Gl.glTexCoord2d(0, 1);
Gl.glVertex2d(p0.x + edegeP2P0Normal.x, p0.y + edegeP2P0Normal.y);
#endif
Gl.glTexCoord2d(0, 0);
Gl.glVertex2d(edgeP0Offset.x, edgeP0Offset.y);
Gl.glTexCoord2d(0, 1);
Gl.glVertex2d(edgeP1Offset.x, edgeP1Offset.y);
Gl.glTexCoord2d(.5, 1);
Gl.glVertex2d(p1.x, p1.y);
Gl.glTexCoord2d(.5 + (edgeDotP3 / 2), 0);
Gl.glVertex2d(p2.x, p2.y);
}
Gl.glEnd();
#if AA_TIPS
Gl.glBegin(Gl.GL_TRIANGLES);
{
Gl.glTexCoord2d(.5, 1);
Gl.glVertex2d(p1.x, p1.y);
Gl.glTexCoord2d(0, 1);
Gl.glVertex2d(edgeP1Offset.x, edgeP1Offset.y);
// the new point
Gl.glTexCoord2d(0, 1);
Gl.glVertex2d(p0.x + edegeP2P1Normal.x, p0.y + edegeP2P1Normal.y);
}
Gl.glEnd();
#endif
}
protected void Draw2EdgeTriangle(Vector2D p0, Vector2D p1, Vector2D p2)
{
//Draw3EdgeTriangle(p0, p1, p2);
Vector2D centerPoint = p0 + p1 + p2;
centerPoint /= 3;
Draw1EdgeTriangle(p0, p1, centerPoint);
Draw1EdgeTriangle(p1, p2, centerPoint);
DrawNonAATriangle(p2, p0, centerPoint);
}
protected void Draw3EdgeTriangle(Vector2D p0, Vector2D p1, Vector2D p2)
{
Vector2D centerPoint = p0 + p1 + p2;
centerPoint /= 3;
Draw1EdgeTriangle(p0, p1, centerPoint);
Draw1EdgeTriangle(p1, p2, centerPoint);
Draw1EdgeTriangle(p2, p0, centerPoint);
}
public void RenderLastToGL()
{
for (int i = 0; i < m_Indices.Count; i += 3)
{
Vector2D v0 = m_Vertices[m_Indices[i + 0].m_Index].m_Vertex;
Vector2D v1 = m_Vertices[m_Indices[i + 1].m_Index].m_Vertex;
Vector2D v2 = m_Vertices[m_Indices[i + 2].m_Index].m_Vertex;
if (v0 == v1 || v1 == v2 || v2 == v0)
{
continue;
}
int e0 = m_Indices[i + 0].m_IsEdge ? 1 : 0;
int e1 = m_Indices[i + 1].m_IsEdge ? 1 : 0;
int e2 = m_Indices[i + 2].m_IsEdge ? 1 : 0;
switch (e0 + e1 + e2)
{
case 0:
DrawNonAATriangle(v0, v1, v2);
break;
case 1:
if (e0 == 1)
{
Draw1EdgeTriangle(v0, v1, v2);
}
else if (e1 == 1)
{
Draw1EdgeTriangle(v1, v2, v0);
}
else
{
Draw1EdgeTriangle(v2, v0, v1);
}
break;
case 2:
if (e0 == 1)
{
if (e1 == 1)
{
Draw2EdgeTriangle(v0, v1, v2);
}
else
{
Draw2EdgeTriangle(v2, v0, v1);
}
}
else
{
Draw2EdgeTriangle(v1, v2, v0);
}
break;
case 3:
Draw3EdgeTriangle(v0, v1, v2);
break;
}
}
}
public override void BeginPolygon()
{
m_Vertices.Clear();
m_Indices.Clear();
base.BeginPolygon();
}
public void VertexCallBack(int index)
{
m_Indices.Add(new RenderIndices(index, m_IsEdge));
}
public void EdgeFlagCallBack(bool isEdge)
{
m_IsEdge = isEdge;
}
public void CombineCallBack(double[] coords3, int[] data4,
double[] weight4, out int outData)
{
outData = AddVertex(coords3[0], coords3[1], false);
}
public override void AddVertex(double x, double y)
{
AddVertex(x, y, true);
}
public int AddVertex(double x, double y, bool passOnToTesselator)
{
int index = m_Vertices.Count;
m_Vertices.Add(new AddedVertex(x, y));
double[] coords = new double[3];
coords[0] = x;
coords[1] = y;
if (passOnToTesselator)
{
AddVertex(coords, index);
}
return index;
}
};
public class RendererOpenGL : RendererBase
{
public bool m_ForceTexturedEdgeAntiAliasing = true;
RenderToGLTesselator m_RenderNowTesselator = new RenderToGLTesselator();
public RendererOpenGL()
{
TextPath = new gsv_text();
StrockedText = new conv_stroke(TextPath);
int[] bounds = new int[4];
Gl.glGetIntegerv(Gl.GL_VIEWPORT, bounds);
}
public override void SetClippingRect(rect_d clippingRect)
{
Gl.glScissor((int)Math.Floor(clippingRect.x1), (int)Math.Floor(clippingRect.y1),
(int)Math.Ceiling(clippingRect.Width), (int)Math.Ceiling(clippingRect.Height));
}
public override IScanlineCache ScanlineCache
{
get { return null; }
set { throw new Exception("There is no scanline cache on a GL surface."); }
}
public static void PushOrthoProjection()
{
Gl.glPushAttrib(Gl.GL_TRANSFORM_BIT | Gl.GL_ENABLE_BIT);
Gl.glEnable(Gl.GL_BLEND);
Gl.glEnable(Gl.GL_SCISSOR_TEST);
Gl.glBlendFunc(Gl.GL_SRC_ALPHA, Gl.GL_ONE_MINUS_SRC_ALPHA);
int[] viewport = new int[4];
Gl.glGetIntegerv(Gl.GL_VIEWPORT, viewport);
Gl.glMatrixMode(Gl.GL_PROJECTION);
Gl.glPushMatrix();
Gl.glLoadIdentity();
Gl.glOrtho(viewport[0], viewport[2], viewport[1], viewport[3], 0, 1);
Gl.glMatrixMode(Gl.GL_MODELVIEW);
Gl.glPushMatrix();
Gl.glLoadIdentity();
viewport = null;
}
public static void PopOrthoProjection()
{
Gl.glMatrixMode(Gl.GL_PROJECTION);
Gl.glPopMatrix();
Gl.glMatrixMode(Gl.GL_MODELVIEW);
Gl.glPopMatrix();
Gl.glPopAttrib();
}
#if use_timers
static CNamedTimer OpenGLRenderTimer = new CNamedTimer("OpenGLRenderTimer");
static CNamedTimer OpenGLEndPolygonTimer = new CNamedTimer("OpenGLEndPolygonTimer");
#endif
void SendShapeToTeselator(VertexCachedTesselator teselator, IVertexSource vertexSource)
{
teselator.BeginPolygon();
Path.FlagsAndCommand PathAndFlags = 0;
double x, y;
bool haveBegunContour = false;
while (!Path.is_stop(PathAndFlags = vertexSource.vertex(out x, out y)))
{
if (Path.is_close(PathAndFlags)
|| (haveBegunContour && Path.is_move_to(PathAndFlags)))
{
teselator.EndContour();
haveBegunContour = false;
}
if (!Path.is_close(PathAndFlags))
{
if (!haveBegunContour)
{
teselator.BeginContour();
haveBegunContour = true;
}
teselator.AddVertex(x, y);
}
}
if (haveBegunContour)
{
teselator.EndContour();
}
#if use_timers
OpenGLEndPolygonTimer.Start();
#endif
teselator.EndPolygon();
#if use_timers
OpenGLEndPolygonTimer.Stop();
#endif
}
int m_AATextureHandle = -1;
void CheckLineImageCache()
{
if (m_AATextureHandle == -1)
{
// Create the texture handle and display list handle
int[] textureHandle = new int[1];
Gl.glGenTextures(1, textureHandle);
m_AATextureHandle = textureHandle[0];
// Set up some texture parameters for openGL
Gl.glBindTexture(Gl.GL_TEXTURE_2D, m_AATextureHandle);
Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MAG_FILTER, Gl.GL_LINEAR);
Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MIN_FILTER, Gl.GL_LINEAR);
Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_WRAP_S, Gl.GL_CLAMP_TO_EDGE);
Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_WRAP_T, Gl.GL_CLAMP_TO_EDGE);
byte[] hardwarePixelBuffer = new byte[8];
hardwarePixelBuffer[0] = hardwarePixelBuffer[1] = hardwarePixelBuffer[2] = 255; hardwarePixelBuffer[3] = 0;
hardwarePixelBuffer[4] = hardwarePixelBuffer[5] = hardwarePixelBuffer[6] = 255; hardwarePixelBuffer[7] = 255;
// Create the texture
Gl.glTexImage2D(Gl.GL_TEXTURE_2D, 0, Gl.GL_RGBA, 2, 1,
0, Gl.GL_RGBA, Gl.GL_UNSIGNED_BYTE, hardwarePixelBuffer);
}
}
void DrawAAShape(IVertexSource vertexSource)
{
CheckLineImageCache();
Gl.glEnable(Gl.GL_TEXTURE_2D);
Gl.glBindTexture(Gl.GL_TEXTURE_2D, m_AATextureHandle);
CacheTriangleWithEdgeInfoTesselator triangleEddgeInfo = new CacheTriangleWithEdgeInfoTesselator();
SendShapeToTeselator(triangleEddgeInfo, vertexSource);
// now render it
triangleEddgeInfo.RenderLastToGL();
}
public override void Render(IVertexSource vertexSource, int pathIndexToRender, RGBA_Bytes colorBytes)
{
#if use_timers
OpenGLRenderTimer.Start();
#endif
PushOrthoProjection();
vertexSource.rewind(pathIndexToRender);
RGBA_Doubles color = colorBytes.GetAsRGBA_Doubles();
Gl.glColor4d(color.m_r, color.m_g, color.m_b, color.m_a);
Affine transform = GetTransform();
if (!transform.is_identity())
{
vertexSource = new conv_transform(vertexSource, transform);
}
if (m_ForceTexturedEdgeAntiAliasing)
{
DrawAAShape(vertexSource);
}
else
{
SendShapeToTeselator(m_RenderNowTesselator, vertexSource);
}
PopOrthoProjection();
#if use_timers
OpenGLRenderTimer.Stop();
#endif
}
public override void Render(IImage source,
double x, double y,
double angleDegrees,
double scaleX, double ScaleY,
RGBA_Bytes color,
BlendMode renderingMode)
{
ImageGL
x = 0;
}
public override void Clear(IColorType color)
{
RGBA_Doubles colorDoubles = color.GetAsRGBA_Doubles();
Gl.glClearColor((float)colorDoubles.m_r, (float)colorDoubles.m_g, (float)colorDoubles.m_b, (float)colorDoubles.m_a);
Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT);
}
}
}
| |
using System;
using System.Data.OleDb;
using FileHelpers.DataLink;
using NUnit.Framework;
namespace FileHelpers.Tests.DataLink
{
[TestFixture]
[Explicit]
[Category("Advanced")]
public class DataLinks
{
private FileDataLink mLink;
#region " FillRecordOrders "
protected void FillRecordOrders(object rec, object[] fields)
{
var record = (OrdersFixed) rec;
record.OrderID = (int) fields[0];
record.CustomerID = (string) fields[1];
record.EmployeeID = (int) fields[2];
record.OrderDate = (DateTime) fields[3];
record.RequiredDate = (DateTime) fields[4];
if (fields[5] != DBNull.Value)
record.ShippedDate = (DateTime) fields[5];
else
record.ShippedDate = DateTime.MinValue;
record.ShipVia = (int) fields[6];
record.Freight = (decimal) fields[7];
}
#endregion
[Test]
public void OrdersDbToFile()
{
var storage = new AccessStorage(typeof (OrdersFixed), @"..\data\TestData.mdb");
storage.SelectSql = "SELECT * FROM Orders";
storage.FillRecordCallback = new FillRecordHandler(FillRecordOrders);
mLink = new FileDataLink(storage);
mLink.ExtractToFile(@"..\data\temp.txt");
int extractNum = mLink.LastExtractedRecords.Length;
var records = (OrdersFixed[]) mLink.FileHelperEngine.ReadFile(@"..\data\temp.txt");
Assert.AreEqual(extractNum, records.Length);
}
[Test]
public void OrdersDbToFileEasy()
{
var storage = new AccessStorage(typeof (OrdersFixed), @"..\data\TestData.mdb");
storage.SelectSql = "SELECT * FROM Orders";
storage.FillRecordCallback = new FillRecordHandler(FillRecordOrders);
var records = (OrdersFixed[]) FileDataLink.EasyExtractToFile(storage, @"..\data\temp.txt");
int extractNum = records.Length;
records = (OrdersFixed[]) CommonEngine.ReadFile(typeof (OrdersFixed), @"..\data\temp.txt");
Assert.AreEqual(extractNum, records.Length);
}
private void FillRecordCustomers(object rec, object[] fields)
{
var record = (CustomersVerticalBar) rec;
record.CustomerID = (string) fields[0];
record.CompanyName = (string) fields[1];
record.ContactName = (string) fields[2];
record.ContactTitle = (string) fields[3];
record.Address = (string) fields[4];
record.City = (string) fields[5];
record.Country = (string) fields[6];
}
[Test]
public void CustomersDbToFile()
{
var storage = new AccessStorage(typeof (CustomersVerticalBar), @"..\data\TestData.mdb");
storage.SelectSql = "SELECT * FROM Customers";
storage.FillRecordCallback = new FillRecordHandler(FillRecordCustomers);
mLink = new FileDataLink(storage);
mLink.ExtractToFile(@"..\data\temp.txt");
int extractNum = mLink.LastExtractedRecords.Length;
var records = (CustomersVerticalBar[]) mLink.FileHelperEngine.ReadFile(@"..\data\temp.txt");
Assert.AreEqual(extractNum, records.Length);
}
private object FillRecord(object[] fields)
{
var record = new CustomersVerticalBar();
record.CustomerID = (string) fields[0];
record.CompanyName = (string) fields[1];
record.ContactName = (string) fields[2];
record.ContactTitle = (string) fields[3];
record.Address = (string) fields[4];
record.City = (string) fields[5];
record.Country = (string) fields[6];
return record;
}
#region " GetInsertSql "
protected string GetInsertSqlCust(object record)
{
var obj = (CustomersVerticalBar) record;
return
String.Format(
"INSERT INTO CustomersTemp (Address, City, CompanyName, ContactName, ContactTitle, Country, CustomerID) " +
" VALUES ( \"{0}\" , \"{1}\" , \"{2}\" , \"{3}\" , \"{4}\" , \"{5}\" , \"{6}\" ); ",
obj.Address,
obj.City,
obj.CompanyName,
obj.ContactName,
obj.ContactTitle,
obj.Country,
obj.CustomerID
);
}
#endregion
[Test]
public void CustomersFileToDb()
{
var storage = new AccessStorage(typeof (CustomersVerticalBar), @"..\data\TestData.mdb");
storage.InsertSqlCallback = new InsertSqlHandler(GetInsertSqlCust);
mLink = new FileDataLink(storage);
ClearData(((AccessStorage) mLink.DataStorage).AccessFileName, "CustomersTemp");
int count = Count(((AccessStorage) mLink.DataStorage).AccessFileName, "CustomersTemp");
Assert.AreEqual(0, count);
mLink.InsertFromFile(@"..\data\UpLoadCustomers.txt");
count = Count(((AccessStorage) mLink.DataStorage).AccessFileName, "CustomersTemp");
Assert.AreEqual(91, count);
ClearData(((AccessStorage) mLink.DataStorage).AccessFileName, "CustomersTemp");
}
protected object FillRecordOrder(object[] fields)
{
var record = new OrdersFixed();
record.OrderID = (int) fields[0];
record.CustomerID = (string) fields[1];
record.EmployeeID = (int) fields[2];
record.OrderDate = (DateTime) fields[3];
record.RequiredDate = (DateTime) fields[4];
if (fields[5] != DBNull.Value)
record.ShippedDate = (DateTime) fields[5];
else
record.ShippedDate = DateTime.MinValue;
record.ShipVia = (int) fields[6];
record.Freight = (decimal) fields[7];
return record;
}
#region " GetInsertSql "
protected string GetInsertSqlOrder(object record)
{
var obj = (OrdersFixed) record;
return
String.Format(
"INSERT INTO OrdersTemp (CustomerID, EmployeeID, Freight, OrderDate, OrderID, RequiredDate, ShippedDate, ShipVia) " +
" VALUES ( \"{0}\" , \"{1}\" , \"{2}\" , \"{3}\" , \"{4}\" , \"{5}\" , \"{6}\" , \"{7}\" ) ",
obj.CustomerID,
obj.EmployeeID,
obj.Freight,
obj.OrderDate,
obj.OrderID,
obj.RequiredDate,
obj.ShippedDate,
obj.ShipVia
);
}
#endregion
[Test]
[Ignore("Needs Access Installed")]
public void OrdersFileToDb()
{
var storage = new AccessStorage(typeof (OrdersFixed), @"..\data\TestData.mdb");
storage.InsertSqlCallback = new InsertSqlHandler(GetInsertSqlOrder);
mLink = new FileDataLink(storage);
ClearData(((AccessStorage) mLink.DataStorage).AccessFileName, "OrdersTemp");
int count = Count(((AccessStorage) mLink.DataStorage).AccessFileName, "OrdersTemp");
Assert.AreEqual(0, count);
mLink.InsertFromFile(@"..\data\UpLoadOrders.txt");
count = Count(((AccessStorage) mLink.DataStorage).AccessFileName, "OrdersTemp");
Assert.AreEqual(830, count);
ClearData(((AccessStorage) mLink.DataStorage).AccessFileName, "OrdersTemp");
}
private const string AccessConnStr =
@"Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Registry Path=;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Database Password=;Data Source=""<BASE>"";Password=;Jet OLEDB:Engine Type=5;Jet OLEDB:Global Bulk Transactions=1;Provider=""Microsoft.Jet.OLEDB.4.0"";Jet OLEDB:System database=;Jet OLEDB:SFP=False;Extended Properties=;Mode=Share Deny None;Jet OLEDB:New Database Password=;Jet OLEDB:Create System Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;User ID=Admin;Jet OLEDB:Encrypt Database=False";
public void ClearData(string fileName, string table)
{
string conString = AccessConnStr.Replace("<BASE>", fileName);
var conn = new OleDbConnection(conString);
var cmd = new OleDbCommand("DELETE FROM " + table, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
int count = Count(((AccessStorage) mLink.DataStorage).AccessFileName, "OrdersTemp");
}
public int Count(string fileName, string table)
{
string conString = AccessConnStr.Replace("<BASE>", fileName);
var conn = new OleDbConnection(conString);
var cmd = new OleDbCommand("SELECT COUNT (*) FROM " + table, conn);
conn.Open();
var res = (int) cmd.ExecuteScalar();
conn.Close();
return res;
}
}
}
| |
// 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.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic.Utils;
using System.Reflection;
namespace System.Linq.Expressions
{
/// <summary>
/// Represents an expression that applies a delegate or lambda expression to a list of argument expressions.
/// </summary>
[DebuggerTypeProxy(typeof(Expression.InvocationExpressionProxy))]
public class InvocationExpression : Expression, IArgumentProvider
{
private readonly Expression _lambda;
private readonly Type _returnType;
internal InvocationExpression(Expression lambda, Type returnType)
{
_lambda = lambda;
_returnType = returnType;
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression" /> represents.
/// </summary>
/// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
public sealed override Type Type
{
get { return _returnType; }
}
/// <summary>
/// Returns the node type of this Expression. Extension nodes should return
/// ExpressionType.Extension when overriding this method.
/// </summary>
/// <returns>The <see cref="ExpressionType"/> of the expression.</returns>
public sealed override ExpressionType NodeType
{
get { return ExpressionType.Invoke; }
}
/// <summary>
/// Gets the delegate or lambda expression to be applied.
/// </summary>
public Expression Expression
{
get { return _lambda; }
}
/// <summary>
/// Gets the arguments that the delegate or lambda expression is applied to.
/// </summary>
public ReadOnlyCollection<Expression> Arguments
{
get { return GetOrMakeArguments(); }
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="expression">The <see cref="Expression" /> property of the result.</param>
/// <param name="arguments">The <see cref="Arguments" /> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public InvocationExpression Update(Expression expression, IEnumerable<Expression> arguments)
{
if (expression == Expression && arguments == Arguments)
{
return this;
}
return Expression.Invoke(expression, arguments);
}
[ExcludeFromCodeCoverage] // Unreachable
internal virtual ReadOnlyCollection<Expression> GetOrMakeArguments()
{
throw ContractUtils.Unreachable;
}
[ExcludeFromCodeCoverage] // Unreachable
public virtual Expression GetArgument(int index)
{
throw ContractUtils.Unreachable;
}
[ExcludeFromCodeCoverage] // Unreachable
public virtual int ArgumentCount
{
get
{
throw ContractUtils.Unreachable;
}
}
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitInvocation(this);
}
[ExcludeFromCodeCoverage] // Unreachable
internal virtual InvocationExpression Rewrite(Expression lambda, Expression[] arguments)
{
throw ContractUtils.Unreachable;
}
internal LambdaExpression LambdaOperand
{
get
{
return (_lambda.NodeType == ExpressionType.Quote)
? (LambdaExpression)((UnaryExpression)_lambda).Operand
: (_lambda as LambdaExpression);
}
}
}
#region Specialized Subclasses
internal class InvocationExpressionN : InvocationExpression
{
private IList<Expression> _arguments;
public InvocationExpressionN(Expression lambda, IList<Expression> arguments, Type returnType)
: base(lambda, returnType)
{
_arguments = arguments;
}
internal override ReadOnlyCollection<Expression> GetOrMakeArguments()
{
return ReturnReadOnly(ref _arguments);
}
public override Expression GetArgument(int index)
{
return _arguments[index];
}
public override int ArgumentCount
{
get
{
return _arguments.Count;
}
}
internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments)
{
Debug.Assert(lambda != null);
Debug.Assert(arguments == null || arguments.Length == _arguments.Count);
return Expression.Invoke(lambda, arguments ?? _arguments);
}
}
internal class InvocationExpression0 : InvocationExpression
{
public InvocationExpression0(Expression lambda, Type returnType)
: base(lambda, returnType)
{
}
internal override ReadOnlyCollection<Expression> GetOrMakeArguments()
{
return EmptyReadOnlyCollection<Expression>.Instance;
}
public override Expression GetArgument(int index)
{
throw new InvalidOperationException();
}
public override int ArgumentCount
{
get
{
return 0;
}
}
internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments)
{
Debug.Assert(lambda != null);
Debug.Assert(arguments == null || arguments.Length == 0);
return Expression.Invoke(lambda);
}
}
internal class InvocationExpression1 : InvocationExpression
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
public InvocationExpression1(Expression lambda, Type returnType, Expression arg0)
: base(lambda, returnType)
{
_arg0 = arg0;
}
internal override ReadOnlyCollection<Expression> GetOrMakeArguments()
{
return ReturnReadOnly(this, ref _arg0);
}
public override Expression GetArgument(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
default: throw new InvalidOperationException();
}
}
public override int ArgumentCount
{
get
{
return 1;
}
}
internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments)
{
Debug.Assert(lambda != null);
Debug.Assert(arguments == null || arguments.Length == 1);
if (arguments != null)
{
return Expression.Invoke(lambda, arguments[0]);
}
return Expression.Invoke(lambda, ReturnObject<Expression>(_arg0));
}
}
internal class InvocationExpression2 : InvocationExpression
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1; // storage for the 2nd arg
public InvocationExpression2(Expression lambda, Type returnType, Expression arg0, Expression arg1)
: base(lambda, returnType)
{
_arg0 = arg0;
_arg1 = arg1;
}
internal override ReadOnlyCollection<Expression> GetOrMakeArguments()
{
return ReturnReadOnly(this, ref _arg0);
}
public override Expression GetArgument(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
default: throw new InvalidOperationException();
}
}
public override int ArgumentCount
{
get
{
return 2;
}
}
internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments)
{
Debug.Assert(lambda != null);
Debug.Assert(arguments == null || arguments.Length == 2);
if (arguments != null)
{
return Expression.Invoke(lambda, arguments[0], arguments[1]);
}
return Expression.Invoke(lambda, ReturnObject<Expression>(_arg0), _arg1);
}
}
internal class InvocationExpression3 : InvocationExpression
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1; // storage for the 2nd arg
private readonly Expression _arg2; // storage for the 3rd arg
public InvocationExpression3(Expression lambda, Type returnType, Expression arg0, Expression arg1, Expression arg2)
: base(lambda, returnType)
{
_arg0 = arg0;
_arg1 = arg1;
_arg2 = arg2;
}
internal override ReadOnlyCollection<Expression> GetOrMakeArguments()
{
return ReturnReadOnly(this, ref _arg0);
}
public override Expression GetArgument(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
case 2: return _arg2;
default: throw new InvalidOperationException();
}
}
public override int ArgumentCount
{
get
{
return 3;
}
}
internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments)
{
Debug.Assert(lambda != null);
Debug.Assert(arguments == null || arguments.Length == 3);
if (arguments != null)
{
return Expression.Invoke(lambda, arguments[0], arguments[1], arguments[2]);
}
return Expression.Invoke(lambda, ReturnObject<Expression>(_arg0), _arg1, _arg2);
}
}
internal class InvocationExpression4 : InvocationExpression
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1; // storage for the 2nd arg
private readonly Expression _arg2; // storage for the 3rd arg
private readonly Expression _arg3; // storage for the 4th arg
public InvocationExpression4(Expression lambda, Type returnType, Expression arg0, Expression arg1, Expression arg2, Expression arg3)
: base(lambda, returnType)
{
_arg0 = arg0;
_arg1 = arg1;
_arg2 = arg2;
_arg3 = arg3;
}
internal override ReadOnlyCollection<Expression> GetOrMakeArguments()
{
return ReturnReadOnly(this, ref _arg0);
}
public override Expression GetArgument(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
case 2: return _arg2;
case 3: return _arg3;
default: throw new InvalidOperationException();
}
}
public override int ArgumentCount
{
get
{
return 4;
}
}
internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments)
{
Debug.Assert(lambda != null);
Debug.Assert(arguments == null || arguments.Length == 4);
if (arguments != null)
{
return Expression.Invoke(lambda, arguments[0], arguments[1], arguments[2], arguments[3]);
}
return Expression.Invoke(lambda, ReturnObject<Expression>(_arg0), _arg1, _arg2, _arg3);
}
}
internal class InvocationExpression5 : InvocationExpression
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1; // storage for the 2nd arg
private readonly Expression _arg2; // storage for the 3rd arg
private readonly Expression _arg3; // storage for the 4th arg
private readonly Expression _arg4; // storage for the 5th arg
public InvocationExpression5(Expression lambda, Type returnType, Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4)
: base(lambda, returnType)
{
_arg0 = arg0;
_arg1 = arg1;
_arg2 = arg2;
_arg3 = arg3;
_arg4 = arg4;
}
internal override ReadOnlyCollection<Expression> GetOrMakeArguments()
{
return ReturnReadOnly(this, ref _arg0);
}
public override Expression GetArgument(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
case 2: return _arg2;
case 3: return _arg3;
case 4: return _arg4;
default: throw new InvalidOperationException();
}
}
public override int ArgumentCount
{
get
{
return 5;
}
}
internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments)
{
Debug.Assert(lambda != null);
Debug.Assert(arguments == null || arguments.Length == 5);
if (arguments != null)
{
return Expression.Invoke(lambda, arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]);
}
return Expression.Invoke(lambda, ReturnObject<Expression>(_arg0), _arg1, _arg2, _arg3, _arg4);
}
}
#endregion
public partial class Expression
{
///<summary>
///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies a delegate or lambda expression with no arguments.
///</summary>
///<returns>
///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies the specified delegate or lambda expression.
///</returns>
///<param name="expression">
///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate
///or lambda expression to be applied.
///</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="expression" /> is null.</exception>
///<exception cref="T:System.ArgumentException">
///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.</exception>
///<exception cref="T:System.InvalidOperationException">
///The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression" />.</exception>
internal static InvocationExpression Invoke(Expression expression)
{
// COMPAT: This method is marked as non-public to avoid a gap between a 0-ary and 2-ary overload (see remark for the unary case below).
RequiresCanRead(expression, "expression");
var method = GetInvokeMethod(expression);
var pis = GetParametersForValidation(method, ExpressionType.Invoke);
ValidateArgumentCount(method, ExpressionType.Invoke, 0, pis);
return new InvocationExpression0(expression, method.ReturnType);
}
///<summary>
///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies a delegate or lambda expression to one argument expression.
///</summary>
///<returns>
///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies the specified delegate or lambda expression to the provided arguments.
///</returns>
///<param name="expression">
///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate
///or lambda expression to be applied.
///</param>
///<param name="arg0">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the first argument.
///</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="expression" /> is null.</exception>
///<exception cref="T:System.ArgumentException">
///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of an arugment expression is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression" />.</exception>
///<exception cref="T:System.InvalidOperationException">
///The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression" />.</exception>
internal static InvocationExpression Invoke(Expression expression, Expression arg0)
{
// COMPAT: This method is marked as non-public to ensure compile-time compatibility for Expression.Invoke(e, null).
RequiresCanRead(expression, "expression");
var method = GetInvokeMethod(expression);
var pis = GetParametersForValidation(method, ExpressionType.Invoke);
ValidateArgumentCount(method, ExpressionType.Invoke, 1, pis);
arg0 = ValidateOneArgument(method, ExpressionType.Invoke, arg0, pis[0]);
return new InvocationExpression1(expression, method.ReturnType, arg0);
}
///<summary>
///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies a delegate or lambda expression to two argument expressions.
///</summary>
///<returns>
///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies the specified delegate or lambda expression to the provided arguments.
///</returns>
///<param name="expression">
///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate
///or lambda expression to be applied.
///</param>
///<param name="arg0">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the first argument.
///</param>
///<param name="arg1">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the second argument.
///</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="expression" /> is null.</exception>
///<exception cref="T:System.ArgumentException">
///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of an arugment expression is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression" />.</exception>
///<exception cref="T:System.InvalidOperationException">
///The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression" />.</exception>
internal static InvocationExpression Invoke(Expression expression, Expression arg0, Expression arg1)
{
// NB: This method is marked as non-public to avoid public API additions at this point.
RequiresCanRead(expression, "expression");
var method = GetInvokeMethod(expression);
var pis = GetParametersForValidation(method, ExpressionType.Invoke);
ValidateArgumentCount(method, ExpressionType.Invoke, 2, pis);
arg0 = ValidateOneArgument(method, ExpressionType.Invoke, arg0, pis[0]);
arg1 = ValidateOneArgument(method, ExpressionType.Invoke, arg1, pis[1]);
return new InvocationExpression2(expression, method.ReturnType, arg0, arg1);
}
///<summary>
///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies a delegate or lambda expression to three argument expressions.
///</summary>
///<returns>
///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies the specified delegate or lambda expression to the provided arguments.
///</returns>
///<param name="expression">
///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate
///or lambda expression to be applied.
///</param>
///<param name="arg0">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the first argument.
///</param>
///<param name="arg1">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the second argument.
///</param>
///<param name="arg2">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the third argument.
///</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="expression" /> is null.</exception>
///<exception cref="T:System.ArgumentException">
///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of an arugment expression is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression" />.</exception>
///<exception cref="T:System.InvalidOperationException">
///The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression" />.</exception>
internal static InvocationExpression Invoke(Expression expression, Expression arg0, Expression arg1, Expression arg2)
{
// NB: This method is marked as non-public to avoid public API additions at this point.
RequiresCanRead(expression, "expression");
var method = GetInvokeMethod(expression);
var pis = GetParametersForValidation(method, ExpressionType.Invoke);
ValidateArgumentCount(method, ExpressionType.Invoke, 3, pis);
arg0 = ValidateOneArgument(method, ExpressionType.Invoke, arg0, pis[0]);
arg1 = ValidateOneArgument(method, ExpressionType.Invoke, arg1, pis[1]);
arg2 = ValidateOneArgument(method, ExpressionType.Invoke, arg2, pis[2]);
return new InvocationExpression3(expression, method.ReturnType, arg0, arg1, arg2);
}
///<summary>
///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies a delegate or lambda expression to four argument expressions.
///</summary>
///<returns>
///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies the specified delegate or lambda expression to the provided arguments.
///</returns>
///<param name="expression">
///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate
///or lambda expression to be applied.
///</param>
///<param name="arg0">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the first argument.
///</param>
///<param name="arg1">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the second argument.
///</param>
///<param name="arg2">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the third argument.
///</param>
///<param name="arg3">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the fourth argument.
///</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="expression" /> is null.</exception>
///<exception cref="T:System.ArgumentException">
///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of an arugment expression is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression" />.</exception>
///<exception cref="T:System.InvalidOperationException">
///The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression" />.</exception>
internal static InvocationExpression Invoke(Expression expression, Expression arg0, Expression arg1, Expression arg2, Expression arg3)
{
// NB: This method is marked as non-public to avoid public API additions at this point.
RequiresCanRead(expression, "expression");
var method = GetInvokeMethod(expression);
var pis = GetParametersForValidation(method, ExpressionType.Invoke);
ValidateArgumentCount(method, ExpressionType.Invoke, 4, pis);
arg0 = ValidateOneArgument(method, ExpressionType.Invoke, arg0, pis[0]);
arg1 = ValidateOneArgument(method, ExpressionType.Invoke, arg1, pis[1]);
arg2 = ValidateOneArgument(method, ExpressionType.Invoke, arg2, pis[2]);
arg3 = ValidateOneArgument(method, ExpressionType.Invoke, arg3, pis[3]);
return new InvocationExpression4(expression, method.ReturnType, arg0, arg1, arg2, arg3);
}
///<summary>
///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies a delegate or lambda expression to five argument expressions.
///</summary>
///<returns>
///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies the specified delegate or lambda expression to the provided arguments.
///</returns>
///<param name="expression">
///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate
///or lambda expression to be applied.
///</param>
///<param name="arg0">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the first argument.
///</param>
///<param name="arg1">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the second argument.
///</param>
///<param name="arg2">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the third argument.
///</param>
///<param name="arg3">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the fourth argument.
///</param>
///<param name="arg4">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the fifth argument.
///</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="expression" /> is null.</exception>
///<exception cref="T:System.ArgumentException">
///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of an arugment expression is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression" />.</exception>
///<exception cref="T:System.InvalidOperationException">
///The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression" />.</exception>
internal static InvocationExpression Invoke(Expression expression, Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4)
{
// NB: This method is marked as non-public to avoid public API additions at this point.
RequiresCanRead(expression, "expression");
var method = GetInvokeMethod(expression);
var pis = GetParametersForValidation(method, ExpressionType.Invoke);
ValidateArgumentCount(method, ExpressionType.Invoke, 5, pis);
arg0 = ValidateOneArgument(method, ExpressionType.Invoke, arg0, pis[0]);
arg1 = ValidateOneArgument(method, ExpressionType.Invoke, arg1, pis[1]);
arg2 = ValidateOneArgument(method, ExpressionType.Invoke, arg2, pis[2]);
arg3 = ValidateOneArgument(method, ExpressionType.Invoke, arg3, pis[3]);
arg4 = ValidateOneArgument(method, ExpressionType.Invoke, arg4, pis[4]);
return new InvocationExpression5(expression, method.ReturnType, arg0, arg1, arg2, arg3, arg4);
}
///<summary>
///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies a delegate or lambda expression to a list of argument expressions.
///</summary>
///<returns>
///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies the specified delegate or lambda expression to the provided arguments.
///</returns>
///<param name="expression">
///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate
///or lambda expression to be applied.
///</param>
///<param name="arguments">
///An array of <see cref="T:System.Linq.Expressions.Expression" /> objects
///that represent the arguments that the delegate or lambda expression is applied to.
///</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="expression" /> is null.</exception>
///<exception cref="T:System.ArgumentException">
///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of an element of <paramref name="arguments" /> is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression" />.</exception>
///<exception cref="T:System.InvalidOperationException">
///<paramref name="arguments" /> does not contain the same number of elements as the list of parameters for the delegate represented by <paramref name="expression" />.</exception>
public static InvocationExpression Invoke(Expression expression, params Expression[] arguments)
{
return Invoke(expression, (IEnumerable<Expression>)arguments);
}
///<summary>
///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies a delegate or lambda expression to a list of argument expressions.
///</summary>
///<returns>
///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies the specified delegate or lambda expression to the provided arguments.
///</returns>
///<param name="expression">
///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate
///or lambda expression to be applied.
///</param>
///<param name="arguments">
///An <see cref="T:System.Collections.Generic.IEnumerable`1" /> of <see cref="T:System.Linq.Expressions.Expression" /> objects
///that represent the arguments that the delegate or lambda expression is applied to.
///</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="expression" /> is null.</exception>
///<exception cref="T:System.ArgumentException">
///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of an element of <paramref name="arguments" /> is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression" />.</exception>
///<exception cref="T:System.InvalidOperationException">
///<paramref name="arguments" /> does not contain the same number of elements as the list of parameters for the delegate represented by <paramref name="expression" />.</exception>
public static InvocationExpression Invoke(Expression expression, IEnumerable<Expression> arguments)
{
var argumentList = arguments as IReadOnlyList<Expression> ?? arguments.ToReadOnly();
switch (argumentList.Count)
{
case 0:
return Invoke(expression);
case 1:
return Invoke(expression, argumentList[0]);
case 2:
return Invoke(expression, argumentList[0], argumentList[1]);
case 3:
return Invoke(expression, argumentList[0], argumentList[1], argumentList[2]);
case 4:
return Invoke(expression, argumentList[0], argumentList[1], argumentList[2], argumentList[3]);
case 5:
return Invoke(expression, argumentList[0], argumentList[1], argumentList[2], argumentList[3], argumentList[4]);
}
RequiresCanRead(expression, "expression");
var args = argumentList.ToReadOnly(); // Ensure is TrueReadOnlyCollection when count > 5. Returns fast if it already is.
var mi = GetInvokeMethod(expression);
ValidateArgumentTypes(mi, ExpressionType.Invoke, ref args);
return new InvocationExpressionN(expression, args, mi.ReturnType);
}
/// <summary>
/// Gets the delegate's Invoke method; used by InvocationExpression.
/// </summary>
/// <param name="expression">The expression to be invoked.</param>
internal static MethodInfo GetInvokeMethod(Expression expression)
{
Type delegateType = expression.Type;
if (!expression.Type.IsSubclassOf(typeof(MulticastDelegate)))
{
Type exprType = TypeUtils.FindGenericType(typeof(Expression<>), expression.Type);
if (exprType == null)
{
throw Error.ExpressionTypeNotInvocable(expression.Type);
}
delegateType = exprType.GetGenericArguments()[0];
}
return delegateType.GetMethod("Invoke");
}
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Marten.Events;
using Marten.Events.Archiving;
using Marten.Testing.Events.Aggregation;
using Marten.Testing.Harness;
using Shouldly;
using Weasel.Core;
using Weasel.Postgresql;
using Xunit;
using Xunit.Abstractions;
namespace Marten.Testing.Events
{
public class archiving_events: IntegrationContext
{
private readonly ITestOutputHelper _output;
public archiving_events(DefaultStoreFixture fixture, ITestOutputHelper output): base(fixture)
{
_output = output;
}
#region sample_archive_stream_usage
public async Task SampleArchive(IDocumentSession session, string streamId)
{
session.Events.ArchiveStream(streamId);
await session.SaveChangesAsync();
}
#endregion
[Fact]
public async Task archive_stream_by_guid()
{
var stream = Guid.NewGuid();
theSession.Events.StartStream(stream, new AEvent(), new BEvent(), new CEvent());
await theSession.SaveChangesAsync();
var stream1 = await theSession.Events.FetchStreamStateAsync(stream);
stream1.IsArchived.ShouldBeFalse();
var isArchived = await theSession.Connection
.CreateCommand("select is_archived from mt_events where stream_id = :stream")
.With("stream", stream).FetchList<bool>();
// None of the events should be archived
isArchived.All(x => !x).ShouldBeTrue();
theSession.Events.ArchiveStream(stream);
await theSession.SaveChangesAsync();
var stream2 = await theSession.Events.FetchStreamStateAsync(stream);
stream2.IsArchived.ShouldBeTrue();
isArchived = await theSession.Connection
.CreateCommand("select is_archived from mt_events where stream_id = :stream")
.With("stream", stream).FetchList<bool>();
// All of the events should be archived
isArchived.All(x => x).ShouldBeTrue();
}
[Fact]
public async Task fetch_stream_filters_out_archived_events()
{
var stream = Guid.NewGuid();
theSession.Events.StartStream(stream, new AEvent(), new BEvent(), new CEvent(), new CEvent(), new CEvent());
await theSession.SaveChangesAsync();
await theSession.Connection.CreateCommand("update mt_events set is_archived = TRUE where version < 2")
.ExecuteNonQueryAsync();
var events = await theSession.Events.FetchStreamAsync(stream);
events.All(x => x.Version >= 2).ShouldBeTrue();
}
[Fact] // TODO -- incorporate this in the events_workflow_specs maybe?
// find some way to share the ByString DocumentStore
public async Task archive_stream_by_string()
{
StoreOptions(opts =>
{
opts.Events.StreamIdentity = StreamIdentity.AsString;
opts.DatabaseSchemaName = "string_events";
});
var stream = Guid.NewGuid().ToString();
theSession.Events.StartStream(stream, new AEvent(), new BEvent(), new CEvent());
await theSession.SaveChangesAsync();
var stream1 = await theSession.Events.FetchStreamStateAsync(stream);
stream1.IsArchived.ShouldBeFalse();
var isArchived = await theSession.Connection
.CreateCommand("select is_archived from string_events.mt_events where stream_id = :stream")
.With("stream", stream).FetchList<bool>();
// None of the events should be archived
isArchived.All(x => !x).ShouldBeTrue();
theSession.Events.ArchiveStream(stream);
await theSession.SaveChangesAsync();
var stream2 = await theSession.Events.FetchStreamStateAsync(stream);
stream2.IsArchived.ShouldBeTrue();
isArchived = await theSession.Connection
.CreateCommand("select is_archived from string_events.mt_events where stream_id = :stream")
.With("stream", stream).FetchList<bool>();
// All of the events should be archived
isArchived.All(x => x).ShouldBeTrue();
}
[Fact]
public async Task query_by_events_filters_out_archived_events_by_default()
{
await theStore.Advanced.Clean.DeleteAllEventDataAsync();
var stream1 = Guid.NewGuid();
var stream2 = Guid.NewGuid();
var stream3 = Guid.NewGuid();
theSession.Events.Append(stream1, new AEvent(), new BEvent(), new CEvent());
theSession.Events.Append(stream2, new AEvent(), new BEvent(), new CEvent());
theSession.Events.Append(stream3, new AEvent(), new BEvent(), new CEvent());
await theSession.SaveChangesAsync();
theSession.Events.ArchiveStream(stream2);
await theSession.SaveChangesAsync();
var events = await theSession.Events.QueryAllRawEvents().ToListAsync();
events.Count.ShouldBe(6);
events.All(x => x.StreamId != stream2).ShouldBeTrue();
}
[Fact]
public async Task query_by_events_and_explicitly_search_for_archived_events()
{
await theStore.Advanced.Clean.DeleteAllEventDataAsync();
var stream1 = Guid.NewGuid();
var stream2 = Guid.NewGuid();
var stream3 = Guid.NewGuid();
theSession.Events.Append(stream1, new AEvent(), new BEvent(), new CEvent());
theSession.Events.Append(stream2, new AEvent(), new BEvent(), new CEvent());
theSession.Events.Append(stream3, new AEvent(), new BEvent(), new CEvent());
await theSession.SaveChangesAsync();
theSession.Events.ArchiveStream(stream2);
await theSession.SaveChangesAsync();
#region sample_querying_for_archived_events
var events = await theSession.Events
.QueryAllRawEvents()
.Where(x => x.IsArchived)
.ToListAsync();
#endregion
events.Count.ShouldBe(3);
events.All(x => x.StreamId == stream2).ShouldBeTrue();
}
[Fact]
public async Task query_by_events_and_explicitly_search_for_maybe_archived_events()
{
await theStore.Advanced.Clean.DeleteAllEventDataAsync();
var stream1 = Guid.NewGuid();
var stream2 = Guid.NewGuid();
var stream3 = Guid.NewGuid();
theSession.Events.Append(stream1, new AEvent(), new BEvent(), new CEvent());
theSession.Events.Append(stream2, new AEvent(), new BEvent(), new CEvent());
theSession.Events.Append(stream3, new AEvent(), new BEvent(), new CEvent());
await theSession.SaveChangesAsync();
theSession.Events.ArchiveStream(stream2);
await theSession.SaveChangesAsync();
#region sample_query_for_maybe_archived_events
var events = await theSession.Events.QueryAllRawEvents()
.Where(x => x.MaybeArchived()).ToListAsync();
#endregion
events.Count(x => x.IsArchived).ShouldBe(3);
events.Count(x => !x.IsArchived).ShouldBe(6);
events.Count.ShouldBe(9);
}
[Fact]
public async Task query_by_a_specific_event_filters_out_archived_events_by_default()
{
await theStore.Advanced.Clean.DeleteAllEventDataAsync();
var stream1 = Guid.NewGuid();
var stream2 = Guid.NewGuid();
var stream3 = Guid.NewGuid();
var aEvent1 = new AEvent();
var aEvent2 = new AEvent();
var aEvent3 = new AEvent();
theSession.Events.Append(stream1, aEvent1, new BEvent(), new CEvent());
theSession.Events.Append(stream2, aEvent2, new BEvent(), new CEvent());
theSession.Events.Append(stream3, aEvent3, new BEvent(), new CEvent());
await theSession.SaveChangesAsync();
theSession.Events.ArchiveStream(stream2);
await theSession.SaveChangesAsync();
#region sample_replacing_logger_per_session
// We frequently use this special marten logger per
// session to pipe Marten logging to the xUnit.Net output
theSession.Logger = new TestOutputMartenLogger(_output);
#endregion
var events = await theSession.Events.QueryRawEventDataOnly<AEvent>().ToListAsync();
events.Count.ShouldBe(2);
events.All(x => x.Tracker != aEvent2.Tracker).ShouldBeTrue();
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Reflection;
using System.Threading;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Communications.Capabilities;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Caps=OpenSim.Framework.Communications.Capabilities.Caps;
using OSDArray=OpenMetaverse.StructuredData.OSDArray;
using OSDMap=OpenMetaverse.StructuredData.OSDMap;
using Amib.Threading;
namespace OpenSim.Region.CoreModules.World.WorldMap
{
public class WorldMapModule : INonSharedRegionModule, IWorldMapModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly string DEFAULT_WORLD_MAP_EXPORT_PATH = "exportmap.jpg";
private static readonly string m_mapLayerPath = "0001/";
//private IConfig m_config;
protected Scene m_scene;
private List<MapBlockData> cachedMapBlocks = new List<MapBlockData>();
private int cachedTime = 0;
private byte[] myMapImageJPEG;
protected volatile bool m_Enabled = false;
private Dictionary<UUID, MapRequestState> m_openRequests = new Dictionary<UUID, MapRequestState>();
private Dictionary<string, int> m_blacklistedurls = new Dictionary<string, int>();
private Dictionary<ulong, int> m_blacklistedregions = new Dictionary<ulong, int>();
private Dictionary<ulong, string> m_cachedRegionMapItemsAddress = new Dictionary<ulong, string>();
private List<UUID> m_rootAgents = new List<UUID>();
private SmartThreadPool _blockRequestPool;
private SmartThreadPool _infoRequestPool;
private Dictionary<UUID, IWorkItemResult> _currentRequests = new Dictionary<UUID, IWorkItemResult>();
//private int CacheRegionsDistance = 256;
#region INonSharedRegionModule Members
public virtual void Initialise (IConfigSource config)
{
IConfig startupConfig = config.Configs["Startup"];
if (startupConfig.GetString("WorldMapModule", "WorldMap") == "WorldMap")
m_Enabled = true;
STPStartInfo reqPoolStartInfo = new STPStartInfo();
reqPoolStartInfo.MaxWorkerThreads = 2;
reqPoolStartInfo.IdleTimeout = 5 * 60 * 1000;
reqPoolStartInfo.ThreadPriority = ThreadPriority.Lowest;
STPStartInfo infoReqPoolStartInfo = new STPStartInfo();
reqPoolStartInfo.MaxWorkerThreads = 4;
reqPoolStartInfo.IdleTimeout = 5 * 60 * 1000;
reqPoolStartInfo.ThreadPriority = ThreadPriority.Lowest;
_blockRequestPool = new SmartThreadPool(reqPoolStartInfo);
_blockRequestPool.Name = "Map Block Requests";
_infoRequestPool = new SmartThreadPool(infoReqPoolStartInfo);
_infoRequestPool.Name = "Map Info Requests";
}
public virtual void AddRegion (Scene scene)
{
if (!m_Enabled)
return;
lock (scene)
{
m_scene = scene;
m_scene.RegisterModuleInterface<IWorldMapModule>(this);
m_scene.AddCommand(
this, "export-map",
"export-map [<path>]",
"Save an image of the world map", HandleExportWorldMapConsoleCommand);
AddHandlers();
}
}
public virtual void RemoveRegion (Scene scene)
{
if (!m_Enabled)
return;
lock (m_scene)
{
m_Enabled = false;
RemoveHandlers();
m_scene = null;
}
}
public virtual void RegionLoaded (Scene scene)
{
}
public virtual void Close()
{
}
public virtual string Name
{
get { return "WorldMapModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
// this has to be called with a lock on m_scene
protected virtual void AddHandlers()
{
myMapImageJPEG = new byte[0];
string regionimage = "regionImage" + m_scene.RegionInfo.RegionID.ToString();
regionimage = regionimage.Replace("-", "");
m_log.Info("[WORLD MAP]: JPEG Map location: http://" + m_scene.RegionInfo.ExternalHostName + ":" + m_scene.RegionInfo.HttpPort.ToString() + "/index.php?method=" + regionimage);
m_scene.CommsManager.HttpServer.AddHTTPHandler(regionimage, OnHTTPGetMapImage);
m_scene.CommsManager.HttpServer.AddLLSDHandler(
"/MAP/MapItems/" + m_scene.RegionInfo.RegionHandle.ToString(), HandleRemoteMapItemRequest);
m_scene.EventManager.OnRegisterCaps += OnRegisterCaps;
m_scene.EventManager.OnNewClient += OnNewClient;
m_scene.EventManager.OnClientClosed += ClientLoggedOut;
m_scene.EventManager.OnMakeChildAgent += MakeChildAgent;
m_scene.EventManager.OnMakeRootAgent += MakeRootAgent;
}
// this has to be called with a lock on m_scene
protected virtual void RemoveHandlers()
{
m_scene.EventManager.OnMakeRootAgent -= MakeRootAgent;
m_scene.EventManager.OnMakeChildAgent -= MakeChildAgent;
m_scene.EventManager.OnClientClosed -= ClientLoggedOut;
m_scene.EventManager.OnNewClient -= OnNewClient;
m_scene.EventManager.OnRegisterCaps -= OnRegisterCaps;
string regionimage = "regionImage" + m_scene.RegionInfo.RegionID.ToString();
regionimage = regionimage.Replace("-", "");
m_scene.CommsManager.HttpServer.RemoveLLSDHandler("/MAP/MapItems/" + m_scene.RegionInfo.RegionHandle.ToString(),
HandleRemoteMapItemRequest);
m_scene.CommsManager.HttpServer.RemoveHTTPHandler("", regionimage);
}
public void OnRegisterCaps(UUID agentID, Caps caps)
{
//m_log.DebugFormat("[WORLD MAP]: OnRegisterCaps: agentID {0} caps {1}", agentID, caps);
string capsBase = "/CAPS/" + caps.CapsObjectPath;
caps.RegisterHandler("MapLayer",
new RestStreamHandler("POST", capsBase + m_mapLayerPath,
delegate(string request, string path, string param,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
return MapLayerRequest(request, path, param,
agentID, caps);
}));
}
/// <summary>
/// Callback for a map layer request
/// </summary>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="agentID"></param>
/// <param name="caps"></param>
/// <returns></returns>
public string MapLayerRequest(string request, string path, string param,
UUID agentID, Caps caps)
{
//try
//{
//m_log.DebugFormat("[MAPLAYER]: request: {0}, path: {1}, param: {2}, agent:{3}",
//request, path, param,agentID.ToString());
// this is here because CAPS map requests work even beyond the 10,000 limit.
ScenePresence avatarPresence = null;
m_scene.TryGetAvatar(agentID, out avatarPresence);
if (avatarPresence != null)
{
bool lookup = false;
lock (cachedMapBlocks)
{
if (cachedMapBlocks.Count > 0 && ((cachedTime + 1800) > Util.UnixTimeSinceEpoch()))
{
List<MapBlockData> mapBlocks;
mapBlocks = cachedMapBlocks;
avatarPresence.ControllingClient.SendMapBlock(mapBlocks, 0);
}
else
{
lookup = true;
}
}
if (lookup)
{
List<MapBlockData> mapBlocks;
mapBlocks = m_scene.SceneGridService.RequestNeighbourMapBlocks((int)m_scene.RegionInfo.RegionLocX - 8, (int)m_scene.RegionInfo.RegionLocY - 8, (int)m_scene.RegionInfo.RegionLocX + 8, (int)m_scene.RegionInfo.RegionLocY + 8);
avatarPresence.ControllingClient.SendMapBlock(mapBlocks,0);
lock (cachedMapBlocks)
cachedMapBlocks = mapBlocks;
cachedTime = Util.UnixTimeSinceEpoch();
}
}
LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse();
mapResponse.LayerData.Array.Add(GetOSDMapLayerResponse());
return mapResponse.ToString();
}
/// <summary>
///
/// </summary>
/// <param name="mapReq"></param>
/// <returns></returns>
public LLSDMapLayerResponse GetMapLayer(LLSDMapRequest mapReq)
{
m_log.Debug("[WORLD MAP]: MapLayer Request in region: " + m_scene.RegionInfo.RegionName);
LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse();
mapResponse.LayerData.Array.Add(GetOSDMapLayerResponse());
return mapResponse;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
protected static OSDMapLayer GetOSDMapLayerResponse()
{
OSDMapLayer mapLayer = new OSDMapLayer();
mapLayer.Right = 5000;
mapLayer.Top = 5000;
mapLayer.ImageID = new UUID("00000000-0000-1111-9999-000000000006");
return mapLayer;
}
#region EventHandlers
/// <summary>
/// Registered for event
/// </summary>
/// <param name="client"></param>
private void OnNewClient(IClientAPI client)
{
client.OnRequestMapBlocks += RequestMapBlocks;
client.OnMapItemRequest += HandleMapItemRequest;
}
/// <summary>
/// Client logged out, check to see if there are any more root agents in the simulator
/// If not, stop the mapItemRequest Thread
/// Event handler
/// </summary>
/// <param name="AgentId">AgentID that logged out</param>
private void ClientLoggedOut(UUID AgentId, Scene scene)
{
lock (m_rootAgents)
{
if (m_rootAgents.Contains(AgentId))
{
m_rootAgents.Remove(AgentId);
}
}
}
#endregion
public virtual void HandleMapItemRequest(IClientAPI remoteClient, uint flags,
uint EstateID, bool godlike, uint itemtype, ulong regionhandle)
{
lock (m_rootAgents)
{
if (!m_rootAgents.Contains(remoteClient.AgentId))
return;
}
uint xstart = 0;
uint ystart = 0;
Utils.LongToUInts(m_scene.RegionInfo.RegionHandle, out xstart, out ystart);
if (itemtype == 6) // we only sevice 6 right now (avatar green dots)
{
if (regionhandle == 0 || regionhandle == m_scene.RegionInfo.RegionHandle)
{
// Local Map Item Request
List<ScenePresence> avatars = m_scene.GetAvatars();
int tc = Environment.TickCount;
List<mapItemReply> mapitems = new List<mapItemReply>();
mapItemReply mapitem = new mapItemReply();
if (avatars.Count == 0 || avatars.Count == 1)
{
mapitem = new mapItemReply();
mapitem.x = (uint)(xstart + 1);
mapitem.y = (uint)(ystart + 1);
mapitem.id = UUID.Zero;
mapitem.name = Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString());
mapitem.Extra = 0;
mapitem.Extra2 = 0;
mapitems.Add(mapitem);
}
else
{
foreach (ScenePresence avatar in avatars)
{
// Don't send a green dot for yourself
Vector3 avpos;
if ((avatar.UUID != remoteClient.AgentId) && avatar.HasSafePosition(out avpos))
{
mapitem = new mapItemReply();
mapitem.x = (uint)(xstart + avpos.X);
mapitem.y = (uint)(ystart + avpos.Y);
mapitem.id = UUID.Zero;
mapitem.name = Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString());
mapitem.Extra = 1;
mapitem.Extra2 = 0;
mapitems.Add(mapitem);
}
}
}
remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags);
}
else
{
RequestMapItems("",remoteClient.AgentId,flags,EstateID,godlike,itemtype,regionhandle);
}
}
}
/// <summary>
/// Sends the mapitem response to the IClientAPI
/// </summary>
/// <param name="response">The OSDMap Response for the mapitem</param>
private void RequestMapItemsCompleted(OSDMap response)
{
UUID requestID = response["requestID"].AsUUID();
if (requestID != UUID.Zero)
{
MapRequestState mrs = new MapRequestState();
mrs.agentID = UUID.Zero;
lock (m_openRequests)
{
if (m_openRequests.ContainsKey(requestID))
{
mrs = m_openRequests[requestID];
m_openRequests.Remove(requestID);
}
}
if (mrs.agentID != UUID.Zero)
{
ScenePresence av = null;
m_scene.TryGetAvatar(mrs.agentID, out av);
if (av != null)
{
if (response.ContainsKey(mrs.itemtype.ToString()))
{
List<mapItemReply> returnitems = new List<mapItemReply>();
OSDArray itemarray = (OSDArray)response[mrs.itemtype.ToString()];
for (int i = 0; i < itemarray.Count; i++)
{
OSDMap mapitem = (OSDMap)itemarray[i];
mapItemReply mi = new mapItemReply();
mi.x = (uint)mapitem["X"].AsInteger();
mi.y = (uint)mapitem["Y"].AsInteger();
mi.id = mapitem["ID"].AsUUID();
mi.Extra = mapitem["Extra"].AsInteger();
mi.Extra2 = mapitem["Extra2"].AsInteger();
mi.name = mapitem["Name"].AsString();
returnitems.Add(mi);
}
av.ControllingClient.SendMapItemReply(returnitems.ToArray(), mrs.itemtype, mrs.flags);
}
}
}
}
}
/// <summary>
/// Enqueue the MapItem request for remote processing
/// </summary>
/// <param name="httpserver">blank string, we discover this in the process</param>
/// <param name="id">Agent ID that we are making this request on behalf</param>
/// <param name="flags">passed in from packet</param>
/// <param name="EstateID">passed in from packet</param>
/// <param name="godlike">passed in from packet</param>
/// <param name="itemtype">passed in from packet</param>
/// <param name="regionhandle">Region we're looking up</param>
public void RequestMapItems(string httpserver, UUID id, uint flags,
uint EstateID, bool godlike, uint itemtype, ulong regionhandle)
{
bool dorequest = true;
lock (m_rootAgents)
{
if (!m_rootAgents.Contains(id))
dorequest = false;
}
if (dorequest)
{
_infoRequestPool.QueueWorkItem(
delegate()
{
OSDMap response = RequestMapItemsAsync(httpserver, id, flags, EstateID, godlike, itemtype, regionhandle);
RequestMapItemsCompleted(response);
}
);
}
}
/// <summary>
/// Does the actual remote mapitem request
/// This should be called from an asynchronous thread
/// Request failures get blacklisted until region restart so we don't
/// continue to spend resources trying to contact regions that are down.
/// </summary>
/// <param name="httpserver">blank string, we discover this in the process</param>
/// <param name="id">Agent ID that we are making this request on behalf</param>
/// <param name="flags">passed in from packet</param>
/// <param name="EstateID">passed in from packet</param>
/// <param name="godlike">passed in from packet</param>
/// <param name="itemtype">passed in from packet</param>
/// <param name="regionhandle">Region we're looking up</param>
/// <returns></returns>
private OSDMap RequestMapItemsAsync(string httpserver, UUID id, uint flags,
uint EstateID, bool godlike, uint itemtype, ulong regionhandle)
{
bool blacklisted = false;
lock (m_blacklistedregions)
{
if (m_blacklistedregions.ContainsKey(regionhandle))
blacklisted = true;
}
if (blacklisted)
return new OSDMap();
UUID requestID = UUID.Random();
lock (m_cachedRegionMapItemsAddress)
{
if (m_cachedRegionMapItemsAddress.ContainsKey(regionhandle))
httpserver = m_cachedRegionMapItemsAddress[regionhandle];
}
if (httpserver.Length == 0)
{
RegionInfo mreg = m_scene.SceneGridService.RequestNeighbouringRegionInfo(regionhandle);
if (mreg != null)
{
httpserver = "http://" + mreg.ExternalHostName + ":" + mreg.HttpPort + "/MAP/MapItems/" + regionhandle.ToString();
lock (m_cachedRegionMapItemsAddress)
{
if (!m_cachedRegionMapItemsAddress.ContainsKey(regionhandle))
m_cachedRegionMapItemsAddress.Add(regionhandle, httpserver);
}
}
else
{
lock (m_blacklistedregions)
{
if (!m_blacklistedregions.ContainsKey(regionhandle))
m_blacklistedregions.Add(regionhandle, Environment.TickCount);
}
m_log.InfoFormat("[WORLD MAP]: Blacklisted region {0}", regionhandle.ToString());
}
}
blacklisted = false;
lock (m_blacklistedurls)
{
if (m_blacklistedurls.ContainsKey(httpserver))
blacklisted = true;
}
// Can't find the http server
if (httpserver.Length == 0 || blacklisted)
return new OSDMap();
MapRequestState mrs = new MapRequestState();
mrs.agentID = id;
mrs.EstateID = EstateID;
mrs.flags = flags;
mrs.godlike = godlike;
mrs.itemtype=itemtype;
mrs.regionhandle = regionhandle;
lock (m_openRequests)
m_openRequests.Add(requestID, mrs);
WebRequest mapitemsrequest = WebRequest.Create(httpserver);
mapitemsrequest.Method = "POST";
mapitemsrequest.ContentType = "application/xml+llsd";
OSDMap RAMap = new OSDMap();
// string RAMapString = RAMap.ToString();
OSD LLSDofRAMap = RAMap; // RENAME if this works
byte[] buffer = OSDParser.SerializeLLSDXmlBytes(LLSDofRAMap);
OSDMap responseMap = new OSDMap();
responseMap["requestID"] = OSD.FromUUID(requestID);
Stream os = null;
try
{ // send the Post
mapitemsrequest.ContentLength = buffer.Length; //Count bytes to send
os = mapitemsrequest.GetRequestStream();
os.Write(buffer, 0, buffer.Length); //Send it
os.Close();
//m_log.DebugFormat("[WORLD MAP]: Getting MapItems from Sim {0}", httpserver);
}
catch (WebException ex)
{
m_log.WarnFormat("[WORLD MAP]: Bad send on GetMapItems {0}", ex.Message);
responseMap["connect"] = OSD.FromBoolean(false);
lock (m_blacklistedurls)
{
if (!m_blacklistedurls.ContainsKey(httpserver))
m_blacklistedurls.Add(httpserver, Environment.TickCount);
}
m_log.WarnFormat("[WORLD MAP]: Blacklisted {0}", httpserver);
return responseMap;
}
string response_mapItems_reply = null;
{ // get the response
try
{
WebResponse webResponse = mapitemsrequest.GetResponse();
if (webResponse != null)
{
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
response_mapItems_reply = sr.ReadToEnd().Trim();
}
else
{
return new OSDMap();
}
}
catch (WebException)
{
responseMap["connect"] = OSD.FromBoolean(false);
lock (m_blacklistedurls)
{
if (!m_blacklistedurls.ContainsKey(httpserver))
m_blacklistedurls.Add(httpserver, Environment.TickCount);
}
m_log.WarnFormat("[WORLD MAP]: Blacklisted {0}", httpserver);
return responseMap;
}
OSD rezResponse = null;
try
{
rezResponse = OSDParser.DeserializeLLSDXml(response_mapItems_reply);
responseMap = (OSDMap)rezResponse;
responseMap["requestID"] = OSD.FromUUID(requestID);
}
catch (Exception)
{
//m_log.InfoFormat("[OGP]: exception on parse of rez reply {0}", ex.Message);
responseMap["connect"] = OSD.FromBoolean(false);
return responseMap;
}
}
return responseMap;
}
private void RequestCompleted(IWorkItemResult workItem)
{
lock (_currentRequests)
{
UUID userId = (UUID)workItem.State;
IWorkItemResult currentRequest;
if (_currentRequests.TryGetValue(userId, out currentRequest))
{
if (currentRequest == workItem)
{
_currentRequests.Remove(userId);
}
}
}
}
/// <summary>
/// Requests map blocks in area of minX, maxX, minY, MaxY in world cordinates
/// </summary>
/// <param name="minX"></param>
/// <param name="minY"></param>
/// <param name="maxX"></param>
/// <param name="maxY"></param>
public virtual void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY, uint flag)
{
IWorkItemResult newItem = null;
if ((flag & 0x10000) != 0) // user clicked on the map a tile that isn't visible
{
lock (_currentRequests)
{
CancelCurrentRequestForUser(remoteClient);
newItem =
_blockRequestPool.QueueWorkItem(
delegate(object state)
{
RequestNonVisibleMapTile(remoteClient, minX, minY, maxX, maxY, flag);
return null;
},
remoteClient.AgentId,
this.RequestCompleted
);
_currentRequests[remoteClient.AgentId] = newItem;
}
}
else
{
lock (_currentRequests)
{
// normal mapblock request. Use the provided values
CancelCurrentRequestForUser(remoteClient);
newItem =
_blockRequestPool.QueueWorkItem(
delegate(object state)
{
GetAndSendBlocks(remoteClient, minX, minY, maxX, maxY, flag);
return null;
},
remoteClient.AgentId,
this.RequestCompleted
);
_currentRequests[remoteClient.AgentId] = newItem;
}
}
}
private void CancelCurrentRequestForUser(IClientAPI remoteClient)
{
IWorkItemResult foundResult;
if (_currentRequests.TryGetValue(remoteClient.AgentId, out foundResult))
{
foundResult.Cancel();
}
}
private void RequestNonVisibleMapTile(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY, uint flag)
{
List<MapBlockData> response = new List<MapBlockData>();
// this should return one mapblock at most. But make sure: Look whether the one we requested is in there
List<MapBlockData> mapBlocks = m_scene.SceneGridService.RequestNeighbourMapBlocks(minX, minY, maxX, maxY);
if (mapBlocks != null)
{
foreach (MapBlockData block in mapBlocks)
{
if (block.X == minX && block.Y == minY)
{
// found it => add it to response
response.Add(block);
break;
}
}
}
if (response.Count == 0)
{
// response still empty => couldn't find the map-tile the user clicked on => tell the client
MapBlockData block = new MapBlockData();
block.X = (ushort)minX;
block.Y = (ushort)minY;
block.Access = 254; // == not there
response.Add(block);
}
//(flag & 0x10000) != 0 is sent by v2 viewers, and it expects flag 2 back
remoteClient.SendMapBlock(response, flag & 0xffff);
}
protected virtual void GetAndSendBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY, uint flag)
{
List<MapBlockData> mapBlocks = m_scene.SceneGridService.RequestNeighbourMapBlocks(minX - 4, minY - 4, maxX + 4, maxY + 4);
remoteClient.SendMapBlock(mapBlocks, flag);
}
/// <summary>
/// The last time a mapimage was cached
/// </summary>
private DateTime _lastImageGenerationTime = DateTime.Now;
/// <summary>
/// Number of days to cache a mapimage
/// </summary>
private const int MAPIMAGE_CACHE_TIME = 2;
public Hashtable OnHTTPGetMapImage(Hashtable keysvals)
{
bool forceRefresh = false;
if (keysvals.ContainsKey("requestvars"))
{
Hashtable rvars = (Hashtable)keysvals["requestvars"];
if (rvars.ContainsKey("forcerefresh")) forceRefresh = true;
}
if (forceRefresh)
{
m_log.Debug("[WORLD MAP]: Forcing refresh of map tile");
//regenerate terrain
m_scene.CreateTerrainTexture(false);
}
m_log.Debug("[WORLD MAP]: Sending map image jpeg");
Hashtable reply = new Hashtable();
int statuscode = 200;
byte[] jpeg = new byte[0];
if (myMapImageJPEG.Length == 0 || (DateTime.Now - _lastImageGenerationTime).TotalDays > MAPIMAGE_CACHE_TIME || forceRefresh)
{
MemoryStream imgstream = new MemoryStream();
Bitmap mapTexture = new Bitmap(1,1);
ManagedImage managedImage;
Image image = (Image)mapTexture;
try
{
// Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular jpeg data
imgstream = new MemoryStream();
// non-async because we know we have the asset immediately.
AssetBase mapasset = m_scene.CommsManager.AssetCache.GetAsset(m_scene.RegionInfo.lastMapUUID,
AssetRequestInfo.InternalRequest());
// Decode image to System.Drawing.Image
if (OpenJPEG.DecodeToImage(mapasset.Data, out managedImage, out image))
{
// Save to bitmap
mapTexture = new Bitmap(image);
EncoderParameters myEncoderParameters = new EncoderParameters();
myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
// Save bitmap to stream
mapTexture.Save(imgstream, GetEncoderInfo("image/jpeg"), myEncoderParameters);
// Write the stream to a byte array for output
jpeg = imgstream.ToArray();
myMapImageJPEG = jpeg;
_lastImageGenerationTime = DateTime.Now;
}
}
catch (Exception)
{
// Dummy!
m_log.Warn("[WORLD MAP]: Unable to generate Map image");
}
finally
{
// Reclaim memory, these are unmanaged resources
mapTexture.Dispose();
image.Dispose();
imgstream.Close();
imgstream.Dispose();
}
}
else
{
// Use cached version so we don't have to loose our mind
jpeg = myMapImageJPEG;
}
reply["str_response_string"] = Convert.ToBase64String(jpeg);
reply["int_response_code"] = statuscode;
reply["content_type"] = "image/jpeg";
return reply;
}
// From msdn
private static ImageCodecInfo GetEncoderInfo(String mimeType)
{
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for (int j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
}
return null;
}
/// <summary>
/// Export the world map
/// </summary>
/// <param name="fileName"></param>
public void HandleExportWorldMapConsoleCommand(string module, string[] cmdparams)
{
if (m_scene.ConsoleScene() == null)
{
// FIXME: If console region is root then this will be printed by every module. Currently, there is no
// way to prevent this, short of making the entire module shared (which is complete overkill).
// One possibility is to return a bool to signal whether the module has completely handled the command
m_log.InfoFormat("[WORLD MAP]: Please change to a specific region in order to export its world map");
return;
}
if (m_scene.ConsoleScene() != m_scene)
return;
string exportPath;
if (cmdparams.Length > 1)
exportPath = cmdparams[1];
else
exportPath = DEFAULT_WORLD_MAP_EXPORT_PATH;
m_log.InfoFormat(
"[WORLD MAP]: Exporting world map for {0} to {1}", m_scene.RegionInfo.RegionName, exportPath);
List<MapBlockData> mapBlocks =
m_scene.CommsManager.GridService.RequestNeighbourMapBlocks(
(int)(m_scene.RegionInfo.RegionLocX - 9),
(int)(m_scene.RegionInfo.RegionLocY - 9),
(int)(m_scene.RegionInfo.RegionLocX + 9),
(int)(m_scene.RegionInfo.RegionLocY + 9));
List<AssetBase> textures = new List<AssetBase>();
List<Image> bitImages = new List<Image>();
foreach (MapBlockData mapBlock in mapBlocks)
{
AssetBase texAsset = m_scene.CommsManager.AssetCache.GetAsset(mapBlock.MapImageId, AssetRequestInfo.InternalRequest());
if (texAsset != null)
{
textures.Add(texAsset);
}
else
{
texAsset = m_scene.CommsManager.AssetCache.GetAsset(mapBlock.MapImageId, AssetRequestInfo.InternalRequest());
if (texAsset != null)
{
textures.Add(texAsset);
}
}
}
foreach (AssetBase asset in textures)
{
ManagedImage managedImage;
Image image;
if (OpenJPEG.DecodeToImage(asset.Data, out managedImage, out image))
bitImages.Add(image);
}
Bitmap mapTexture = new Bitmap(2560, 2560);
Graphics g = Graphics.FromImage(mapTexture);
SolidBrush sea = new SolidBrush(Color.DarkBlue);
g.FillRectangle(sea, 0, 0, 2560, 2560);
for (int i = 0; i < mapBlocks.Count; i++)
{
ushort x = (ushort)((mapBlocks[i].X - m_scene.RegionInfo.RegionLocX) + 10);
ushort y = (ushort)((mapBlocks[i].Y - m_scene.RegionInfo.RegionLocY) + 10);
g.DrawImage(bitImages[i], (x * 128), (y * 128), 128, 128);
}
mapTexture.Save(exportPath, ImageFormat.Jpeg);
m_log.InfoFormat(
"[WORLD MAP]: Successfully exported world map for {0} to {1}",
m_scene.RegionInfo.RegionName, exportPath);
}
public OSD HandleRemoteMapItemRequest(string path, OSD request, IPEndPoint endpoint)
{
uint xstart = 0;
uint ystart = 0;
Utils.LongToUInts(m_scene.RegionInfo.RegionHandle,out xstart,out ystart);
OSDMap responsemap = new OSDMap();
OSDMap responsemapdata = new OSDMap();
int tc = Environment.TickCount;
List<ScenePresence> avatars = m_scene.GetAvatars();
OSDArray responsearr = new OSDArray(avatars.Count);
if (avatars.Count == 0)
{
responsemapdata = new OSDMap();
responsemapdata["X"] = OSD.FromInteger((int)(xstart + 1));
responsemapdata["Y"] = OSD.FromInteger((int)(ystart + 1));
responsemapdata["ID"] = OSD.FromUUID(UUID.Zero);
responsemapdata["Name"] = OSD.FromString(Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString()));
responsemapdata["Extra"] = OSD.FromInteger(0);
responsemapdata["Extra2"] = OSD.FromInteger(0);
responsearr.Add(responsemapdata);
responsemap["6"] = responsearr;
}
else
{
responsearr = new OSDArray(avatars.Count);
foreach (ScenePresence av in avatars)
{
Vector3 avpos;
if (av.HasSafePosition(out avpos))
{
responsemapdata = new OSDMap();
responsemapdata["X"] = OSD.FromInteger((int)(xstart + avpos.X));
responsemapdata["Y"] = OSD.FromInteger((int)(ystart + avpos.Y));
responsemapdata["ID"] = OSD.FromUUID(UUID.Zero);
responsemapdata["Name"] = OSD.FromString(Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString()));
responsemapdata["Extra"] = OSD.FromInteger(1);
responsemapdata["Extra2"] = OSD.FromInteger(0);
responsearr.Add(responsemapdata);
}
}
responsemap["6"] = responsearr;
}
return responsemap;
}
public void LazySaveGeneratedMaptile(byte[] data, bool temporary)
{
// Overwrites the local Asset cache with new maptile data
// Assets are single write, this causes the asset server to ignore this update,
// but the local asset cache does not
// this is on purpose! The net result of this is the region always has the most up to date
// map tile while protecting the (grid) asset database from bloat caused by a new asset each
// time a mapimage is generated!
UUID lastMapRegionUUID = m_scene.RegionInfo.lastMapUUID;
int lastMapRefresh = 0;
int twoDays = 172800;
int RefreshSeconds = twoDays;
try
{
lastMapRefresh = Convert.ToInt32(m_scene.RegionInfo.lastMapRefresh);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
UUID TerrainImageUUID = UUID.Random();
if (lastMapRegionUUID == UUID.Zero || (lastMapRefresh + RefreshSeconds) < Util.UnixTimeSinceEpoch())
{
m_scene.RegionInfo.SaveLastMapUUID(TerrainImageUUID);
m_log.Debug("[MAPTILE]: STORING MAPTILE IMAGE");
}
else
{
TerrainImageUUID = lastMapRegionUUID;
m_log.Debug("[MAPTILE]: REUSING OLD MAPTILE IMAGE ID");
}
m_scene.RegionInfo.RegionSettings.TerrainImageID = TerrainImageUUID;
AssetBase asset = new AssetBase();
asset.FullID = m_scene.RegionInfo.RegionSettings.TerrainImageID;
asset.Data = data;
asset.Name
= "terrainImage_" + m_scene.RegionInfo.RegionID.ToString() + "_" + lastMapRefresh.ToString();
asset.Description = m_scene.RegionInfo.RegionName;
asset.Type = 0;
asset.Temporary = temporary;
try
{
m_scene.CommsManager.AssetCache.AddAsset(asset, AssetRequestInfo.InternalRequest());
}
catch (AssetServerException)
{
}
}
private void MakeRootAgent(ScenePresence avatar)
{
lock (m_rootAgents)
{
if (!m_rootAgents.Contains(avatar.UUID))
{
m_rootAgents.Add(avatar.UUID);
}
}
}
private void MakeChildAgent(ScenePresence avatar)
{
lock (m_rootAgents)
{
if (m_rootAgents.Contains(avatar.UUID))
{
m_rootAgents.Remove(avatar.UUID);
}
}
}
}
public struct MapRequestState
{
public UUID agentID;
public uint flags;
public uint EstateID;
public bool godlike;
public uint itemtype;
public ulong regionhandle;
}
}
| |
/*
* SymReader.cs - Implementation of the
* "System.Diagnostics.SymbolStore.SymReader" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Diagnostics.SymbolStore
{
#if CONFIG_EXTENDED_DIAGNOSTICS
using System.IO;
using System.Text;
using System.Collections;
public class SymReader : ISymbolReader
{
// Internal state.
private unsafe ISymUnmanagedReader *pReader;
private String linkDirectory;
private String filename;
private Encoding utf8;
internal byte[] data;
internal int indexOffset;
internal int numIndexEntries;
private int stringOffset;
private int stringLength;
private ISymbolDocument[] documents;
private Hashtable documentCache;
private Hashtable methodCache;
// Types of data blocks within debug symbol data.
internal const int DataType_LineColumn = 1;
internal const int DataType_LineOffsets = 2;
internal const int DataType_LineColumnOffsets = 3;
internal const int DataType_LocalVariables = 4;
internal const int DataType_LocalVariablesOffsets = 5;
// Constructors.
public unsafe SymReader(ISymUnmanagedReader *pReader)
{
this.pReader = pReader;
}
internal SymReader(String filename, byte[] data)
{
// Store the parameters for later.
this.filename = filename;
this.data = data;
// We need the UTF8 encoding object to decode strings.
utf8 = Encoding.UTF8;
// Read and validate the header.
if(data.Length < 24)
{
throw new ArgumentException();
}
if(data[0] != (byte)'I' ||
data[1] != (byte)'L' ||
data[2] != (byte)'D' ||
data[3] != (byte)'B' ||
data[4] != (byte)0x01 ||
data[5] != (byte)0x00 ||
data[6] != (byte)0x00 ||
data[7] != (byte)0x00)
{
throw new ArgumentException();
}
indexOffset = Utils.ReadInt32(data, 8);
numIndexEntries = Utils.ReadInt32(data, 12);
stringOffset = Utils.ReadInt32(data, 16);
stringLength = Utils.ReadInt32(data, 20);
if(indexOffset < 24 || indexOffset >= data.Length)
{
throw new ArgumentException();
}
if(numIndexEntries < 0 ||
((data.Length - indexOffset) / 8) < numIndexEntries)
{
throw new ArgumentException();
}
if(stringOffset < 24 || stringOffset >= data.Length)
{
throw new ArgumentException();
}
if(stringLength <= 0 ||
stringLength > (data.Length - stringOffset) ||
data[stringOffset + stringLength - 1] != 0)
{
throw new ArgumentException();
}
// Get the link directory, if specified.
SymInfoEnumerator e = new SymInfoEnumerator(this, "LDIR");
if(e.MoveNext())
{
linkDirectory = ReadString(e.GetNextInt());
}
}
// Destructor (C++ style).
~SymReader() {}
public void __dtor()
{
GC.SuppressFinalize(this);
Finalize();
}
// Implement the ISymbolReader interface.
public virtual ISymbolDocument GetDocument
(String url, Guid language, Guid languageVendor,
Guid documentType)
{
String lang;
// Validate the url parameter.
if(url == null)
{
throw new ArgumentNullException("url");
}
// Convert the language GUID into a language name.
// We ignore the vendor and document type, because
// they are not important.
if(language == SymLanguageType.Basic)
{
lang = "basic";
}
else if(language == SymLanguageType.C)
{
lang = "c";
}
else if(language == SymLanguageType.Cobol)
{
lang = "cobol";
}
else if(language == SymLanguageType.CPlusPlus)
{
lang = "cplusplus";
}
else if(language == SymLanguageType.CSharp)
{
lang = "csharp";
}
else if(language == SymLanguageType.ILAssembly)
{
lang = "ilassembly";
}
else if(language == SymLanguageType.Java)
{
lang = "java";
}
else if(language == SymLanguageType.JScript)
{
lang = "jscript";
}
else if(language == SymLanguageType.MCPlusPlus)
{
lang = "mcplusplus";
}
else if(language == SymLanguageType.Pascal)
{
lang = "pascal";
}
else if(language == SymLanguageType.SMC)
{
lang = "smc";
}
else
{
lang = null;
}
// Create a new document object for the URL and return it.
return new SymDocument(this, lang, url);
}
public virtual ISymbolDocument[] GetDocuments()
{
// Bail out early if we already loaded the document list.
if(documents != null)
{
return documents;
}
// Read the document information list from the symbol data.
ArrayList list = new ArrayList();
SymInfoEnumerator e = new SymInfoEnumerator(this);
String filename;
ISymbolDocument doc;
while(e.MoveNext())
{
if(e.Type == DataType_LineColumn ||
e.Type == DataType_LineOffsets ||
e.Type == DataType_LineColumnOffsets)
{
filename = ReadString(e.GetNextInt());
doc = GetDocument(filename);
if(doc != null && !list.Contains(doc))
{
list.Add(doc);
}
}
}
// Return the final document list.
documents = new ISymbolDocument [list.Count];
int index = 0;
foreach(ISymbolDocument d in list)
{
documents[index++] = d;
}
return documents;
}
public virtual ISymbolVariable[] GetGlobalVariables()
{
throw new NotSupportedException();
}
public virtual ISymbolMethod GetMethod(SymbolToken method)
{
return GetMethod(method, 0);
}
public virtual ISymbolMethod GetMethod(SymbolToken method, int version)
{
ISymbolMethod meth;
if(methodCache == null)
{
methodCache = new Hashtable();
}
else if((meth = (ISymbolMethod)methodCache
[method.GetToken()]) != null)
{
return meth;
}
meth = new SymMethod(this, method.GetToken());
methodCache[method.GetToken()] = meth;
return meth;
}
public virtual ISymbolMethod GetMethodFromDocumentPosition
(ISymbolDocument document, int line, int column)
{
if(document == null || document.URL == null)
{
return null;
}
SymInfoEnumerator e = new SymInfoEnumerator(this);
String filename;
ISymbolDocument doc;
int tempLine, tempColumn, tempOffset;
int closestBelow = 0;
int closestBelowToken = 0;
while(e.MoveNext())
{
// We only check on line because column values
// are likely to be inaccurate.
if(e.Type == DataType_LineColumn)
{
filename = ReadString(e.GetNextInt());
doc = GetDocument(filename);
if(doc != null && doc.URL == document.URL)
{
while((tempLine = e.GetNextInt()) != -1)
{
tempColumn = e.GetNextInt();
if(tempLine == line)
{
return GetMethod(new SymbolToken(e.Token));
}
else if(tempLine < line &&
tempLine > closestBelow)
{
closestBelow = tempLine;
closestBelowToken = e.Token;
}
}
}
}
else if(e.Type == DataType_LineOffsets)
{
filename = ReadString(e.GetNextInt());
doc = GetDocument(filename);
if(doc != null && doc.URL == document.URL)
{
while((tempLine = e.GetNextInt()) != -1)
{
tempOffset = e.GetNextInt();
if(tempLine == line)
{
return GetMethod(new SymbolToken(e.Token));
}
else if(tempLine < line &&
tempLine > closestBelow)
{
closestBelow = tempLine;
closestBelowToken = e.Token;
}
}
}
}
else if(e.Type == DataType_LineColumnOffsets)
{
filename = ReadString(e.GetNextInt());
doc = GetDocument(filename);
if(doc != null && doc.URL == document.URL)
{
while((tempLine = e.GetNextInt()) != -1)
{
tempColumn = e.GetNextInt();
tempOffset = e.GetNextInt();
if(tempLine == line)
{
return GetMethod(new SymbolToken(e.Token));
}
else if(tempLine < line &&
tempLine > closestBelow)
{
closestBelow = tempLine;
closestBelowToken = e.Token;
}
}
}
}
}
if(closestBelowToken != 0)
{
// Return the closest match that we found in the
// document that is below the specified line.
return GetMethod(new SymbolToken(closestBelowToken));
}
return null;
}
public virtual ISymbolNamespace[] GetNamespaces()
{
throw new NotSupportedException();
}
public virtual byte[] GetSymAttribute(SymbolToken parent, String name)
{
throw new NotSupportedException();
}
public virtual ISymbolVariable[] GetVariables(SymbolToken parent)
{
throw new NotSupportedException();
}
public virtual SymbolToken UserEntryPoint
{
get
{
// Not used in this implementation, because it
// duplicates information available via metadata.
return new SymbolToken(0);
}
}
// Read a string value from the debug symbol information.
internal String ReadString(int offset)
{
if(data == null)
{
return String.Empty;
}
if(offset < 0 || offset >= stringLength)
{
return String.Empty;
}
offset += stringOffset;
int len = 0;
while(data[offset + len] != 0)
{
++len;
}
return utf8.GetString(data, offset, len);
}
// Convert a filename into a URL.
internal String FilenameToURL(String name)
{
String temp;
bool checkOther;
// Bail out if the name is empty.
if(name == null || name.Length == 0)
{
return null;
}
// Get the full absolute pathname for the file.
checkOther = true;
if(!Path.IsPathRooted(name) && linkDirectory != null)
{
temp = Path.Combine(linkDirectory, name);
if(File.Exists(temp))
{
name = temp;
checkOther = false;
}
}
if(checkOther && !Path.IsPathRooted(name) && filename != null)
{
temp = Path.Combine
(Path.GetDirectoryName(filename), name);
if(File.Exists(temp))
{
name = temp;
}
}
name = Path.GetFullPath(name);
// Normalize pathname separators to "/".
name = name.Replace('\\', '/');
// Add the "file:" prefix to the name to form the URL.
if(name.Length >= 2 && name[1] == ':')
{
// The filename includes a Windows-style drive letter.
return "file:/" + name;
}
else
{
// The filename is absolute from a Unix-style root.
return "file:" + name;
}
}
// Get a document block for a particular filename.
internal ISymbolDocument GetDocument(String filename)
{
ISymbolDocument document;
// Convert the filename into a full URL.
filename = FilenameToURL(filename);
if(filename == null)
{
return null;
}
// See if we already have a document for this file.
if(documentCache == null)
{
documentCache = new Hashtable();
}
else if((document = (ISymbolDocument)documentCache[filename])
!= null)
{
return document;
}
// Create a new document object and add it to the cache.
document = new SymDocument(this, null, filename);
documentCache[filename] = document;
return document;
}
}; // class SymReader
#endif // CONFIG_EXTENDED_DIAGNOSTICS
}; // namespace System.Diagnostics.SymbolStore
| |
// 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.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Linq.Parallel.Tests
{
// a key part of cancellation testing is 'promptness'. Those tests appear in pfxperfunittests.
// the tests here are only regarding basic API correctness and sanity checking.
public static class WithCancellationTests
{
[Fact]
public static void PreCanceledToken_ForAll()
{
OperationCanceledException caughtException = null;
var cs = new CancellationTokenSource();
cs.Cancel();
IEnumerable<int> throwOnFirstEnumerable = Enumerables<int>.ThrowOnEnumeration();
try
{
throwOnFirstEnumerable
.AsParallel()
.WithCancellation(cs.Token)
.ForAll((x) => { Debug.WriteLine(x.ToString()); });
}
catch (OperationCanceledException ex)
{
caughtException = ex;
}
Assert.NotNull(caughtException);
Assert.Equal(cs.Token, caughtException.CancellationToken);
}
[Fact]
public static void PreCanceledToken_SimpleEnumerator()
{
OperationCanceledException caughtException = null;
var cs = new CancellationTokenSource();
cs.Cancel();
IEnumerable<int> throwOnFirstEnumerable = Enumerables<int>.ThrowOnEnumeration();
try
{
var query = throwOnFirstEnumerable
.AsParallel()
.WithCancellation(cs.Token);
foreach (var item in query)
{
}
}
catch (OperationCanceledException ex)
{
caughtException = ex;
}
Assert.NotNull(caughtException);
Assert.Equal(cs.Token, caughtException.CancellationToken);
}
[Fact]
public static void MultiplesWithCancellationIsIllegal()
{
InvalidOperationException caughtException = null;
try
{
CancellationTokenSource cs = new CancellationTokenSource();
CancellationToken ct = cs.Token;
var query = Enumerable.Range(1, 10).AsParallel().WithDegreeOfParallelism(2).WithDegreeOfParallelism(2);
query.ToArray();
}
catch (InvalidOperationException ex)
{
caughtException = ex;
//Program.TestHarness.Log("IOE caught. message = " + ex.Message);
}
Assert.NotNull(caughtException);
}
[Fact]
public static void CTT_Sorting_ToArray()
{
int size = 10000;
CancellationTokenSource tokenSource = new CancellationTokenSource();
OperationCanceledException caughtException = null;
try
{
Enumerable.Range(1, size).AsParallel()
.WithCancellation(tokenSource.Token)
.Select(i =>
{
tokenSource.Cancel();
return i;
})
.ToArray();
}
catch (OperationCanceledException ex)
{
caughtException = ex;
}
Assert.NotNull(caughtException);
Assert.Equal(tokenSource.Token, caughtException.CancellationToken);
}
/// <summary>
///
/// [Regression Test]
/// This issue occurred because the QuerySettings structure was not being deep-cloned during
/// query-opening. As a result, the concurrent inner-enumerators (for the RHS operators)
/// that occur in SelectMany were sharing CancellationState that they should not have.
/// The result was that enumerators could falsely believe they had been canceled when
/// another inner-enumerator was disposed.
///
/// Note: the failure was intermittent. this test would fail about 1 in 2 times on mikelid1 (4-core).
/// </summary>
/// <returns></returns>
[Fact]
public static void CloningQuerySettingsForSelectMany()
{
var plinq_src = ParallelEnumerable.Range(0, 1999).AsParallel();
Exception caughtException = null;
try
{
var inner = ParallelEnumerable.Range(0, 20).AsParallel().Select(_item => _item);
var output = plinq_src
.SelectMany(
_x => inner,
(_x, _y) => _x
)
.ToArray();
}
catch (Exception ex)
{
caughtException = ex;
}
Assert.Null(caughtException);
}
// [Regression Test]
// Use of the async channel can block both the consumer and producer threads.. before the cancellation work
// these had no means of being awoken.
//
// However, only the producers need to wake up on cancellation as the consumer
// will wake up once all the producers have gone away (via AsynchronousOneToOneChannel.SetDone())
//
// To specifically verify this test, we want to know that the Async channels were blocked in TryEnqueChunk before Dispose() is called
// -> this was verified manually, but is not simple to automate
[Fact]
[OuterLoop] // explicit timeouts / delays
public static void ChannelCancellation_ProducerBlocked()
{
Debug.WriteLine("PlinqCancellationTests.ChannelCancellation_ProducerBlocked()");
Debug.WriteLine(" Query running (should be few seconds max)..");
var query1 = Enumerable.Range(0, 100000000) //provide 100million elements to ensure all the cores get >64K ints. Good up to 1600cores
.AsParallel()
.Select(x => x);
var enumerator1 = query1.GetEnumerator();
enumerator1.MoveNext();
Task.Delay(1000).Wait();
enumerator1.MoveNext();
enumerator1.Dispose(); //can potentially hang
Debug.WriteLine(" Done (success).");
}
/// <summary>
/// [Regression Test]
/// This issue occurred because aggregations like Sum or Average would incorrectly
/// wrap OperationCanceledException with AggregateException.
/// </summary>
[Fact]
public static void AggregatesShouldntWrapOCE()
{
var cs = new CancellationTokenSource();
cs.Cancel();
// Expect OperationCanceledException rather than AggregateException or something else
try
{
Enumerable.Range(0, 1000).AsParallel().WithCancellation(cs.Token).Sum(x => x);
}
catch (OperationCanceledException)
{
return;
}
catch (Exception e)
{
Assert.True(false, string.Format("PlinqCancellationTests.AggregatesShouldntWrapOCE: > Failed: got {0}, expected OperationCanceledException", e.GetType().ToString()));
}
Assert.True(false, string.Format("PlinqCancellationTests.AggregatesShouldntWrapOCE: > Failed: no exception occurred, expected OperationCanceledException"));
}
// Plinq suppresses OCE(externalCT) occurring in worker threads and then throws a single OCE(ct)
// if a manual OCE(ct) is thrown but ct is not canceled, Plinq should not suppress it, else things
// get confusing...
// ONLY an OCE(ct) for ct.IsCancellationRequested=true is co-operative cancellation
[Fact]
public static void OnlySuppressOCEifCTCanceled()
{
AggregateException caughtException = null;
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken externalToken = cts.Token;
try
{
Enumerable.Range(1, 10).AsParallel()
.WithCancellation(externalToken)
.Select(
x =>
{
if (x % 2 == 0) throw new OperationCanceledException(externalToken);
return x;
}
)
.ToArray();
}
catch (AggregateException ae)
{
caughtException = ae;
}
Assert.NotNull(caughtException);
}
// a specific repro where inner queries would see an ODE on the merged cancellation token source
// when the implementation involved disposing and recreating the token on each worker thread
[Fact]
public static void Cancellation_ODEIssue()
{
AggregateException caughtException = null;
try
{
Enumerable.Range(0, 1999).ToArray()
.AsParallel().AsUnordered()
.WithExecutionMode(ParallelExecutionMode.ForceParallelism)
.Zip<int, int, int>(
Enumerable.Range(1000, 20).Select<int, int>(_item => (int)_item).AsParallel().AsUnordered(),
(first, second) => { throw new OperationCanceledException(); })
.ForAll(x => { });
}
catch (AggregateException ae)
{
caughtException = ae;
}
//the failure was an ODE coming out due to an ephemeral disposed merged cancellation token source.
Assert.True(caughtException != null,
"Cancellation_ODEIssue: We expect an aggregate exception with OCEs in it.");
}
[Fact]
[OuterLoop] // explicit timeouts / delays
public static void CancellationSequentialWhere()
{
IEnumerable<int> src = Enumerable.Repeat(0, int.MaxValue);
CancellationTokenSource tokenSrc = new CancellationTokenSource();
var q = src.AsParallel().WithCancellation(tokenSrc.Token).Where(x => false).TakeWhile(x => true);
Task task = Task.Run(
() =>
{
try
{
foreach (var x in q) { }
Assert.True(false, string.Format("PlinqCancellationTests.CancellationSequentialWhere: > Failed: OperationCanceledException was not caught."));
}
catch (OperationCanceledException oce)
{
if (oce.CancellationToken != tokenSrc.Token)
{
Assert.True(false, string.Format("PlinqCancellationTests.CancellationSequentialWhere: > Failed: Wrong cancellation token."));
}
}
}
);
// We wait for 100 ms. If we canceled the token source immediately, the cancellation
// would occur at the query opening time. The goal of this test is to test cancellation
// at query execution time.
Task.Delay(100).Wait();
//Thread.Sleep(100);
tokenSrc.Cancel();
task.Wait();
}
[Fact]
[OuterLoop] // explicit timeouts / delays
public static void CancellationSequentialElementAt()
{
IEnumerable<int> src = Enumerable.Repeat(0, int.MaxValue);
CancellationTokenSource tokenSrc = new CancellationTokenSource();
Task task = Task.Run(
() =>
{
try
{
int res = src.AsParallel()
.WithCancellation(tokenSrc.Token)
.Where(x => true)
.TakeWhile(x => true)
.ElementAt(int.MaxValue - 1);
Assert.True(false, string.Format("PlinqCancellationTests.CancellationSequentialElementAt: > Failed: OperationCanceledException was not caught."));
}
catch (OperationCanceledException oce)
{
Assert.Equal(oce.CancellationToken, tokenSrc.Token);
}
}
);
// We wait for 100 ms. If we canceled the token source immediately, the cancellation
// would occur at the query opening time. The goal of this test is to test cancellation
// at query execution time.
Task.Delay(100).Wait();
tokenSrc.Cancel();
task.Wait();
}
[Fact]
[OuterLoop] // explicit timeouts / delays
public static void CancellationSequentialDistinct()
{
IEnumerable<int> src = Enumerable.Repeat(0, int.MaxValue);
CancellationTokenSource tokenSrc = new CancellationTokenSource();
Task task = Task.Run(
() =>
{
try
{
var q = src.AsParallel()
.WithCancellation(tokenSrc.Token)
.Distinct()
.TakeWhile(x => true);
foreach (var x in q) { }
Assert.True(false, string.Format("PlinqCancellationTests.CancellationSequentialDistinct: > Failed: OperationCanceledException was not caught."));
}
catch (OperationCanceledException oce)
{
Assert.Equal(oce.CancellationToken, tokenSrc.Token);
}
}
);
// We wait for 100 ms. If we canceled the token source immediately, the cancellation
// would occur at the query opening time. The goal of this test is to test cancellation
// at query execution time.
Task.Delay(100).Wait();
tokenSrc.Cancel();
task.Wait();
}
// Regression test for an issue causing ODE if a queryEnumerator is disposed before moveNext is called.
[Fact]
public static void ImmediateDispose()
{
var queryEnumerator = Enumerable.Range(1, 10).AsParallel().Select(x => x).GetEnumerator();
queryEnumerator.Dispose();
}
// REPRO 1 -- cancellation
[Fact]
public static void SetOperationsThrowAggregateOnCancelOrDispose_1()
{
CancellationTokenSource cs = new CancellationTokenSource();
var plinq_src =
Enumerable.Range(0, 5000000).Select(x =>
{
cs.Cancel();
return x;
});
try
{
var plinq = plinq_src
.AsParallel().WithCancellation(cs.Token)
.WithDegreeOfParallelism(1)
.Union(Enumerable.Range(0, 10).AsParallel());
var walker = plinq.GetEnumerator();
while (walker.MoveNext())
{
var item = walker.Current;
}
Assert.True(false, string.Format("PlinqCancellationTests.SetOperationsThrowAggregateOnCancelOrDispose_1: OperationCanceledException was expected, but no exception occurred."));
}
catch (OperationCanceledException)
{
//This is expected.
}
catch (Exception e)
{
Assert.True(false, string.Format("PlinqCancellationTests.SetOperationsThrowAggregateOnCancelOrDispose_1: OperationCanceledException was expected, but a different exception occurred. " + e.ToString()));
}
}
// throwing a fake OCE(ct) when the ct isn't canceled should produce an AggregateException.
[Fact]
public static void SetOperationsThrowAggregateOnCancelOrDispose_2()
{
try
{
CancellationTokenSource cs = new CancellationTokenSource();
var plinq = Enumerable.Range(0, 50)
.AsParallel().WithCancellation(cs.Token)
.WithDegreeOfParallelism(1)
.Union(Enumerable.Range(0, 10).AsParallel().Select<int, int>(x => { throw new OperationCanceledException(cs.Token); }));
var walker = plinq.GetEnumerator();
while (walker.MoveNext())
{
}
Assert.True(false, string.Format("PlinqCancellationTests.SetOperationsThrowAggregateOnCancelOrDispose_2: failed. AggregateException was expected, but no exception occurred."));
}
catch (AggregateException)
{
// expected
}
catch (Exception e)
{
Assert.True(false, string.Format("PlinqCancellationTests.SetOperationsThrowAggregateOnCancelOrDispose_2. failed. AggregateException was expected, but some other exception occurred." + e.ToString()));
}
}
// Changes made to hash-partitioning (April'09) lost the cancellation checks during the
// main repartitioning loop (matrix building).
[Fact]
public static void HashPartitioningCancellation()
{
OperationCanceledException caughtException = null;
CancellationTokenSource cs = new CancellationTokenSource();
//Without ordering
var queryUnordered = Enumerable.Range(0, int.MaxValue)
.Select(x => { if (x == 0) cs.Cancel(); return x; })
.AsParallel()
.WithCancellation(cs.Token)
.Intersect(Enumerable.Range(0, 1000000).AsParallel());
try
{
foreach (var item in queryUnordered)
{
}
}
catch (OperationCanceledException oce)
{
caughtException = oce;
}
Assert.NotNull(caughtException);
caughtException = null;
//With ordering
var queryOrdered = Enumerable.Range(0, int.MaxValue)
.Select(x => { if (x == 0) cs.Cancel(); return x; })
.AsParallel().AsOrdered()
.WithCancellation(cs.Token)
.Intersect(Enumerable.Range(0, 1000000).AsParallel());
try
{
foreach (var item in queryOrdered)
{
}
}
catch (OperationCanceledException oce)
{
caughtException = oce;
}
Assert.NotNull(caughtException);
}
// If a query is cancelled and immediately disposed, the dispose should not throw an OCE.
[Fact]
public static void CancelThenDispose()
{
try
{
CancellationTokenSource cancel = new CancellationTokenSource();
var q = ParallelEnumerable.Range(0, 1000).WithCancellation(cancel.Token).Select(x => x);
IEnumerator<int> e = q.GetEnumerator();
e.MoveNext();
cancel.Cancel();
e.Dispose();
}
catch (Exception e)
{
Assert.True(false, string.Format("PlinqCancellationTests.CancelThenDispose: > Failed. Expected no exception, got " + e.GetType()));
}
}
[Fact]
public static void DontDoWorkIfTokenAlreadyCanceled()
{
OperationCanceledException oce = null;
CancellationTokenSource cs = new CancellationTokenSource();
var query = Enumerable.Range(0, 100000000)
.Select(x =>
{
if (x > 0) // to avoid the "Error:unreachable code detected"
throw new ArgumentException("User-delegate exception.");
return x;
})
.AsParallel()
.WithCancellation(cs.Token)
.Select(x => x);
cs.Cancel();
try
{
foreach (var item in query) //We expect an OperationCancelledException during the MoveNext
{
}
}
catch (OperationCanceledException ex)
{
oce = ex;
}
Assert.NotNull(oce);
}
}
}
| |
using nHydrate.Generator.Common.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
namespace nHydrate.Generator.Common.Models
{
public class Database : BaseModelObject
{
#region Member Variables
protected const string _def_createdByColumnName = "CreatedBy";
protected const string _def_createdDateColumnName = "CreatedDate";
protected const string _def_modifiedByColumnName = "ModifiedBy";
protected const string _def_modifiedDateColumnName = "ModifiedDate";
protected const string _def_timestampColumnName = "__concurrency";
protected const string _def_fullIndexSearchColumnName = "full_index_text";
#endregion
#region Constructor
public Database(INHydrateModelObject root)
: base(root)
{
this.Tables = new TableCollection(root);
this.Tables.ResetKey(Guid.Empty.ToString());
this.Columns = new ColumnCollection(root);
this.Columns.ResetKey(Guid.Empty.ToString());
this.Relations = new RelationCollection(root);
this.Relations.ResetKey(Guid.Empty.ToString());
this.CustomViews = new CustomViewCollection(root);
this.CustomViews.ResetKey(Guid.Empty.ToString());
this.CustomViewColumns = new CustomViewColumnCollection(root);
this.CustomViewColumns.ResetKey(Guid.Empty.ToString());
}
#endregion
#region Property Implementations
public ColumnCollection Columns { get; }
public RelationCollection Relations { get; }
public string DatabaseName { get; set; } = string.Empty;
public string CreatedByColumnName { get; set; } = _def_createdByColumnName;
public string CreatedDateColumnName { get; set; } = _def_createdDateColumnName;
public virtual string CreatedDatePascalName => this.CreatedDateColumnName;
public virtual string CreatedByPascalName => this.CreatedByColumnName;
public virtual string ModifiedDatePascalName => this.ModifiedDateColumnName;
public virtual string ModifiedByPascalName => this.ModifiedByColumnName;
public virtual string ConcurrencyCheckPascalName => this.ConcurrencyCheckColumnName;
public virtual string CreatedDateDatabaseName => this.CreatedDateColumnName;
public virtual string CreatedByDatabaseName => this.CreatedByColumnName;
public virtual string ModifiedDateDatabaseName => this.ModifiedDateColumnName;
public virtual string ModifiedByDatabaseName => this.ModifiedByColumnName;
public virtual string ConcurrencyCheckDatabaseName => this.ConcurrencyCheckColumnName;
public string ModifiedByColumnName { get; set; } = _def_modifiedByColumnName;
public string ModifiedDateColumnName { get; set; } = _def_modifiedDateColumnName;
public string FullIndexSearchColumnName { get; set; } = _def_fullIndexSearchColumnName;
public string ConcurrencyCheckColumnName { get; set; } = _def_timestampColumnName;
public TableCollection Tables { get; }
public CustomViewCollection CustomViews { get; }
public CustomViewColumnCollection CustomViewColumns { get; }
public string GrantExecUser { get; set; } = string.Empty;
#endregion
#region Methods
public IEnumerable<Relation> GetRelationsWhereChild(Table table, bool fullHierarchy)
{
var retval = new List<Relation>();
foreach (var relation in this.Relations)
{
var childTable = relation.ChildTable;
if (childTable == table)
retval.Add(relation);
else if (fullHierarchy && table.IsInheritedFrom(childTable))
retval.Add(relation);
}
return retval;
}
#endregion
#region IXMLable Members
public override XmlNode XmlAppend(XmlNode node)
{
//node.AddAttribute("key", this.Key);
node.AddAttribute("createdByColumnName", CreatedByColumnName);
node.AddAttribute("createdDateColumnName", CreatedDateColumnName);
node.AddAttribute("modifiedByColumnName", ModifiedByColumnName);
node.AddAttribute("modifiedDateColumnName", ModifiedDateColumnName);
node.AddAttribute("timestampColumnName", ConcurrencyCheckColumnName);
node.AddAttribute("fullIndexSearchColumnName", FullIndexSearchColumnName);
node.AddAttribute("grantExecUser", GrantExecUser);
node.AddAttribute("databaseName", this.DatabaseName);
node.AppendChild(this.Columns.XmlAppend(node.CreateElement("columns")));
node.AppendChild(this.CustomViewColumns.XmlAppend(node.CreateElement("customviewcolumns")));
node.AppendChild(this.Relations.XmlAppend(node.CreateElement("relations")));
node.AppendChild(this.Tables.XmlAppend(node.CreateElement("tables")));
node.AppendChild(this.CustomViews.XmlAppend(node.CreateElement("customviews")));
return node;
}
public override string Key { get => System.Guid.Empty.ToString(); }
public override XmlNode XmlLoad(XmlNode node)
{
//this.Key = node.GetAttributeValue("key", string.Empty);
CreatedByColumnName = node.GetAttributeValue("createdByColumnName", CreatedByColumnName);
CreatedDateColumnName = node.GetAttributeValue("createdDateColumName", CreatedDateColumnName);
ModifiedByColumnName = node.GetAttributeValue("modifiedByColumnName", ModifiedByColumnName);
ModifiedDateColumnName = node.GetAttributeValue("modifiedDateColumnName", ModifiedDateColumnName);
ConcurrencyCheckColumnName = node.GetAttributeValue("timestampColumnName", ConcurrencyCheckColumnName);
FullIndexSearchColumnName = node.GetAttributeValue("fullIndexSearchColumnName", FullIndexSearchColumnName);
GrantExecUser = node.GetAttributeValue("grantExecUser", GrantExecUser);
this.Relations?.XmlLoad(node.SelectSingleNode("relations"));
this.Tables?.XmlLoad(node.SelectSingleNode("tables"));
this.CustomViews?.XmlLoad(node.SelectSingleNode("customviews"));
this.Columns?.XmlLoad(node.SelectSingleNode("columns"));
this.CustomViewColumns?.XmlLoad(node.SelectSingleNode("customviewcolumns"));
//Clean all tables that are dead
foreach (var t in this.Tables)
{
foreach (var c in t.Columns.Where(x => x.Object == null).ToList())
t.Columns.Remove(c);
}
this.DatabaseName = node.GetAttributeValue("databaseName", string.Empty);
this.CreatedByColumnName = node.GetAttributeValue("createdByColumnName", _def_createdByColumnName);
this.CreatedDateColumnName = node.GetAttributeValue("createdDateColumnName", _def_createdDateColumnName);
this.ModifiedByColumnName = node.GetAttributeValue("modifiedByColumnName", _def_modifiedByColumnName);
this.ModifiedDateColumnName = node.GetAttributeValue("modifiedDateColumnName", _def_modifiedDateColumnName);
this.ConcurrencyCheckColumnName = node.GetAttributeValue("timestampColumnName", _def_timestampColumnName);
this.FullIndexSearchColumnName = node.GetAttributeValue("fullIndexSearchColumnName", _def_fullIndexSearchColumnName);
this.GrantExecUser = node.GetAttributeValue("grantExecUser", string.Empty);
#region Are any of these columns orphans
var allColumns = this.Tables.GetAllColumns();
this.Columns
.Where(x => !allColumns.Contains(x))
.ToList()
.ForEach(x => this.Columns.Remove(x));
#endregion
#region Error Check for columns with duplicate Keys (if someone manually edits XML file)
var usedList = new List<string>();
foreach (var column in this.Columns)
{
if (usedList.Contains(column.Key.ToString()))
column.ResetKey(Guid.NewGuid().ToString());
usedList.Add(column.Key.ToString());
}
#endregion
#region Clean relations in case there are dead ones
var deleteRelationList = new List<Relation>();
foreach (var relation in this.Relations.AsEnumerable())
{
if ((relation.ParentTableRef == null) || (relation.ChildTableRef == null))
{
if (!deleteRelationList.Contains(relation)) deleteRelationList.Add(relation);
}
else
{
var t = relation.ParentTable;
if (t != null)
{
if (!t.Relationships.Contains(relation.Id))
{
if (!deleteRelationList.Contains(relation)) deleteRelationList.Add(relation);
}
}
}
}
//Now do the actual deletes
deleteRelationList.ForEach(x => this.Relations.Remove(x));
#endregion
foreach (var table in this.Tables)
{
foreach (var column in table.GetColumns().Where(x => x.ParentTable != table))
column.ParentTableRef = table.CreateRef();
}
return node;
}
#endregion
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Description: BamlTreeNode structures
//
// History:
// 3/30/2005 garyyang - created it
//
//---------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using System.Windows.Markup;
namespace MS.Internal.Globalization
{
#region BamlTree
/// <summary>
/// This reprenents a BamlTree.
/// It contains two views of the tree.
/// 1) the tree itself through BamlTreeNode. It maintains the Baml
/// file structure for serialization
/// 2) flat baml through in depth first order
/// it will be used when creating flat baml resources
/// </summary>
internal sealed class BamlTree
{
//----------------------------------
// Constructor
//----------------------------------
/// <summary>
/// create an emtpy baml tree
/// </summary>
internal BamlTree(){}
/// <summary>
/// Create a baml tree on a root node.
/// </summary>
internal BamlTree(BamlTreeNode root, int size)
{
Debug.Assert(root != null, "Baml tree root is null!");
Debug.Assert(size > 0, "Baml tree size is less than 1");
_root = root;
_nodeList = new List<BamlTreeNode>(size);
CreateInternalIndex(ref _root, ref _nodeList, false);
}
internal BamlTreeNode Root
{
get { return _root;}
}
internal int Size
{
get { return _nodeList.Count;}
}
// index into the flattened baml tree
internal BamlTreeNode this[int i]
{
get{
return _nodeList[i];
}
}
// create a deep copy of the tree
internal BamlTree Copy()
{
// create new root and new list
BamlTreeNode newTreeRoot = _root;
List<BamlTreeNode> newNodeList = new List<BamlTreeNode>(Size);
// create a new copy of the tree.
CreateInternalIndex(ref newTreeRoot, ref newNodeList, true);
BamlTree newTree = new BamlTree();
newTree._root = newTreeRoot;
newTree._nodeList = newNodeList;
return newTree;
}
// adds a node into the flattened tree node list.
internal void AddTreeNode(BamlTreeNode node)
{
_nodeList.Add(node);
}
// travese the tree and store the node in the arraylist in the same order as travesals.
// it can also create a a new tree by give true to "toCopy"
private void CreateInternalIndex(ref BamlTreeNode parent, ref List<BamlTreeNode> nodeList, bool toCopy)
{
// gets the old children
List<BamlTreeNode> children = parent.Children;
if (toCopy)
{
// creates a copy of the current node
parent = parent.Copy();
if (children != null)
{
// create an new list if there are children.
parent.Children = new List<BamlTreeNode>(children.Count);
}
}
// add the node to the flattened list
nodeList.Add(parent);
// return if this is the leaf
if (children == null)
return;
// for each child
for (int i = 0; i < children.Count; i++)
{
// get to the child
BamlTreeNode child = children[i];
// recursively create index
CreateInternalIndex(ref child, ref nodeList, toCopy);
if (toCopy)
{
// if toCopy, we link the new child and new parent.
child.Parent = parent;
parent.Children.Add(child);
}
}
}
private BamlTreeNode _root; // the root of the tree
private List<BamlTreeNode> _nodeList; // stores flattened baml tree in depth first order
}
#endregion
#region ILocalizabilityInheritable inteface
/// <summary>
/// Nodes in the Baml tree can inherit localizability from parent nodes. Nodes that
/// implements this interface will be part of the localizabilty inheritance tree.
/// </summary>
internal interface ILocalizabilityInheritable
{
/// <summary>
/// The ancestor node to inherit localizability from
/// </summary>
ILocalizabilityInheritable LocalizabilityAncestor {get;}
/// <summary>
/// The inheritable attributs to child nodes.
/// </summary>
LocalizabilityAttribute InheritableAttribute
{
get; set;
}
bool IsIgnored
{
get; set;
}
}
#endregion
#region BamlTreeNode and sub-classes
/// <summary>
/// The node for the internal baml tree
/// </summary>
internal abstract class BamlTreeNode
{
//---------------------------
// Constructor
//---------------------------
internal BamlTreeNode(BamlNodeType type)
{
NodeType = type;
}
//----------------------------
// internal methods
//----------------------------
/// <summary>
/// Add a child to this node.
/// </summary>
/// <param name="child">child node to add</param>
internal void AddChild(BamlTreeNode child)
{
if (_children == null)
{
_children = new List<BamlTreeNode>();
}
_children.Add(child); // Add the children
child.Parent = this; // Link to its parent
}
/// <summary>
/// Create a copy of the BamlTreeNode
/// </summary>
internal abstract BamlTreeNode Copy();
/// <summary>
/// Serialize the node through BamlWriter
/// </summary>
internal abstract void Serialize(BamlWriter writer);
//----------------------------
// internal properties.
//----------------------------
/// <summary>
/// NodeType
/// </summary>
/// <value>BamlNodeType</value>
internal BamlNodeType NodeType
{
get
{
return _nodeType;
}
set
{
_nodeType = value;
}
}
/// <summary>
/// List of children nodes.
/// </summary>
internal List<BamlTreeNode> Children
{
get
{
return _children;
}
set
{
_children = value;
}
}
/// <summary>
/// Parent node.
/// </summary>
/// <value>BamlTreeNode</value>
internal BamlTreeNode Parent
{
get
{
return _parent;
}
set
{
_parent = value;
}
}
/// <summary>
/// Whether the content of this node has been formatted to be part of
/// parent node's content.
/// </summary>
internal bool Formatted
{
get
{
return (_state & BamlTreeNodeState.ContentFormatted) != 0;
}
set
{
if (value)
{
_state |= BamlTreeNodeState.ContentFormatted;
}
else
{
_state &= (~BamlTreeNodeState.ContentFormatted);
}
}
}
/// <summary>
/// Whether the node has been visited. Used to detect loop in the tree.
/// </summary>
internal bool Visited
{
get
{
return (_state & BamlTreeNodeState.NodeVisited) != 0;
}
set
{
if (value)
{
_state |= BamlTreeNodeState.NodeVisited;
}
else
{
_state &= (~BamlTreeNodeState.NodeVisited);
}
}
}
/// <summary>
/// Indicate if the node is not uniquely identifiable in the tree. Its value
/// is true when the node or its parent doesn't have unique Uid.
/// </summary>
internal bool Unidentifiable
{
get
{
return (_state & BamlTreeNodeState.Unidentifiable) != 0;
}
set
{
if (value)
{
_state |= BamlTreeNodeState.Unidentifiable;
}
else
{
_state &= (~BamlTreeNodeState.Unidentifiable);
}
}
}
//----------------------------
// protected members
//----------------------------
protected BamlNodeType _nodeType; // node type
protected List<BamlTreeNode> _children; // the children list.
protected BamlTreeNode _parent ; // the tree parent of this node
private BamlTreeNodeState _state; // the state of this tree node
[Flags]
private enum BamlTreeNodeState : byte
{
/// <summary>
/// Default state
/// </summary>
None = 0,
/// <summary>
/// Indicate that the content of this node has been formatted inline. We don't need to
/// produce an individual localizable resource for it.
/// </summary>
ContentFormatted = 1,
/// <summary>
/// Indicate that this node has already been visited once in the tree traversal (such as serialization).
/// It is used to prevent the Baml tree contains multiple references to one node.
/// </summary>
NodeVisited = 2,
/// <summary>
/// Indicate that this node cannot be uniquely identify in the Baml tree. It happens when
/// it or its parent element has a duplicate Uid.
/// </summary>
Unidentifiable = 4,
}
}
/// <summary>
/// Baml StartDocument node
/// </summary>
internal sealed class BamlStartDocumentNode : BamlTreeNode, ILocalizabilityInheritable
{
internal BamlStartDocumentNode() : base(BamlNodeType.StartDocument){}
internal override void Serialize(BamlWriter writer)
{
writer.WriteStartDocument();
}
internal override BamlTreeNode Copy()
{
return new BamlStartDocumentNode();
}
public ILocalizabilityInheritable LocalizabilityAncestor
{
// return null as StartDocument is the root of the inheritance tree
get { return null; }
}
public LocalizabilityAttribute InheritableAttribute
{
get
{
// return the default attribute as it is at the root of the inheritance
LocalizabilityAttribute defaultAttribute = new LocalizabilityAttribute(LocalizationCategory.None);
defaultAttribute.Readability = Readability.Readable;
defaultAttribute.Modifiability = Modifiability.Modifiable;
return defaultAttribute;
}
set {}
}
public bool IsIgnored
{
get { return false; }
set {}
}
}
/// <summary>
/// Baml EndDocument node
/// </summary>
internal sealed class BamlEndDocumentNode : BamlTreeNode
{
internal BamlEndDocumentNode() : base(BamlNodeType.EndDocument) {}
internal override void Serialize(BamlWriter writer)
{
writer.WriteEndDocument();
}
internal override BamlTreeNode Copy()
{
return new BamlEndDocumentNode();
}
}
/// <summary>
/// Baml ConnectionId node
/// </summary>
internal sealed class BamlConnectionIdNode : BamlTreeNode
{
internal BamlConnectionIdNode(Int32 connectionId) : base(BamlNodeType.ConnectionId)
{
_connectionId = connectionId;
}
internal override void Serialize(BamlWriter writer)
{
writer.WriteConnectionId(_connectionId);
}
internal override BamlTreeNode Copy()
{
return new BamlConnectionIdNode(_connectionId);
}
private Int32 _connectionId;
}
/// <summary>
/// Baml StartElement node, it can also inherit localizability attributes from parent nodes.
/// </summary>
internal sealed class BamlStartElementNode : BamlTreeNode, ILocalizabilityInheritable
{
internal BamlStartElementNode(
string assemblyName,
string typeFullName,
bool isInjected,
bool useTypeConverter
): base (BamlNodeType.StartElement)
{
_assemblyName = assemblyName;
_typeFullName = typeFullName;
_isInjected = isInjected;
_useTypeConverter = useTypeConverter;
}
internal override void Serialize(BamlWriter writer)
{
writer.WriteStartElement(_assemblyName, _typeFullName, _isInjected, _useTypeConverter);
}
internal override BamlTreeNode Copy()
{
BamlStartElementNode node = new BamlStartElementNode(_assemblyName, _typeFullName, _isInjected, _useTypeConverter);
node._content = _content;
node._uid = _uid;
node._inheritableAttribute = _inheritableAttribute;
return node;
}
/// <summary>
/// insert property node
/// </summary>
/// <remarks>
/// Property node needs to be group in front of
/// child elements. This method is called when creating a
/// new property node.
/// </remarks>
internal void InsertProperty(BamlTreeNode child)
{
if (_children == null)
{
AddChild(child);
}
else
{
int lastProperty = 0;
for (int i = 0; i < _children.Count; i++)
{
if (_children[i].NodeType == BamlNodeType.Property)
{
lastProperty = i;
}
}
_children.Insert(lastProperty, child);
child.Parent = this;
}
}
//-------------------------------
// Internal properties
//-------------------------------
internal string AssemblyName
{
get { return _assemblyName; }
}
internal string TypeFullName
{
get { return _typeFullName; }
}
internal string Content
{
get { return _content; }
set { _content = value; }
}
internal string Uid
{
get { return _uid; }
set { _uid = value;}
}
public ILocalizabilityInheritable LocalizabilityAncestor
{
// Baml element node inherit from parent element
get
{
if (_localizabilityAncestor == null)
{
// walk up the tree to find a parent node that is ILocalizabilityInheritable
for (BamlTreeNode parentNode = Parent;
_localizabilityAncestor == null && parentNode != null;
parentNode = parentNode.Parent)
{
_localizabilityAncestor = (parentNode as ILocalizabilityInheritable);
}
}
return _localizabilityAncestor;
}
}
public LocalizabilityAttribute InheritableAttribute
{
get { return _inheritableAttribute; }
set
{
Debug.Assert(value.Category != LocalizationCategory.Ignore && value.Category != LocalizationCategory.Inherit);
_inheritableAttribute = value;
}
}
public bool IsIgnored
{
get { return _isIgnored; }
set { _isIgnored = value; }
}
//----------------------
// Private members
//----------------------
private string _assemblyName;
private string _typeFullName;
private string _content;
private string _uid;
private LocalizabilityAttribute _inheritableAttribute;
private ILocalizabilityInheritable _localizabilityAncestor;
private bool _isIgnored;
private bool _isInjected;
private bool _useTypeConverter;
}
/// <summary>
/// Baml EndElement node
/// </summary>
internal sealed class BamlEndElementNode : BamlTreeNode
{
internal BamlEndElementNode() : base(BamlNodeType.EndElement)
{
}
internal override void Serialize(BamlWriter writer)
{
writer.WriteEndElement();
}
internal override BamlTreeNode Copy()
{
return new BamlEndElementNode();
}
}
/// <summary>
/// Baml XmlnsProperty node
/// </summary>
internal sealed class BamlXmlnsPropertyNode : BamlTreeNode
{
internal BamlXmlnsPropertyNode(
string prefix,
string xmlns
): base(BamlNodeType.XmlnsProperty)
{
_prefix = prefix;
_xmlns = xmlns;
}
internal override void Serialize(BamlWriter writer)
{
writer.WriteXmlnsProperty(_prefix, _xmlns);
}
internal override BamlTreeNode Copy()
{
return new BamlXmlnsPropertyNode(_prefix, _xmlns);
}
private string _prefix;
private string _xmlns;
}
/// <summary>
/// StartComplexProperty node
/// </summary>
internal class BamlStartComplexPropertyNode : BamlTreeNode, ILocalizabilityInheritable
{
internal BamlStartComplexPropertyNode(
string assemblyName,
string ownerTypeFullName,
string propertyName
) : base(BamlNodeType.StartComplexProperty)
{
_assemblyName = assemblyName;
_ownerTypeFullName = ownerTypeFullName;
_propertyName = propertyName;
}
internal override void Serialize(BamlWriter writer)
{
writer.WriteStartComplexProperty(
_assemblyName,
_ownerTypeFullName,
_propertyName
);
}
internal override BamlTreeNode Copy()
{
return new BamlStartComplexPropertyNode(
_assemblyName,
_ownerTypeFullName,
_propertyName
);
}
internal string AssemblyName
{
get { return _assemblyName; }
}
internal string PropertyName
{
get { return _propertyName; }
}
internal string OwnerTypeFullName
{
get { return _ownerTypeFullName; }
}
public ILocalizabilityInheritable LocalizabilityAncestor
{
get { return _localizabilityAncestor; }
set { _localizabilityAncestor = value; }
}
public LocalizabilityAttribute InheritableAttribute
{
get { return _inheritableAttribute; }
set
{
Debug.Assert(value.Category != LocalizationCategory.Ignore && value.Category != LocalizationCategory.Inherit);
_inheritableAttribute = value;
}
}
public bool IsIgnored
{
get { return _isIgnored; }
set { _isIgnored = value; }
}
protected string _assemblyName;
protected string _ownerTypeFullName;
protected string _propertyName;
private ILocalizabilityInheritable _localizabilityAncestor;
private LocalizabilityAttribute _inheritableAttribute;
private bool _isIgnored;
}
/// <summary>
/// EndComplexProperty node
/// </summary>
internal sealed class BamlEndComplexPropertyNode : BamlTreeNode
{
internal BamlEndComplexPropertyNode() : base(BamlNodeType.EndComplexProperty)
{
}
internal override void Serialize(BamlWriter writer)
{
writer.WriteEndComplexProperty();
}
internal override BamlTreeNode Copy()
{
return new BamlEndComplexPropertyNode();
}
}
/// <summary>
/// Baml Property node, it can inherit localizable attributes from parent nodes.
/// </summary>
internal sealed class BamlPropertyNode : BamlStartComplexPropertyNode
{
internal BamlPropertyNode(
string assemblyName,
string ownerTypeFullName,
string propertyName,
string value,
BamlAttributeUsage usage
): base(assemblyName, ownerTypeFullName, propertyName)
{
_value = value;
_attributeUsage = usage;
_nodeType = BamlNodeType.Property;
}
internal override void Serialize(BamlWriter writer)
{
// skip seralizing Localization.Comments and Localization.Attributes properties
if (!LocComments.IsLocCommentsProperty(_ownerTypeFullName, _propertyName)
&& !LocComments.IsLocLocalizabilityProperty(_ownerTypeFullName, _propertyName))
{
writer.WriteProperty(
_assemblyName,
_ownerTypeFullName,
_propertyName,
_value,
_attributeUsage
);
}
}
internal override BamlTreeNode Copy()
{
return new BamlPropertyNode(
_assemblyName,
_ownerTypeFullName,
_propertyName,
_value,
_attributeUsage
);
}
internal string Value
{
get { return _value; }
set { _value = value; }
}
internal int Index
{
get { return _index; }
set { _index = value; }
}
private string _value;
private BamlAttributeUsage _attributeUsage;
private int _index = 0; // used for auto-numbering repeated properties within an element
}
/// <summary>
/// LiteralContent node
/// </summary>
internal sealed class BamlLiteralContentNode : BamlTreeNode
{
internal BamlLiteralContentNode(string literalContent) : base(BamlNodeType.LiteralContent)
{
_literalContent = literalContent;
}
internal override void Serialize(BamlWriter writer)
{
writer.WriteLiteralContent(_literalContent);
}
internal override BamlTreeNode Copy()
{
return new BamlLiteralContentNode(_literalContent);
}
internal string Content
{
get { return _literalContent; }
set { _literalContent = value; }
}
private string _literalContent;
}
/// <summary>
/// Text node
/// </summary>
internal sealed class BamlTextNode : BamlTreeNode
{
internal BamlTextNode(string text) : this (text, null, null)
{
}
internal BamlTextNode(
string text,
string typeConverterAssemblyName,
string typeConverterName
) : base(BamlNodeType.Text)
{
_content = text;
_typeConverterAssemblyName = typeConverterAssemblyName;
_typeConverterName = typeConverterName;
}
internal override void Serialize(BamlWriter writer)
{
writer.WriteText(_content, _typeConverterAssemblyName, _typeConverterName);
}
internal override BamlTreeNode Copy()
{
return new BamlTextNode(_content, _typeConverterAssemblyName, _typeConverterName);
}
internal string Content
{
get { return _content; }
}
private string _content;
private string _typeConverterAssemblyName;
private string _typeConverterName;
}
/// <summary>
/// Routed event node
/// </summary>
internal sealed class BamlRoutedEventNode : BamlTreeNode
{
internal BamlRoutedEventNode(
string assemblyName,
string ownerTypeFullName,
string eventIdName,
string handlerName
) : base(BamlNodeType.RoutedEvent)
{
_assemblyName = assemblyName;
_ownerTypeFullName = ownerTypeFullName;
_eventIdName = eventIdName;
_handlerName = handlerName;
}
internal override void Serialize(BamlWriter writer)
{
writer.WriteRoutedEvent(
_assemblyName,
_ownerTypeFullName,
_eventIdName,
_handlerName
);
}
internal override BamlTreeNode Copy()
{
return new BamlRoutedEventNode(
_assemblyName,
_ownerTypeFullName,
_eventIdName,
_handlerName
);
}
private string _assemblyName;
private string _ownerTypeFullName;
private string _eventIdName;
private string _handlerName;
}
/// <summary>
/// event node
/// </summary>
internal sealed class BamlEventNode : BamlTreeNode
{
internal BamlEventNode(
string eventName,
string handlerName
) : base(BamlNodeType.Event)
{
_eventName = eventName;
_handlerName = handlerName;
}
internal override void Serialize(BamlWriter writer)
{
writer.WriteEvent(
_eventName,
_handlerName
);
}
internal override BamlTreeNode Copy()
{
return new BamlEventNode(_eventName, _handlerName);
}
private string _eventName;
private string _handlerName;
}
/// <summary>
/// DefAttribute node
/// </summary>
internal sealed class BamlDefAttributeNode : BamlTreeNode
{
internal BamlDefAttributeNode(string name, string value) : base(BamlNodeType.DefAttribute)
{
_name = name;
_value = value;
}
internal override void Serialize(BamlWriter writer)
{
writer.WriteDefAttribute(_name, _value);
}
internal override BamlTreeNode Copy()
{
return new BamlDefAttributeNode(_name, _value);
}
private string _name;
private string _value;
}
/// <summary>
/// PIMapping node
/// </summary>
internal sealed class BamlPIMappingNode : BamlTreeNode
{
internal BamlPIMappingNode(
string xmlNamespace,
string clrNamespace,
string assemblyName
) : base(BamlNodeType.PIMapping)
{
_xmlNamespace = xmlNamespace;
_clrNamespace = clrNamespace;
_assemblyName = assemblyName;
}
internal override void Serialize(BamlWriter writer)
{
writer.WritePIMapping(
_xmlNamespace,
_clrNamespace,
_assemblyName
);
}
internal override BamlTreeNode Copy()
{
return new BamlPIMappingNode(
_xmlNamespace,
_clrNamespace,
_assemblyName
);
}
private string _xmlNamespace;
private string _clrNamespace;
private string _assemblyName;
}
/// <summary>
/// StartConstructor node
/// </summary>
internal sealed class BamlStartConstructorNode : BamlTreeNode
{
internal BamlStartConstructorNode(): base(BamlNodeType.StartConstructor)
{
}
internal override void Serialize(BamlWriter writer)
{
writer.WriteStartConstructor();
}
internal override BamlTreeNode Copy()
{
return new BamlStartConstructorNode();
}
}
/// <summary>
/// EndConstructor node
/// </summary>
internal sealed class BamlEndConstructorNode : BamlTreeNode
{
internal BamlEndConstructorNode(): base(BamlNodeType.EndConstructor)
{
}
internal override void Serialize(BamlWriter writer)
{
writer.WriteEndConstructor();
}
internal override BamlTreeNode Copy()
{
return new BamlEndConstructorNode();
}
}
///// <summary>
///// ContentProperty node
///// </summary>
internal sealed class BamlContentPropertyNode : BamlTreeNode
{
internal BamlContentPropertyNode(
string assemblyName,
string typeFullName,
string propertyName
) : base(BamlNodeType.ContentProperty)
{
_assemblyName = assemblyName;
_typeFullName = typeFullName;
_propertyName = propertyName;
}
internal override void Serialize(BamlWriter writer)
{
writer.WriteContentProperty(
_assemblyName,
_typeFullName,
_propertyName
);
}
internal override BamlTreeNode Copy()
{
return new BamlContentPropertyNode(
_assemblyName,
_typeFullName,
_propertyName
);
}
private string _assemblyName;
private string _typeFullName;
private string _propertyName;
}
internal sealed class BamlPresentationOptionsAttributeNode : BamlTreeNode
{
internal BamlPresentationOptionsAttributeNode(string name, string value)
: base(BamlNodeType.PresentationOptionsAttribute)
{
_name = name;
_value = value;
}
internal override void Serialize(BamlWriter writer)
{
writer.WritePresentationOptionsAttribute(_name, _value);
}
internal override BamlTreeNode Copy()
{
return new BamlPresentationOptionsAttributeNode(_name, _value);
}
private string _name;
private string _value;
}
#endregion
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.Build.Construction;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudioTools.Project;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
namespace Microsoft.PythonTools.Project {
/// <summary>
/// Creates Python Projects
/// </summary>
[Guid(PythonConstants.ProjectFactoryGuid)]
class PythonProjectFactory : ProjectFactory {
// We don't want to create projects with these GUIDs because they are
// either incompatible or don't really exist (e.g. telemetry markers).
private static readonly HashSet<Guid> IgnoredProjectTypeGuids = new HashSet<Guid> {
new Guid("{789894C7-04A9-4A11-A6B5-3F4435165112}"), // Flask Web Project marker
new Guid("{E614C764-6D9E-4607-9337-B7073809A0BD}"), // Bottle Web Project marker
new Guid("{725071E1-96AE-4405-9303-1BA64EFF6EBD}"), // Worker Role Project marker
new Guid("{A41C8EA1-112A-4A2D-9F91-29557995525F}"), // ML Classifier template marker
new Guid("{8267E218-6B96-4D5D-A9DF-50CEDF58D05F}"), // ML Clustering template marker
new Guid("{6C0EFAFA-1A04-41B6-A6D7-511B90951B5B}"), // ML Regression template marker
// Reserved for future use
new Guid("{C6BB79BC-0657-4BB5-8732-4FFE9EB5352D}"),
new Guid("{C966CC89-2BC8-4036-85D1-478A085253AD}"),
new Guid("{D848A2D7-0C4D-4A6A-9048-2B62DC103475}"),
new Guid("{74DCBC5F-E288-431D-A7A0-B7CD4BE4B611}"),
new Guid("{2BAC7739-571D-41CB-953C-7101995EBD9E}"),
new Guid("{B452423D-5304-416F-975E-351476E8705C}"),
new Guid("{587EF8DD-BE2D-4792-AE5F-8AE0A49AC1A5}")
};
// These targets files existed in PTVS 2.1 Beta but were removed. We
// want to replace them with some properties and Web.targets.
// Some intermediate builds of PTVS have different paths that will not
// be upgraded automatically.
private const string Ptvs21BetaBottleTargets = @"$(VSToolsPath)\Python Tools\Microsoft.PythonTools.Bottle.targets";
private const string Ptvs21BetaFlaskTargets = @"$(VSToolsPath)\Python Tools\Microsoft.PythonTools.Flask.targets";
// These targets files existed in early PTVS versions but are no longer
// suitable and need to be replaced with our own targets file.
internal const string CommonTargets = @"$(MSBuildToolsPath)\Microsoft.Common.targets";
internal const string CommonProps = @"$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props";
internal const string PtvsTargets = @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.targets";
internal const string WebTargets = @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.Web.targets";
// These GUIDs were used for well-known interpreter IDs
private static readonly Dictionary<Guid, string> InterpreterIdMap = new Dictionary<Guid, string> {
{ new Guid("{2AF0F10D-7135-4994-9156-5D01C9C11B7E}"), "Global|PythonCore|{0}|x86" },
{ new Guid("{9A7A9026-48C1-4688-9D5D-E5699D47D074}"), "Global|PythonCore|{0}|x64" },
{ new Guid("{80659AB7-4D53-4E0C-8588-A766116CBD46}"), "IronPython|{0}-32" },
{ new Guid("{FCC291AA-427C-498C-A4D7-4502D6449B8C}"), "IronPython|{0}-64" },
};
public PythonProjectFactory(IServiceProvider/*!*/ package)
: base(package) {
}
internal override ProjectNode/*!*/ CreateProject() {
return new PythonProjectNode(Site);
}
protected override string ProjectTypeGuids(string file) {
var guids = base.ProjectTypeGuids(file);
// Exclude GUIDs from IgnoredProjectTypeGuids so we don't try and
// create projects from them.
return string.Join(";", guids
.Split(';')
.Where(s => {
Guid g;
return Guid.TryParse(s, out g) && !IgnoredProjectTypeGuids.Contains(g);
})
);
}
private static bool IsGuidValue(ProjectPropertyElement e) {
Guid g;
return Guid.TryParse(e.Value, out g);
}
private static bool IsGuidValue(ProjectMetadataElement e) {
Guid g;
return Guid.TryParse(e.Value, out g);
}
private static bool IsGuidValue(ProjectItemElement e) {
Guid g;
foreach (var i in (e.Include?.Split('/', '\\')).MaybeEnumerate()) {
if (Guid.TryParse(i?.Trim() ?? "", out g)) {
return true;
}
}
return false;
}
protected override ProjectUpgradeState UpgradeProjectCheck(
ProjectRootElement projectXml,
ProjectRootElement userProjectXml,
Action<__VSUL_ERRORLEVEL, string> log,
ref Guid projectFactory,
ref __VSPPROJECTUPGRADEVIAFACTORYFLAGS backupSupport
) {
Version version;
// Web projects are incompatible with WDExpress/Shell
ProjectPropertyElement projectType;
if (!IsWebProjectSupported &&
(projectType = projectXml.Properties.FirstOrDefault(p => p.Name == "ProjectTypeGuids")) != null) {
var webProjectGuid = new Guid(PythonConstants.WebProjectFactoryGuid);
if (projectType.Value
.Split(';')
.Select(s => {
Guid g;
return Guid.TryParse(s, out g) ? g : Guid.Empty;
})
.Contains(webProjectGuid)
) {
log(__VSUL_ERRORLEVEL.VSUL_ERROR, Strings.ProjectRequiresVWDExpress);
return ProjectUpgradeState.Incompatible;
}
}
// Referencing an interpreter by GUID
if (projectXml.Properties.Where(p => p.Name == "InterpreterId").Any(IsGuidValue) ||
projectXml.ItemGroups.SelectMany(g => g.Items)
.Where(i => i.ItemType == "InterpreterReference")
.Any(IsGuidValue) ||
projectXml.ItemGroups.SelectMany(g => g.Items)
.Where(i => i.ItemType == "Interpreter")
.SelectMany(i => i.Metadata.Where(m => m.Name == "BaseInterpreter"))
.Any(IsGuidValue)
) {
return ProjectUpgradeState.OneWayUpgrade;
}
var imports = new HashSet<string>(projectXml.Imports.Select(p => p.Project), StringComparer.OrdinalIgnoreCase);
// Importing a targets file from 2.1 Beta
if (imports.Contains(Ptvs21BetaBottleTargets) || imports.Contains(Ptvs21BetaFlaskTargets)) {
return ProjectUpgradeState.SafeRepair;
}
// Only importing the Common targets and/or props.
if (imports.Contains(CommonProps) || imports.Contains(CommonTargets) && imports.Count == 1) {
return ProjectUpgradeState.OneWayUpgrade;
}
// ToolsVersion less than 4.0 (or unspecified) is not supported, so
// set it to 4.0.
if (!Version.TryParse(projectXml.ToolsVersion, out version) ||
version < new Version(4, 0)) {
return ProjectUpgradeState.SafeRepair;
}
return ProjectUpgradeState.NotNeeded;
}
protected override void UpgradeProject(
ref ProjectRootElement projectXml,
ref ProjectRootElement userProjectXml,
Action<__VSUL_ERRORLEVEL, string> log
) {
Version version;
// ToolsVersion less than 4.0 (or unspecified) is not supported, so
// set it to 4.0.
if (!Version.TryParse(projectXml.ToolsVersion, out version) ||
version < new Version(4, 0)) {
projectXml.ToolsVersion = "4.0";
log(__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, Strings.UpgradedToolsVersion);
}
// Referencing an interpreter by GUID
bool interpreterChanged = false;
var msbuildInterpreters = new Dictionary<Guid, string>();
foreach (var i in projectXml.ItemGroups.SelectMany(g => g.Items).Where(i => i.ItemType == "Interpreter")) {
var id = i.Metadata.LastOrDefault(m => m.Name == "Id");
if (id != null) {
Guid guid;
if (Guid.TryParse(id.Value, out guid)) {
msbuildInterpreters[guid] = i.Include?.Trim('/', '\\');
}
}
var mdBase = i.Metadata.LastOrDefault(m => m.Name == "BaseInterpreter");
if (mdBase == null) {
continue;
}
var mdVer = i.Metadata.LastOrDefault(m => m.Name == "Version");
if (mdVer == null) {
log(__VSUL_ERRORLEVEL.VSUL_ERROR, Strings.UpgradedInterpreterReferenceFailed);
continue;
}
var newId = MapInterpreterId(mdBase.Value, mdVer.Value, null);
if (newId != null) {
mdBase.Value = newId;
interpreterChanged = true;
}
}
var interpreterId = projectXml.Properties.LastOrDefault(p => p.Name == "InterpreterId");
var interpreterVersion = projectXml.Properties.LastOrDefault(p => p.Name == "InterpreterVersion");
if (interpreterId != null && interpreterVersion != null) {
var newId = MapInterpreterId(interpreterId.Value, interpreterVersion.Value, msbuildInterpreters);
if (newId != null) {
interpreterId.Value = newId;
interpreterVersion.Parent.RemoveChild(interpreterVersion);
interpreterChanged = true;
}
}
foreach (var i in projectXml.ItemGroups.SelectMany(g => g.Items).Where(i => i.ItemType == "InterpreterReference")) {
var newId = MapInterpreterId(i.Include, null, null);
if (newId != null) {
i.Include = newId;
interpreterChanged = true;
}
}
if (interpreterChanged) {
log(__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, Strings.UpgradedInterpreterReference);
}
// Importing a targets file from 2.1 Beta
var bottleImports = projectXml.Imports.Where(p => p.Project.Equals(Ptvs21BetaBottleTargets, StringComparison.OrdinalIgnoreCase)).ToList();
var flaskImports = projectXml.Imports.Where(p => p.Project.Equals(Ptvs21BetaFlaskTargets, StringComparison.OrdinalIgnoreCase)).ToList();
foreach (var import in bottleImports.Concat(flaskImports)) {
import.Project = WebTargets;
}
if (bottleImports.Any()) {
var globals = projectXml.PropertyGroups.FirstOrDefault() ?? projectXml.AddPropertyGroup();
AddOrSetProperty(globals, "PythonDebugWebServerCommandArguments", "--debug $(CommandLineArguments)");
AddOrSetProperty(globals, "PythonWsgiHandler", "{StartupModule}.wsgi_app()");
log(__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, Strings.UpgradedBottleImports);
}
if (flaskImports.Any()) {
var globals = projectXml.PropertyGroups.FirstOrDefault() ?? projectXml.AddPropertyGroup();
AddOrSetProperty(globals, "PythonWsgiHandler", "{StartupModule}.wsgi_app");
log(__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, Strings.UpgradedFlaskImports);
}
var commonPropsImports = projectXml.Imports.Where(p => p.Project.Equals(CommonProps, StringComparison.OrdinalIgnoreCase)).ToList();
foreach (var p in commonPropsImports) {
projectXml.RemoveChild(p);
log(__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, Strings.UpgradedRemoveCommonProps);
}
if (projectXml.Imports.Count == 1 && projectXml.Imports.First().Project.Equals(CommonTargets, StringComparison.OrdinalIgnoreCase)) {
projectXml.RemoveChild(projectXml.Imports.First());
var group = projectXml.AddPropertyGroup();
if (!projectXml.Properties.Any(p => p.Name == "VisualStudioVersion")) {
group.AddProperty("VisualStudioVersion", "10.0").Condition = "'$(VisualStudioVersion)' == ''";
}
group.AddProperty("PtvsTargetsFile", PtvsTargets);
projectXml.AddImport("$(PtvsTargetsFile)").Condition = "Exists($(PtvsTargetsFile))";
projectXml.AddImport(CommonTargets).Condition = "!Exists($(PtvsTargetsFile))";
log(__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, Strings.UpgradedRemoveCommonTargets);
}
}
private const int ExpressSkuValue = 500;
private const int ShellSkuValue = 1000;
private const int ProSkuValue = 2000;
private const int PremiumUltimateSkuValue = 3000;
private const int VWDExpressSkuValue = 0x0040;
private const int WDExpressSkuValue = 0x8000;
private const int PremiumSubSkuValue = 0x0080;
private const int UltimateSubSkuValue = 0x0188;
private bool IsWebProjectSupported {
get {
var shell = (IVsShell)Site.GetService(typeof(SVsShell));
if (shell == null) {
// Outside of VS, so we're probably only here for tests.
return true;
}
object obj;
ErrorHandler.ThrowOnFailure(shell.GetProperty((int)__VSSPROPID2.VSSPROPID_SKUEdition, out obj));
var sku = (obj as int?) ?? 0;
if (sku == ShellSkuValue) {
return false;
} else if (sku == ExpressSkuValue) {
ErrorHandler.ThrowOnFailure(shell.GetProperty((int)__VSSPROPID2.VSSPROPID_SubSKUEdition, out obj));
if ((obj as int?) == WDExpressSkuValue) {
return false;
}
}
return true;
}
}
private static void AddOrSetProperty(ProjectPropertyGroupElement group, string name, string value) {
bool anySet = false;
foreach (var prop in group.Properties.Where(p => p.Name == name)) {
prop.Value = value;
anySet = true;
}
if (!anySet) {
group.AddProperty(name, value);
}
}
private static string MapInterpreterId(string idStr, string versionStr, IDictionary<Guid, string> msBuildInterpreters) {
int splitter = idStr.IndexOfAny(new[] { '/', '\\' });
if (splitter > 0) {
versionStr = idStr.Substring(splitter + 1);
idStr = idStr.Remove(splitter);
}
Guid id;
Version version;
if (string.IsNullOrEmpty(idStr) || !Guid.TryParse(idStr, out id)) {
return null;
}
string fmt;
if (InterpreterIdMap.TryGetValue(id, out fmt)) {
if (string.IsNullOrEmpty(versionStr) || !Version.TryParse(versionStr, out version)) {
return null;
}
// CPython 3.5 32-bit needs a special fix to the version string
if (id == new Guid("{2AF0F10D-7135-4994-9156-5D01C9C11B7E}") && version == new Version(3, 5)) {
return fmt.FormatInvariant("3.5-32");
}
return fmt.FormatInvariant(version.ToString());
}
string msbuildId = null;
if ((msBuildInterpreters?.TryGetValue(id, out msbuildId) ?? false) && !string.IsNullOrEmpty(msbuildId)) {
return "MSBuild|{0}|$(MSBuildProjectFullPath)".FormatInvariant(msbuildId);
}
return null;
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#pragma warning disable 1634, 1691
namespace System.ServiceModel.ComIntegration
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Proxies;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.Threading;
class TypedServiceChannelBuilder : IProxyCreator, IProvideChannelBuilderSettings, ICreateServiceChannel
{
ServiceChannelFactory serviceChannelFactory = null;
Type contractType = null;
// Double-checked locking pattern requires volatile for read/write synchronization
volatile RealProxy serviceProxy = null;
ServiceEndpoint serviceEndpoint = null;
KeyedByTypeCollection<IEndpointBehavior> behaviors = new KeyedByTypeCollection<IEndpointBehavior>();
Binding binding = null;
string configurationName = null;
string address = null;
EndpointIdentity identity = null;
void IDisposable.Dispose()
{
if (serviceProxy != null)
{
IChannel channel = serviceProxy.GetTransparentProxy() as IChannel;
if (channel == null)
{
throw Fx.AssertAndThrow("serviceProxy MUST support IChannel");
}
channel.Close();
}
}
//Suppressing PreSharp warning that property get methods should not throw
#pragma warning disable 6503
ServiceChannelFactory IProvideChannelBuilderSettings.ServiceChannelFactoryReadWrite
{
get
{
if (serviceProxy != null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new COMException(SR.GetString(SR.TooLate), HR.RPC_E_TOO_LATE));
return serviceChannelFactory;
}
}
#pragma warning restore 6503
ServiceChannelFactory IProvideChannelBuilderSettings.ServiceChannelFactoryReadOnly
{
get
{
return serviceChannelFactory;
}
}
//Suppressing PreSharp warning that property get methods should not throw
#pragma warning disable 6503
KeyedByTypeCollection<IEndpointBehavior> IProvideChannelBuilderSettings.Behaviors
{
get
{
if (serviceProxy != null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new COMException(SR.GetString(SR.TooLate), HR.RPC_E_TOO_LATE));
return behaviors;
}
}
#pragma warning restore 6503
ServiceChannel IProvideChannelBuilderSettings.ServiceChannel
{
get
{
return null;
}
}
RealProxy ICreateServiceChannel.CreateChannel()
{
if (serviceProxy == null)
{
lock (this)
{
if (serviceProxy == null)
{
try
{
if (serviceChannelFactory == null)
{
FaultInserviceChannelFactory();
}
if (serviceChannelFactory == null)
{
throw Fx.AssertAndThrow("ServiceChannelFactory cannot be null at this point");
}
serviceChannelFactory.Open();
if (contractType == null)
{
throw Fx.AssertAndThrow("contractType cannot be null");
}
if (serviceEndpoint == null)
{
throw Fx.AssertAndThrow("serviceEndpoint cannot be null");
}
object transparentProxy = serviceChannelFactory.CreateChannel(contractType, new EndpointAddress(serviceEndpoint.Address.Uri, serviceEndpoint.Address.Identity, serviceEndpoint.Address.Headers), serviceEndpoint.Address.Uri);
ComPlusChannelCreatedTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationChannelCreated,
SR.TraceCodeComIntegrationChannelCreated, serviceEndpoint.Address.Uri, contractType);
RealProxy localProxy = RemotingServices.GetRealProxy(transparentProxy);
serviceProxy = localProxy;
if (serviceProxy == null)
{
throw Fx.AssertAndThrow("serviceProxy MUST derive from RealProxy");
}
}
finally
{
if ((serviceProxy == null) && (serviceChannelFactory != null))
serviceChannelFactory.Close();
}
}
}
}
return serviceProxy;
}
private ServiceEndpoint CreateServiceEndpoint()
{
TypeLoader loader = new TypeLoader();
ContractDescription contractDescription = loader.LoadContractDescription(contractType);
ServiceEndpoint endpoint = new ServiceEndpoint(contractDescription);
if (address != null)
endpoint.Address = new EndpointAddress(new Uri(address), identity);
if (binding != null)
endpoint.Binding = binding;
if (configurationName != null)
{
ConfigLoader configLoader = new ConfigLoader();
configLoader.LoadChannelBehaviors(endpoint, configurationName);
}
ComPlusTypedChannelBuilderTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationTypedChannelBuilderLoaded,
SR.TraceCodeComIntegrationTypedChannelBuilderLoaded, contractType, binding);
return endpoint;
}
private ServiceChannelFactory CreateServiceChannelFactory()
{
ServiceChannelFactory serviceChannelFactory = ServiceChannelFactory.BuildChannelFactory(serviceEndpoint) as ServiceChannelFactory;
if (serviceChannelFactory == null)
{
throw Fx.AssertAndThrow("We should get a ServiceChannelFactory back");
}
return serviceChannelFactory;
}
void FaultInserviceChannelFactory()
{
if (contractType == null)
{
throw Fx.AssertAndThrow("contractType should not be null");
}
if (serviceEndpoint == null)
{
serviceEndpoint = CreateServiceEndpoint();
}
foreach (IEndpointBehavior behavior in behaviors)
serviceEndpoint.Behaviors.Add(behavior);
serviceChannelFactory = CreateServiceChannelFactory();
}
internal void ResolveTypeIfPossible(Dictionary<MonikerHelper.MonikerAttribute, string> propertyTable)
{
string typeIID;
propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Contract, out typeIID);
Guid iid;
if (!string.IsNullOrEmpty(typeIID))
{
try
{
dispatchEnabled = true;
iid = new Guid(typeIID);
TypeCacheManager.Provider.FindOrCreateType(iid, out contractType, true, false);
serviceEndpoint = CreateServiceEndpoint();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.TypeLoadForContractTypeIIDFailedWith, typeIID, e.Message)));
}
}
}
internal TypedServiceChannelBuilder(Dictionary<MonikerHelper.MonikerAttribute, string> propertyTable)
{
string bindingType = null;
string bindingConfigName = null;
string spnIdentity = null;
string upnIdentity = null;
string dnsIdentity = null;
propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Address, out address);
propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Binding, out bindingType);
propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.BindingConfiguration, out bindingConfigName);
propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.SpnIdentity, out spnIdentity);
propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.UpnIdentity, out upnIdentity);
propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.DnsIdentity, out dnsIdentity);
if (!string.IsNullOrEmpty(bindingType))
{
try
{
binding = ConfigLoader.LookupBinding(bindingType, bindingConfigName);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.BindingLoadFromConfigFailedWith, bindingType, e.Message)));
}
if (binding == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.BindingNotFoundInConfig, bindingType, bindingConfigName)));
}
if (binding == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.BindingNotSpecified)));
if (string.IsNullOrEmpty(address))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.AddressNotSpecified)));
if (!string.IsNullOrEmpty(spnIdentity))
{
if ((!string.IsNullOrEmpty(upnIdentity)) || (!string.IsNullOrEmpty(dnsIdentity)))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorrectServerIdentity)));
identity = EndpointIdentity.CreateSpnIdentity(spnIdentity);
}
else if (!string.IsNullOrEmpty(upnIdentity))
{
if ((!string.IsNullOrEmpty(spnIdentity)) || (!string.IsNullOrEmpty(dnsIdentity)))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorrectServerIdentity)));
identity = EndpointIdentity.CreateUpnIdentity(upnIdentity);
}
else if (!string.IsNullOrEmpty(dnsIdentity))
{
if ((!string.IsNullOrEmpty(spnIdentity)) || (!string.IsNullOrEmpty(upnIdentity)))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorrectServerIdentity)));
identity = EndpointIdentity.CreateDnsIdentity(dnsIdentity);
}
else
identity = null;
ResolveTypeIfPossible(propertyTable);
}
bool dispatchEnabled = false;
private bool CheckDispatch(ref Guid riid)
{
if ((dispatchEnabled) && (riid == InterfaceID.idIDispatch))
return true;
else
return false;
}
ComProxy IProxyCreator.CreateProxy(IntPtr outer, ref Guid riid)
{
if (outer == IntPtr.Zero)
{
throw Fx.AssertAndThrow("OuterProxy cannot be null");
}
// No contract Fault on in
if (contractType == null)
TypeCacheManager.Provider.FindOrCreateType(riid, out contractType, true, false);
if ((contractType.GUID != riid) && !(CheckDispatch(ref riid)))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidCastException(SR.GetString(SR.NoInterface, riid)));
Type proxiedType = EmitterCache.TypeEmitter.FindOrCreateType(contractType);
ComProxy comProxy = null;
TearOffProxy tearoffProxy = null;
try
{
tearoffProxy = new TearOffProxy(this, proxiedType);
comProxy = ComProxy.Create(outer, tearoffProxy.GetTransparentProxy(), tearoffProxy);
return comProxy;
}
finally
{
if ((comProxy == null) && (tearoffProxy != null))
((IDisposable)tearoffProxy).Dispose();
}
}
bool IProxyCreator.SupportsErrorInfo(ref Guid riid)
{
if (contractType == null)
return false;
else
{
if ((contractType.GUID != riid) && !(CheckDispatch(ref riid)))
return false;
else
return true;
}
}
bool IProxyCreator.SupportsDispatch()
{
return dispatchEnabled;
}
bool IProxyCreator.SupportsIntrinsics()
{
return true;
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Util;
namespace QuantConnect.Data.Market
{
/// <summary>
/// Represents an entire chain of option contracts for a single underying security.
/// This type is <see cref="IEnumerable{OptionContract}"/>
/// </summary>
public class OptionChain : BaseData, IEnumerable<OptionContract>
{
private readonly Dictionary<Type, Dictionary<Symbol, List<BaseData>>> _auxiliaryData = new Dictionary<Type, Dictionary<Symbol, List<BaseData>>>();
/// <summary>
/// Gets the most recent trade information for the underlying. This may
/// be a <see cref="Tick"/> or a <see cref="TradeBar"/>
/// </summary>
public BaseData Underlying
{
get; internal set;
}
/// <summary>
/// Gets all ticks for every option contract in this chain, keyed by option symbol
/// </summary>
public Ticks Ticks
{
get; private set;
}
/// <summary>
/// Gets all trade bars for every option contract in this chain, keyed by option symbol
/// </summary>
public TradeBars TradeBars
{
get; private set;
}
/// <summary>
/// Gets all quote bars for every option contract in this chain, keyed by option symbol
/// </summary>
public QuoteBars QuoteBars
{
get; private set;
}
/// <summary>
/// Gets all contracts in the chain, keyed by option symbol
/// </summary>
public OptionContracts Contracts
{
get; private set;
}
/// <summary>
/// Gets the set of symbols that passed the <see cref="Option.ContractFilter"/>
/// </summary>
public HashSet<Symbol> FilteredContracts
{
get; private set;
}
/// <summary>
/// Initializes a new default instance of the <see cref="OptionChain"/> class
/// </summary>
private OptionChain()
{
DataType = MarketDataType.OptionChain;
}
/// <summary>
/// Initializes a new instance of the <see cref="OptionChain"/> class
/// </summary>
/// <param name="canonicalOptionSymbol">The symbol for this chain.</param>
/// <param name="time">The time of this chain</param>
public OptionChain(Symbol canonicalOptionSymbol, DateTime time)
{
Time = time;
Symbol = canonicalOptionSymbol;
DataType = MarketDataType.OptionChain;
Ticks = new Ticks(time);
TradeBars = new TradeBars(time);
QuoteBars = new QuoteBars(time);
Contracts = new OptionContracts(time);
FilteredContracts = new HashSet<Symbol>();
Underlying = new QuoteBar();
}
/// <summary>
/// Initializes a new instance of the <see cref="OptionChain"/> class
/// </summary>
/// <param name="canonicalOptionSymbol">The symbol for this chain.</param>
/// <param name="time">The time of this chain</param>
/// <param name="underlying">The most recent underlying trade data</param>
/// <param name="trades">All trade data for the entire option chain</param>
/// <param name="quotes">All quote data for the entire option chain</param>
/// <param name="contracts">All contrains for this option chain</param>
public OptionChain(Symbol canonicalOptionSymbol, DateTime time, BaseData underlying, IEnumerable<BaseData> trades, IEnumerable<BaseData> quotes, IEnumerable<OptionContract> contracts, IEnumerable<Symbol> filteredContracts)
{
Time = time;
Underlying = underlying;
Symbol = canonicalOptionSymbol;
DataType = MarketDataType.OptionChain;
FilteredContracts = filteredContracts.ToHashSet();
Ticks = new Ticks(time);
TradeBars = new TradeBars(time);
QuoteBars = new QuoteBars(time);
Contracts = new OptionContracts(time);
foreach (var trade in trades)
{
var tick = trade as Tick;
if (tick != null)
{
List<Tick> ticks;
if (!Ticks.TryGetValue(tick.Symbol, out ticks))
{
ticks = new List<Tick>();
Ticks[tick.Symbol] = ticks;
}
ticks.Add(tick);
continue;
}
var bar = trade as TradeBar;
if (bar != null)
{
TradeBars[trade.Symbol] = bar;
}
}
foreach (var quote in quotes)
{
var tick = quote as Tick;
if (tick != null)
{
List<Tick> ticks;
if (!Ticks.TryGetValue(tick.Symbol, out ticks))
{
ticks = new List<Tick>();
Ticks[tick.Symbol] = ticks;
}
ticks.Add(tick);
continue;
}
var bar = quote as QuoteBar;
if (bar != null)
{
QuoteBars[quote.Symbol] = bar;
}
}
foreach (var contract in contracts)
{
Contracts[contract.Symbol] = contract;
}
}
/// <summary>
/// Gets the auxiliary data with the specified type and symbol
/// </summary>
/// <typeparam name="T">The type of auxiliary data</typeparam>
/// <param name="symbol">The symbol of the auxiliary data</param>
/// <returns>The last auxiliary data with the specified type and symbol</returns>
public T GetAux<T>(Symbol symbol)
{
List<BaseData> list;
Dictionary<Symbol, List<BaseData>> dictionary;
if (!_auxiliaryData.TryGetValue(typeof(T), out dictionary) || !dictionary.TryGetValue(symbol, out list))
{
return default(T);
}
return list.OfType<T>().LastOrDefault();
}
/// <summary>
/// Gets all auxiliary data of the specified type as a dictionary keyed by symbol
/// </summary>
/// <typeparam name="T">The type of auxiliary data</typeparam>
/// <returns>A dictionary containing all auxiliary data of the specified type</returns>
public DataDictionary<T> GetAux<T>()
{
Dictionary<Symbol, List<BaseData>> d;
if (!_auxiliaryData.TryGetValue(typeof(T), out d))
{
return new DataDictionary<T>();
}
var dictionary = new DataDictionary<T>();
foreach (var kvp in d)
{
var item = kvp.Value.OfType<T>().LastOrDefault();
if (item != null)
{
dictionary.Add(kvp.Key, item);
}
}
return dictionary;
}
/// <summary>
/// Gets all auxiliary data of the specified type as a dictionary keyed by symbol
/// </summary>
/// <typeparam name="T">The type of auxiliary data</typeparam>
/// <returns>A dictionary containing all auxiliary data of the specified type</returns>
public Dictionary<Symbol, List<BaseData>> GetAuxList<T>()
{
Dictionary<Symbol, List<BaseData>> dictionary;
if (!_auxiliaryData.TryGetValue(typeof(T), out dictionary))
{
return new Dictionary<Symbol, List<BaseData>>();
}
return dictionary;
}
/// <summary>
/// Gets a list of auxiliary data with the specified type and symbol
/// </summary>
/// <typeparam name="T">The type of auxiliary data</typeparam>
/// <param name="symbol">The symbol of the auxiliary data</param>
/// <returns>The list of auxiliary data with the specified type and symbol</returns>
public List<T> GetAuxList<T>(Symbol symbol)
{
List<BaseData> list;
Dictionary<Symbol, List<BaseData>> dictionary;
if (!_auxiliaryData.TryGetValue(typeof(T), out dictionary) || !dictionary.TryGetValue(symbol, out list))
{
return new List<T>();
}
return list.OfType<T>().ToList();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// An enumerator that can be used to iterate through the collection.
/// </returns>
public IEnumerator<OptionContract> GetEnumerator()
{
return Contracts.Values.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Return a new instance clone of this object, used in fill forward
/// </summary>
/// <returns>A clone of the current object</returns>
public override BaseData Clone()
{
return new OptionChain
{
Underlying = Underlying,
Ticks = Ticks,
Contracts = Contracts,
QuoteBars = QuoteBars,
TradeBars = TradeBars,
FilteredContracts = FilteredContracts,
Symbol = Symbol,
Time = Time,
DataType = DataType,
Value = Value
};
}
/// <summary>
/// Adds the specified auxiliary data to this option chain
/// </summary>
/// <param name="baseData">The auxiliary data to be added</param>
internal void AddAuxData(BaseData baseData)
{
var type = baseData.GetType();
Dictionary<Symbol, List<BaseData>> dictionary;
if (!_auxiliaryData.TryGetValue(type, out dictionary))
{
dictionary = new Dictionary<Symbol, List<BaseData>>();
_auxiliaryData[type] = dictionary;
}
List<BaseData> list;
if (!dictionary.TryGetValue(baseData.Symbol, out list))
{
list = new List<BaseData>();
dictionary[baseData.Symbol] = list;
}
list.Add(baseData);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureSpecials
{
using System;
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>
/// ApiVersionLocalOperations operations.
/// </summary>
internal partial class ApiVersionLocalOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, IApiVersionLocalOperations
{
/// <summary>
/// Initializes a new instance of the ApiVersionLocalOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ApiVersionLocalOperations(AutoRestAzureSpecialParametersTestClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestAzureSpecialParametersTestClient
/// </summary>
public AutoRestAzureSpecialParametersTestClient Client { get; private set; }
/// <summary>
/// Get method with api-version modeled in the method. pass in api-version =
/// '2.0' to succeed
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetMethodLocalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string apiVersion = "2.0";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetMethodLocalValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/method/string/none/query/local/2.0").ToString();
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get method with api-version modeled in the method. pass in api-version =
/// null to succeed
/// </summary>
/// <param name='apiVersion'>
/// This should appear as a method parameter, use value null, this should
/// result in no serialized parameter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetMethodLocalNullWithHttpMessagesAsync(string apiVersion = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetMethodLocalNull", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/method/string/none/query/local/null").ToString();
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get method with api-version modeled in the method. pass in api-version =
/// '2.0' to succeed
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetPathLocalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string apiVersion = "2.0";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetPathLocalValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/path/string/none/query/local/2.0").ToString();
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get method with api-version modeled in the method. pass in api-version =
/// '2.0' to succeed
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetSwaggerLocalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string apiVersion = "2.0";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetSwaggerLocalValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/swagger/string/none/query/local/2.0").ToString();
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace CoreXml.Test.XLinq
{
public class ManagedNodeWriter
{
public static bool DEBUG = false;
private const string XML_DECL = "<?xml version='1.0' ?>\n";
private const string S_ROOT = "<root>";
private const string E_ROOT = "</root>";
private const string E_NAME = "ELEMENT_";
private const string A_NAME = "ATTRIB_";
private const string A_VALUE = "VALUE_";
private const string CDATA = "CDATA_";
private const string TEXT = "TEXT_";
private const string PI = "PI_";
private const string COMMENT = "COMMENT_";
private long _eCount = 0; //element indexer
private long _aCount = 0; //attribute indexer
private long _cCount = 0; //Cdata indexer
private long _tCount = 0; //Text indexer
private long _pCount = 0; //PI Indexer
private long _mCount = 0; //Comment Indexer
private StreamWriter _textWriter = null;
private Stack<string> _elementStack = new Stack<string>();
private StringBuilder _nodeQueue = new StringBuilder();
private const string LT = "<";
private const string GT = ">";
private const string MT = "/>";
private const string ET = "</";
private const string SPACE = " ";
private const string S_QUOTE = "'";
private const string D_QUOTE = "\"";
private const string EQ = "=";
private const string LF = "\n";
public ManagedNodeWriter()
{ }
public ManagedNodeWriter(Stream myStream, Encoding enc)
{
_textWriter = new StreamWriter(myStream, enc);
}
/// <summary>
/// GetNodes returns the existing XML string thats been written so far.
/// </summary>
/// <returns>String of XML</returns>
public string GetNodes()
{
return _nodeQueue.ToString();
}
/// Closing the NodeWriter
public void Close()
{
if (_textWriter != null)
{
_textWriter.Write(_nodeQueue.ToString());
_textWriter.Dispose();
_textWriter = null;
}
}
/// Writing XML Decl
public void PutDecl()
{
_nodeQueue.Append(XML_DECL);
}
/// Writing a Root Element.
public void PutRoot()
{
_nodeQueue.Append(S_ROOT);
}
/// Writing End Root Element.
public void PutEndRoot()
{
_nodeQueue.Append(E_ROOT);
}
/// Writing a start of open element.
public void OpenElement()
{
string elem = LT + E_NAME + _eCount + SPACE;
_nodeQueue.Append(elem);
_elementStack.Push(E_NAME + _eCount);
++_eCount;
}
/// Writing a start of open element with user supplied name.
public void OpenElement(string myName)
{
string elem = LT + myName + SPACE;
_elementStack.Push(myName);
_nodeQueue.Append(elem);
}
/// Closing the open element.
public void CloseElement()
{
_nodeQueue.Append(GT);
}
// Closing the open element as empty element
public void CloseEmptyElement()
{
_nodeQueue.Append(MT);
}
/// Writing an attribute.
public void PutAttribute()
{
string attr = A_NAME + _aCount + EQ + S_QUOTE + A_VALUE + _aCount + S_QUOTE + SPACE;
_nodeQueue.Append(attr);
++_aCount;
}
/// Overloaded PutAttribute which takes user values.
public void PutAttribute(string myAttrName, string myAttrValue)
{
string attr = SPACE + myAttrName + EQ + S_QUOTE + myAttrValue + S_QUOTE;
_nodeQueue.Append(attr);
}
/// Writing empty element.
public void PutEmptyElement()
{
string elem = LT + E_NAME + _eCount + MT;
_nodeQueue.Append(elem);
++_eCount;
}
/// Writing an end element from the stack.
public void PutEndElement()
{
string elem = _elementStack.Pop();
_nodeQueue.Append(ET + elem + GT);
}
/// Writing an end element for a given name.
public void PutEndElement(string myName)
{
if (DEBUG)
{
string elem = _elementStack.Pop();
}
_nodeQueue.Append(ET + myName + GT);
}
/// <summary>
/// Finish allows user to complete xml file with the end element tags that were so far open.
/// </summary>
public void Finish()
{
while (_elementStack.Count > 0)
{
string elem = _elementStack.Pop();
_nodeQueue.Append(ET + elem + GT);
}
}
/// Writing text.
/// Note : This is basically equivalent to WriteRaw and the string may contain any number of embedded tags.
/// No checking is performed on them either.
public void PutText(string myStr)
{
_nodeQueue.Append(myStr);
}
/// <summary>
/// AutoGenerated Text
/// </summary>
public void PutText()
{
_nodeQueue.Append(TEXT + _tCount++);
}
/// <summary>
/// Writing a Byte Array.
/// </summary>
/// <param name="bArr"></param>
public void PutBytes(byte[] bArr)
{
foreach (byte b in bArr)
{
_nodeQueue.Append(b);
}
}
public void PutByte()
{
_nodeQueue.Append(Convert.ToByte("a"));
}
/// <summary>
/// Writes out CDATA Node.
/// </summary>
public void PutCData()
{
_nodeQueue.Append("<![CDATA[" + CDATA + _cCount++ + "]]>");
}
/// <summary>
/// Writes out a PI Node.
/// </summary>
public void PutPI()
{
_nodeQueue.Append("<?" + PI + _pCount++ + "?>");
}
/// <summary>
/// Writes out a Comment Node.
/// </summary>
public void PutComment()
{
_nodeQueue.Append("<!--" + COMMENT + _mCount++ + " -->");
}
/// <summary>
/// Writes out a single whitespace
/// </summary>
public void PutWhiteSpace()
{
_nodeQueue.Append(" ");
}
/// <summary>
/// This method is a convenience method and a shortcut to create an XML string. Each character in the pattern
/// maps to a particular Put/Open function and calls it for you. For e.g. XEAA/ will call PutDecl, OpenElement,
/// PutAttribute, PutAttribute and CloseElement for you.
/// The following is the list of all allowed characters and their function mappings :
///
///'X' : PutDecl()
///'E' : OpenElement()
///'M' : CloseEmptyElement()
///'/' : CloseElement()
///'e' : PutEndElement()
///'A' : PutAttribute()
///'P' : PutPI()
///'T' : PutText()
///'C' : PutComment()
///'R' : PutRoot()
///'r' : PutEndRoot()
///'B' : PutEndRoot()
///'W' : PutWhiteSpace()
///
/// </summary>
/// <param name="pattern">String containing the pattern which you want to use to create
/// the XML string. Refer to table above for supported chars.</param>
public void PutPattern(string pattern)
{
char[] patternArr = pattern.ToCharArray();
foreach (char ch in patternArr)
{
switch (ch)
{
case 'X':
PutDecl();
break;
case 'E':
OpenElement();
break;
case 'M':
CloseEmptyElement();
break;
case '/':
CloseElement();
break;
case 'e':
PutEndElement();
break;
case 'A':
PutAttribute();
break;
case 'P':
PutPI();
break;
case 'T':
PutText();
break;
case 'C':
PutComment();
break;
case 'R':
PutRoot();
break;
case 'r':
PutEndRoot();
break;
case 'B':
PutEndRoot();
break;
case 'W':
PutWhiteSpace();
break;
default:
break;
}
}
}
}
}
| |
// 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 AndUInt32()
{
var test = new SimpleBinaryOpTest__AndUInt32();
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 SimpleBinaryOpTest__AndUInt32
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(UInt32);
private const int Op2ElementCount = VectorSize / sizeof(UInt32);
private const int RetElementCount = VectorSize / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static Vector128<UInt32> _clsVar1;
private static Vector128<UInt32> _clsVar2;
private Vector128<UInt32> _fld1;
private Vector128<UInt32> _fld2;
private SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32> _dataTable;
static SimpleBinaryOpTest__AndUInt32()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__AndUInt32()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32>(_data1, _data2, new UInt32[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.And(
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.And(
Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.And(
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt32*)(_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.And), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.And(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr);
var result = Sse2.And(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr));
var result = Sse2.And(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr));
var result = Sse2.And(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AndUInt32();
var result = Sse2.And(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.And(_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<UInt32> left, Vector128<UInt32> right, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, 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 = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "")
{
if ((uint)(left[0] & right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((uint)(left[i] & right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.And)}<UInt32>(Vector128<UInt32>, Vector128<UInt32>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
/***************************************************************************
* Timer.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
namespace HackMaineIrcBot
{
public enum TimerPriority
{
EveryTick,
TenMS,
TwentyFiveMS,
FiftyMS,
TwoFiftyMS,
OneSecond,
FiveSeconds,
OneMinute
}
public delegate void TimerCallback();
public delegate void TimerStateCallback( object state );
public delegate void TimerStateCallback<T>( T state );
public class Timer
{
private DateTime m_Next;
private TimeSpan m_Delay;
private TimeSpan m_Interval;
private bool m_Running;
private int m_Index, m_Count;
private TimerPriority m_Priority;
private List<Timer> m_List;
private bool m_PrioritySet;
private static string FormatDelegate( Delegate callback )
{
if ( callback == null )
return "null";
return String.Format( "{0}.{1}", callback.Method.DeclaringType.FullName, callback.Method.Name );
}
public static void DumpInfo( TextWriter tw )
{
TimerThread.DumpInfo( tw );
}
public TimerPriority Priority
{
get
{
return m_Priority;
}
set
{
if ( !m_PrioritySet )
m_PrioritySet = true;
if ( m_Priority != value )
{
m_Priority = value;
if ( m_Running )
TimerThread.PriorityChange( this, (int)m_Priority );
}
}
}
public DateTime Next
{
get { return m_Next; }
}
public TimeSpan Delay
{
get { return m_Delay; }
set { m_Delay = value; }
}
public TimeSpan Interval
{
get { return m_Interval; }
set { m_Interval = value; }
}
public bool Running
{
get { return m_Running; }
set {
if ( value ) {
Start();
} else {
Stop();
}
}
}
public class TimerThread
{
private static Queue m_ChangeQueue = Queue.Synchronized( new Queue() );
private static DateTime[] m_NextPriorities = new DateTime[8];
private static TimeSpan[] m_PriorityDelays = new TimeSpan[8]
{
TimeSpan.Zero,
TimeSpan.FromMilliseconds( 10.0 ),
TimeSpan.FromMilliseconds( 25.0 ),
TimeSpan.FromMilliseconds( 50.0 ),
TimeSpan.FromMilliseconds( 250.0 ),
TimeSpan.FromSeconds( 1.0 ),
TimeSpan.FromSeconds( 5.0 ),
TimeSpan.FromMinutes( 1.0 )
};
private static List<Timer>[] m_Timers = new List<Timer>[8]
{
new List<Timer>(),
new List<Timer>(),
new List<Timer>(),
new List<Timer>(),
new List<Timer>(),
new List<Timer>(),
new List<Timer>(),
new List<Timer>(),
};
public static void DumpInfo( TextWriter tw )
{
for ( int i = 0; i < 8; ++i )
{
tw.WriteLine( "Priority: {0}", (TimerPriority)i );
tw.WriteLine();
Dictionary<string, List<Timer>> hash = new Dictionary<string, List<Timer>>();
for ( int j = 0; j < m_Timers[i].Count; ++j )
{
Timer t = m_Timers[i][j];
string key = t.ToString();
List<Timer> list;
hash.TryGetValue( key, out list );
if ( list == null )
hash[key] = list = new List<Timer>();
list.Add( t );
}
foreach ( KeyValuePair<string, List<Timer>> kv in hash )
{
string key = kv.Key;
List<Timer> list = kv.Value;
tw.WriteLine( "Type: {0}; Count: {1}; Percent: {2}%", key, list.Count, (int)(100 * (list.Count / (double)m_Timers[i].Count)) );
}
tw.WriteLine();
tw.WriteLine();
}
}
private class TimerChangeEntry
{
public Timer m_Timer;
public int m_NewIndex;
public bool m_IsAdd;
private TimerChangeEntry( Timer t, int newIndex, bool isAdd )
{
m_Timer = t;
m_NewIndex = newIndex;
m_IsAdd = isAdd;
}
public void Free()
{
//m_InstancePool.Enqueue( this );
}
private static Queue<TimerChangeEntry> m_InstancePool = new Queue<TimerChangeEntry>();
public static TimerChangeEntry GetInstance( Timer t, int newIndex, bool isAdd )
{
TimerChangeEntry e;
if ( m_InstancePool.Count > 0 )
{
e = m_InstancePool.Dequeue();
if ( e == null )
e = new TimerChangeEntry( t, newIndex, isAdd );
else
{
e.m_Timer = t;
e.m_NewIndex = newIndex;
e.m_IsAdd = isAdd;
}
}
else
{
e = new TimerChangeEntry( t, newIndex, isAdd );
}
return e;
}
}
public TimerThread()
{
}
public static void Change( Timer t, int newIndex, bool isAdd )
{
m_ChangeQueue.Enqueue( TimerChangeEntry.GetInstance( t, newIndex, isAdd ) );
m_Signal.Set();
}
public static void AddTimer( Timer t )
{
Change( t, (int)t.Priority, true );
}
public static void PriorityChange( Timer t, int newPrio )
{
Change( t, newPrio, false );
}
public static void RemoveTimer( Timer t )
{
Change( t, -1, false );
}
private static void ProcessChangeQueue()
{
while ( m_ChangeQueue.Count > 0 )
{
TimerChangeEntry tce = (TimerChangeEntry)m_ChangeQueue.Dequeue();
Timer timer = tce.m_Timer;
int newIndex = tce.m_NewIndex;
if ( timer.m_List != null )
timer.m_List.Remove( timer );
if ( tce.m_IsAdd )
{
timer.m_Next = DateTime.Now + timer.m_Delay;
timer.m_Index = 0;
}
if ( newIndex >= 0 )
{
timer.m_List = m_Timers[newIndex];
timer.m_List.Add( timer );
}
else
{
timer.m_List = null;
}
tce.Free();
}
}
private static AutoResetEvent m_Signal = new AutoResetEvent( false );
public static void Set() { m_Signal.Set(); }
public void TimerMain()
{
DateTime now;
int i, j;
bool loaded;
while ( !Program.Closing )
{
ProcessChangeQueue();
loaded = false;
for ( i = 0; i < m_Timers.Length; i++)
{
now = DateTime.Now;
if ( now < m_NextPriorities[i] )
break;
m_NextPriorities[i] = now + m_PriorityDelays[i];
for ( j = 0; j < m_Timers[i].Count; j++)
{
Timer t = m_Timers[i][j];
if ( !t.m_Queued && now > t.m_Next )
{
t.m_Queued = true;
lock ( m_Queue )
m_Queue.Enqueue( t );
loaded = true;
if ( t.m_Count != 0 && (++t.m_Index >= t.m_Count) )
{
t.Stop();
}
else
{
t.m_Next = now + t.m_Interval;
}
}
}
}
if ( loaded )
Program.Set();
m_Signal.WaitOne( 10, false );
}
}
}
private static Queue<Timer> m_Queue = new Queue<Timer>();
private static int m_BreakCount = 20000;
public static int BreakCount{ get{ return m_BreakCount; } set{ m_BreakCount = value; } }
private static int m_QueueCountAtSlice;
private bool m_Queued;
public static void Slice()
{
lock ( m_Queue )
{
m_QueueCountAtSlice = m_Queue.Count;
int index = 0;
while ( index < m_BreakCount && m_Queue.Count != 0 )
{
Timer t = m_Queue.Dequeue();
t.OnTick();
t.m_Queued = false;
++index;
}
}
}
public Timer( TimeSpan delay ) : this( delay, TimeSpan.Zero, 1 )
{
}
public Timer( TimeSpan delay, TimeSpan interval ) : this( delay, interval, 0 )
{
}
public Timer( TimeSpan delay, TimeSpan interval, int count )
{
m_Delay = delay;
m_Interval = interval;
m_Count = count;
if ( !m_PrioritySet ) {
if ( count == 1 ) {
m_Priority = ComputePriority( delay );
} else {
m_Priority = ComputePriority( interval );
}
m_PrioritySet = true;
}
}
public override string ToString()
{
return GetType().FullName;
}
public static TimerPriority ComputePriority( TimeSpan ts )
{
if ( ts >= TimeSpan.FromMinutes( 1.0 ) )
return TimerPriority.FiveSeconds;
if ( ts >= TimeSpan.FromSeconds( 10.0 ) )
return TimerPriority.OneSecond;
if ( ts >= TimeSpan.FromSeconds( 5.0 ) )
return TimerPriority.TwoFiftyMS;
if ( ts >= TimeSpan.FromSeconds( 2.5 ) )
return TimerPriority.FiftyMS;
if ( ts >= TimeSpan.FromSeconds( 1.0 ) )
return TimerPriority.TwentyFiveMS;
if ( ts >= TimeSpan.FromSeconds( 0.5 ) )
return TimerPriority.TenMS;
return TimerPriority.EveryTick;
}
#region DelayCall(..)
public static Timer DelayCall( TimerCallback callback )
{
return DelayCall( TimeSpan.Zero, TimeSpan.Zero, 1, callback );
}
public static Timer DelayCall( TimeSpan delay, TimerCallback callback )
{
return DelayCall( delay, TimeSpan.Zero, 1, callback );
}
public static Timer DelayCall( TimeSpan delay, TimeSpan interval, TimerCallback callback )
{
return DelayCall( delay, interval, 0, callback );
}
public static Timer DelayCall( TimeSpan delay, TimeSpan interval, int count, TimerCallback callback )
{
Timer t = new DelayCallTimer( delay, interval, count, callback );
if ( count == 1 )
t.Priority = ComputePriority( delay );
else
t.Priority = ComputePriority( interval );
t.Start();
return t;
}
public static Timer DelayCall( TimerStateCallback callback, object state )
{
return DelayCall( TimeSpan.Zero, TimeSpan.Zero, 1, callback, state );
}
public static Timer DelayCall( TimeSpan delay, TimerStateCallback callback, object state )
{
return DelayCall( delay, TimeSpan.Zero, 1, callback, state );
}
public static Timer DelayCall( TimeSpan delay, TimeSpan interval, TimerStateCallback callback, object state )
{
return DelayCall( delay, interval, 0, callback, state );
}
public static Timer DelayCall( TimeSpan delay, TimeSpan interval, int count, TimerStateCallback callback, object state )
{
Timer t = new DelayStateCallTimer( delay, interval, count, callback, state );
if ( count == 1 )
t.Priority = ComputePriority( delay );
else
t.Priority = ComputePriority( interval );
t.Start();
return t;
}
#endregion
#region DelayCall<T>(..)
public static Timer DelayCall<T>( TimerStateCallback<T> callback, T state )
{
return DelayCall( TimeSpan.Zero, TimeSpan.Zero, 1, callback, state );
}
public static Timer DelayCall<T>( TimeSpan delay, TimerStateCallback<T> callback, T state )
{
return DelayCall( delay, TimeSpan.Zero, 1, callback, state );
}
public static Timer DelayCall<T>( TimeSpan delay, TimeSpan interval, TimerStateCallback<T> callback, T state )
{
return DelayCall( delay, interval, 0, callback, state );
}
public static Timer DelayCall<T>( TimeSpan delay, TimeSpan interval, int count, TimerStateCallback<T> callback, T state )
{
Timer t = new DelayStateCallTimer<T>( delay, interval, count, callback, state );
if( count == 1 )
t.Priority = ComputePriority( delay );
else
t.Priority = ComputePriority( interval );
t.Start();
return t;
}
#endregion
#region DelayCall Timers
private class DelayCallTimer : Timer
{
private TimerCallback m_Callback;
public TimerCallback Callback{ get{ return m_Callback; } }
public DelayCallTimer( TimeSpan delay, TimeSpan interval, int count, TimerCallback callback ) : base( delay, interval, count )
{
m_Callback = callback;
}
protected override void OnTick()
{
if ( m_Callback != null )
m_Callback();
}
public override string ToString()
{
return String.Format( "DelayCallTimer[{0}]", FormatDelegate( m_Callback ) );
}
}
private class DelayStateCallTimer : Timer
{
private TimerStateCallback m_Callback;
private object m_State;
public TimerStateCallback Callback{ get{ return m_Callback; } }
public DelayStateCallTimer( TimeSpan delay, TimeSpan interval, int count, TimerStateCallback callback, object state ) : base( delay, interval, count )
{
m_Callback = callback;
m_State = state;
}
protected override void OnTick()
{
if ( m_Callback != null )
m_Callback( m_State );
}
public override string ToString()
{
return String.Format( "DelayStateCall[{0}]", FormatDelegate( m_Callback ) );
}
}
private class DelayStateCallTimer<T> : Timer
{
private TimerStateCallback<T> m_Callback;
private T m_State;
public TimerStateCallback<T> Callback { get { return m_Callback; } }
public DelayStateCallTimer( TimeSpan delay, TimeSpan interval, int count, TimerStateCallback<T> callback, T state )
: base( delay, interval, count )
{
m_Callback = callback;
m_State = state;
}
protected override void OnTick()
{
if( m_Callback != null )
m_Callback( m_State );
}
public override string ToString()
{
return String.Format( "DelayStateCall[{0}]", FormatDelegate( m_Callback ) );
}
}
#endregion
public void Start()
{
if ( !m_Running )
{
m_Running = true;
TimerThread.AddTimer( this );
}
}
public void Stop()
{
if ( m_Running )
{
m_Running = false;
TimerThread.RemoveTimer( this );
}
}
protected virtual void OnTick()
{
}
}
}
| |
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Collections.Generic;
using FluorineFx.Threading;
#if !SILVERLIGHT
using log4net;
#endif
namespace FluorineFx.Util
{
/// <summary>
/// This type supports the Fluorine infrastructure and is not intended to be used directly from your code.
/// </summary>
public class ObjectPool<T> : DisposableBase
{
#if !SILVERLIGHT
private static readonly ILog Log = LogManager.GetLogger(typeof(ObjectPool<>));
#endif
private readonly int _capacity;
private readonly int _growth;
private readonly bool _forceGC;
private readonly FastReaderWriterLock _lock;
private Queue<T> _queue;
/// <summary>
/// Initializes a new instance of the <see cref="ObjectPool<T>"/> class.
/// </summary>
/// <param name="capacity">The number of elements that the object pool object initially contains.</param>
public ObjectPool(int capacity)
: this(capacity, 10, true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ObjectPool<T>"/> class.
/// </summary>
/// <param name="capacity">The number of elements that the object pool object initially contains.</param>
/// <param name="growth">The number of elements reserved in the object pool when there are no available objects.</param>
public ObjectPool(int capacity, int growth)
: this(capacity, growth, true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ObjectPool<T>"/> class.
/// </summary>
/// <param name="capacity">The number of elements that the object pool object initially contains.</param>
/// <param name="growth">The number of elements reserved in the object pool when there are no available objects.</param>
/// <param name="forceGCOnGrowth">If set to <c>true</c> forces GC on growth.</param>
public ObjectPool(int capacity, int growth, bool forceGCOnGrowth)
{
_lock = new FastReaderWriterLock();
_forceGC = forceGCOnGrowth;
_growth = growth;
_capacity = capacity;
if (_forceGC)
GC.WaitForPendingFinalizers();
}
#region IDisposable Members
/// <summary>
/// Free managed resources.
/// </summary>
protected override void Free()
{
try
{
_lock.AcquireWriterLock();
if (_queue != null)
{
while (_queue.Count > 0)
{
try
{
using (_queue.Dequeue() as IDisposable)
{
}
}
catch (Exception ex)
{
Unreferenced.Parameter(ex);
}
}
}
}
finally
{
_lock.ReleaseWriterLock();
}
base.Free();
}
#endregion IDisposable Members
/// <summary>
/// Reserve new objects in the object pool.
/// </summary>
/// <param name="count">The number of elements reserved in the object pool.</param>
private void AddObjects(int count)
{
#if !SILVERLIGHT
Log.Debug(string.Format("ObjectPool creating {0} pooled objects", count));
#endif
if (_forceGC)
GC.Collect();
if( _queue == null )
_queue = new Queue<T>(_capacity);
for (int i = 1; i <= count; i++)
{
T obj = GetObject();
_queue.Enqueue(obj);
}
if (_forceGC)
GC.Collect();
}
/// <summary>
/// Releases the object back to the object pool.
/// </summary>
/// <param name="obj">The object to check in.</param>
public void CheckIn(T obj)
{
if (IsDisposed)
throw new ObjectDisposedException("ObjectPool");
try
{
_lock.AcquireWriterLock();
if (_queue == null)
throw new InvalidOperationException("Invalid CheckIn operation");
_queue.Enqueue(obj);
}
finally
{
_lock.ReleaseWriterLock();
}
}
/// <summary>
/// Aquires an object from the object pool.
/// </summary>
/// <returns>An object from the object pool.</returns>
public T CheckOut()
{
if (IsDisposed)
throw new ObjectDisposedException("ObjectPool");
try
{
_lock.AcquireWriterLock();
if (_queue == null || _queue.Count == 0)
AddObjects(_growth);
return _queue.Dequeue();
}
finally
{
_lock.ReleaseWriterLock();
}
}
/// <summary>
/// Creates instances of the object pool element's class.
/// </summary>
/// <returns>A new object instance.</returns>
protected virtual T GetObject()
{
throw new NotImplementedException();
}
/// <summary>
/// Gets the length of the object pool.
/// </summary>
/// <value>The length of the object pool.</value>
protected int Length
{
get
{
if (IsDisposed)
throw new ObjectDisposedException("ObjectPool");
try
{
_lock.AcquireReaderLock();
return _queue != null ? _queue.Count : 0;
}
finally
{
_lock.ReleaseReaderLock();
}
}
}
/// <summary>
/// Gets the growth parameter of the object pool.
/// </summary>
/// <value>The growth parameter of the object pool.</value>
public int Growth
{
get
{
if (IsDisposed)
throw new ObjectDisposedException("ObjectPool");
return _growth;
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Test algorithm using a <see cref="ConstituentsUniverse"/> with test data
/// </summary>
public class ConstituentsUniverseRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private readonly Symbol _appl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
private readonly Symbol _spy = QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA);
private readonly Symbol _qqq = QuantConnect.Symbol.Create("QQQ", SecurityType.Equity, Market.USA);
private readonly Symbol _fb = QuantConnect.Symbol.Create("FB", SecurityType.Equity, Market.USA);
private int _step;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 07); //Set Start Date
SetEndDate(2013, 10, 11); //Set End Date
SetCash(100000); //Set Strategy Cash
UniverseSettings.Resolution = Resolution.Daily;
var customUniverseSymbol = new Symbol(SecurityIdentifier.GenerateConstituentIdentifier(
"constituents-universe-qctest",
SecurityType.Equity,
Market.USA),
"constituents-universe-qctest");
AddUniverse(new ConstituentsUniverse(customUniverseSymbol, UniverseSettings));
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
_step++;
if (_step == 1)
{
if (!data.ContainsKey(_qqq)
|| !data.ContainsKey(_appl))
{
throw new Exception($"Unexpected symbols found, step: {_step}");
}
if (data.Count != 2)
{
throw new Exception($"Unexpected data count, step: {_step}");
}
// AAPL will be deselected by the ConstituentsUniverse
// but it shouldn't be removed since we hold it
SetHoldings(_appl, 0.5);
}
else if (_step == 2)
{
if (!data.ContainsKey(_appl))
{
throw new Exception($"Unexpected symbols found, step: {_step}");
}
if (data.Count != 1)
{
throw new Exception($"Unexpected data count, step: {_step}");
}
// AAPL should now be released
// note: takes one extra loop because the order is executed on market open
Liquidate();
}
else if (_step == 3)
{
if (!data.ContainsKey(_fb)
|| !data.ContainsKey(_spy)
|| !data.ContainsKey(_appl))
{
throw new Exception($"Unexpected symbols found, step: {_step}");
}
if (data.Count != 3)
{
throw new Exception($"Unexpected data count, step: {_step}");
}
}
else if (_step == 4)
{
if (!data.ContainsKey(_fb)
|| !data.ContainsKey(_spy))
{
throw new Exception($"Unexpected symbols found, step: {_step}");
}
if (data.Count != 2)
{
throw new Exception($"Unexpected data count, step: {_step}");
}
}
else if (_step == 5)
{
if (!data.ContainsKey(_fb)
|| !data.ContainsKey(_spy))
{
throw new Exception($"Unexpected symbols found, step: {_step}");
}
if (data.Count != 2)
{
throw new Exception($"Unexpected data count, step: {_step}");
}
}
}
public override void OnEndOfAlgorithm()
{
if (_step != 5)
{
throw new Exception($"Unexpected step count: {_step}");
}
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
foreach (var added in changes.AddedSecurities)
{
Log($"AddedSecurities {added}");
}
foreach (var removed in changes.RemovedSecurities)
{
Log($"RemovedSecurities {removed} {_step}");
// we are currently notifying the removal of AAPl twice,
// when deselected and when finally removed (since it stayed pending)
if (removed.Symbol == _appl && _step != 1 && _step != 2
|| removed.Symbol == _qqq && _step != 1)
{
throw new Exception($"Unexpected removal step count: {_step}");
}
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.54%"},
{"Compounding Annual Return", "-32.671%"},
{"Drawdown", "0.900%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.540%"},
{"Sharpe Ratio", "-3.349"},
{"Probabilistic Sharpe Ratio", "25.715%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.724"},
{"Beta", "0.22"},
{"Annual Standard Deviation", "0.086"},
{"Annual Variance", "0.007"},
{"Information Ratio", "-12.125"},
{"Tracking Error", "0.187"},
{"Treynor Ratio", "-1.304"},
{"Total Fees", "$32.32"},
{"Estimated Strategy Capacity", "$95000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Fitness Score", "0.1"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-36.199"},
{"Portfolio Turnover", "0.2"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "3b9c93151bf191a82529e6e915961356"}
};
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryDivideTests
{
#region Test methods
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
public static void CheckByteDivideTest()
{
byte[] array = new byte[] { 0, 1, byte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyByteDivide(array[i], array[j]);
}
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
public static void CheckSByteDivideTest()
{
sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifySByteDivide(array[i], array[j]);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void CheckUShortDivideTest(bool useInterpreter)
{
ushort[] array = new ushort[] { 0, 1, ushort.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyUShortDivide(array[i], array[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void CheckShortDivideTest(bool useInterpreter)
{
short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyShortDivide(array[i], array[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void CheckUIntDivideTest(bool useInterpreter)
{
uint[] array = new uint[] { 0, 1, uint.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyUIntDivide(array[i], array[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void CheckIntDivideTest(bool useInterpreter)
{
int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyIntDivide(array[i], array[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void CheckULongDivideTest(bool useInterpreter)
{
ulong[] array = new ulong[] { 0, 1, ulong.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyULongDivide(array[i], array[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void CheckLongDivideTest(bool useInterpreter)
{
long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyLongDivide(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckFloatDivideTest(bool useInterpreter)
{
float[] array = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyFloatDivide(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDoubleDivideTest(bool useInterpreter)
{
double[] array = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyDoubleDivide(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDecimalDivideTest(bool useInterpreter)
{
decimal[] array = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyDecimalDivide(array[i], array[j], useInterpreter);
}
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
public static void CheckCharDivideTest()
{
char[] array = new char[] { '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyCharDivide(array[i], array[j]);
}
}
}
#endregion
#region Test verifiers
private static void VerifyByteDivide(byte a, byte b)
{
Expression aExp = Expression.Constant(a, typeof(byte));
Expression bExp = Expression.Constant(b, typeof(byte));
Assert.Throws<InvalidOperationException>(() => Expression.Divide(aExp, bExp));
}
private static void VerifySByteDivide(sbyte a, sbyte b)
{
Expression aExp = Expression.Constant(a, typeof(sbyte));
Expression bExp = Expression.Constant(b, typeof(sbyte));
Assert.Throws<InvalidOperationException>(() => Expression.Divide(aExp, bExp));
}
private static void VerifyUShortDivide(ushort a, ushort b, bool useInterpreter)
{
Expression<Func<ushort>> e =
Expression.Lambda<Func<ushort>>(
Expression.Divide(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(ushort))),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f = e.Compile(useInterpreter);
if (b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal((ushort)(a / b), f());
}
private static void VerifyShortDivide(short a, short b, bool useInterpreter)
{
Expression<Func<short>> e =
Expression.Lambda<Func<short>>(
Expression.Divide(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(short))),
Enumerable.Empty<ParameterExpression>());
Func<short> f = e.Compile(useInterpreter);
if (b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal(unchecked((short)(a / b)), f());
}
private static void VerifyUIntDivide(uint a, uint b, bool useInterpreter)
{
Expression<Func<uint>> e =
Expression.Lambda<Func<uint>>(
Expression.Divide(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(uint))),
Enumerable.Empty<ParameterExpression>());
Func<uint> f = e.Compile(useInterpreter);
if (b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal(a / b, f());
}
private static void VerifyIntDivide(int a, int b, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Divide(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
if (b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else if (b == -1 && a == int.MinValue)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(a / b, f());
}
private static void VerifyULongDivide(ulong a, ulong b, bool useInterpreter)
{
Expression<Func<ulong>> e =
Expression.Lambda<Func<ulong>>(
Expression.Divide(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(ulong))),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f = e.Compile(useInterpreter);
if (b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal(a / b, f());
}
private static void VerifyLongDivide(long a, long b, bool useInterpreter)
{
Expression<Func<long>> e =
Expression.Lambda<Func<long>>(
Expression.Divide(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(long))),
Enumerable.Empty<ParameterExpression>());
Func<long> f = e.Compile(useInterpreter);
if (b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else if (b == -1 && a == long.MinValue)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(a / b, f());
}
private static void VerifyFloatDivide(float a, float b, bool useInterpreter)
{
Expression<Func<float>> e =
Expression.Lambda<Func<float>>(
Expression.Divide(
Expression.Constant(a, typeof(float)),
Expression.Constant(b, typeof(float))),
Enumerable.Empty<ParameterExpression>());
Func<float> f = e.Compile(useInterpreter);
Assert.Equal(a / b, f());
}
private static void VerifyDoubleDivide(double a, double b, bool useInterpreter)
{
Expression<Func<double>> e =
Expression.Lambda<Func<double>>(
Expression.Divide(
Expression.Constant(a, typeof(double)),
Expression.Constant(b, typeof(double))),
Enumerable.Empty<ParameterExpression>());
Func<double> f = e.Compile(useInterpreter);
Assert.Equal(a / b, f());
}
private static void VerifyDecimalDivide(decimal a, decimal b, bool useInterpreter)
{
Expression<Func<decimal>> e =
Expression.Lambda<Func<decimal>>(
Expression.Divide(
Expression.Constant(a, typeof(decimal)),
Expression.Constant(b, typeof(decimal))),
Enumerable.Empty<ParameterExpression>());
Func<decimal> f = e.Compile(useInterpreter);
if (b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal(a / b, f());
}
private static void VerifyCharDivide(char a, char b)
{
Expression aExp = Expression.Constant(a, typeof(char));
Expression bExp = Expression.Constant(b, typeof(char));
Assert.Throws<InvalidOperationException>(() => Expression.Divide(aExp, bExp));
}
#endregion
[Fact]
public static void CannotReduce()
{
Expression exp = Expression.Divide(Expression.Constant(0), Expression.Constant(0));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
AssertExtensions.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void ThrowsOnLeftNull()
{
AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.Divide(null, Expression.Constant("")));
}
[Fact]
public static void ThrowsOnRightNull()
{
AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.Divide(Expression.Constant(""), null));
}
private static class Unreadable<T>
{
public static T WriteOnly
{
set { }
}
}
[Fact]
public static void ThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("left", () => Expression.Divide(value, Expression.Constant(1)));
}
[Fact]
public static void ThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("right", () => Expression.Divide(Expression.Constant(1), value));
}
[Fact]
public static void ToStringTest()
{
BinaryExpression e = Expression.Divide(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b"));
Assert.Equal("(a / b)", e.ToString());
}
}
}
| |
namespace Macabresoft.Macabre2D.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using Macabresoft.Core;
using Microsoft.Xna.Framework;
/// <summary>
/// Interface for a combination of <see cref="IUpdateableSystem" /> and <see cref="IEntity" />
/// which runs on a <see cref="IGame" />.
/// </summary>
public interface IScene : IUpdateableGameObject, IGridContainer {
/// <summary>
/// Gets the asset manager.
/// </summary>
IAssetManager Assets => AssetManager.Empty;
/// <summary>
/// Gets the cameras in the scene.
/// </summary>
/// <value>The cameras.</value>
IReadOnlyCollection<ICamera> Cameras => Array.Empty<ICamera>();
/// <summary>
/// Gets the game currently running this scene.
/// </summary>
/// <value>The game.</value>
IGame Game => BaseGame.Empty;
/// <summary>
/// Gets the named children.
/// </summary>
IReadOnlyCollection<INameableCollection> NamedChildren => Array.Empty<INameableCollection>();
/// <summary>
/// Gets the physics bodies.
/// </summary>
/// <value>The physics bodies.</value>
IReadOnlyCollection<IPhysicsBody> PhysicsBodies => Array.Empty<IPhysicsBody>();
/// <summary>
/// Gets the renderable entities in the scene.
/// </summary>
/// <value>The renderable entities.</value>
IReadOnlyCollection<IRenderableEntity> RenderableEntities => Array.Empty<IRenderableEntity>();
/// <summary>
/// Gets the systems.
/// </summary>
/// <value>The systems.</value>
IReadOnlyCollection<IUpdateableSystem> Systems => Array.Empty<IUpdateableSystem>();
/// <summary>
/// Gets the updateable entities.
/// </summary>
/// <value>The updateable entities.</value>
IReadOnlyCollection<IUpdateableEntity> UpdateableEntities => Array.Empty<IUpdateableEntity>();
/// <summary>
/// Gets or sets the color of the background.
/// </summary>
/// <value>The color of the background.</value>
Color BackgroundColor { get; set; }
/// <summary>
/// Gets or sets the version of this scene.
/// </summary>
Version Version { get; set; }
/// <summary>
/// Adds the system.
/// </summary>
/// <typeparam name="T">
/// A type that implements <see cref="IUpdateableSystem" /> and has an empty constructor.
/// </typeparam>
/// <returns>The added system.</returns>
T AddSystem<T>() where T : IUpdateableSystem, new();
/// <summary>
/// Adds the system.
/// </summary>
/// <param name="system">The system.</param>
void AddSystem(IUpdateableSystem system);
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="game">The game.</param>
/// <param name="assetManager">The asset manager.</param>
void Initialize(IGame game, IAssetManager assetManager);
/// <summary>
/// Invokes the specified action after the current update
/// </summary>
/// <param name="action">The action.</param>
void Invoke(Action action);
/// <summary>
/// Registers the entity with relevant services.
/// </summary>
/// <param name="entity">The entity.</param>
void RegisterEntity(IEntity entity);
/// <summary>
/// Removes the system.
/// </summary>
/// <param name="system">The system.</param>
/// <returns>A value indicating whether or not the system was removed.</returns>
bool RemoveSystem(IUpdateableSystem system);
/// <summary>
/// Renders the scene.
/// </summary>
/// <param name="frameTime">The frame time.</param>
/// <param name="inputState">The input state.</param>
public void Render(FrameTime frameTime, InputState inputState);
/// <summary>
/// Resolves the dependency.
/// </summary>
/// <typeparam name="T">The type of the dependency.</typeparam>
/// <returns>The dependency if it already exists or a newly created dependency.</returns>
T ResolveDependency<T>() where T : new();
/// <summary>
/// Resolves the dependency.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="objectFactory">The object factory.</param>
/// <returns>
/// The dependency if it already exists or a dependency created from the provided factory.
/// </returns>
T ResolveDependency<T>(Func<T> objectFactory) where T : class;
/// <summary>
/// Unregisters the entity from services.
/// </summary>
/// <param name="entity">The entity.</param>
void UnregisterEntity(IEntity entity);
}
/// <summary>
/// A user-created combination of <see cref="IUpdateableSystem" /> and <see cref="IEntity" />
/// which runs on a <see cref="IGame" />.
/// </summary>
public sealed class Scene : GridContainer, IScene {
/// <summary>
/// The default empty <see cref="IScene" /> that is present before initialization.
/// </summary>
public new static readonly IScene Empty = new EmptyScene();
private readonly HashSet<IEntity> _allEntitiesInScene = new();
private readonly FilterSortCollection<ICamera> _cameras = new(
c => c.IsEnabled,
nameof(IEnableable.IsEnabled),
(c1, c2) => Comparer<int>.Default.Compare(c1.RenderOrder, c2.RenderOrder),
nameof(ICamera.RenderOrder));
private readonly Dictionary<Type, object> _dependencies = new();
private readonly List<INameableCollection> _namedChildren = new();
private readonly List<Action> _pendingActions = new();
private readonly FilterSortCollection<IPhysicsBody> _physicsBodies = new(
r => r.IsEnabled,
nameof(IEnableable.IsEnabled),
(r1, r2) => Comparer<int>.Default.Compare(r1.UpdateOrder, r2.UpdateOrder),
nameof(IPhysicsBody.UpdateOrder));
private readonly FilterSortCollection<IRenderableEntity> _renderableEntities = new(
c => c.IsVisible,
nameof(IRenderableEntity.IsVisible),
(c1, c2) => Comparer<int>.Default.Compare(c1.RenderOrder, c2.RenderOrder),
nameof(IRenderableEntity.RenderOrder));
[DataMember]
private readonly SystemCollection _systems = new();
private readonly FilterSortCollection<IUpdateableEntity> _updateableEntities = new(
c => c.IsEnabled,
nameof(IUpdateableEntity.IsEnabled),
(c1, c2) => Comparer<int>.Default.Compare(c1.UpdateOrder, c2.UpdateOrder),
nameof(IUpdateableEntity.UpdateOrder));
private Color _backgroundColor = DefinedColors.MacabresoftBlack;
private bool _isBusy;
private bool _isInitialized;
private Version _version = new(0, 0, 0, 0);
/// <summary>
/// Initializes a new instance of the <see cref="Scene" /> class.
/// </summary>
public Scene() : base() {
this._namedChildren.Add(this._systems);
if (this.Children is INameableCollection nameableCollection) {
this._namedChildren.Add(nameableCollection);
}
}
/// <inheritdoc />
public IReadOnlyCollection<ICamera> Cameras => this._cameras;
/// <inheritdoc />
public IReadOnlyCollection<INameableCollection> NamedChildren => this._namedChildren;
/// <inheritdoc />
public IReadOnlyCollection<IPhysicsBody> PhysicsBodies => this._physicsBodies;
/// <inheritdoc />
public IReadOnlyCollection<IRenderableEntity> RenderableEntities => this._renderableEntities;
/// <inheritdoc />
public IReadOnlyCollection<IUpdateableSystem> Systems => this._systems;
/// <inheritdoc />
public IReadOnlyCollection<IUpdateableEntity> UpdateableEntities => this._updateableEntities;
/// <inheritdoc />
public IAssetManager Assets { get; private set; } = AssetManager.Empty;
/// <inheritdoc />
[DataMember]
public Color BackgroundColor {
get => this._backgroundColor;
set => this.Set(ref this._backgroundColor, value);
}
/// <inheritdoc />
public IGame Game { get; private set; } = BaseGame.Empty;
/// <inheritdoc />
[DataMember]
public Version Version {
get => this._version;
set => this.Set(ref this._version, value);
}
/// <inheritdoc />
public T AddSystem<T>() where T : IUpdateableSystem, new() {
var system = new T();
this.AddSystem(system);
return system;
}
/// <inheritdoc />
public void AddSystem(IUpdateableSystem system) {
this._systems.Add(system);
if (this._isInitialized) {
system.Initialize(this);
}
}
/// <inheritdoc />
public void Initialize(IGame game, IAssetManager assetManager) {
if (!this._isInitialized) {
try {
this._isBusy = true;
this.Assets = assetManager;
this.Game = game;
this.Initialize(this, this);
foreach (var system in this.Systems) {
system.Initialize(this);
}
}
finally {
this._isInitialized = true;
this._isBusy = false;
}
this.InvokePendingActions();
}
}
/// <inheritdoc />
public void Invoke(Action action) {
if (this._isBusy) {
this._pendingActions.Add(action);
}
else {
action();
}
}
/// <summary>
/// Determines whether the specified scene is null or <see cref="Scene.Empty" />.
/// </summary>
/// <param name="scene">The scene.</param>
/// <returns>
/// <c>true</c> if the specified scene is null or <see cref="Scene.Empty" />; otherwise, <c>false</c>.
/// </returns>
public static bool IsNullOrEmpty(IScene? scene) {
return scene == null || scene == Empty;
}
/// <inheritdoc />
public void RegisterEntity(IEntity entity) {
this._allEntitiesInScene.Add(entity);
this._cameras.Add(entity);
this._physicsBodies.Add(entity);
this._renderableEntities.Add(entity);
this._updateableEntities.Add(entity);
}
/// <inheritdoc />
public bool RemoveSystem(IUpdateableSystem system) {
var result = false;
if (this._systems.Contains(system)) {
this.Invoke(() => this._systems.Remove(system));
result = true;
}
return result;
}
/// <inheritdoc />
public void Render(FrameTime frameTime, InputState inputState) {
try {
this._isBusy = true;
foreach (var system in this.Systems.Where(x => x.IsEnabled && x.Loop == SystemLoop.Render)) {
system.Update(frameTime, inputState);
}
}
finally {
this._isBusy = false;
}
}
/// <inheritdoc />
public T ResolveDependency<T>() where T : new() {
if (this._dependencies.TryGetValue(typeof(T), out var dependency)) {
return (T)dependency;
}
dependency = new T();
this._dependencies.Add(typeof(T), dependency);
return (T)dependency;
}
/// <inheritdoc />
public T ResolveDependency<T>(Func<T> objectFactory) where T : class {
if (this._dependencies.TryGetValue(typeof(T), out var found) && found is T dependency) {
return dependency;
}
dependency = objectFactory.SafeInvoke();
this._dependencies.Add(typeof(T), dependency);
return dependency;
}
/// <inheritdoc />
public override bool TryGetParentEntity<T>(out T? entity) where T : class {
entity = null;
return false;
}
/// <inheritdoc />
public void UnregisterEntity(IEntity entity) {
this._allEntitiesInScene.Remove(entity);
this._cameras.Remove(entity);
this._physicsBodies.Remove(entity);
this._renderableEntities.Remove(entity);
this._updateableEntities.Remove(entity);
}
/// <inheritdoc />
public void Update(FrameTime frameTime, InputState inputState) {
try {
this._isBusy = true;
this.InvokePendingActions();
foreach (var system in this.Systems.Where(x => x.IsEnabled && x.Loop == SystemLoop.Update)) {
system.Update(frameTime, inputState);
}
}
finally {
this._isBusy = false;
}
}
/// <inheritdoc />
protected override void OnDisposing() {
base.OnDisposing();
this.Assets.Dispose();
}
private void InvokePendingActions() {
var actions = this._pendingActions.ToList();
foreach (var action in actions) {
action();
this._pendingActions.Remove(action);
}
}
private class EmptyScene : EmptyGridContainer, IScene {
/// <inheritdoc />
public Color BackgroundColor {
get => Color.HotPink;
set { }
}
/// <inheritdoc />
public Version Version { get; set; } = new();
/// <inheritdoc />
public T AddSystem<T>() where T : IUpdateableSystem, new() {
return new T();
}
/// <inheritdoc />
public void AddSystem(IUpdateableSystem service) {
}
/// <inheritdoc />
public void Initialize(IGame gameLoop, IAssetManager assetManager) {
}
/// <inheritdoc />
public void Invoke(Action action) {
}
/// <inheritdoc />
public void RegisterEntity(IEntity entity) {
}
/// <inheritdoc />
public bool RemoveSystem(IUpdateableSystem service) {
return false;
}
/// <inheritdoc />
public void Render(FrameTime frameTime, InputState inputState) {
}
/// <inheritdoc />
public T ResolveDependency<T>() where T : new() {
return new T();
}
/// <inheritdoc />
public T ResolveDependency<T>(Func<T> objectFactory) where T : class {
return objectFactory.SafeInvoke();
}
/// <inheritdoc />
public void UnregisterEntity(IEntity entity) {
}
/// <inheritdoc />
public void Update(FrameTime frameTime, InputState inputState) {
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using JetBrains.Annotations;
using JetBrains.Diagnostics;
using JetBrains.Rider.Unity.Editor.NonUnity;
using UnityEditor;
using UnityEngine;
namespace JetBrains.Rider.Unity.Editor.AssetPostprocessors
{
public class CsprojAssetPostprocessor : AssetPostprocessor
{
private static readonly ILog ourLogger = Log.GetLog<CsprojAssetPostprocessor>();
private const string UnityUnsafeKeyword = "-unsafe";
private const string UnityDefineKeyword = "-define:";
private const string UnityReferenceKeyword = "-r:";
private static readonly string ourProjectManualConfigRoslynFilePath = Path.GetFullPath("Assets/csc.rsp");
private static readonly string ourProjectManualConfigFilePath = Path.GetFullPath("Assets/mcs.rsp");
private static readonly string ourPlayerProjectManualConfigFilePath = Path.GetFullPath("Assets/smcs.rsp");
private static readonly string ourEditorProjectManualConfigFilePath = Path.GetFullPath("Assets/gmcs.rsp");
private static int? ourApiCompatibilityLevel;
private static int OurApiCompatibilityLevel
{
get
{
if (ourApiCompatibilityLevel == null)
ourApiCompatibilityLevel = GetApiCompatibilityLevel();
return (int) ourApiCompatibilityLevel;
}
}
private const int APICompatibilityLevelNet20Subset = 2;
private const int APICompatibilityLevelNet46 = 3;
// Note that this does not affect the order in which postprocessors are evaluated. Order of execution is undefined.
// https://github.com/Unity-Technologies/UnityCsReference/blob/2018.2/Editor/Mono/AssetPostprocessor.cs#L152
public override int GetPostprocessOrder()
{
return 10;
}
// This method is new for 2018.1. It allows multiple processors to modify the contents of the generated .csproj in
// memory, and Unity will only write to disk if it's different to the existing file. It's safe for pre-2018.1 as it
// simply won't get called https://github.com/Unity-Technologies/UnityCsReference/blob/2018.1/Editor/Mono/AssetPostprocessor.cs#L76
// ReSharper disable once InconsistentNaming
[UsedImplicitly]
public static string OnGeneratedCSProject(string path, string contents)
{
if (UnityUtils.IsInBatchModeAndNotInRiderTests)
return contents;
try
{
ourLogger.Verbose("Post-processing {0} (in memory)", path);
var doc = XDocument.Parse(contents);
if (UpgradeProjectFile(path, doc))
{
ourLogger.Verbose("Post-processed with changes {0} (in memory)", path);
using (var sw = new Utf8StringWriter())
{
doc.Save(sw);
return sw.ToString(); // https://github.com/JetBrains/resharper-unity/issues/727
}
}
ourLogger.Verbose("Post-processed with NO changes {0}", path);
return contents;
}
catch (Exception e)
{
// unhandled exception kills editor
Debug.LogError(e);
return contents;
}
}
// This method is for pre-2018.1, and is called after the file has been written to disk
public static void OnGeneratedCSProjectFiles()
{
if (UnityUtils.IsInBatchModeAndNotInRiderTests)
return;
if (UnityUtils.UnityVersion >= new Version(2018, 1))
return;
try
{
ourLogger.Verbose("Post-processing {0} (old version)");
// get only csproj files, which are mentioned in sln
var lines = SlnAssetPostprocessor.GetCsprojLinesInSln();
var currentDirectory = Directory.GetCurrentDirectory();
var projectFiles = Directory.GetFiles(currentDirectory, "*.csproj")
.Where(csprojFile => lines.Any(line => line.Contains("\"" + Path.GetFileName(csprojFile) + "\""))).ToArray();
foreach (var file in projectFiles)
{
UpgradeProjectFile(file);
}
}
catch (Exception e)
{
// unhandled exception kills editor
Debug.LogError(e);
}
}
private static void UpgradeProjectFile(string projectFile)
{
ourLogger.Verbose("Post-processing {0}", projectFile);
XDocument doc;
try
{
doc = XDocument.Load(projectFile);
}
catch (Exception)
{
ourLogger.Verbose("Failed to Load {0}", projectFile);
return;
}
if (UpgradeProjectFile(projectFile, doc))
{
ourLogger.Verbose("Post-processed with changes {0}ss", projectFile);
doc.Save(projectFile);
return;
}
ourLogger.Verbose("Post-processed with NO changes {0}", projectFile);
}
private static bool UpgradeProjectFile(string projectFile, XDocument doc)
{
var projectContentElement = doc.Root;
XNamespace xmlns = projectContentElement.Name.NamespaceName; // do not use var
var changed = FixTargetFrameworkVersion(projectContentElement, xmlns); // no need for new Unity
changed |= FixUnityEngineReference(projectContentElement, xmlns); // no need for new Unity
changed |= FixSystemXml(projectContentElement, xmlns); // hopefully not needed
changed |= SetLangVersion(projectContentElement, xmlns); // reimplemented in package
changed |= SetProjectFlavour(projectContentElement, xmlns); // hopefully not needed
changed |= SetManuallyDefinedCompilerSettings(projectFile, projectContentElement, xmlns); // hopefully not needed
changed |= TrySetHintPathsForSystemAssemblies(projectContentElement, xmlns); // no need for new Unity
changed |= FixImplicitReferences(projectContentElement, xmlns); // no need for new Unity
changed |= AvoidGetReferenceAssemblyPathsCall(projectContentElement, xmlns); // reimplemeted
changed |= AddMicrosoftCSharpReference(projectContentElement, xmlns); // not needed
changed |= SetXCodeDllReference("UnityEditor.iOS.Extensions.Xcode.dll", projectContentElement, xmlns);
changed |= SetXCodeDllReference("UnityEditor.iOS.Extensions.Common.dll", projectContentElement, xmlns);
changed |= SetDisableHandlePackageFileConflicts(projectContentElement, xmlns); // already exists
changed |= SetGenerateTargetFrameworkAttribute(projectContentElement, xmlns); // no need
return changed;
}
/* Since Unity 2018.1.5f1 it looks like this:
<PropertyGroup>
<NoConfig>true</NoConfig>
<NoStdLib>true</NoStdLib>
<AddAdditionalExplicitAssemblyReferences>false</AddAdditionalExplicitAssemblyReferences>
<ImplicitlyExpandNETStandardFacades>false</ImplicitlyExpandNETStandardFacades>
<ImplicitlyExpandDesignTimeFacades>false</ImplicitlyExpandDesignTimeFacades>
</PropertyGroup>
*/
// https://github.com/JetBrains/resharper-unity/issues/988
private static bool FixImplicitReferences(XElement projectContentElement, XNamespace xmlns)
{
var changed = false;
// For Unity 2017.x, we are adding tags and reference to mscorlib
if (UnityUtils.UnityVersion.Major == 2017)
{
// appears in Unity 2018.1.0b10
SetOrUpdateProperty(projectContentElement, xmlns, "NoConfig", existing => "true");
SetOrUpdateProperty(projectContentElement, xmlns, "NoStdLib", existing => "true");
SetOrUpdateProperty(projectContentElement, xmlns, "AddAdditionalExplicitAssemblyReferences",existing => "false");
// Unity 2018.x+ itself adds mscorlib reference
var referenceName = "mscorlib.dll";
var hintPath = GetHintPath(referenceName);
AddCustomReference(referenceName, projectContentElement, xmlns, hintPath);
changed = true;
}
if (UnityUtils.UnityVersion.Major == 2017 || UnityUtils.UnityVersion.Major == 2018)
{
// appears in Unity 2018.1.5f1
changed |= SetOrUpdateProperty(projectContentElement, xmlns, "ImplicitlyExpandNETStandardFacades",existing => "false");
changed |= SetOrUpdateProperty(projectContentElement, xmlns, "ImplicitlyExpandDesignTimeFacades",existing => "false");
}
return changed;
}
// Computer may not have specific TargetFramework, msbuild will resolve System from different TargetFramework
// If we set HintPaths together with DisableHandlePackageFileConflicts we help msbuild to resolve libs from Unity installation
// Unity 2018+ already have HintPaths by default
private static bool TrySetHintPathsForSystemAssemblies(XElement projectContentElement, XNamespace xmlns)
{
var elementsToUpdate = projectContentElement
.Elements(xmlns+"ItemGroup")
.Elements(xmlns+"Reference")
.Where(a => a.Attribute("Include") != null && a.Elements(xmlns + "HintPath").SingleOrDefault() == null)
.ToArray();
foreach (var element in elementsToUpdate)
{
var referenceName = element.Attribute("Include").Value + ".dll";
var hintPath = GetHintPath(referenceName);
AddCustomReference(referenceName, projectContentElement, xmlns, hintPath);
}
if (elementsToUpdate.Any())
{
elementsToUpdate.Remove();
return true;
}
return false;
}
private static bool SetGenerateTargetFrameworkAttribute(XElement projectContentElement, XNamespace xmlns)
{
//https://youtrack.jetbrains.com/issue/RIDER-17390
if (UnityUtils.ScriptingRuntime > 0)
return false;
return SetOrUpdateProperty(projectContentElement, xmlns, "GenerateTargetFrameworkAttribute", existing => "false");
}
private static bool AddMicrosoftCSharpReference (XElement projectContentElement, XNamespace xmlns)
{
string referenceName = "Microsoft.CSharp.dll";
if (UnityUtils.ScriptingRuntime == 0)
return false;
if (OurApiCompatibilityLevel != APICompatibilityLevelNet46)
return false;
var hintPath = GetHintPath(referenceName);
AddCustomReference(referenceName, projectContentElement, xmlns, hintPath);
return true;
}
private static bool AvoidGetReferenceAssemblyPathsCall(XElement projectContentElement, XNamespace xmlns)
{
// Starting with Unity 2017, dotnet target pack is not required
if (UnityUtils.UnityVersion.Major < 2017)
return false;
// Set _TargetFrameworkDirectories and _FullFrameworkReferenceAssemblyPaths to something to avoid GetReferenceAssemblyPaths task being called
return SetOrUpdateProperty(projectContentElement, xmlns, "_TargetFrameworkDirectories",
existing => string.IsNullOrEmpty(existing) ? "non_empty_path_generated_by_rider_editor_plugin" : existing)
&&
SetOrUpdateProperty(projectContentElement, xmlns, "_FullFrameworkReferenceAssemblyPaths",
existing => string.IsNullOrEmpty(existing) ? "non_empty_path_generated_by_rider_editor_plugin" : existing);
}
private static bool SetDisableHandlePackageFileConflicts(XElement projectContentElement, XNamespace xmlns)
{
// https://developercommunity.visualstudio.com/content/problem/138986/1550-preview-2-breaks-scriptsharp-compilation.html
// RIDER-18316 Rider fails to resolve mscorlib
return SetOrUpdateProperty(projectContentElement, xmlns, "DisableHandlePackageFileConflicts", existing => "true");
}
private static bool FixSystemXml(XElement projectContentElement, XNamespace xmlns)
{
var el = projectContentElement
.Elements(xmlns+"ItemGroup")
.Elements(xmlns+"Reference")
.FirstOrDefault(a => a.Attribute("Include") !=null && a.Attribute("Include").Value=="System.XML");
if (el != null)
{
el.Attribute("Include").Value = "System.Xml";
return true;
}
return false;
}
private static bool SetManuallyDefinedCompilerSettings(string projectFile, XElement projectContentElement, XNamespace xmlns)
{
var configPath = GetConfigPath(projectFile);
return ApplyManualCompilerSettings(configPath, projectContentElement, xmlns);
}
[CanBeNull]
private static string GetConfigPath(string projectFile)
{
// First choice - prefer csc.rsp if it exists
if (File.Exists(ourProjectManualConfigRoslynFilePath))
return ourProjectManualConfigRoslynFilePath;
// Second choice - prefer mcs.rsp if it exists
if (File.Exists(ourProjectManualConfigFilePath))
return ourProjectManualConfigFilePath;
var filename = Path.GetFileName(projectFile);
if (filename == "Assembly-CSharp.csproj")
return ourPlayerProjectManualConfigFilePath;
if (filename == "Assembly-CSharp-Editor.csproj")
return ourEditorProjectManualConfigFilePath;
return null;
}
private static bool ApplyManualCompilerSettings([CanBeNull] string configFilePath, XElement projectContentElement, XNamespace xmlns)
{
if (string.IsNullOrEmpty(configFilePath) || !File.Exists(configFilePath))
return false;
var configText = File.ReadAllText(configFilePath);
var isUnity20171OrLater = UnityUtils.UnityVersion >= new Version(2017, 1);
var changed = false;
// Unity sets AllowUnsafeBlocks in 2017.1+ depending on Player settings or asmdef
// Strictly necessary to compile unsafe code
// https://github.com/Unity-Technologies/UnityCsReference/blob/2017.1/Editor/Mono/VisualStudioIntegration/SolutionSynchronizationSettings.cs#L119
if (configText.Contains(UnityUnsafeKeyword) && !isUnity20171OrLater)
{
changed |= ApplyAllowUnsafeBlocks(projectContentElement, xmlns);
}
// Unity natively handles this in 2017.1+
// https://github.com/Unity-Technologies/UnityCsReference/blob/33cbfe062d795667c39e16777230e790fcd4b28b/Editor/Mono/VisualStudioIntegration/SolutionSynchronizer.cs#L191
// Also note that we don't support the short "-d" form. Neither does Unity
if (configText.Contains(UnityDefineKeyword) && !isUnity20171OrLater)
{
// defines could be
// 1) -define:DEFINE1,DEFINE2
// 2) -define:DEFINE1;DEFINE2
// 3) -define:DEFINE1 -define:DEFINE2
// 4) -define:DEFINE1,DEFINE2;DEFINE3
// tested on "-define:DEF1;DEF2 -define:DEF3,DEF4;DEFFFF \n -define:DEF5"
// result: DEF1, DEF2, DEF3, DEF4, DEFFFF, DEF5
var definesList = new List<string>();
var compileFlags = configText.Split(' ', '\n');
foreach (var flag in compileFlags)
{
var f = flag.Trim();
if (f.Contains(UnityDefineKeyword))
{
var defineEndPos = f.IndexOf(UnityDefineKeyword) + UnityDefineKeyword.Length;
var definesSubString = f.Substring(defineEndPos, f.Length - defineEndPos);
definesSubString = definesSubString.Replace(";", ",");
definesList.AddRange(definesSubString.Split(','));
}
}
changed |= ApplyCustomDefines(definesList.ToArray(), projectContentElement, xmlns);
}
// Note that this doesn't handle the long version "-reference:"
if (configText.Contains(UnityReferenceKeyword))
{
changed |= ApplyManualCompilerSettingsReferences(projectContentElement, xmlns, configText);
}
return changed;
}
private static bool ApplyCustomDefines(string[] customDefines, XElement projectContentElement, XNamespace xmlns)
{
var definesString = string.Join(";", customDefines);
var defineConstants = projectContentElement
.Elements(xmlns+"PropertyGroup")
.Elements(xmlns+"DefineConstants")
.FirstOrDefault(definesConsts=> !string.IsNullOrEmpty(definesConsts.Value));
defineConstants?.SetValue(defineConstants.Value + ";" + definesString);
return true;
}
private static bool ApplyAllowUnsafeBlocks(XElement projectContentElement, XNamespace xmlns)
{
projectContentElement.AddFirst(
new XElement(xmlns + "PropertyGroup", new XElement(xmlns + "AllowUnsafeBlocks", true)));
return true;
}
private static bool SetXCodeDllReference(string name, XElement projectContentElement, XNamespace xmlns)
{
// C:\Program Files\Unity\Editor\Data\PlaybackEngines\iOSSupport\
var unityAppBaseDataFolder = Path.GetFullPath(EditorApplication.applicationContentsPath);
var folders = new List<string> { unityAppBaseDataFolder};
// https://github.com/JetBrains/resharper-unity/issues/841
// /Applications/Unity/Hub/Editor/2018.2.10f1/PlaybackEngines/iOSSupport/
var directoryInfo = new FileInfo(EditorApplication.applicationPath).Directory;
if (directoryInfo != null)
folders.Add(directoryInfo.FullName);
var xcodeDllPath = folders
.Select(folder => Path.Combine(folder, Path.Combine("PlaybackEngines/iOSSupport", name)))
.Where(File.Exists).FirstOrDefault();
if (string.IsNullOrEmpty(xcodeDllPath))
return false;
AddCustomReference(Path.GetFileNameWithoutExtension(xcodeDllPath), projectContentElement, xmlns, xcodeDllPath);
return true;
}
private static bool FixUnityEngineReference(XElement projectContentElement, XNamespace xmlns)
{
// Handled natively by Unity 2018.2+
if (UnityUtils.UnityVersion >= new Version(2018, 2))
return false;
var unityAppBaseFolder = Path.GetDirectoryName(EditorApplication.applicationPath);
if (string.IsNullOrEmpty(unityAppBaseFolder))
{
ourLogger.Verbose("FixUnityEngineReference. unityAppBaseFolder IsNullOrEmpty");
return false;
}
var el = projectContentElement
.Elements(xmlns+"ItemGroup")
.Elements(xmlns+"Reference")
.FirstOrDefault(a => a.Attribute("Include") !=null && a.Attribute("Include").Value=="UnityEngine");
var hintPath = el?.Elements(xmlns + "HintPath").FirstOrDefault();
if (hintPath == null)
return false;
var oldUnityEngineDllFileInfo = new FileInfo(hintPath.Value);
var unityEngineDir = new DirectoryInfo(Path.Combine(oldUnityEngineDllFileInfo.Directory.FullName, "UnityEngine"));
if (!unityEngineDir.Exists)
return false;
var newDllPath = Path.Combine(unityEngineDir.FullName, "UnityEngine.dll");
if (!File.Exists(newDllPath))
return false;
hintPath.SetValue(newDllPath);
var files = unityEngineDir.GetFiles("*.dll");
foreach (var file in files)
{
AddCustomReference(Path.GetFileNameWithoutExtension(file.Name), projectContentElement, xmlns, file.FullName);
}
return true;
}
private static bool ApplyManualCompilerSettingsReferences(XElement projectContentElement, XNamespace xmlns, string configText)
{
var referenceList = new List<string>();
var compileFlags = configText.Split(' ', '\n');
foreach (var flag in compileFlags)
{
var f = flag.Trim();
if (f.Contains(UnityReferenceKeyword))
{
var defineEndPos = f.IndexOf(UnityReferenceKeyword) + UnityReferenceKeyword.Length;
var definesSubString = f.Substring(defineEndPos, f.Length - defineEndPos);
definesSubString = definesSubString.Replace(";", ",");
referenceList.AddRange(definesSubString.Split(','));
}
}
foreach (var reference in referenceList)
{
var name = reference.Trim().TrimStart('"').TrimEnd('"');
var nameFileInfo = new FileInfo(name);
if (nameFileInfo.Extension.ToLower() != ".dll")
name += ".dll"; // RIDER-15093
string hintPath;
if (!nameFileInfo.Exists)
hintPath = GetHintPath(name);
else
hintPath = nameFileInfo.FullName;
AddCustomReference(name, projectContentElement, xmlns, hintPath);
}
return true;
}
[CanBeNull]
private static string GetHintPath(string name)
{
// Without HintPath non-Unity MSBuild will resolve assembly from DotNetFramework targets path
string hintPath = null;
var unityAppBaseFolder = Path.GetFullPath(EditorApplication.applicationContentsPath);
var monoDir = new DirectoryInfo(Path.Combine(unityAppBaseFolder, "MonoBleedingEdge/lib/mono"));
if (!monoDir.Exists)
monoDir = new DirectoryInfo(Path.Combine(unityAppBaseFolder, "Data/MonoBleedingEdge/lib/mono"));
var mask = "4.*";
if (UnityUtils.ScriptingRuntime == 0)
{
mask = "2.*"; // 1 = ApiCompatibilityLevel.NET_2_0
if (OurApiCompatibilityLevel == APICompatibilityLevelNet20Subset) // ApiCompatibilityLevel.NET_2_0_Subset
mask = "unity";
}
if (!monoDir.Exists)
return null;
var apiDir = monoDir.GetDirectories(mask).LastOrDefault(); // take newest
if (apiDir != null)
{
var dllPath = new FileInfo(Path.Combine(apiDir.FullName, name));
if (dllPath.Exists)
hintPath = dllPath.FullName;
}
return hintPath;
}
private static void AddCustomReference(string name, XElement projectContentElement, XNamespace xmlns, string hintPath = null)
{
ourLogger.Verbose($"AddCustomReference {name}, {hintPath}");
var itemGroup = projectContentElement.Elements(xmlns + "ItemGroup").FirstOrDefault();
if (itemGroup == null)
{
ourLogger.Verbose("Skip AddCustomReference, ItemGroup is null.");
return;
}
var reference = new XElement(xmlns + "Reference");
reference.Add(new XAttribute("Include", Path.GetFileNameWithoutExtension(name)));
if (!string.IsNullOrEmpty(hintPath))
reference.Add(new XElement(xmlns + "HintPath", hintPath));
itemGroup.Add(reference);
}
// Set appropriate version
private static bool FixTargetFrameworkVersion(XElement projectElement, XNamespace xmlns)
{
return SetOrUpdateProperty(projectElement, xmlns, "TargetFrameworkVersion", s =>
{
if (UnityUtils.ScriptingRuntime > 0)
{
if (PluginSettings.OverrideTargetFrameworkVersion)
{
return "v" + PluginSettings.TargetFrameworkVersion;
}
}
else
{
if (PluginSettings.OverrideTargetFrameworkVersionOldMono)
{
return "v" + PluginSettings.TargetFrameworkVersionOldMono;
}
}
if (string.IsNullOrEmpty(s))
{
ourLogger.Verbose("TargetFrameworkVersion in csproj is null or empty.");
return string.Empty;
}
var version = string.Empty;
try
{
version = s.Substring(1);
// for windows try to use installed dotnet framework
// Unity 2018.1 doesn't require installed dotnet framework, it references everything from Unity installation
if (PluginSettings.SystemInfoRiderPlugin.operatingSystemFamily == OperatingSystemFamilyRider.Windows && UnityUtils.UnityVersion < new Version(2018, 1))
{
var versions = PluginSettings.GetInstalledNetFrameworks();
if (versions.Any())
{
var versionOrderedList = versions.OrderBy(v1 => new Version(v1));
var foundVersion = UnityUtils.ScriptingRuntime > 0
? versionOrderedList.Last()
: versionOrderedList.First();
// Unity may require dotnet 4.7.1, which may not be present
var fvIsParsed = VersionExtensions.TryParse(foundVersion, out var fv);
var vIsParsed = VersionExtensions.TryParse(version, out var v);
if (fvIsParsed && vIsParsed && (UnityUtils.ScriptingRuntime == 0 || UnityUtils.ScriptingRuntime > 0 && fv > v))
version = foundVersion;
else if (foundVersion == version)
ourLogger.Verbose("Found TargetFrameworkVersion {0} equals the one set-by-Unity itself {1}",
foundVersion, version);
else if (ourLogger.IsVersboseEnabled())
{
var message = $"Rider may require \".NET Framework {version} Developer Pack\", which is not installed.";
Debug.Log(message);
}
}
}
}
catch (Exception e)
{
ourLogger.Log(LoggingLevel.WARN, "Fail to FixTargetFrameworkVersion", e);
}
return "v" + version;
}
);
}
private static bool SetLangVersion(XElement projectElement, XNamespace xmlns)
{
// Set the C# language level, so Rider doesn't have to guess (although it does a good job)
// VSTU sets this, and I think newer versions of Unity do too (should check which version)
return SetOrUpdateProperty(projectElement, xmlns, "LangVersion", existing =>
{
if (PluginSettings.OverrideLangVersion)
{
return PluginSettings.LangVersion;
}
var expected = GetExpectedLanguageLevel();
if (string.IsNullOrEmpty(existing))
return expected;
if (existing == "default")
return expected;
if (expected == "latest" || existing == "latest")
return "latest";
// Only use our version if it's not already set, or it's less than what we would set
var currentIsParsed = VersionExtensions.TryParse(existing, out var currentLanguageLevel);
var expectedIsParsed = VersionExtensions.TryParse(expected, out var expectedLanguageLevel);
if (currentIsParsed && expectedIsParsed && currentLanguageLevel < expectedLanguageLevel)
{
return expected;
}
return existing;
});
}
private static string GetExpectedLanguageLevel()
{
// https://bitbucket.org/alexzzzz/unity-c-5.0-and-6.0-integration/src
if (Directory.Exists(Path.GetFullPath("CSharp70Support")))
return "latest";
if (Directory.Exists(Path.GetFullPath("CSharp60Support")))
return "6";
// Unity 5.5+ supports C# 6, but only when targeting .NET 4.6. The enum doesn't exist pre Unity 5.5
if (OurApiCompatibilityLevel >= APICompatibilityLevelNet46)
return "6";
return "4";
}
private static int GetApiCompatibilityLevel()
{
var apiCompatibilityLevel = 0;
try
{
//PlayerSettings.GetApiCompatibilityLevel(EditorUserBuildSettings.selectedBuildTargetGroup)
var method = typeof(PlayerSettings).GetMethod("GetApiCompatibilityLevel");
var parameter = typeof(EditorUserBuildSettings).GetProperty("selectedBuildTargetGroup");
var val = parameter.GetValue(null, null);
apiCompatibilityLevel = (int) method.Invoke(null, new[] {val});
}
catch (Exception ex)
{
ourLogger.Verbose(
"Exception on evaluating PlayerSettings.GetApiCompatibilityLevel(EditorUserBuildSettings.selectedBuildTargetGroup)" +
ex);
}
try
{
var property = typeof(PlayerSettings).GetProperty("apiCompatibilityLevel");
apiCompatibilityLevel = (int) property.GetValue(null, null);
}
catch (Exception)
{
ourLogger.Verbose("Exception on evaluating PlayerSettings.apiCompatibilityLevel");
}
return apiCompatibilityLevel;
}
private static bool SetProjectFlavour(XElement projectElement, XNamespace xmlns)
{
// This is the VSTU project flavour GUID, followed by the C# project type
return SetOrUpdateProperty(projectElement, xmlns, "ProjectTypeGuids",
"{E097FAD1-6243-4DAD-9C02-E9B9EFC3FFC1};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}");
}
private static bool SetOrUpdateProperty(XElement root, XNamespace xmlns, string name, string content)
{
return SetOrUpdateProperty(root, xmlns, name, v => content);
}
private static bool SetOrUpdateProperty(XElement root, XNamespace xmlns, string name, Func<string, string> updater)
{
var elements = root.Elements(xmlns + "PropertyGroup").Elements(xmlns + name).ToList();
if (elements.Any())
{
var updated = false;
foreach (var element in elements)
{
var result = updater(element.Value);
if (result != element.Value)
{
ourLogger.Verbose("Overriding existing project property {0}. Old value: {1}, new value: {2}", name,
element.Value, result);
element.SetValue(result);
updated = true;
}
ourLogger.Verbose("Property {0} already set. Old value: {1}, new value: {2}", name, element.Value, result);
}
return updated;
}
AddProperty(root, xmlns, name, updater(string.Empty));
return true;
}
// Adds a property to the first property group without a condition
private static void AddProperty(XElement root, XNamespace xmlns, string name, string content)
{
ourLogger.Verbose("Adding project property {0}. Value: {1}", name, content);
var propertyGroup = root.Elements(xmlns + "PropertyGroup")
.FirstOrDefault(e => !e.Attributes(xmlns + "Condition").Any());
if (propertyGroup == null)
{
propertyGroup = new XElement(xmlns + "PropertyGroup");
root.AddFirst(propertyGroup);
}
propertyGroup.Add(new XElement(xmlns + name, content));
}
class Utf8StringWriter : StringWriter
{
public override Encoding Encoding => Encoding.UTF8;
}
}
}
| |
// 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.
/*=============================================================================
**
**
** Purpose: A circular-array implementation of a generic queue.
**
**
=============================================================================*/
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace System.Collections.Generic
{
// A simple Queue of generic objects. Internally it is implemented as a
// circular buffer, so Enqueue can be O(n). Dequeue is O(1).
[DebuggerTypeProxy(typeof(QueueDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public class Queue<T> : IEnumerable<T>,
System.Collections.ICollection,
IReadOnlyCollection<T>
{
private T[] _array;
private int _head; // The index from which to dequeue if the queue isn't empty.
private int _tail; // The index at which to enqueue if the queue isn't full.
private int _size; // Number of elements.
private int _version;
private object _syncRoot;
private const int MinimumGrow = 4;
private const int GrowFactor = 200; // double each time
// Creates a queue with room for capacity objects. The default initial
// capacity and grow factor are used.
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Queue"]/*' />
public Queue()
{
_array = Array.Empty<T>();
}
// Creates a queue with room for capacity objects. The default grow factor
// is used.
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Queue1"]/*' />
public Queue(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum);
_array = new T[capacity];
}
// Fills a Queue with the elements of an ICollection. Uses the enumerator
// to get each of the elements.
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Queue3"]/*' />
public Queue(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
_array = EnumerableHelpers.ToArray(collection, out _size);
if (_size != _array.Length) _tail = _size;
}
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Count"]/*' />
public int Count
{
get { return _size; }
}
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.IsSynchronized"]/*' />
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
Threading.Interlocked.CompareExchange<object>(ref _syncRoot, new object(), null);
}
return _syncRoot;
}
}
// Removes all Objects from the queue.
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Clear"]/*' />
public void Clear()
{
if (_size != 0)
{
if (_head < _tail)
Array.Clear(_array, _head, _size);
else
{
Array.Clear(_array, _head, _array.Length - _head);
Array.Clear(_array, 0, _tail);
}
_size = 0;
}
_head = 0;
_tail = 0;
_version++;
}
// CopyTo copies a collection into an Array, starting at a particular
// index into the array.
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.CopyTo"]/*' />
public void CopyTo(T[] array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index);
}
int arrayLen = array.Length;
if (arrayLen - arrayIndex < _size)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
int numToCopy = _size;
if (numToCopy == 0) return;
int firstPart = Math.Min(_array.Length - _head, numToCopy);
Array.Copy(_array, _head, array, arrayIndex, firstPart);
numToCopy -= firstPart;
if (numToCopy > 0)
{
Array.Copy(_array, 0, array, arrayIndex + _array.Length - _head, numToCopy);
}
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array));
}
int arrayLen = array.Length;
if (index < 0 || index > arrayLen)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
}
if (arrayLen - index < _size)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
int numToCopy = _size;
if (numToCopy == 0) return;
try
{
int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy;
Array.Copy(_array, _head, array, index, firstPart);
numToCopy -= firstPart;
if (numToCopy > 0)
{
Array.Copy(_array, 0, array, index + _array.Length - _head, numToCopy);
}
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
// Adds item to the tail of the queue.
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Enqueue"]/*' />
public void Enqueue(T item)
{
if (_size == _array.Length)
{
int newcapacity = (int)((long)_array.Length * (long)GrowFactor / 100);
if (newcapacity < _array.Length + MinimumGrow)
{
newcapacity = _array.Length + MinimumGrow;
}
SetCapacity(newcapacity);
}
_array[_tail] = item;
MoveNext(ref _tail);
_size++;
_version++;
}
// GetEnumerator returns an IEnumerator over this Queue. This
// Enumerator will support removing.
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.GetEnumerator"]/*' />
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.IEnumerable.GetEnumerator"]/*' />
/// <internalonly/>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
// Removes the object at the head of the queue and returns it. If the queue
// is empty, this method simply returns null.
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Dequeue"]/*' />
public T Dequeue()
{
if (_size == 0)
throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue);
T removed = _array[_head];
_array[_head] = default(T);
MoveNext(ref _head);
_size--;
_version++;
return removed;
}
// Returns the object at the head of the queue. The object remains in the
// queue. If the queue is empty, this method throws an
// InvalidOperationException.
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Peek"]/*' />
public T Peek()
{
if (_size == 0)
throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue);
return _array[_head];
}
// Returns true if the queue contains at least one object equal to item.
// Equality is determined using item.Equals().
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Contains"]/*' />
public bool Contains(T item)
{
int index = _head;
int count = _size;
EqualityComparer<T> c = EqualityComparer<T>.Default;
while (count-- > 0)
{
if (c.Equals(_array[index], item))
{
return true;
}
MoveNext(ref index);
}
return false;
}
private T GetElement(int i)
{
return _array[(_head + i) % _array.Length];
}
// Iterates over the objects in the queue, returning an array of the
// objects in the Queue, or an empty array if the queue is empty.
// The order of elements in the array is first in to last in, the same
// order produced by successive calls to Dequeue.
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.ToArray"]/*' />
public T[] ToArray()
{
if (_size == 0)
{
return Array.Empty<T>();
}
T[] arr = new T[_size];
if (_head < _tail)
{
Array.Copy(_array, _head, arr, 0, _size);
}
else
{
Array.Copy(_array, _head, arr, 0, _array.Length - _head);
Array.Copy(_array, 0, arr, _array.Length - _head, _tail);
}
return arr;
}
// PRIVATE Grows or shrinks the buffer to hold capacity objects. Capacity
// must be >= _size.
private void SetCapacity(int capacity)
{
T[] newarray = new T[capacity];
if (_size > 0)
{
if (_head < _tail)
{
Array.Copy(_array, _head, newarray, 0, _size);
}
else
{
Array.Copy(_array, _head, newarray, 0, _array.Length - _head);
Array.Copy(_array, 0, newarray, _array.Length - _head, _tail);
}
}
_array = newarray;
_head = 0;
_tail = (_size == capacity) ? 0 : _size;
_version++;
}
// Increments the index wrapping it if necessary.
private void MoveNext(ref int index)
{
// It is tempting to use the remainder operator here but it is actually much slower
// than a simple comparison and a rarely taken branch.
int tmp = index + 1;
index = (tmp == _array.Length) ? 0 : tmp;
}
public void TrimExcess()
{
int threshold = (int)(((double)_array.Length) * 0.9);
if (_size < threshold)
{
SetCapacity(_size);
}
}
// Implements an enumerator for a Queue. The enumerator uses the
// internal version number of the list to ensure that no modifications are
// made to the list while an enumeration is in progress.
/// <include file='doc\Queue.uex' path='docs/doc[@for="QueueEnumerator"]/*' />
[SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")]
public struct Enumerator : IEnumerator<T>,
System.Collections.IEnumerator
{
private readonly Queue<T> _q;
private readonly int _version;
private int _index; // -1 = not started, -2 = ended/disposed
private T _currentElement;
internal Enumerator(Queue<T> q)
{
_q = q;
_version = q._version;
_index = -1;
_currentElement = default(T);
}
/// <include file='doc\Queue.uex' path='docs/doc[@for="QueueEnumerator.Dispose"]/*' />
public void Dispose()
{
_index = -2;
_currentElement = default(T);
}
/// <include file='doc\Queue.uex' path='docs/doc[@for="QueueEnumerator.MoveNext"]/*' />
public bool MoveNext()
{
if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_index == -2)
return false;
_index++;
if (_index == _q._size)
{
_index = -2;
_currentElement = default(T);
return false;
}
_currentElement = _q.GetElement(_index);
return true;
}
/// <include file='doc\Queue.uex' path='docs/doc[@for="QueueEnumerator.Current"]/*' />
public T Current
{
get
{
if (_index < 0)
ThrowEnumerationNotStartedOrEnded();
return _currentElement;
}
}
private void ThrowEnumerationNotStartedOrEnded()
{
Debug.Assert(_index == -1 || _index == -2);
throw new InvalidOperationException(_index == -1 ? SR.InvalidOperation_EnumNotStarted : SR.InvalidOperation_EnumEnded);
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
_index = -1;
_currentElement = default(T);
}
}
}
}
| |
// 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 OrInt32()
{
var test = new SimpleBinaryOpTest__OrInt32();
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__OrInt32
{
private const int VectorSize = 32;
private const int ElementCount = VectorSize / sizeof(Int32);
private static Int32[] _data1 = new Int32[ElementCount];
private static Int32[] _data2 = new Int32[ElementCount];
private static Vector256<Int32> _clsVar1;
private static Vector256<Int32> _clsVar2;
private Vector256<Int32> _fld1;
private Vector256<Int32> _fld2;
private SimpleBinaryOpTest__DataTable<Int32> _dataTable;
static SimpleBinaryOpTest__OrInt32()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__OrInt32()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int32>(_data1, _data2, new Int32[ElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.Or(
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.Or(
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.Or(
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.Or(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr);
var result = Avx2.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx2.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx2.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__OrInt32();
var result = Avx2.Or(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.Or(_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(Vector256<Int32> left, Vector256<Int32> right, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[ElementCount];
Int32[] inArray2 = new Int32[ElementCount];
Int32[] outArray = new Int32[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, 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 = "")
{
Int32[] inArray1 = new Int32[ElementCount];
Int32[] inArray2 = new Int32[ElementCount];
Int32[] outArray = new Int32[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
if ((int)(left[0] | right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((int)(left[i] | right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Or)}<Int32>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.