context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using net.flashpunk.graphics;
namespace net.flashpunk
{
/**
* Main game Entity class updated by World.
*/
public class Entity : Tweener
{
/**
* If the Entity should render.
*/
public bool visible = true;
/**
* If the Entity should respond to collision checks.
*/
public bool collidable = true;
/**
* X position of the Entity in the World.
*/
public float x = 0;
/**
* Y position of the Entity in the World.
*/
public float y = 0;
/**
* Width of the Entity's hitbox.
*/
public int width;
/**
* Height of the Entity's hitbox.
*/
public int height;
/**
* X origin of the Entity's hitbox.
*/
public int originX;
/**
* Y origin of the Entity's hitbox.
*/
public int originY;
/**
* The Texture2D target to draw the Entity to. Leave as null to render to the current screen buffer (default).
*/
public SpriteBatch renderTarget;
/// <summary>
/// Initializes a new instance of the <see cref="Entity"/> class.
/// </summary>
public Entity()
: this(0, 0, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Entity"/> class.
/// </summary>
/// <param name="x">X position to place the Entity.</param>
/// <param name="y">Y position to place the Entity.</param>
public Entity(float x, float y)
: this(x, y, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Entity"/> class.
/// </summary>
/// <param name="x">X position to place the Entity.</param>
/// <param name="y">Y position to place the Entity.</param>
/// <param name="graphic">Graphic to assign to the Entity.</param>
public Entity(float x, float y, Graphic graphic)
: this(x, y, graphic, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Entity"/> class.
/// </summary>
/// <param name="x">X position to place the Entity.</param>
/// <param name="y">Y position to place the Entity.</param>
/// <param name="graphic">Graphic to assign to the Entity.</param>
/// <param name="mask">Mask to assign to the Entity.</param>
public Entity(float x, float y, Graphic graphic, Mask mask)
{
this.x = x;
this.y = y;
if (graphic != null) this.graphic = graphic;
if (mask != null) this.mask = mask;
HITBOX.assignTo(this);
_class = GetType();
}
/// <summary>
/// Override this, called when the Entity is added to a World.
/// </summary>
public virtual void added()
{
}
/// <summary>
/// Override this, called when the Entity is removed from a World.
/// </summary>
public virtual void removed()
{
}
/// <summary>
/// Updates the Entity.
/// </summary>
override public void update()
{
}
/// <summary>
/// Renders the Entity. If you override this for special behaviour,
/// remember to call base.render() to render the Entity's graphic.
/// </summary>
public virtual void render()
{
if (_graphic != null && _graphic.visible)
{
if (_graphic.relative)
{
_point.X = x;
_point.Y = y;
}
else _point.X = _point.Y = 0;
_camera.X = FP.camera.X;
_camera.Y = FP.camera.Y;
_graphic.render(renderTarget != null ? renderTarget : FP.buffer, _point, _camera);
}
}
/// <summary>
/// Checks for a collision against an Entity type.
/// </summary>
/// <param name="type">The Entity type to check for.</param>
/// <param name="x">Virtual x position to place this Entity.</param>
/// <param name="y">Virtual y position to place this Entity.</param>
/// <returns>The first Entity collided with, or null if none were collided.</returns>
public Entity collide(string type, float x, float y)
{
if (_world != null) return null;
Entity e = _world._typeFirst[type];
if (!collidable || e == null) return null;
_x = this.x; _y = this.y;
this.x = x; this.y = y;
if (_mask == null)
{
while (e != null)
{
if (x - originX + width > e.x - e.originX
&& y - originY + height > e.y - e.originY
&& x - originX < e.x - e.originX + e.width
&& y - originY < e.y - e.originY + e.height
&& e.collidable && e != this)
{
if (e._mask == null || e._mask.collide(HITBOX))
{
this.x = _x; this.y = _y;
return e;
}
}
e = e._typeNext;
}
this.x = _x; this.y = _y;
return null;
}
while (e != null)
{
if (x - originX + width > e.x - e.originX
&& y - originY + height > e.y - e.originY
&& x - originX < e.x - e.originX + e.width
&& y - originY < e.y - e.originY + e.height
&& e.collidable && e != this)
{
if (_mask.collide(e._mask != null ? e._mask : e.HITBOX))
{
this.x = _x; this.y = _y;
return e;
}
}
e = e._typeNext;
}
this.x = _x; this.y = _y;
return null;
}
/**
* Checks for collision against multiple Entity types.
* @param types An Array or Vector of Entity types to check for.
* @param x Virtual x position to place this Entity.
* @param y Virtual y position to place this Entity.
* @return The first Entity collided with, or null if none were collided.
*/
public Entity collideTypes(IEnumerable<string> types, float x, float y)
{
if (_world == null) return null;
Entity e;
foreach (string type in types)
{
if ((e = collide(type, x, y)) != null) return e;
}
return null;
}
/**
* Checks if this Entity collides with a specific Entity.
* @param e The Entity to collide against.
* @param x Virtual x position to place this Entity.
* @param y Virtual y position to place this Entity.
* @return The Entity if they overlap, or null if they don't.
*/
public Entity collideWith(Entity e, float x, float y)
{
_x = this.x; _y = this.y;
this.x = x; this.y = y;
if (x - originX + width > e.x - e.originX
&& y - originY + height > e.y - e.originY
&& x - originX < e.x - e.originX + e.width
&& y - originY < e.y - e.originY + e.height
&& collidable && e.collidable)
{
if (_mask == null)
{
if (e._mask == null || e._mask.collide(HITBOX))
{
this.x = _x; this.y = _y;
return e;
}
this.x = _x; this.y = _y;
return null;
}
if (_mask.collide(e._mask != null ? e._mask : e.HITBOX))
{
this.x = _x; this.y = _y;
return e;
}
}
this.x = _x; this.y = _y;
return null;
}
/**
* Checks if this Entity overlaps the specified rectangle.
* @param x Virtual x position to place this Entity.
* @param y Virtual y position to place this Entity.
* @param rX X position of the rectangle.
* @param rY Y position of the rectangle.
* @param rWidth Width of the rectangle.
* @param rHeight Height of the rectangle.
* @return If they overlap.
*/
public bool collideRect(float x, float y, float rX, float rY, float rWidth, float rHeight)
{
if (x - originX + width >= rX && y - originY + height >= rY
&& x - originX <= rX + rWidth && y - originY <= rY + rHeight)
{
if (_mask == null) return true;
_x = this.x; _y = this.y;
this.x = x; this.y = y;
FP.entity.x = rX;
FP.entity.y = rY;
FP.entity.width = (int)rWidth;
FP.entity.height = (int)rHeight;
if (_mask.collide(FP.entity.HITBOX))
{
this.x = _x; this.y = _y;
return true;
}
this.x = _x; this.y = _y;
return false;
}
return false;
}
/**
* Checks if this Entity overlaps the specified position.
* @param x Virtual x position to place this Entity.
* @param y Virtual y position to place this Entity.
* @param pX X position.
* @param pY Y position.
* @return If the Entity intersects with the position.
*/
public bool collidePoint(float x, float y, float pX, float pY)
{
if (pX >= x - originX && pY >= y - originY
&& pX < x - originX + width && pY < y - originY + height)
{
if (_mask == null) return true;
_x = this.x; _y = this.y;
this.x = x; this.y = y;
FP.entity.x = pX;
FP.entity.y = pY;
FP.entity.width = 1;
FP.entity.height = 1;
if (_mask.collide(FP.entity.HITBOX))
{
this.x = _x; this.y = _y;
return true;
}
this.x = _x; this.y = _y;
return false;
}
return false;
}
/**
* Populates an array with all collided Entities of a type.
* @param type The Entity type to check for.
* @param x Virtual x position to place this Entity.
* @param y Virtual y position to place this Entity.
* @param array The Array or Vector object to populate.
* @return The array, populated with all collided Entities.
*/
public void collideInto(string type, float x, float y, List<Entity> array)
{
if (_world == null) return;
Entity e = _world._typeFirst[type];
if (!collidable || e == null) return;
_x = this.x; _y = this.y;
this.x = x; this.y = y;
if (_mask == null)
{
while (e != null)
{
if (x - originX + width > e.x - e.originX
&& y - originY + height > e.y - e.originY
&& x - originX < e.x - e.originX + e.width
&& y - originY < e.y - e.originY + e.height
&& e.collidable && e != this)
{
if (e._mask == null || e._mask.collide(HITBOX)) array.Add(e);
}
e = e._typeNext;
}
this.x = _x; this.y = _y;
return;
}
while (e != null)
{
if (x - originX + width > e.x - e.originX
&& y - originY + height > e.y - e.originY
&& x - originX < e.x - e.originX + e.width
&& y - originY < e.y - e.originY + e.height
&& e.collidable && e != this)
{
if (_mask.collide(e._mask != null ? e._mask : e.HITBOX)) array.Add(e);
}
e = e._typeNext;
}
this.x = _x; this.y = _y;
return;
}
/**
* Populates an array with all collided Entities of multiple types.
* @param types An array of Entity types to check for.
* @param x Virtual x position to place this Entity.
* @param y Virtual y position to place this Entity.
* @param array The Array or Vector object to populate.
* @return The array, populated with all collided Entities.
*/
public void collideTypesInto(IEnumerable<string> types, float x, float y, List<Entity> array)
{
if (_world == null) return;
foreach (string type in types) collideInto(type, x, y, array);
}
/**
* If the Entity collides with the camera rectangle.
*/
public bool onCamera
{
get
{
return collideRect(x, y, FP.camera.X, FP.camera.Y, FP.width, FP.height);
}
}
/**
* The World object this Entity has been added to.
*/
public World world
{
get
{
return _world;
}
}
/**
* Half the Entity's width.
*/
public float halfWidth { get { return width / 2; } }
/**
* Half the Entity's height.
*/
public float halfHeight { get { return height / 2; } }
/**
* The center x position of the Entity's hitbox.
*/
public float centerX { get { return x - originX + width / 2; } }
/**
* The center y position of the Entity's hitbox.
*/
public float centerY { get { return y - originY + height / 2; } }
/**
* The leftmost position of the Entity's hitbox.
*/
public float left { get { return x - originX; } }
/**
* The rightmost position of the Entity's hitbox.
*/
public float right { get { return x - originX + width; } }
/**
* The topmost position of the Entity's hitbox.
*/
public float top { get { return y - originY; } }
/**
* The bottommost position of the Entity's hitbox.
*/
public float bottom { get { return y - originY + height; } }
/**
* The rendering layer of this Entity. Higher layers are rendered first.
*/
public int layer
{
get { return _layer; }
set
{
if (_layer == value) return;
if (!_added)
{
_layer = value;
return;
}
_world.removeRender(this);
_layer = value;
_world.addRender(this);
}
}
/**
* The collision type, used for collision checking.
*/
public string type
{
get { return _type; }
set
{
if (_type == value) return;
if (!_added)
{
_type = value;
return;
}
if (!string.IsNullOrWhiteSpace(_type)) _world.removeType(this);
_type = value;
if (!string.IsNullOrWhiteSpace(value)) _world.addType(this);
}
}
/**
* An optional Mask component, used for specialized collision. If this is
* not assigned, collision checks will use the Entity's hitbox by default.
*/
public Mask mask
{
get { return _mask; }
set
{
if (_mask == value) return;
if (_mask != null) _mask.assignTo(null);
_mask = value;
if (value != null) _mask.assignTo(this);
}
}
/**
* Graphical component to render to the screen.
*/
public Graphic graphic
{
get { return _graphic; }
set
{
if (_graphic == value) return;
_graphic = value;
if (value != null && value._assign != null) value._assign();
}
}
/**
* Adds the graphic to the Entity via a Graphiclist.
* @param g Graphic to add.
*/
public Graphic addGraphic(Graphic g)
{
if (graphic is Graphiclist) (graphic as Graphiclist).add(g);
else
{
Graphiclist list = new Graphiclist();
if (graphic != null) list.add(graphic);
list.add(g);
graphic = list;
}
return g;
}
public void setHitbox(int width, int height)
{
setHitbox(width, height, originX, originY);
}
/**
* Sets the Entity's hitbox properties.
* @param width Width of the hitbox.
* @param height Height of the hitbox.
* @param originX X origin of the hitbox.
* @param originY Y origin of the hitbox.
*/
public void setHitbox(int width, int height, int originX, int originY)
{
this.width = width;
this.height = height;
this.originX = originX;
this.originY = originY;
}
/**
* Sets the Entity's hitbox to match that of the provided object.
* @param o The object defining the hitbox (eg. an Image or Rectangle).
*/
public void setHitboxTo(Rectangle r)
{
setHitbox(r.Width, r.Height, -r.X, -r.Y);
}
/**
* Sets the Entity's hitbox to match that of the provided object.
* @param o The object defining the hitbox (eg. an Image or Rectangle).
*/
public void setHitboxTo(Texture2D t)
{
setHitboxTo(t.Bounds);
}
public void setOrigin()
{
setOrigin(0, 0);
}
/**
* Sets the origin of the Entity.
* @param x X origin.
* @param y Y origin.
*/
public void setOrigin(int x, int y)
{
originX = x;
originY = y;
}
/**
* Center's the Entity's origin (half width & height).
*/
public void centerOrigin()
{
originX = width / 2;
originY = height / 2;
}
public float distanceFrom(Entity e)
{
return distanceFrom(e, false);
}
/**
* Calculates the distance from another Entity.
* @param e The other Entity.
* @param useHitboxes If hitboxes should be used to determine the distance. If not, the Entities' x/y positions are used.
* @return The distance.
*/
public float distanceFrom(Entity e, bool useHitboxes)
{
if (!useHitboxes) return (float)Math.Sqrt((x - e.x) * (x - e.x) + (y - e.y) * (y - e.y));
return FP.distanceRects(x - originX, y - originY, width, height, e.x - e.originX, e.y - e.originY, e.width, e.height);
}
public float distanceToPoint(float px, float py)
{
return distanceToPoint(px, py, false);
}
/**
* Calculates the distance from this Entity to the point.
* @param px X position.
* @param py Y position.
* @param useHitboxes If hitboxes should be used to determine the distance. If not, the Entities' x/y positions are used.
* @return The distance.
*/
public float distanceToPoint(float px, float py, bool useHitbox)
{
if (!useHitbox) return (float)Math.Sqrt((x - px) * (x - px) + (y - py) * (y - py));
return FP.distanceRectPoint(px, py, x - originX, y - originY, width, height);
}
/**
* Calculates the distance from this Entity to the rectangle.
* @param rx X position of the rectangle.
* @param ry Y position of the rectangle.
* @param rwidth Width of the rectangle.
* @param rheight Height of the rectangle.
* @return The distance.
*/
public float distanceToRect(float rx, float ry, float rwidth, float rheight)
{
return FP.distanceRects(rx, ry, rwidth, rheight, x - originX, y - originY, width, height);
}
public void moveBy(float x, float y)
{
moveBy(x, y, null, false);
}
public void moveBy(float x, float y, string solidType)
{
moveBy(x, y, solidType, false);
}
/**
* Moves the Entity by the amount, retaining integer values for its x and y.
* @param x Horizontal offset.
* @param y Vertical offset.
* @param solidType An optional collision type to stop flush against upon collision.
* @param sweep If sweeping should be used (prevents fast-moving objects from going through solidType).
*/
public void moveBy(float x, float y, string solidType, bool sweep)
{
_moveX += x;
_moveY += y;
x = (float)Math.Round(_moveX);
y = (float)Math.Round(_moveY);
_moveX -= x;
_moveY -= y;
if (!string.IsNullOrWhiteSpace(solidType))
{
int sign; Entity e;
if (x != 0)
{
if (collidable && (sweep || collide(solidType, this.x + x, this.y) != null))
{
sign = x > 0 ? 1 : -1;
while (x != 0)
{
if ((e = collide(solidType, this.x + sign, this.y)) != null)
{
moveCollideX(e);
break;
}
else
{
this.x += sign;
x -= sign;
}
}
}
else this.x += x;
}
if (y != 0)
{
if (collidable && (sweep || collide(solidType, this.x, this.y + y) != null))
{
sign = y > 0 ? 1 : -1;
while (y != 0)
{
if ((e = collide(solidType, this.x, this.y + sign)) != null)
{
moveCollideY(e);
break;
}
else
{
this.y += sign;
y -= sign;
}
}
}
else this.y += y;
}
}
else
{
this.x += x;
this.y += y;
}
}
public void moveTo(float x, float y)
{
moveTo(x, y, null, false);
}
public void moveTo(float x, float y, string solidType)
{
moveTo(x, y, solidType, false);
}
/**
* Moves the Entity to the position, retaining integer values for its x and y.
* @param x X position.
* @param y Y position.
* @param solidType An optional collision type to stop flush against upon collision.
* @param sweep If sweeping should be used (prevents fast-moving objects from going through solidType).
*/
public void moveTo(float x, float y, string solidType, bool sweep)
{
moveBy(x - this.x, y - this.y, solidType, sweep);
}
/**
* Moves towards the target position, retaining integer values for its x and y.
* @param x X target.
* @param y Y target.
* @param amount Amount to move.
* @param solidType An optional collision type to stop flush against upon collision.
* @param sweep If sweeping should be used (prevents fast-moving objects from going through solidType).
*/
public void moveTowards(float x, float y, float amount, string solidType, bool sweep)
{
_point.X = x - this.x;
_point.Y = y - this.y;
if (_point != Vector2.Zero) _point.Normalize();
_point *= amount;
moveBy(_point.X, _point.Y, solidType, sweep);
}
/**
* When you collide with an Entity on the x-axis with moveTo() or moveBy().
* @param e The Entity you collided with.
*/
public virtual void moveCollideX(Entity e)
{
}
/**
* When you collide with an Entity on the y-axis with moveTo() or moveBy().
* @param e The Entity you collided with.
*/
public virtual void moveCollideY(Entity e)
{
}
public void clampHorizontal(float left, float right)
{
clampHorizontal(left, right, 0);
}
/**
* Clamps the Entity's hitbox on the x-axis.
* @param left Left bounds.
* @param right Right bounds.
* @param padding Optional padding on the clamp.
*/
public void clampHorizontal(float left, float right, float padding)
{
if (x - originX < left + padding) x = left + originX + padding;
if (x - originX + width > right - padding) x = right - width + originX - padding;
}
public void clampVertical(float top, float bottom)
{
clampVertical(top, bottom, 0);
}
/**
* Clamps the Entity's hitbox on the y axis.
* @param top Min bounds.
* @param bottom Max bounds.
* @param padding Optional padding on the clamp.
*/
public void clampVertical(float top, float bottom, float padding)
{
if (y - originY < top + padding) y = top + originY + padding;
if (y - originY + height > bottom - padding) y = bottom - height + originY - padding;
}
// Entity information.
internal Type _class;
internal World _world;
internal bool _added;
internal string _type = "";
internal int _layer;
internal Entity _updatePrev;
internal Entity _updateNext;
internal Entity _renderPrev;
internal Entity _renderNext;
internal Entity _typePrev;
internal Entity _typeNext;
internal Entity _recycleNext;
// Collision information.
private readonly Mask HITBOX = new Mask();
private Mask _mask;
private float _x;
private float _y;
private float _moveX = 0;
private float _moveY = 0;
// Rendering information.
internal Graphic _graphic;
private Vector2 _point = FP.point;
private Vector2 _camera = FP.point2;
}
}
| |
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.3
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# 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.
//
//----------------------------------------------------------------------------
//
// The author gratefully acknowledges the support of David Turner,
// Robert Wilhelm, and Werner Lemberg - the authors of the FreeType
// library - in producing this work. See http://www.freetype.org for details.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// Adaptation for 32-bit screen coordinates has been sponsored by
// Liberty Technology Systems, Inc., visit http://lib-sys.com
//
// Liberty Technology Systems, Inc. is the provider of
// PostScript and PDF technology for software developers.
//
//----------------------------------------------------------------------------
using MatterHackers.Agg.VertexSource;
namespace MatterHackers.Agg
{
//===========================================================layer_order_e
public enum layer_order_e
{
layer_unsorted, //------layer_unsorted
layer_direct, //------layer_direct
layer_inverse //------layer_inverse
};
//==================================================rasterizer_compound_aa
//template<class Clip=rasterizer_sl_clip_int>
sealed public class rasterizer_compound_aa : IRasterizer
{
private rasterizer_cells_aa m_Rasterizer;
private VectorClipper m_VectorClipper;
private agg_basics.filling_rule_e m_filling_rule;
private layer_order_e m_layer_order;
private VectorPOD<style_info> m_styles; // Active Styles
private VectorPOD<int> m_ast; // Active Style Table (unique values)
private VectorPOD<byte> m_asm; // Active Style Mask
private VectorPOD<cell_aa> m_cells;
private VectorPOD<byte> m_cover_buf;
private VectorPOD<int> m_master_alpha;
private int m_min_style;
private int m_max_style;
private int m_start_x;
private int m_start_y;
private int m_scan_y;
private int m_sl_start;
private int m_sl_len;
private struct style_info
{
internal int start_cell;
internal int num_cells;
internal int last_x;
};
private const int aa_shift = 8;
private const int aa_scale = 1 << aa_shift;
private const int aa_mask = aa_scale - 1;
private const int aa_scale2 = aa_scale * 2;
private const int aa_mask2 = aa_scale2 - 1;
private const int poly_subpixel_shift = (int)agg_basics.poly_subpixel_scale_e.poly_subpixel_shift;
public rasterizer_compound_aa()
{
m_Rasterizer = new rasterizer_cells_aa();
m_VectorClipper = new VectorClipper();
m_filling_rule = agg_basics.filling_rule_e.fill_non_zero;
m_layer_order = layer_order_e.layer_direct;
m_styles = new VectorPOD<style_info>(); // Active Styles
m_ast = new VectorPOD<int>(); // Active Style Table (unique values)
m_asm = new VectorPOD<byte>(); // Active Style Mask
m_cells = new VectorPOD<cell_aa>();
m_cover_buf = new VectorPOD<byte>();
m_master_alpha = new VectorPOD<int>();
m_min_style = (0x7FFFFFFF);
m_max_style = (-0x7FFFFFFF);
m_start_x = (0);
m_start_y = (0);
m_scan_y = (0x7FFFFFFF);
m_sl_start = (0);
m_sl_len = (0);
}
public void gamma(IGammaFunction gamma_function)
{
throw new System.NotImplementedException();
}
public void reset()
{
m_Rasterizer.reset();
m_min_style = 0x7FFFFFFF;
m_max_style = -0x7FFFFFFF;
m_scan_y = 0x7FFFFFFF;
m_sl_start = 0;
m_sl_len = 0;
}
private void filling_rule(agg_basics.filling_rule_e filling_rule)
{
m_filling_rule = filling_rule;
}
private void layer_order(layer_order_e order)
{
m_layer_order = order;
}
private void clip_box(double x1, double y1,
double x2, double y2)
{
reset();
m_VectorClipper.clip_box(m_VectorClipper.upscale(x1), m_VectorClipper.upscale(y1),
m_VectorClipper.upscale(x2), m_VectorClipper.upscale(y2));
}
private void reset_clipping()
{
reset();
m_VectorClipper.reset_clipping();
}
public void styles(int left, int right)
{
cell_aa cell = new cell_aa();
cell.initial();
cell.left = (int)left;
cell.right = (int)right;
m_Rasterizer.style(cell);
if (left >= 0 && left < m_min_style) m_min_style = left;
if (left >= 0 && left > m_max_style) m_max_style = left;
if (right >= 0 && right < m_min_style) m_min_style = right;
if (right >= 0 && right > m_max_style) m_max_style = right;
}
public void move_to(int x, int y)
{
if (m_Rasterizer.sorted()) reset();
m_VectorClipper.move_to(m_start_x = m_VectorClipper.downscale(x),
m_start_y = m_VectorClipper.downscale(y));
}
public void line_to(int x, int y)
{
m_VectorClipper.line_to(m_Rasterizer,
m_VectorClipper.downscale(x),
m_VectorClipper.downscale(y));
}
public void move_to_d(double x, double y)
{
if (m_Rasterizer.sorted()) reset();
m_VectorClipper.move_to(m_start_x = m_VectorClipper.upscale(x),
m_start_y = m_VectorClipper.upscale(y));
}
public void line_to_d(double x, double y)
{
m_VectorClipper.line_to(m_Rasterizer,
m_VectorClipper.upscale(x),
m_VectorClipper.upscale(y));
}
private void add_vertex(double x, double y, ShapePath.FlagsAndCommand cmd)
{
if (ShapePath.is_move_to(cmd))
{
move_to_d(x, y);
}
else
if (ShapePath.is_vertex(cmd))
{
line_to_d(x, y);
}
else
if (ShapePath.is_close(cmd))
{
m_VectorClipper.line_to(m_Rasterizer, m_start_x, m_start_y);
}
}
private void edge(int x1, int y1, int x2, int y2)
{
if (m_Rasterizer.sorted()) reset();
m_VectorClipper.move_to(m_VectorClipper.downscale(x1), m_VectorClipper.downscale(y1));
m_VectorClipper.line_to(m_Rasterizer,
m_VectorClipper.downscale(x2),
m_VectorClipper.downscale(y2));
}
private void edge_d(double x1, double y1,
double x2, double y2)
{
if (m_Rasterizer.sorted()) reset();
m_VectorClipper.move_to(m_VectorClipper.upscale(x1), m_VectorClipper.upscale(y1));
m_VectorClipper.line_to(m_Rasterizer,
m_VectorClipper.upscale(x2),
m_VectorClipper.upscale(y2));
}
private void sort()
{
m_Rasterizer.sort_cells();
}
public bool rewind_scanlines()
{
m_Rasterizer.sort_cells();
if (m_Rasterizer.total_cells() == 0)
{
return false;
}
if (m_max_style < m_min_style)
{
return false;
}
m_scan_y = m_Rasterizer.min_y();
m_styles.Allocate((int)(m_max_style - m_min_style + 2), 128);
allocate_master_alpha();
return true;
}
// Returns the number of styles
public int sweep_styles()
{
for (; ; )
{
if (m_scan_y > m_Rasterizer.max_y()) return 0;
int num_cells = (int)m_Rasterizer.scanline_num_cells(m_scan_y);
cell_aa[] cells;
int cellOffset = 0;
int curCellOffset;
m_Rasterizer.scanline_cells(m_scan_y, out cells, out cellOffset);
int num_styles = (int)(m_max_style - m_min_style + 2);
int style_id;
int styleOffset = 0;
m_cells.Allocate((int)num_cells * 2, 256); // Each cell can have two styles
m_ast.Capacity(num_styles, 64);
m_asm.Allocate((num_styles + 7) >> 3, 8);
m_asm.zero();
if (num_cells > 0)
{
// Pre-add zero (for no-fill style, that is, -1).
// We need that to ensure that the "-1 style" would go first.
m_asm.Array[0] |= 1;
m_ast.add(0);
m_styles.Array[styleOffset].start_cell = 0;
m_styles.Array[styleOffset].num_cells = 0;
m_styles.Array[styleOffset].last_x = -0x7FFFFFFF;
m_sl_start = cells[0].x;
m_sl_len = (int)(cells[num_cells - 1].x - m_sl_start + 1);
while (num_cells-- != 0)
{
curCellOffset = (int)cellOffset++;
add_style(cells[curCellOffset].left);
add_style(cells[curCellOffset].right);
}
// Convert the Y-histogram into the array of starting indexes
int i;
int start_cell = 0;
style_info[] stylesArray = m_styles.Array;
for (i = 0; i < m_ast.size(); i++)
{
int IndexToModify = (int)m_ast[i];
int v = stylesArray[IndexToModify].start_cell;
stylesArray[IndexToModify].start_cell = start_cell;
start_cell += v;
}
num_cells = (int)m_Rasterizer.scanline_num_cells(m_scan_y);
m_Rasterizer.scanline_cells(m_scan_y, out cells, out cellOffset);
while (num_cells-- > 0)
{
curCellOffset = (int)cellOffset++;
style_id = (int)((cells[curCellOffset].left < 0) ? 0 :
cells[curCellOffset].left - m_min_style + 1);
styleOffset = (int)style_id;
if (cells[curCellOffset].x == stylesArray[styleOffset].last_x)
{
cellOffset = stylesArray[styleOffset].start_cell + stylesArray[styleOffset].num_cells - 1;
unchecked
{
cells[cellOffset].area += cells[curCellOffset].area;
cells[cellOffset].cover += cells[curCellOffset].cover;
}
}
else
{
cellOffset = stylesArray[styleOffset].start_cell + stylesArray[styleOffset].num_cells;
cells[cellOffset].x = cells[curCellOffset].x;
cells[cellOffset].area = cells[curCellOffset].area;
cells[cellOffset].cover = cells[curCellOffset].cover;
stylesArray[styleOffset].last_x = cells[curCellOffset].x;
stylesArray[styleOffset].num_cells++;
}
style_id = (int)((cells[curCellOffset].right < 0) ? 0 :
cells[curCellOffset].right - m_min_style + 1);
styleOffset = (int)style_id;
if (cells[curCellOffset].x == stylesArray[styleOffset].last_x)
{
cellOffset = stylesArray[styleOffset].start_cell + stylesArray[styleOffset].num_cells - 1;
unchecked
{
cells[cellOffset].area -= cells[curCellOffset].area;
cells[cellOffset].cover -= cells[curCellOffset].cover;
}
}
else
{
cellOffset = stylesArray[styleOffset].start_cell + stylesArray[styleOffset].num_cells;
cells[cellOffset].x = cells[curCellOffset].x;
cells[cellOffset].area = -cells[curCellOffset].area;
cells[cellOffset].cover = -cells[curCellOffset].cover;
stylesArray[styleOffset].last_x = cells[curCellOffset].x;
stylesArray[styleOffset].num_cells++;
}
}
}
if (m_ast.size() > 1) break;
++m_scan_y;
}
++m_scan_y;
if (m_layer_order != layer_order_e.layer_unsorted)
{
VectorPOD_RangeAdaptor ra = new VectorPOD_RangeAdaptor(m_ast, 1, m_ast.size() - 1);
if (m_layer_order == layer_order_e.layer_direct)
{
QuickSort_range_adaptor_uint m_QSorter = new QuickSort_range_adaptor_uint();
m_QSorter.Sort(ra);
//quick_sort(ra, uint_greater);
}
else
{
throw new System.NotImplementedException();
//QuickSort_range_adaptor_uint m_QSorter = new QuickSort_range_adaptor_uint();
//m_QSorter.Sort(ra);
//quick_sort(ra, uint_less);
}
}
return m_ast.size() - 1;
}
// Returns style ID depending of the existing style index
public int style(int style_idx)
{
return m_ast[style_idx + 1] + (int)m_min_style - 1;
}
private bool navigate_scanline(int y)
{
m_Rasterizer.sort_cells();
if (m_Rasterizer.total_cells() == 0)
{
return false;
}
if (m_max_style < m_min_style)
{
return false;
}
if (y < m_Rasterizer.min_y() || y > m_Rasterizer.max_y())
{
return false;
}
m_scan_y = y;
m_styles.Allocate((int)(m_max_style - m_min_style + 2), 128);
allocate_master_alpha();
return true;
}
private bool hit_test(int tx, int ty)
{
if (!navigate_scanline(ty))
{
return false;
}
int num_styles = sweep_styles();
if (num_styles <= 0)
{
return false;
}
scanline_hit_test sl = new scanline_hit_test(tx);
sweep_scanline(sl, -1);
return sl.hit();
}
private byte[] allocate_cover_buffer(int len)
{
m_cover_buf.Allocate(len, 256);
return m_cover_buf.Array;
}
private void master_alpha(int style, double alpha)
{
if (style >= 0)
{
while ((int)m_master_alpha.size() <= style)
{
m_master_alpha.add(aa_mask);
}
m_master_alpha.Array[style] = agg_basics.uround(alpha * aa_mask);
}
}
public void add_path(IVertexSource vs)
{
add_path(vs, 0);
}
public void add_path(IVertexSource vs, int path_id)
{
double x;
double y;
ShapePath.FlagsAndCommand cmd;
vs.rewind(path_id);
if (m_Rasterizer.sorted()) reset();
while (!ShapePath.is_stop(cmd = vs.vertex(out x, out y)))
{
add_vertex(x, y, cmd);
}
}
public int min_x()
{
return m_Rasterizer.min_x();
}
public int min_y()
{
return m_Rasterizer.min_y();
}
public int max_x()
{
return m_Rasterizer.max_x();
}
public int max_y()
{
return m_Rasterizer.max_y();
}
public int min_style()
{
return m_min_style;
}
public int max_style()
{
return m_max_style;
}
public int scanline_start()
{
return m_sl_start;
}
public int scanline_length()
{
return m_sl_len;
}
public int calculate_alpha(int area, int master_alpha)
{
int cover = area >> (poly_subpixel_shift * 2 + 1 - aa_shift);
if (cover < 0) cover = -cover;
if (m_filling_rule == agg_basics.filling_rule_e.fill_even_odd)
{
cover &= aa_mask2;
if (cover > aa_scale)
{
cover = aa_scale2 - cover;
}
}
if (cover > aa_mask) cover = aa_mask;
return (int)((cover * master_alpha + aa_mask) >> aa_shift);
}
public bool sweep_scanline(IScanlineCache sl)
{
throw new System.NotImplementedException();
}
// Sweeps one scanline with one style index. The style ID can be
// determined by calling style().
//template<class Scanline>
public bool sweep_scanline(IScanlineCache sl, int style_idx)
{
int scan_y = m_scan_y - 1;
if (scan_y > m_Rasterizer.max_y()) return false;
sl.ResetSpans();
int master_alpha = aa_mask;
if (style_idx < 0)
{
style_idx = 0;
}
else
{
style_idx++;
master_alpha = m_master_alpha[(int)(m_ast[(int)style_idx] + m_min_style - 1)];
}
style_info st = m_styles[m_ast[style_idx]];
int num_cells = (int)st.num_cells;
int CellOffset = st.start_cell;
cell_aa cell = m_cells[CellOffset];
int cover = 0;
while (num_cells-- != 0)
{
int alpha;
int x = cell.x;
int area = cell.area;
cover += cell.cover;
cell = m_cells[++CellOffset];
if (area != 0)
{
alpha = calculate_alpha((cover << (poly_subpixel_shift + 1)) - area,
master_alpha);
sl.add_cell(x, alpha);
x++;
}
if (num_cells != 0 && cell.x > x)
{
alpha = calculate_alpha(cover << (poly_subpixel_shift + 1),
master_alpha);
if (alpha != 0)
{
sl.add_span(x, cell.x - x, alpha);
}
}
}
if (sl.num_spans() == 0) return false;
sl.finalize(scan_y);
return true;
}
private void add_style(int style_id)
{
if (style_id < 0) style_id = 0;
else style_id -= m_min_style - 1;
int nbyte = (int)((int)style_id >> 3);
int mask = (int)(1 << (style_id & 7));
style_info[] stylesArray = m_styles.Array;
if ((m_asm[nbyte] & mask) == 0)
{
m_ast.add((int)style_id);
m_asm.Array[nbyte] |= (byte)mask;
stylesArray[style_id].start_cell = 0;
stylesArray[style_id].num_cells = 0;
stylesArray[style_id].last_x = -0x7FFFFFFF;
}
++stylesArray[style_id].start_cell;
}
private void allocate_master_alpha()
{
while ((int)m_master_alpha.size() <= m_max_style)
{
m_master_alpha.add(aa_mask);
}
}
};
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Runtime.InteropServices;
using System.Threading;
namespace Erwine.Leonard.T.GDIPlus
{
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
[StructLayout(LayoutKind.Sequential)]
public struct Fraction64 : IEquatable<Fraction64>, IComparable<Fraction64>, IFraction<long>
{
#region Fields
public static readonly Fraction64 Zero = new Fraction64(0, 0, 1);
private long _wholeNumber;
private long _numerator;
private long _denominator;
#endregion
#region Properties
public long WholeNumber { get { return _wholeNumber; } }
IConvertible IFraction.WholeNumber { get { return _wholeNumber; } }
public long Numerator { get { return _numerator; } }
IConvertible IFraction.Numerator { get { return _numerator; } }
public long Denominator { get { return _denominator; } }
IConvertible IFraction.Denominator { get { return _denominator; } }
#endregion
#region Constructors
public Fraction64(long wholeNumber, long numerator, long denominator)
{
_wholeNumber = FractionUtil.GetNormalizedRational64(wholeNumber, numerator, denominator, out numerator, out denominator);
_numerator = numerator;
_denominator = denominator;
}
public Fraction64(long numerator, long denominator)
{
_wholeNumber = FractionUtil.GetNormalizedRational64(0, numerator, denominator, out numerator, out denominator);
_numerator = numerator;
_denominator = denominator;
}
public Fraction64(IFraction fraction)
{
long numerator, denominator;
_wholeNumber = FractionUtil.GetNormalizedRational64(FractionUtil.ToInt64(fraction.WholeNumber), FractionUtil.ToInt64(fraction.Numerator), FractionUtil.ToInt64(fraction.Denominator, 1), out numerator, out denominator);
_numerator = numerator;
_denominator = denominator;
}
public Fraction64(long wholeNumber)
{
_wholeNumber = wholeNumber;
_numerator = 0;
_denominator = 1;
}
#endregion
#region *Parse
public static Fraction64 Parse(string s)
{
long numerator, denominator;
long wholeNumber = FractionUtil.Parse64(s, out numerator, out denominator);
return new Fraction64(wholeNumber, numerator, denominator);
}
public static bool TryParse(string s, out Fraction64 value)
{
long wholeNumber, numerator, denominator;
if (FractionUtil.TryParse64(s, out wholeNumber, out numerator, out denominator))
{
value = new Fraction64(wholeNumber, numerator, denominator);
return true;
}
value = new Fraction64();
return false;
}
#endregion
#region Operators
public static Fraction64 operator +(Fraction64 x, Fraction64 y) { return x.Add(y); }
public static Fraction64 operator -(Fraction64 x, Fraction64 y) { return x.Subtract(y); }
public static Fraction64 operator *(Fraction64 x, Fraction64 y) { return x.Multiply(y); }
public static Fraction64 operator /(Fraction64 x, Fraction64 y) { return x.Divide(y); }
public static bool operator ==(Fraction64 x, Fraction64 y) { return x.Equals(y); }
public static bool operator !=(Fraction64 x, Fraction64 y) { return !x.Equals(y); }
public static bool operator <(Fraction64 x, Fraction64 y) { return x.CompareTo(y) < 0; }
public static bool operator <=(Fraction64 x, Fraction64 y) { return x.CompareTo(y) <= 0; }
public static bool operator >(Fraction64 x, Fraction64 y) { return x.CompareTo(y) > 0; }
public static bool operator >=(Fraction64 x, Fraction64 y) { return x.CompareTo(y) >= 0; }
#endregion
#region Add
public Fraction64 Add(long wholeNumber, long numerator, long denominator)
{
if (_numerator == 0 && _wholeNumber == 0)
return new Fraction64(wholeNumber, numerator, denominator);
if (numerator == 0 && wholeNumber == 0)
return (_denominator == 0) ? Fraction64.Zero : this;
long w1 = _wholeNumber, n1 = _numerator, d1 = _denominator, w2, n2 = numerator, d2 = denominator;
w2 = FractionUtil.GetNormalizedRational64(wholeNumber, numerator, denominator, out n2, out d2);
FractionUtil.ToCommonDenominator64(ref n1, ref d1, ref n2, ref d2);
w1 = FractionUtil.GetNormalizedRational64(w1 + w2, n1 + n2, d1, out n1, out d1);
return new Fraction64((long)w1, (long)n1, (long)d1);
}
IFraction<long> IFraction<long>.Add(long wholeNumber, long numerator, long denominator) { return Add(wholeNumber, numerator, denominator); }
public Fraction64 Add(long numerator, long denominator) { return Add(0, numerator, denominator); }
IFraction<long> IFraction<long>.Add(long numerator, long denominator) { return Add(0, numerator, denominator); }
public Fraction64 Add(Fraction64 other)
{
if (_numerator == 0 && _wholeNumber == 0)
return (other._denominator == 0) ? Fraction64.Zero : other;
if (other._numerator == 0 && other._wholeNumber == 0)
return (_denominator == 0) ? Fraction64.Zero : this;
long w1 = _wholeNumber, n1 = _numerator, d1 = _denominator, w2 = other._wholeNumber, n2 = other._numerator, d2 = other._denominator;
FractionUtil.ToCommonDenominator64(ref n1, ref d1, ref n2, ref d2);
w1 = FractionUtil.GetNormalizedRational64(w1 + w2, n1 + n2, d1, out n1, out d1);
return new Fraction64((long)w1, (long)n1, (long)d1);
}
IFraction<long> IFraction<long>.Add(IFraction<long> other)
{
if (other == null)
throw new ArgumentNullException("other");
if (other is Fraction64)
return Add((Fraction64)other);
return Add(other.WholeNumber, other.Numerator, other.Denominator);
}
public Fraction64 Add(long wholeNumber) { return Add(wholeNumber, 0, 1); }
IFraction<long> IFraction<long>.Add(long wholeNumber) { return Add(wholeNumber, 0, 1); }
public IFraction Add(IFraction other)
{
if (other == null)
throw new ArgumentNullException("other");
if (other is IFraction<long>)
return Add((IFraction<long>)other);
if (other.Equals(0))
return this;
if (_numerator == 0 && _wholeNumber == 0)
return other;
if (other.GetMaxUnderlyingValue().CompareTo(long.MaxValue) <= 0 && other.GetMinUnderlyingValue().CompareTo(long.MinValue) >= 0)
return Add(Convert.ToInt64(other.WholeNumber), Convert.ToInt64(other.Numerator), Convert.ToInt64(other.Denominator));
return (new Fraction64(this)).Add(other);
}
#endregion
#region AsInverted
public Fraction64 AsInverted()
{
if (_numerator == 0)
{
if (_wholeNumber == 0)
return Fraction64.Zero;
return new Fraction64(0, 1, _wholeNumber);
}
if (_wholeNumber == 0)
return new Fraction64(0, _denominator, _numerator);
return new Fraction64(0, _denominator, _numerator + (_wholeNumber * _denominator));
}
IFraction<long> IFraction<long>.AsInverted() { return AsInverted(); }
IFraction IFraction.AsInverted() { return AsInverted(); }
#endregion
public long AsRoundedValue()
{
if (_numerator == 0 || _numerator < (_denominator >> 1))
return _wholeNumber;
return _wholeNumber + 1;
}
#region CompareTo
public int CompareTo(Fraction64 other)
{
int i = _wholeNumber.CompareTo(other._wholeNumber);
if (i != 0)
return i;
if (_wholeNumber == 0)
{
if (_numerator == 0 || other._numerator == 0 || _denominator == other._denominator)
return _numerator.CompareTo(other._numerator);
}
else
{
if (_numerator == 0)
return (other._numerator < (long)(int.MinValue)) ? -1 : ((other._numerator > 0L) ? 1 : 0);
if (other._numerator == 0)
return (_numerator < (long)(int.MinValue)) ? -1 : ((_numerator > 0L) ? 1 : 0);
}
long n1 = _numerator, d1 = _denominator, n2 = other._numerator, d2 = other._denominator;
FractionUtil.ToCommonDenominator64(ref n1, ref d1, ref n2, ref d2);
return n1.CompareTo(n2);
}
private int CompareTo(IFraction<long> other)
{
if (other == null)
return 1;
if (other is Fraction64)
return CompareTo((Fraction64)other);
long n, d;
long w = FractionUtil.GetNormalizedRational64(other.WholeNumber, other.Numerator, other.Denominator, out n, out d);
int i = _wholeNumber.CompareTo(w);
if (i != 0)
return i;
if (_wholeNumber == 0)
{
if (_numerator == 0 || n == 0 || _denominator == d)
return _numerator.CompareTo(n);
}
else
{
if (_numerator == 0)
return (n < (long)(int.MinValue)) ? -1 : ((n > 0L) ? 1 : 0);
if (n == 0)
return (_numerator < (long)(int.MinValue)) ? -1 : ((_numerator > 0L) ? 1 : 0);
}
long n1 = _numerator, d1 = _denominator, n2 = n, d2 = d;
FractionUtil.ToCommonDenominator64(ref n1, ref d1, ref n2, ref d2);
return n1.CompareTo(n2);
}
int IComparable<IFraction<long>>.CompareTo(IFraction<long> other) { return CompareTo(other); }
public int CompareTo(IFraction other)
{
if (other == null)
return 1;
if (other is IFraction<long>)
return CompareTo((IFraction<long>)other);
if (other.GetMaxUnderlyingValue().CompareTo(long.MaxValue) <= 0 && other.GetMinUnderlyingValue().CompareTo(long.MinValue) >= 0)
return CompareTo(new Fraction64(Convert.ToInt64(other.WholeNumber), Convert.ToInt64(other.Numerator), Convert.ToInt64(other.Denominator)));
return (new Fraction64(this)).CompareTo(other);
}
public int CompareTo(object obj) { return FractionUtil.Compare<long>(this, obj); }
#endregion
#region Divide
public Fraction64 Divide(long wholeNumber, long numerator, long denominator)
{
if (_numerator == 0 && _wholeNumber == 0)
return Fraction64.Zero;
if (numerator == 0 && wholeNumber == 0)
throw new DivideByZeroException();
long w1 = _wholeNumber, n1 = _numerator, d1 = _denominator, w2, n2, d2;
w2 = FractionUtil.GetInvertedRational64(wholeNumber, numerator, denominator, out n2, out d2);
if (n2 == 0 && w2 == 0)
throw new DivideByZeroException();
w1 = FractionUtil.GetNormalizedRational64(w1 * w2, n1 * n2, d1 * d2, out n1, out d1);
return new Fraction64((long)w1, (long)n1, (long)d1);
}
IFraction<long> IFraction<long>.Divide(long wholeNumber, long numerator, long denominator) { return Divide(wholeNumber, numerator, denominator); }
public Fraction64 Divide(long numerator, long denominator) { return Divide(0, numerator, denominator); }
IFraction<long> IFraction<long>.Divide(long numerator, long denominator) { return Divide(0, numerator, denominator); }
public Fraction64 Divide(Fraction64 other)
{
if (other._numerator == 0 && other._wholeNumber == 0)
throw new DivideByZeroException();
return Multiply(other.AsInverted());
}
IFraction<long> IFraction<long>.Divide(IFraction<long> other)
{
if (other == null)
throw new ArgumentNullException("other");
if (other.Numerator == 0 && other.WholeNumber == 0)
throw new DivideByZeroException();
if ((other = other.AsInverted()) is Fraction64)
return Multiply((Fraction64)other);
return Multiply(other.WholeNumber, other.Numerator, other.Denominator);
}
public IFraction Divide(IFraction other)
{
if (other == null)
throw new ArgumentNullException("other");
if (other is IFraction<long>)
return Add((IFraction<long>)other);
if (other.Equals(0))
throw new DivideByZeroException();
if (_numerator == 0 && _wholeNumber == 0)
return other;
if (other.GetMaxUnderlyingValue().CompareTo(long.MaxValue) <= 0 && other.GetMinUnderlyingValue().CompareTo(long.MinValue) >= 0)
return Divide(Convert.ToInt64(other.WholeNumber), Convert.ToInt64(other.Numerator), Convert.ToInt64(other.Denominator));
return (new Fraction64(this)).Divide(other);
}
public Fraction64 Divide(long wholeNumber) { return Divide(wholeNumber, 0, 1); }
IFraction<long> IFraction<long>.Divide(long wholeNumber) { return Divide(wholeNumber, 0, 1); }
#endregion
#region Equals
public bool Equals(Fraction64 other)
{
if (_numerator == 0)
return other._numerator == 0 && _wholeNumber == other._wholeNumber;
return _numerator == other._numerator && _denominator == other._denominator && _wholeNumber == other._wholeNumber;
}
private bool Equals(IFraction<long> other)
{
if (other == null)
return false;
if (other is Fraction64)
return Equals((Fraction64)other);
long n, d;
long w = FractionUtil.GetNormalizedRational64(other.WholeNumber, other.Numerator, other.Denominator, out n, out d);
if (_numerator == 0)
return n == 0 && _wholeNumber == w;
return _numerator == n && _denominator == d && _wholeNumber == w;
}
bool IEquatable<IFraction<long>>.Equals(IFraction<long> other) { return Equals(other); }
public bool Equals(IFraction other)
{
if (other == null)
return false;
if (other is IFraction<long>)
return Equals((IFraction<long>)other);
if (other.GetMaxUnderlyingValue().CompareTo(long.MaxValue) <= 0 && other.GetMinUnderlyingValue().CompareTo(long.MinValue) >= 0)
return Equals(new Fraction64(Convert.ToInt64(other.WholeNumber), Convert.ToInt64(other.Numerator), Convert.ToInt64(other.Denominator)));
return (new Fraction64(this)).Equals(other);
}
public override bool Equals(object obj) { return FractionUtil.EqualTo<long>(this, obj); }
#endregion
public override int GetHashCode() { return ToSingle().GetHashCode(); }
IComparable IFraction.GetMinUnderlyingValue() { return long.MinValue; }
IComparable IFraction.GetMaxUnderlyingValue() { return long.MaxValue; }
TypeCode IConvertible.GetTypeCode() { return TypeCode.Double; }
#region Multiply
public Fraction64 Multiply(long wholeNumber, long numerator, long denominator)
{
if ((_numerator == 0 && _wholeNumber == 0) || (numerator == 0 && wholeNumber == 0))
return Fraction64.Zero;
long w1 = _wholeNumber, n1 = _numerator, d1 = _denominator, w2, n2 = numerator, d2 = denominator;
w2 = FractionUtil.GetNormalizedRational64(wholeNumber, numerator, denominator, out n2, out d2);
if (numerator == 0 && wholeNumber == 0)
return Fraction64.Zero;
w1 = FractionUtil.GetNormalizedRational64(w1 * w2, n1 * n2, d1 * d2, out n1, out d1);
return new Fraction64((long)w1, (long)n1, (long)d1);
}
IFraction<long> IFraction<long>.Multiply(long wholeNumber, long numerator, long denominator) { return Multiply(wholeNumber, numerator, denominator); }
public Fraction64 Multiply(long numerator, long denominator) { return Multiply(0, numerator, denominator); }
IFraction<long> IFraction<long>.Multiply(long numerator, long denominator) { return Multiply(0, numerator, denominator); }
public Fraction64 Multiply(Fraction64 other)
{
if ((_numerator == 0 && _wholeNumber == 0) || (other._numerator == 0 && other._wholeNumber == 0))
return Fraction64.Zero;
long w1 = _wholeNumber, n1 = _numerator, d1 = _denominator, w2 = other._wholeNumber, n2 = other._numerator, d2 = other._denominator;
w1 = FractionUtil.GetNormalizedRational64(w1 * w2, n1 * n2, d1 * d2, out n1, out d1);
return new Fraction64((long)w1, (long)n1, (long)d1);
}
IFraction<long> IFraction<long>.Multiply(IFraction<long> other)
{
if (other == null)
throw new ArgumentNullException("other");
if (other is Fraction64)
return Multiply((Fraction64)other);
return Multiply(other.WholeNumber, other.Numerator, other.Denominator);
}
public Fraction64 Multiply(long wholeNumber) { return Multiply(wholeNumber, 0, 1); }
IFraction<long> IFraction<long>.Multiply(long wholeNumber) { return Multiply(wholeNumber, 0, 1); }
public IFraction Multiply(IFraction other)
{
if (other == null)
throw new ArgumentNullException("other");
if (other is IFraction<long>)
return Add((IFraction<long>)other);
if (_numerator == 0 && _wholeNumber == 0)
return other;
if (other.Equals(0))
return Fraction64.Zero;
if (other.GetMaxUnderlyingValue().CompareTo(long.MaxValue) <= 0 && other.GetMinUnderlyingValue().CompareTo(long.MinValue) >= 0)
return Multiply(Convert.ToInt64(other.WholeNumber), Convert.ToInt64(other.Numerator), Convert.ToInt64(other.Denominator));
return (new Fraction64(this)).Multiply(other);
}
#endregion
#region Subtract
public Fraction64 Subtract(long wholeNumber, long numerator, long denominator)
{
if (numerator == 0 && wholeNumber == 0)
return (_denominator == 0) ? Fraction64.Zero : this;
long w1 = _wholeNumber, n1 = _numerator, d1 = _denominator, w2, n2 = numerator, d2 = denominator;
w2 = FractionUtil.GetNormalizedRational64(wholeNumber, numerator, denominator, out n2, out d2);
FractionUtil.ToCommonDenominator64(ref n1, ref d1, ref n2, ref d2);
w1 = FractionUtil.GetNormalizedRational64(w1 + w2, n1 + n2, d1, out n1, out d1);
return new Fraction64((long)w1, (long)n1, (long)d1);
}
IFraction<long> IFraction<long>.Subtract(long wholeNumber, long numerator, long denominator) { return Subtract(wholeNumber, numerator, denominator); }
public Fraction64 Subtract(long numerator, long denominator) { return Subtract(0, numerator, denominator); }
IFraction<long> IFraction<long>.Subtract(long numerator, long denominator) { return Subtract(0, numerator, denominator); }
public Fraction64 Subtract(Fraction64 other)
{
if (other._denominator == 0)
return Subtract(0, 0, 1);
return Subtract(other._wholeNumber, other._numerator, other._denominator);
}
IFraction<long> IFraction<long>.Subtract(IFraction<long> other)
{
if (other == null)
throw new ArgumentNullException("other");
return Subtract(other.WholeNumber, other.Numerator, other.Denominator);
}
public Fraction64 Subtract(long wholeNumber) { return Subtract(wholeNumber, 0, 1); }
IFraction<long> IFraction<long>.Subtract(long wholeNumber) { return Subtract(wholeNumber, 0, 1); }
public IFraction Subtract(IFraction other)
{
if (other == null)
throw new ArgumentNullException("other");
if (other is IFraction<long>)
return Subtract((IFraction<long>)other);
if (other.GetMaxUnderlyingValue().CompareTo(long.MaxValue) <= 0 && other.GetMinUnderlyingValue().CompareTo(long.MinValue) >= 0)
return Subtract(Convert.ToInt64(other.WholeNumber), Convert.ToInt64(other.Numerator), Convert.ToInt64(other.Denominator));
return (new Fraction64(this)).Subtract(other);
}
#endregion
#region To*
bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(ToDouble(), provider); }
byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(AsRoundedValue(), provider); }
char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(AsRoundedValue(), provider); }
DateTime IConvertible.ToDateTime(IFormatProvider provider) { return Convert.ToDateTime(ToDouble(), provider); }
public decimal ToDecimal()
{
if (_numerator == 0)
return Convert.ToDecimal(_wholeNumber);
return Convert.ToDecimal(_wholeNumber) + (Convert.ToDecimal(_numerator) / Convert.ToDecimal(_denominator));
}
decimal IConvertible.ToDecimal(IFormatProvider provider) { return ToDecimal(); }
public double ToDouble()
{
if (_numerator == 0)
return Convert.ToDouble(_wholeNumber);
return Convert.ToDouble(_wholeNumber) + (Convert.ToDouble(_numerator) / Convert.ToDouble(_denominator));
}
double IConvertible.ToDouble(IFormatProvider provider) { return ToDouble(); }
short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(AsRoundedValue(), provider); }
int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(AsRoundedValue(), provider); }
long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(AsRoundedValue(), provider); }
sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(AsRoundedValue(), provider); }
public float ToSingle()
{
if (_numerator == 0)
return Convert.ToSingle(_wholeNumber);
return Convert.ToSingle(_wholeNumber) + (Convert.ToSingle(_numerator) / Convert.ToSingle(_denominator));
}
float IConvertible.ToSingle(IFormatProvider provider) { return ToSingle(); }
public override string ToString()
{
if (_numerator == 0)
return _wholeNumber.ToString();
if (_wholeNumber == 0)
return _numerator.ToString() + "/" + _denominator.ToString();
return _wholeNumber.ToString() + " " + _numerator.ToString() + "/" + _denominator.ToString();
}
string IConvertible.ToString(IFormatProvider provider) { return ToString(); }
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
if (conversionType == null || conversionType.AssemblyQualifiedName == (typeof(double)).AssemblyQualifiedName)
return ToDouble();
IConvertible c = this;
if (conversionType.AssemblyQualifiedName == (typeof(float)).AssemblyQualifiedName)
c.ToSingle(provider);
if (conversionType.AssemblyQualifiedName == (typeof(int)).AssemblyQualifiedName)
c.ToInt32(provider);
if (conversionType.AssemblyQualifiedName == (typeof(string)).AssemblyQualifiedName)
c.ToString(provider);
if (conversionType.AssemblyQualifiedName == (typeof(long)).AssemblyQualifiedName)
c.ToInt64(provider);
if (conversionType.AssemblyQualifiedName == (typeof(decimal)).AssemblyQualifiedName)
c.ToDecimal(provider);
if (conversionType.AssemblyQualifiedName == (typeof(uint)).AssemblyQualifiedName)
c.ToUInt32(provider);
if (conversionType.AssemblyQualifiedName == (typeof(ulong)).AssemblyQualifiedName)
c.ToUInt64(provider);
if (conversionType.AssemblyQualifiedName == (typeof(short)).AssemblyQualifiedName)
c.ToInt16(provider);
if (conversionType.AssemblyQualifiedName == (typeof(ushort)).AssemblyQualifiedName)
c.ToUInt16(provider);
if (conversionType.AssemblyQualifiedName == (typeof(sbyte)).AssemblyQualifiedName)
c.ToSByte(provider);
if (conversionType.AssemblyQualifiedName == (typeof(byte)).AssemblyQualifiedName)
c.ToByte(provider);
if (conversionType.AssemblyQualifiedName == (typeof(DateTime)).AssemblyQualifiedName)
c.ToDateTime(provider);
if (conversionType.AssemblyQualifiedName == (typeof(bool)).AssemblyQualifiedName)
c.ToBoolean(provider);
if (conversionType.AssemblyQualifiedName == (typeof(char)).AssemblyQualifiedName)
c.ToChar(provider);
return Convert.ChangeType(ToDouble(), conversionType);
}
ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(AsRoundedValue(), provider); }
uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(AsRoundedValue(), provider); }
ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(AsRoundedValue(), provider); }
#endregion
}
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || UNITY_WP8
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;
using System.Globalization;
namespace Newtonsoft.Json.Bson
{
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating Json data.
/// </summary>
public class BsonWriter : JsonWriter
{
private readonly BsonBinaryWriter _writer;
private BsonToken _root;
private BsonToken _parent;
private string _propertyName;
/// <summary>
/// Gets or sets the <see cref="DateTimeKind" /> used when writing <see cref="DateTime"/> values to BSON.
/// When set to <see cref="DateTimeKind.Unspecified" /> no conversion will occur.
/// </summary>
/// <value>The <see cref="DateTimeKind" /> used when writing <see cref="DateTime"/> values to BSON.</value>
public DateTimeKind DateTimeKindHandling
{
get { return _writer.DateTimeKindHandling; }
set { _writer.DateTimeKindHandling = value; }
}
/// <summary>
/// Initializes a new instance of the <see cref="BsonWriter"/> class.
/// </summary>
/// <param name="stream">The stream.</param>
public BsonWriter(Stream stream)
{
ValidationUtils.ArgumentNotNull(stream, "stream");
_writer = new BsonBinaryWriter(stream);
}
/// <summary>
/// Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream.
/// </summary>
public override void Flush()
{
_writer.Flush();
}
/// <summary>
/// Writes the end.
/// </summary>
/// <param name="token">The token.</param>
protected override void WriteEnd(JsonToken token)
{
base.WriteEnd(token);
RemoveParent();
if (Top == 0)
{
_writer.WriteToken(_root);
}
}
/// <summary>
/// Writes out a comment <code>/*...*/</code> containing the specified text.
/// </summary>
/// <param name="text">Text to place inside the comment.</param>
public override void WriteComment(string text)
{
throw new JsonWriterException("Cannot write JSON comment as BSON.");
}
/// <summary>
/// Writes the start of a constructor with the given name.
/// </summary>
/// <param name="name">The name of the constructor.</param>
public override void WriteStartConstructor(string name)
{
throw new JsonWriterException("Cannot write JSON constructor as BSON.");
}
/// <summary>
/// Writes raw JSON.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public override void WriteRaw(string json)
{
throw new JsonWriterException("Cannot write raw JSON as BSON.");
}
/// <summary>
/// Writes raw JSON where a value is expected and updates the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public override void WriteRawValue(string json)
{
throw new JsonWriterException("Cannot write raw JSON as BSON.");
}
/// <summary>
/// Writes the beginning of a Json array.
/// </summary>
public override void WriteStartArray()
{
base.WriteStartArray();
AddParent(new BsonArray());
}
/// <summary>
/// Writes the beginning of a Json object.
/// </summary>
public override void WriteStartObject()
{
base.WriteStartObject();
AddParent(new BsonObject());
}
/// <summary>
/// Writes the property name of a name/value pair on a Json object.
/// </summary>
/// <param name="name">The name of the property.</param>
public override void WritePropertyName(string name)
{
base.WritePropertyName(name);
_propertyName = name;
}
/// <summary>
/// Closes this stream and the underlying stream.
/// </summary>
public override void Close()
{
base.Close();
if (CloseOutput && _writer != null)
_writer.Close();
}
private void AddParent(BsonToken container)
{
AddToken(container);
_parent = container;
}
private void RemoveParent()
{
_parent = _parent.Parent;
}
private void AddValue(object value, BsonType type)
{
AddToken(new BsonValue(value, type));
}
internal void AddToken(BsonToken token)
{
if (_parent != null)
{
if (_parent is BsonObject)
{
((BsonObject)_parent).Add(_propertyName, token);
_propertyName = null;
}
else
{
((BsonArray)_parent).Add(token);
}
}
else
{
if (token.Type != BsonType.Object && token.Type != BsonType.Array)
throw new JsonWriterException("Error writing {0} value. BSON must start with an Object or Array.".FormatWith(CultureInfo.InvariantCulture, token.Type));
_parent = token;
_root = token;
}
}
#region WriteValue methods
/// <summary>
/// Writes a null value.
/// </summary>
public override void WriteNull()
{
base.WriteNull();
AddValue(null, BsonType.Null);
}
/// <summary>
/// Writes an undefined value.
/// </summary>
public override void WriteUndefined()
{
base.WriteUndefined();
AddValue(null, BsonType.Undefined);
}
/// <summary>
/// Writes a <see cref="String"/> value.
/// </summary>
/// <param name="value">The <see cref="String"/> value to write.</param>
public override void WriteValue(string value)
{
base.WriteValue(value);
if (value == null)
AddValue(null, BsonType.Null);
else
AddToken(new BsonString(value, true));
}
/// <summary>
/// Writes a <see cref="Int32"/> value.
/// </summary>
/// <param name="value">The <see cref="Int32"/> value to write.</param>
public override void WriteValue(int value)
{
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
/// <summary>
/// Writes a <see cref="UInt32"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt32"/> value to write.</param>
//
public override void WriteValue(uint value)
{
if (value > int.MaxValue)
throw new JsonWriterException("Value is too large to fit in a signed 32 bit integer. BSON does not support unsigned values.");
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
/// <summary>
/// Writes a <see cref="Int64"/> value.
/// </summary>
/// <param name="value">The <see cref="Int64"/> value to write.</param>
public override void WriteValue(long value)
{
base.WriteValue(value);
AddValue(value, BsonType.Long);
}
/// <summary>
/// Writes a <see cref="UInt64"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt64"/> value to write.</param>
//
public override void WriteValue(ulong value)
{
if (value > long.MaxValue)
throw new JsonWriterException("Value is too large to fit in a signed 64 bit integer. BSON does not support unsigned values.");
base.WriteValue(value);
AddValue(value, BsonType.Long);
}
/// <summary>
/// Writes a <see cref="Single"/> value.
/// </summary>
/// <param name="value">The <see cref="Single"/> value to write.</param>
public override void WriteValue(float value)
{
base.WriteValue(value);
AddValue(value, BsonType.Number);
}
/// <summary>
/// Writes a <see cref="Double"/> value.
/// </summary>
/// <param name="value">The <see cref="Double"/> value to write.</param>
public override void WriteValue(double value)
{
base.WriteValue(value);
AddValue(value, BsonType.Number);
}
/// <summary>
/// Writes a <see cref="Boolean"/> value.
/// </summary>
/// <param name="value">The <see cref="Boolean"/> value to write.</param>
public override void WriteValue(bool value)
{
base.WriteValue(value);
AddValue(value, BsonType.Boolean);
}
/// <summary>
/// Writes a <see cref="Int16"/> value.
/// </summary>
/// <param name="value">The <see cref="Int16"/> value to write.</param>
public override void WriteValue(short value)
{
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
/// <summary>
/// Writes a <see cref="UInt16"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt16"/> value to write.</param>
//
public override void WriteValue(ushort value)
{
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
/// <summary>
/// Writes a <see cref="Char"/> value.
/// </summary>
/// <param name="value">The <see cref="Char"/> value to write.</param>
public override void WriteValue(char value)
{
base.WriteValue(value);
AddToken(new BsonString(value.ToString(), true));
}
/// <summary>
/// Writes a <see cref="Byte"/> value.
/// </summary>
/// <param name="value">The <see cref="Byte"/> value to write.</param>
public override void WriteValue(byte value)
{
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
/// <summary>
/// Writes a <see cref="SByte"/> value.
/// </summary>
/// <param name="value">The <see cref="SByte"/> value to write.</param>
//
public override void WriteValue(sbyte value)
{
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
/// <summary>
/// Writes a <see cref="Decimal"/> value.
/// </summary>
/// <param name="value">The <see cref="Decimal"/> value to write.</param>
public override void WriteValue(decimal value)
{
base.WriteValue(value);
AddValue(value, BsonType.Number);
}
/// <summary>
/// Writes a <see cref="DateTime"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTime"/> value to write.</param>
public override void WriteValue(DateTime value)
{
base.WriteValue(value);
AddValue(value, BsonType.Date);
}
/// <summary>
/// Writes a <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param>
public override void WriteValue(DateTimeOffset value)
{
base.WriteValue(value);
AddValue(value, BsonType.Date);
}
/// <summary>
/// Writes a <see cref="T:Byte[]"/> value.
/// </summary>
/// <param name="value">The <see cref="T:Byte[]"/> value to write.</param>
public override void WriteValue(byte[] value)
{
base.WriteValue(value);
AddValue(value, BsonType.Binary);
}
/// <summary>
/// Writes a <see cref="Guid"/> value.
/// </summary>
/// <param name="value">The <see cref="Guid"/> value to write.</param>
public override void WriteValue(Guid value)
{
base.WriteValue(value);
AddToken(new BsonString(value.ToString(), true));
}
/// <summary>
/// Writes a <see cref="TimeSpan"/> value.
/// </summary>
/// <param name="value">The <see cref="TimeSpan"/> value to write.</param>
public override void WriteValue(TimeSpan value)
{
base.WriteValue(value);
AddToken(new BsonString(value.ToString(), true));
}
/// <summary>
/// Writes a <see cref="Uri"/> value.
/// </summary>
/// <param name="value">The <see cref="Uri"/> value to write.</param>
public override void WriteValue(Uri value)
{
base.WriteValue(value);
AddToken(new BsonString(value.ToString(), true));
}
#endregion
/// <summary>
/// Writes a <see cref="T:Byte[]"/> value that represents a BSON object id.
/// </summary>
/// <param name="value"></param>
public void WriteObjectId(byte[] value)
{
ValidationUtils.ArgumentNotNull(value, "value");
if (value.Length != 12)
throw new Exception("An object id must be 12 bytes");
// hack to update the writer state
AutoComplete(JsonToken.Undefined);
AddValue(value, BsonType.Oid);
}
/// <summary>
/// Writes a BSON regex.
/// </summary>
/// <param name="pattern">The regex pattern.</param>
/// <param name="options">The regex options.</param>
public void WriteRegex(string pattern, string options)
{
ValidationUtils.ArgumentNotNull(pattern, "pattern");
// hack to update the writer state
AutoComplete(JsonToken.Undefined);
AddToken(new BsonRegex(pattern, options));
}
}
}
#endif
| |
/*
* @author Valentin Simonov / http://va.lent.in/
*/
using System;
using System.Collections.Generic;
using TouchScript.Utils;
using UnityEngine;
namespace TouchScript.Gestures.Simple
{
/// <summary>
/// Simple Scale gesture which takes into account only the first two touch points.
/// </summary>
[AddComponentMenu("TouchScript/Gestures/Simple Scale Gesture")]
public class SimpleScaleGesture : TwoPointTransform2DGestureBase
{
#region Constants
/// <summary>
/// Message name when gesture starts
/// </summary>
public const string SCALE_START_MESSAGE = "OnScaleStart";
/// <summary>
/// Message name when gesture updates
/// </summary>
public const string SCALE_MESSAGE = "OnScale";
/// <summary>
/// Message name when gesture ends
/// </summary>
public const string SCALE_COMPLETE_MESSAGE = "OnScaleComplete";
#endregion
#region Events
/// <summary>
/// Occurs when gesture starts.
/// </summary>
public event EventHandler<EventArgs> ScaleStarted
{
add { scaleStartedInvoker += value; }
remove { scaleStartedInvoker -= value; }
}
/// <summary>
/// Occurs when gesture updates.
/// </summary>
public event EventHandler<EventArgs> Scaled
{
add { scaledInvoker += value; }
remove { scaledInvoker -= value; }
}
/// <summary>
/// Occurs when gesture ends.
/// </summary>
public event EventHandler<EventArgs> ScaleCompleted
{
add { scaleCompletedInvoker += value; }
remove { scaleCompletedInvoker -= value; }
}
// iOS Events AOT hack
private EventHandler<EventArgs> scaleStartedInvoker, scaledInvoker, scaleCompletedInvoker;
#endregion
#region Private variables
[SerializeField]
private float scalingThreshold = .5f;
private float scalingBuffer;
private bool isScaling = false;
#endregion
#region Public properties
/// <summary>
/// Minimum distance in cm between touch points for gesture to begin.
/// </summary>
public float ScalingThreshold
{
get { return scalingThreshold; }
set { scalingThreshold = value; }
}
/// <summary>
/// Contains local delta scale when gesture is recognized.
/// Value is between 0 and +infinity, where 1 is no scale, 0.5 is scaled in half, 2 scaled twice.
/// </summary>
public float LocalDeltaScale { get; private set; }
#endregion
#region Gesture callbacks
/// <inheritdoc />
protected override void touchesMoved(IList<ITouch> touches)
{
if (!gotEnoughTouches()) return;
if (!relevantTouches(touches)) return;
Vector3 oldWorldCenter, newWorldCenter;
var deltaScale = 1f;
var newScreenPos1 = getPointScreenPosition(0);
var newScreenPos2 = getPointScreenPosition(1);
var newScreenDelta = newScreenPos2 - newScreenPos1;
if (newScreenDelta.sqrMagnitude < minPixelDistanceSquared) return;
base.touchesMoved(touches);
var oldScreenPos1 = getPointPreviousScreenPosition(0);
var oldScreenPos2 = getPointPreviousScreenPosition(1);
var oldWorldPos1 = projectionLayer.ProjectTo(oldScreenPos1, WorldTransformPlane);
var oldWorldPos2 = projectionLayer.ProjectTo(oldScreenPos2, WorldTransformPlane);
var newWorldPos1 = projectionLayer.ProjectTo(newScreenPos1, WorldTransformPlane);
var newWorldPos2 = projectionLayer.ProjectTo(newScreenPos2, WorldTransformPlane);
var newVector = newWorldPos2 - newWorldPos1;
Vector2 oldScreenCenter = (oldScreenPos1 + oldScreenPos2) * .5f;
Vector2 newScreenCenter = (newScreenPos1 + newScreenPos2) * .5f;
if (isScaling)
{
var distance = Vector3.Distance(oldWorldPos2, oldWorldPos1);
deltaScale = distance > 0 ? newVector.magnitude / distance : 1;
}
else
{
var oldScreenDistance = Vector2.Distance(oldScreenPos1, oldScreenPos2);
var newScreenDistance = newScreenDelta.magnitude;
var screenDeltaDistance = newScreenDistance - oldScreenDistance;
scalingBuffer += screenDeltaDistance;
var dpiScalingThreshold = ScalingThreshold * touchManager.DotsPerCentimeter;
if (scalingBuffer * scalingBuffer >= dpiScalingThreshold * dpiScalingThreshold)
{
isScaling = true;
var oldScreenDirection = (oldScreenPos2 - oldScreenPos1).normalized;
var startScale = (newScreenDistance - scalingBuffer) * .5f;
var startVector = oldScreenDirection * startScale;
deltaScale = newVector.magnitude / (projectionLayer.ProjectTo(oldScreenCenter + startVector, WorldTransformPlane) - projectionLayer.ProjectTo(oldScreenCenter - startVector, WorldTransformPlane)).magnitude;
}
}
oldWorldCenter = projectionLayer.ProjectTo(oldScreenCenter, WorldTransformPlane);
newWorldCenter = projectionLayer.ProjectTo(newScreenCenter, WorldTransformPlane);
if (Mathf.Abs(deltaScale - 1f) > 0.00001)
{
switch (State)
{
case GestureState.Possible:
case GestureState.Began:
case GestureState.Changed:
screenPosition = newScreenCenter;
previousScreenPosition = oldScreenCenter;
PreviousWorldTransformCenter = oldWorldCenter;
WorldTransformCenter = newWorldCenter;
LocalDeltaScale = deltaScale;
if (State == GestureState.Possible)
{
setState(GestureState.Began);
}
else
{
setState(GestureState.Changed);
}
break;
}
}
}
/// <inheritdoc />
protected override void onBegan()
{
base.onBegan();
scaleStartedInvoker.InvokeHandleExceptions(this, EventArgs.Empty);
scaledInvoker.InvokeHandleExceptions(this, EventArgs.Empty);
if (UseSendMessage && SendMessageTarget != null)
{
SendMessageTarget.SendMessage(SCALE_START_MESSAGE, this, SendMessageOptions.DontRequireReceiver);
SendMessageTarget.SendMessage(SCALE_MESSAGE, this, SendMessageOptions.DontRequireReceiver);
}
}
/// <inheritdoc />
protected override void onChanged()
{
base.onChanged();
scaledInvoker.InvokeHandleExceptions(this, EventArgs.Empty);
if (UseSendMessage && SendMessageTarget != null) SendMessageTarget.SendMessage(SCALE_MESSAGE, this, SendMessageOptions.DontRequireReceiver);
}
/// <inheritdoc />
protected override void onRecognized()
{
base.onRecognized();
scaleCompletedInvoker.InvokeHandleExceptions(this, EventArgs.Empty);
if (UseSendMessage && SendMessageTarget != null) SendMessageTarget.SendMessage(SCALE_COMPLETE_MESSAGE, this, SendMessageOptions.DontRequireReceiver);
}
/// <inheritdoc />
protected override void onFailed()
{
base.onFailed();
if (PreviousState != GestureState.Possible)
{
scaleCompletedInvoker.InvokeHandleExceptions(this, EventArgs.Empty);
if (UseSendMessage && SendMessageTarget != null) SendMessageTarget.SendMessage(SCALE_COMPLETE_MESSAGE, this, SendMessageOptions.DontRequireReceiver);
}
}
/// <inheritdoc />
protected override void onCancelled()
{
base.onCancelled();
if (PreviousState != GestureState.Possible)
{
scaleCompletedInvoker.InvokeHandleExceptions(this, EventArgs.Empty);
if (UseSendMessage && SendMessageTarget != null) SendMessageTarget.SendMessage(SCALE_COMPLETE_MESSAGE, this, SendMessageOptions.DontRequireReceiver);
}
}
/// <inheritdoc />
protected override void reset()
{
base.reset();
scalingBuffer = 0f;
isScaling = false;
}
/// <inheritdoc />
protected override void restart()
{
base.restart();
LocalDeltaScale = 1f;
}
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Graphics.Textures;
using osu.Framework.IO.Stores;
using osu.Framework.Testing;
using osu.Game.Audio;
using osu.Game.Configuration;
using osu.Game.Database;
using osu.Game.IO;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.UI;
using osu.Game.Screens.Play;
using osu.Game.Skinning;
using osu.Game.Storyboards;
using osu.Game.Storyboards.Drawables;
using osu.Game.Tests.Resources;
using osu.Game.Tests.Visual;
namespace osu.Game.Tests.Gameplay
{
[HeadlessTest]
public class TestSceneStoryboardSamples : OsuTestScene, IStorageResourceProvider
{
[Resolved]
private OsuConfigManager config { get; set; }
[Test]
public void TestRetrieveTopLevelSample()
{
ISkin skin = null;
ISample channel = null;
AddStep("create skin", () => skin = new TestSkin("test-sample", this));
AddStep("retrieve sample", () => channel = skin.GetSample(new SampleInfo("test-sample")));
AddAssert("sample is non-null", () => channel != null);
}
[Test]
public void TestRetrieveSampleInSubFolder()
{
ISkin skin = null;
ISample channel = null;
AddStep("create skin", () => skin = new TestSkin("folder/test-sample", this));
AddStep("retrieve sample", () => channel = skin.GetSample(new SampleInfo("folder/test-sample")));
AddAssert("sample is non-null", () => channel != null);
}
[Test]
public void TestSamplePlaybackAtZero()
{
GameplayClockContainer gameplayContainer = null;
DrawableStoryboardSample sample = null;
AddStep("create container", () =>
{
var working = CreateWorkingBeatmap(new OsuRuleset().RulesetInfo);
working.LoadTrack();
Add(gameplayContainer = new MasterGameplayClockContainer(working, 0)
{
IsPaused = { Value = true },
Child = new FrameStabilityContainer
{
Child = sample = new DrawableStoryboardSample(new StoryboardSampleInfo(string.Empty, 0, 1))
}
});
});
AddStep("reset clock", () => gameplayContainer.Start());
AddUntilStep("sample played", () => sample.RequestedPlaying);
AddUntilStep("sample has lifetime end", () => sample.LifetimeEnd < double.MaxValue);
}
[Test]
public void TestSampleHasLifetimeEndWithInitialClockTime()
{
GameplayClockContainer gameplayContainer = null;
DrawableStoryboardSample sample = null;
AddStep("create container", () =>
{
var working = CreateWorkingBeatmap(new OsuRuleset().RulesetInfo);
working.LoadTrack();
Add(gameplayContainer = new MasterGameplayClockContainer(working, 1000, true)
{
IsPaused = { Value = true },
Child = new FrameStabilityContainer
{
Child = sample = new DrawableStoryboardSample(new StoryboardSampleInfo(string.Empty, 0, 1))
}
});
});
AddStep("start time", () => gameplayContainer.Start());
AddUntilStep("sample not played", () => !sample.RequestedPlaying);
AddUntilStep("sample has lifetime end", () => sample.LifetimeEnd < double.MaxValue);
}
[Test]
public void TestSamplePlaybackWithBeatmapHitsoundsOff()
{
GameplayClockContainer gameplayContainer = null;
TestDrawableStoryboardSample sample = null;
AddStep("disable beatmap hitsounds", () => config.SetValue(OsuSetting.BeatmapHitsounds, false));
AddStep("setup storyboard sample", () =>
{
Beatmap.Value = new TestCustomSkinWorkingBeatmap(new OsuRuleset().RulesetInfo, this);
var beatmapSkinSourceContainer = new BeatmapSkinProvidingContainer(Beatmap.Value.Skin);
Add(gameplayContainer = new MasterGameplayClockContainer(Beatmap.Value, 0)
{
Child = beatmapSkinSourceContainer
});
beatmapSkinSourceContainer.Add(sample = new TestDrawableStoryboardSample(new StoryboardSampleInfo("test-sample", 1, 1))
{
Clock = gameplayContainer.GameplayClock
});
});
AddStep("start", () => gameplayContainer.Start());
AddUntilStep("sample played", () => sample.IsPlayed);
AddUntilStep("sample has lifetime end", () => sample.LifetimeEnd < double.MaxValue);
AddStep("restore default", () => config.GetBindable<bool>(OsuSetting.BeatmapHitsounds).SetDefault());
}
private class TestSkin : LegacySkin
{
public TestSkin(string resourceName, IStorageResourceProvider resources)
: base(DefaultLegacySkin.CreateInfo(), new TestResourceStore(resourceName), resources, "skin.ini")
{
}
}
private class TestResourceStore : IResourceStore<byte[]>
{
private readonly string resourceName;
public TestResourceStore(string resourceName)
{
this.resourceName = resourceName;
}
public byte[] Get(string name) => name == resourceName ? TestResources.GetStore().Get("Resources/Samples/test-sample.mp3") : null;
public Task<byte[]> GetAsync(string name, CancellationToken cancellationToken = default)
=> name == resourceName ? TestResources.GetStore().GetAsync("Resources/Samples/test-sample.mp3", cancellationToken) : null;
public Stream GetStream(string name) => name == resourceName ? TestResources.GetStore().GetStream("Resources/Samples/test-sample.mp3") : null;
public IEnumerable<string> GetAvailableResources() => new[] { resourceName };
public void Dispose()
{
}
}
private class TestCustomSkinWorkingBeatmap : ClockBackedTestWorkingBeatmap
{
private readonly IStorageResourceProvider resources;
public TestCustomSkinWorkingBeatmap(RulesetInfo ruleset, IStorageResourceProvider resources)
: base(ruleset, null, resources.AudioManager)
{
this.resources = resources;
}
protected internal override ISkin GetSkin() => new TestSkin("test-sample", resources);
}
private class TestDrawableStoryboardSample : DrawableStoryboardSample
{
public TestDrawableStoryboardSample(StoryboardSampleInfo sampleInfo)
: base(sampleInfo)
{
}
}
#region IResourceStorageProvider
public AudioManager AudioManager => Audio;
public IResourceStore<byte[]> Files => null;
public new IResourceStore<byte[]> Resources => base.Resources;
public RealmAccess RealmAccess => null;
public IResourceStore<TextureUpload> CreateTextureLoaderStore(IResourceStore<byte[]> underlyingStore) => null;
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.Win32.SafeHandles
{
[System.Security.SecurityCriticalAttribute]
public sealed partial class SafeAccessTokenHandle : System.Runtime.InteropServices.SafeHandle
{
public SafeAccessTokenHandle(System.IntPtr handle) : base(default(System.IntPtr), default(bool)) { }
public static Microsoft.Win32.SafeHandles.SafeAccessTokenHandle InvalidHandle {[System.Security.SecurityCriticalAttribute]get { return default(Microsoft.Win32.SafeHandles.SafeAccessTokenHandle); } }
public override bool IsInvalid {[System.Security.SecurityCriticalAttribute]get { return default(bool); } }
[System.Security.SecurityCriticalAttribute]
protected override bool ReleaseHandle() { return default(bool); }
}
}
namespace System.Security.Principal
{
public sealed partial class IdentityNotMappedException : System.Exception
{
public IdentityNotMappedException() { }
public IdentityNotMappedException(string message) { }
public IdentityNotMappedException(string message, System.Exception inner) { }
public System.Security.Principal.IdentityReferenceCollection UnmappedIdentities { get { return default(System.Security.Principal.IdentityReferenceCollection); } }
}
public abstract partial class IdentityReference
{
internal IdentityReference() { }
public abstract string Value { get; }
public abstract override bool Equals(object o);
public abstract override int GetHashCode();
public abstract bool IsValidTargetType(System.Type targetType);
public static bool operator ==(System.Security.Principal.IdentityReference left, System.Security.Principal.IdentityReference right) { return default(bool); }
public static bool operator !=(System.Security.Principal.IdentityReference left, System.Security.Principal.IdentityReference right) { return default(bool); }
public abstract override string ToString();
public abstract System.Security.Principal.IdentityReference Translate(System.Type targetType);
}
public partial class IdentityReferenceCollection : System.Collections.Generic.ICollection<System.Security.Principal.IdentityReference>, System.Collections.Generic.IEnumerable<System.Security.Principal.IdentityReference>, System.Collections.IEnumerable
{
public IdentityReferenceCollection() { }
public IdentityReferenceCollection(int capacity) { }
public int Count { get { return default(int); } }
public System.Security.Principal.IdentityReference this[int index] { get { return default(System.Security.Principal.IdentityReference); } set { } }
bool System.Collections.Generic.ICollection<System.Security.Principal.IdentityReference>.IsReadOnly { get { return default(bool); } }
public void Add(System.Security.Principal.IdentityReference identity) { }
public void Clear() { }
public bool Contains(System.Security.Principal.IdentityReference identity) { return default(bool); }
public void CopyTo(System.Security.Principal.IdentityReference[] array, int offset) { }
public System.Collections.Generic.IEnumerator<System.Security.Principal.IdentityReference> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Security.Principal.IdentityReference>); }
public bool Remove(System.Security.Principal.IdentityReference identity) { return default(bool); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
public System.Security.Principal.IdentityReferenceCollection Translate(System.Type targetType) { return default(System.Security.Principal.IdentityReferenceCollection); }
public System.Security.Principal.IdentityReferenceCollection Translate(System.Type targetType, bool forceSuccess) { return default(System.Security.Principal.IdentityReferenceCollection); }
}
public sealed partial class NTAccount : System.Security.Principal.IdentityReference
{
public NTAccount(string name) { }
public NTAccount(string domainName, string accountName) { }
public override string Value { get { return default(string); } }
public override bool Equals(object o) { return default(bool); }
public override int GetHashCode() { return default(int); }
public override bool IsValidTargetType(System.Type targetType) { return default(bool); }
public static bool operator ==(System.Security.Principal.NTAccount left, System.Security.Principal.NTAccount right) { return default(bool); }
public static bool operator !=(System.Security.Principal.NTAccount left, System.Security.Principal.NTAccount right) { return default(bool); }
public override string ToString() { return default(string); }
public override System.Security.Principal.IdentityReference Translate(System.Type targetType) { return default(System.Security.Principal.IdentityReference); }
}
public sealed partial class SecurityIdentifier : System.Security.Principal.IdentityReference, System.IComparable<System.Security.Principal.SecurityIdentifier>
{
public static readonly int MaxBinaryLength;
public static readonly int MinBinaryLength;
public SecurityIdentifier(byte[] binaryForm, int offset) { }
public SecurityIdentifier(System.IntPtr binaryForm) { }
public SecurityIdentifier(System.Security.Principal.WellKnownSidType sidType, System.Security.Principal.SecurityIdentifier domainSid) { }
public SecurityIdentifier(string sddlForm) { }
public System.Security.Principal.SecurityIdentifier AccountDomainSid { get { return default(System.Security.Principal.SecurityIdentifier); } }
public int BinaryLength { get { return default(int); } }
public override string Value { get { return default(string); } }
public int CompareTo(System.Security.Principal.SecurityIdentifier sid) { return default(int); }
public override bool Equals(object o) { return default(bool); }
public bool Equals(System.Security.Principal.SecurityIdentifier sid) { return default(bool); }
public void GetBinaryForm(byte[] binaryForm, int offset) { }
public override int GetHashCode() { return default(int); }
public bool IsAccountSid() { return default(bool); }
public bool IsEqualDomainSid(System.Security.Principal.SecurityIdentifier sid) { return default(bool); }
public override bool IsValidTargetType(System.Type targetType) { return default(bool); }
public bool IsWellKnown(System.Security.Principal.WellKnownSidType type) { return default(bool); }
public static bool operator ==(System.Security.Principal.SecurityIdentifier left, System.Security.Principal.SecurityIdentifier right) { return default(bool); }
public static bool operator !=(System.Security.Principal.SecurityIdentifier left, System.Security.Principal.SecurityIdentifier right) { return default(bool); }
public override string ToString() { return default(string); }
public override System.Security.Principal.IdentityReference Translate(System.Type targetType) { return default(System.Security.Principal.IdentityReference); }
}
[System.FlagsAttribute]
public enum TokenAccessLevels
{
AdjustDefault = 128,
AdjustGroups = 64,
AdjustPrivileges = 32,
AdjustSessionId = 256,
AllAccess = 983551,
AssignPrimary = 1,
Duplicate = 2,
Impersonate = 4,
MaximumAllowed = 33554432,
Query = 8,
QuerySource = 16,
Read = 131080,
Write = 131296,
}
public enum WellKnownSidType
{
AccountAdministratorSid = 38,
AccountCertAdminsSid = 46,
AccountComputersSid = 44,
AccountControllersSid = 45,
AccountDomainAdminsSid = 41,
AccountDomainGuestsSid = 43,
AccountDomainUsersSid = 42,
AccountEnterpriseAdminsSid = 48,
AccountGuestSid = 39,
AccountKrbtgtSid = 40,
AccountPolicyAdminsSid = 49,
AccountRasAndIasServersSid = 50,
AccountSchemaAdminsSid = 47,
AnonymousSid = 13,
AuthenticatedUserSid = 17,
BatchSid = 10,
BuiltinAccountOperatorsSid = 30,
BuiltinAdministratorsSid = 26,
BuiltinAuthorizationAccessSid = 59,
BuiltinBackupOperatorsSid = 33,
BuiltinDomainSid = 25,
BuiltinGuestsSid = 28,
BuiltinIncomingForestTrustBuildersSid = 56,
BuiltinNetworkConfigurationOperatorsSid = 37,
BuiltinPerformanceLoggingUsersSid = 58,
BuiltinPerformanceMonitoringUsersSid = 57,
BuiltinPowerUsersSid = 29,
BuiltinPreWindows2000CompatibleAccessSid = 35,
BuiltinPrintOperatorsSid = 32,
BuiltinRemoteDesktopUsersSid = 36,
BuiltinReplicatorSid = 34,
BuiltinSystemOperatorsSid = 31,
BuiltinUsersSid = 27,
CreatorGroupServerSid = 6,
CreatorGroupSid = 4,
CreatorOwnerServerSid = 5,
CreatorOwnerSid = 3,
DialupSid = 8,
DigestAuthenticationSid = 52,
EnterpriseControllersSid = 15,
InteractiveSid = 11,
LocalServiceSid = 23,
LocalSid = 2,
LocalSystemSid = 22,
LogonIdsSid = 21,
MaxDefined = 60,
NetworkServiceSid = 24,
NetworkSid = 9,
NTAuthoritySid = 7,
NtlmAuthenticationSid = 51,
NullSid = 0,
OtherOrganizationSid = 55,
ProxySid = 14,
RemoteLogonIdSid = 20,
RestrictedCodeSid = 18,
SChannelAuthenticationSid = 53,
SelfSid = 16,
ServiceSid = 12,
TerminalServerSid = 19,
ThisOrganizationSid = 54,
WinBuiltinTerminalServerLicenseServersSid = 60,
WorldSid = 1,
}
public enum WindowsBuiltInRole
{
AccountOperator = 548,
Administrator = 544,
BackupOperator = 551,
Guest = 546,
PowerUser = 547,
PrintOperator = 550,
Replicator = 552,
SystemOperator = 549,
User = 545,
}
public partial class WindowsIdentity : System.Security.Claims.ClaimsIdentity, System.IDisposable
{
public new const string DefaultIssuer = "AD AUTHORITY";
public WindowsIdentity(System.IntPtr userToken) { }
public WindowsIdentity(System.IntPtr userToken, string type) { }
public WindowsIdentity(string sUserPrincipalName) { }
public Microsoft.Win32.SafeHandles.SafeAccessTokenHandle AccessToken {[System.Security.SecurityCriticalAttribute]get { return default(Microsoft.Win32.SafeHandles.SafeAccessTokenHandle); } }
public sealed override string AuthenticationType { get { return default(string); } }
public override System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> Claims { get { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); } }
public System.Security.Principal.IdentityReferenceCollection Groups { get { return default(System.Security.Principal.IdentityReferenceCollection); } }
public System.Security.Principal.TokenImpersonationLevel ImpersonationLevel { get { return default(System.Security.Principal.TokenImpersonationLevel); } }
public virtual bool IsAnonymous { get { return default(bool); } }
public override bool IsAuthenticated { get { return default(bool); } }
public virtual bool IsGuest { get { return default(bool); } }
public virtual bool IsSystem { get { return default(bool); } }
public override string Name { get { return default(string); } }
public System.Security.Principal.SecurityIdentifier Owner { get { return default(System.Security.Principal.SecurityIdentifier); } }
public System.Security.Principal.SecurityIdentifier User { get { return default(System.Security.Principal.SecurityIdentifier); } }
public override System.Security.Claims.ClaimsIdentity Clone() { return default(System.Security.Claims.ClaimsIdentity); }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public static System.Security.Principal.WindowsIdentity GetAnonymous() { return default(System.Security.Principal.WindowsIdentity); }
public static System.Security.Principal.WindowsIdentity GetCurrent() { return default(System.Security.Principal.WindowsIdentity); }
public static System.Security.Principal.WindowsIdentity GetCurrent(bool ifImpersonating) { return default(System.Security.Principal.WindowsIdentity); }
public static System.Security.Principal.WindowsIdentity GetCurrent(System.Security.Principal.TokenAccessLevels desiredAccess) { return default(System.Security.Principal.WindowsIdentity); }
public static void RunImpersonated(Microsoft.Win32.SafeHandles.SafeAccessTokenHandle safeAccessTokenHandle, System.Action action) { }
public static T RunImpersonated<T>(Microsoft.Win32.SafeHandles.SafeAccessTokenHandle safeAccessTokenHandle, System.Func<T> func) { return default(T); }
}
public partial class WindowsPrincipal : System.Security.Claims.ClaimsPrincipal
{
public WindowsPrincipal(System.Security.Principal.WindowsIdentity ntIdentity) { }
public override System.Security.Principal.IIdentity Identity { get { return default(System.Security.Principal.IIdentity); } }
public virtual bool IsInRole(int rid) { return default(bool); }
public virtual bool IsInRole(System.Security.Principal.SecurityIdentifier sid) { return default(bool); }
public virtual bool IsInRole(System.Security.Principal.WindowsBuiltInRole role) { return default(bool); }
public override bool IsInRole(string role) { return default(bool); }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using Xunit.Abstractions;
using System.IO;
using System.Xml.Xsl;
using System.Text;
namespace System.Xml.Tests
{
//[TestCase(Name = "OutputSettings", Desc = "This testcase tests the OutputSettings on XslCompiledTransform", Param = "Debug")]
public class COutputSettings : XsltApiTestCaseBase2
{
private XslCompiledTransform _xsl = null;
private string _xmlFile = string.Empty;
private string _xslFile = string.Empty;
private ITestOutputHelper _output;
public COutputSettings(ITestOutputHelper output) : base(output)
{
_output = output;
}
private void Init(string xmlFile, string xslFile)
{
_xsl = new XslCompiledTransform();
_xmlFile = FullFilePath(xmlFile);
_xslFile = FullFilePath(xslFile);
return;
}
private StringWriter Transform()
{
StringWriter sw = new StringWriter();
_xsl.Transform(_xmlFile, null, sw);
return sw;
}
private void VerifyResult(object actual, object expected, string message)
{
_output.WriteLine("Expected : {0}", expected);
_output.WriteLine("Actual : {0}", actual);
Assert.Equal(actual, expected);
}
//[Variation(id = 1, Desc = "Verify the default value of the OutputSettings, expected null", Pri = 0)]
[Fact]
public void OS1()
{
XslCompiledTransform xslt = new XslCompiledTransform();
Assert.True(xslt.OutputSettings == null);
return;
}
//[Variation(id = 2, Desc = "Verify the OutputMethod when output method is not specified, expected AutoDetect", Pri = 1, Params = new object[] { "books.xml", "OutputMethod_Default.xsl" })]
[InlineData("books.xml", "OutputMethod_Default.xsl", 2)]
//[Variation(id = 3, Desc = "Verify the OutputMethod when output method is xml, expected Xml", Pri = 0, Params = new object[] { "books.xml", "OutputMethod_Xml.xsl" })]
[InlineData("books.xml", "OutputMethod_Xml.xsl", 3)]
//[Variation(id = 4, Desc = "Verify the OutputMethod when output method is html, expected Html", Pri = 0, Params = new object[] { "books.xml", "OutputMethod_Html.xsl" })]
[InlineData("books.xml", "OutputMethod_Html.xsl", 4)]
//[Variation(id = 5, Desc = "Verify the OutputMethod when output method is text, expected Text", Pri = 1, Params = new object[] { "books.xml", "OutputMethod_Text.xsl" })]
[InlineData("books.xml", "OutputMethod_Text.xsl", 5)]
//[Variation(id = 6, Desc = "Verify the OutputMethod when output method is not specified, first output element is html, expected AutoDetect", Pri = 1, Params = new object[] { "books.xml", "OutputMethod_LiteralHtml.xsl" })]
[InlineData("books.xml", "OutputMethod_LiteralHtml.xsl", 6)]
//[Variation(id = 7, Desc = "Verify the OutputMethod when multiple output methods (Xml,Html,Text) are defined, expected Text", Pri = 1, Params = new object[] { "books.xml", "OutputMethod_Multiple1.xsl" })]
[InlineData("books.xml", "OutputMethod_Multiple1.xsl", 7)]
//[Variation(id = 8, Desc = "Verify the OutputMethod when multiple output methods (Html,Text,Xml) are defined, expected Xml", Pri = 1, Params = new object[] { "books.xml", "OutputMethod_Multiple2.xsl" })]
[InlineData("books.xml", "OutputMethod_Multiple2.xsl", 8)]
//[Variation(id = 9, Desc = "Verify the OutputMethod when multiple output methods (Text,Xml,Html) are defined, expected Html", Pri = 1, Params = new object[] { "books.xml", "OutputMethod_Multiple3.xsl" })]
[InlineData("books.xml", "OutputMethod_Multiple3.xsl", 9)]
[Theory]
public void OS2(object param0, object param1, object param2)
{
Init(param0.ToString(), param1.ToString());
_xsl.Load(_xslFile);
XmlWriterSettings os = _xsl.OutputSettings;
switch ((int)param2)
{
case 2:
Assert.Equal(XmlOutputMethod.AutoDetect, os.OutputMethod);
break;
case 3:
Assert.Equal(XmlOutputMethod.Xml, os.OutputMethod);
break;
case 4:
Assert.Equal(XmlOutputMethod.Html, os.OutputMethod);
break;
case 5:
Assert.Equal(XmlOutputMethod.Text, os.OutputMethod);
break;
case 6:
Assert.Equal(XmlOutputMethod.AutoDetect, os.OutputMethod);
break;
case 7:
Assert.Equal(XmlOutputMethod.Text, os.OutputMethod);
break;
case 8:
Assert.Equal(XmlOutputMethod.Xml, os.OutputMethod);
break;
case 9:
Assert.Equal(XmlOutputMethod.Html, os.OutputMethod);
break;
}
return;
}
//[Variation(id = 10, Desc = "Verify OmitXmlDeclaration when omit-xml-declared is omitted in XSLT, expected false", Pri = 0, Params = new object[] { "books.xml", "OmitXmlDecl_Default.xsl", false, "Default value for OmitXmlDeclaration is 'no'" })]
[InlineData("books.xml", "OmitXmlDecl_Default.xsl", false)]
//[Variation(id = 11, Desc = "Verify OmitXmlDeclaration when omit-xml-declared is yes in XSLT, expected true", Pri = 0, Params = new object[] { "books.xml", "OmitXmlDecl_Yes.xsl", true, "OmitXmlDeclaration must be 'yes'" })]
[InlineData("books.xml", "OmitXmlDecl_Yes.xsl", true)]
//[Variation(id = 12, Desc = "Verify OmitXmlDeclaration when omit-xml-declared is no in XSLT, expected false", Pri = 1, Params = new object[] { "books.xml", "OmitXmlDecl_No.xsl", false, "OmitXmlDeclaration must be 'no'" })]
[InlineData("books.xml", "OmitXmlDecl_No.xsl", false)]
[Theory]
public void OS3(object param0, object param1, object param2)
{
Init(param0.ToString(), param1.ToString());
_xsl.Load(_xslFile);
XmlWriterSettings os = _xsl.OutputSettings;
Assert.Equal(os.OmitXmlDeclaration, (bool)param2);
return;
}
//[Variation(id = 13, Desc = "Verify OutputSettings when omit-xml-declaration has an invalid value, expected null", Pri = 2, Params = new object[] { "books.xml", "OmitXmlDecl_Invalid1.xsl" })]
[InlineData("books.xml", "OmitXmlDecl_Invalid1.xsl")]
[Theory]
public void OS4(object param0, object param1)
{
Init(param0.ToString(), param1.ToString());
try
{
_xsl.Load(_xslFile);
}
catch (XsltException e)
{
_output.WriteLine(e.ToString());
XmlWriterSettings os = _xsl.OutputSettings;
Assert.Null(os);
}
return;
}
//[Variation(id = 14, Desc = "Verify OutputSettings on non well-formed XSLT, expected null", Pri = 2, Params = new object[] { "books.xml", "OmitXmlDecl_Invalid2.xsl" })]
[InlineData("books.xml", "OmitXmlDecl_Invalid2.xsl")]
[Theory]
public void OS5(object param0, object param1)
{
Init(param0.ToString(), param1.ToString());
try
{
_xsl.Load(_xslFile);
}
catch (XsltException e)
{
_output.WriteLine(e.ToString());
XmlWriterSettings os = _xsl.OutputSettings;
Assert.Null(os);
}
return;
}
//[Variation(id = 18, Desc = "Verify Encoding set to windows-1252 explicitly, expected windows-1252", Pri = 1, Params = new object[] { "books.xml", "Encoding4.xsl", "windows-1252", "Encoding must be windows-1252" })]
[InlineData("books.xml", "Encoding4.xsl", "windows-1252")]
[Theory]
public void OS6_Windows1252Encoding(object param0, object param1, object param2)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
OS6(param0, param1, param2);
}
//[Variation(id = 15, Desc = "Verify default Encoding, expected UTF-8", Pri = 1, Params = new object[] { "books.xml", "Encoding1.xsl", "utf-8", "Default Encoding must be utf-8" })]
[InlineData("books.xml", "Encoding1.xsl", "utf-8")]
//[Variation(id = 16, Desc = "Verify Encoding set to UTF-8 explicitly, expected UTF-8", Pri = 1, Params = new object[] { "books.xml", "Encoding2.xsl", "utf-8", "Encoding must be utf-8" })]
[InlineData("books.xml", "Encoding2.xsl", "utf-8")]
//[Variation(id = 17, Desc = "Verify Encoding set to UTF-16 explicitly, expected UTF-16", Pri = 1, Params = new object[] { "books.xml", "Encoding3.xsl", "utf-16", "Encoding must be utf-16" })]
[InlineData("books.xml", "Encoding3.xsl", "utf-16")]
//[Variation(id = 19, Desc = "Verify Encoding when multiple xsl:output tags are present, expected the last set (iso-8859-1)", Pri = 1, Params = new object[] { "books.xml", "Encoding5.xsl", "iso-8859-1", "Encoding must be iso-8859-1" })]
[InlineData("books.xml", "Encoding5.xsl", "iso-8859-1")]
[Theory]
public void OS6(object param0, object param1, object param2)
{
Init(param0.ToString(), param1.ToString());
_xsl.Load(_xslFile);
XmlWriterSettings os = _xsl.OutputSettings;
Assert.Equal(os.Encoding, System.Text.Encoding.GetEncoding((string)param2));
return;
}
//[Variation(id = 20, Desc = "Verify Indent when indent is omitted in XSLT, expected false", Pri = 0, Params = new object[] { "books.xml", "Indent_Default.xsl", false, "Default value for Indent is 'no'" })]
[InlineData("books.xml", "Indent_Default.xsl", false)]
//[Variation(id = 21, Desc = "Verify Indent when indent is yes in XSLT, expected true", Pri = 0, Params = new object[] { "books.xml", "Indent_Yes.xsl", true, "Indent must be 'yes'" })]
[InlineData("books.xml", "Indent_Yes.xsl", true)]
//[Variation(id = 22, Desc = "Verify Indent when indent is no in XSLT, expected false", Pri = 1, Params = new object[] { "books.xml", "Indent_No.xsl", false, "Indent must be 'no'" })]
[InlineData("books.xml", "Indent_No.xsl", false)]
[Theory]
public void OS7(object param0, object param1, object param2)
{
Init(param0.ToString(), param1.ToString());
_xsl.Load(_xslFile);
XmlWriterSettings os = _xsl.OutputSettings;
Assert.Equal(os.Indent, (bool)param2);
return;
}
//[Variation(id = 23, Desc = "Verify OutputSettings when Indent has an invalid value, expected null", Pri = 2, Params = new object[] { "books.xml", "Indent_Invalid1.xsl" })]
[InlineData("books.xml", "Indent_Invalid1.xsl")]
[Theory]
public void OS8(object param0, object param1)
{
Init(param0.ToString(), param1.ToString());
try
{
_xsl.Load(_xslFile);
}
catch (XsltException e)
{
_output.WriteLine(e.ToString());
XmlWriterSettings os = _xsl.OutputSettings;
Assert.Null(os);
}
return;
}
//[Variation(id = 24, Desc = "Verify OutputSettings on non well-formed XSLT, expected null", Pri = 2, Params = new object[] { "books.xml", "Indent_Invalid2.xsl" })]
[InlineData("books.xml", "Indent_Invalid2.xsl")]
[Theory]
public void OS9(object param0, object param1)
{
Init(param0.ToString(), param1.ToString());
try
{
_xsl.Load(_xslFile);
}
catch (XsltException e)
{
_output.WriteLine(e.ToString());
XmlWriterSettings os = _xsl.OutputSettings;
Assert.Null(os);
}
return;
}
//[Variation(id = 25, Desc = "Verify OutputSettings with all attributes on xsl:output", Pri = 0, Params = new object[] { "books.xml", "OutputSettings.xsl" })]
[InlineData("books.xml", "OutputSettings.xsl")]
[Theory]
public void OS10(object param0, object param1)
{
Init(param0.ToString(), param1.ToString());
_xsl.Load(_xslFile);
XmlWriterSettings os = _xsl.OutputSettings;
_output.WriteLine("OmitXmlDeclaration : {0}", os.OmitXmlDeclaration);
Assert.True(os.OmitXmlDeclaration);
_output.WriteLine("Indent : {0}", os.Indent);
Assert.True(os.Indent);
_output.WriteLine("OutputMethod : {0}", os.OutputMethod);
Assert.Equal(XmlOutputMethod.Xml, os.OutputMethod);
_output.WriteLine("Encoding : {0}", os.Encoding.ToString());
Assert.Equal(os.Encoding, System.Text.Encoding.GetEncoding("utf-8"));
return;
}
//[Variation(id = 26, Desc = "Compare Stream Output with XmlWriter over Stream with OutputSettings", Pri = 0, Params = new object[] { "books.xml", "OutputSettings1.xsl" })]
[InlineData("books.xml", "OutputSettings1.xsl")]
[Theory]
public void OS11(object param0, object param1)
{
Init(param0.ToString(), param1.ToString());
_xsl.Load(_xslFile);
//Transform to Stream
Stream stm1 = new FileStream("out1.xml", FileMode.Create, FileAccess.ReadWrite);
_output.WriteLine("Transforming to Stream1 - 'out1.xml'");
_xsl.Transform(_xmlFile, null, stm1);
//Create an XmlWriter using OutputSettings
Stream stm2 = new FileStream("out2.xml", FileMode.Create, FileAccess.ReadWrite);
XmlWriterSettings os = _xsl.OutputSettings;
XmlWriter xw = XmlWriter.Create(stm2, os);
//Transform to XmlWriter
_output.WriteLine("Transforming to XmlWriter over Stream2 with XSLT OutputSettings - 'out2.xml'");
_xsl.Transform(_xmlFile, null, xw);
//Close the streams
stm1.Dispose();
stm2.Dispose();
//XmlDiff the 2 Outputs.
XmlDiff.XmlDiff diff = new XmlDiff.XmlDiff();
XmlReader xr1 = XmlReader.Create("out1.xml");
XmlReader xr2 = XmlReader.Create("out2.xml");
//XmlDiff
_output.WriteLine("Comparing the Stream Output and XmlWriter Output");
Assert.True(diff.Compare(xr1, xr2));
//Delete the temp files
xr1.Dispose();
xr2.Dispose();
File.Delete("out1.xml");
File.Delete("out2.xml");
return;
}
}
}
| |
// NaticeCode.cs
// Copyright (C) 2004 Mike Krueger
//
// This program is free software. It is dual licensed under GNU GPL and GNU LGPL.
// See COPYING_GPL.txt and COPYING_LGPL.txt for details.
//
using System;
using System.Text;
using System.Security;
using System.Runtime.InteropServices;
namespace ICSharpCode.USBlib.Internal
{
/// <summary>
/// Descriptor sizes per descriptor type.
/// </summary>
public enum UsbDescriptorTypeSize
{
Device = 18,
Config = 9,
Interface = 9,
EndPoint = 7,
EndPointAudio = 9, // Audio extension
HUBNonVar = 7
}
/// <summary>
/// All standard descriptors have these 2 fields in common
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct usb_descriptor_header
{
public byte bLength;
public byte bDescriptorType;
public override string ToString()
{
return String.Format("[usb_descriptor_header: bDescriptorType = {0}, bLength = {1}]",
bDescriptorType,
bLength);
}
};
/// <summary>
/// String descriptor
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct usb_string_descriptor
{
public byte bLength;
public byte bDescriptorType;
public ushort wData0;
public override string ToString()
{
return String.Format("[usb_string_descriptor: bDescriptorType = {0}, bLength = {1}, wData0 = {2}]",
bDescriptorType,
bLength,
wData0);
}
};
/// <summary>
/// HID descriptor
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct usb_hid_descriptor
{
public byte bLength;
public byte bDescriptorType;
public ushort bcdHID;
public byte bCountryCode;
public byte bNumDescriptors;
/* byte bReportDescriptorType; */
/* ushort wDescriptorLength; */
/* ... */
public override string ToString()
{
return String.Format("[usb_hid_descriptor: bcdHID = {0}, bCountryCode = {1}, bDescriptorType = {2}, bLength = {3}, bNumDescriptors = {4}]",
bcdHID,
bCountryCode,
bDescriptorType,
bLength,
bNumDescriptors);
}
};
/// <summary>
/// Endpoint descriptor
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct usb_endpoint_descriptor
{
public const byte USB_MAXENDPOINTS = 32;
public byte bLength;
public byte bDescriptorType;
public byte bEndpointAddress;
public byte bmAttributes;
public ushort wMaxPacketSize;
public byte bInterval;
public byte bRefresh;
public byte bSynchAddress;
public IntPtr extra; // Extra descriptors
public int extralen;
public const byte USB_ENDPOINT_ADDRESS_MASK = 0x0f; // in bEndpointAddress
public const byte USB_ENDPOINT_DIR_MASK = 0x80;
public const byte USB_ENDPOINT_TYPE_MASK = 0x03; // in bmAttributes
public const byte USB_ENDPOINT_TYPE_CONTROL = 0;
public const byte USB_ENDPOINT_TYPE_ISOCHRONOUS = 1;
public const byte USB_ENDPOINT_TYPE_BULK = 2;
public const byte USB_ENDPOINT_TYPE_INTERRUPT = 3;
public override string ToString() {
return String.Format("[usb_endpoint_descriptor: bDescriptorType = {0}, bEndpointAddress = {1}, bInterval = {2}, bLength = {3}, bmAttributes = {4}, bRefresh = {5}, bSynchAddress = {6}, extra = {7}, extralen = {8}, wMaxPacketSize = {9}]",
bDescriptorType,
bEndpointAddress,
bInterval,
bLength,
bmAttributes,
bRefresh,
bSynchAddress,
extra,
extralen,
wMaxPacketSize);
}
};
/// <summary>
/// Interface descriptor
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct usb_interface_descriptor
{
public const int USB_MAXINTERFACES = 32;
public byte bLength;
public byte bDescriptorType;
public byte bInterfaceNumber;
public byte bAlternateSetting;
public byte bNumEndpoints;
public byte bInterfaceClass;
public byte bInterfaceSubClass;
public byte bInterfaceProtocol;
public byte iInterface;
public IntPtr endpoint;
public IntPtr extra; /* Extra descriptors */
public int extralen;
public usb_endpoint_descriptor Endpoint {
get {
if (endpoint == IntPtr.Zero) {
return new usb_endpoint_descriptor();
}
return (usb_endpoint_descriptor)Marshal.PtrToStructure(endpoint, typeof(usb_endpoint_descriptor));
}
}
public override string ToString()
{
return String.Format("[usb_interface_descriptor: bAlternateSetting = {0}, bDescriptorType = {1}, bInterfaceClass = {2}, bInterfaceNumber = {3}, bInterfaceProtocol = {4}, bInterfaceSubClass = {5}, bLength = {6}, bNumEndpoints = {7}, endpoint = {8}, extra = {9}, extralen = {10}, iInterface = {11}]",
bAlternateSetting,
bDescriptorType,
bInterfaceClass,
bInterfaceNumber,
bInterfaceProtocol,
bInterfaceSubClass,
bLength,
bNumEndpoints,
endpoint,
extra,
extralen,
iInterface);
}
};
[StructLayout(LayoutKind.Sequential)]
internal struct usb_interface
{
public const int USB_MAXALTSETTING = 128; /* Hard limit */
public IntPtr altsetting;
public int num_altsetting;
public usb_interface_descriptor Altsetting {
get {
if (altsetting == IntPtr.Zero) {
return new usb_interface_descriptor();
}
return (usb_interface_descriptor)Marshal.PtrToStructure(altsetting, typeof(usb_interface_descriptor));
}
}
public override string ToString()
{
return String.Format("[usb_interface: altsetting = {0}, num_altsetting = {1}]",
altsetting,
num_altsetting);
}
};
/* Configuration descriptor information.. */
[StructLayout(LayoutKind.Sequential)]
internal struct usb_config_descriptor
{
public const int USB_MAXCONFIG = 8;
public byte bLength;
public byte bDescriptorType;
public ushort wTotalLength;
public byte bNumInterfaces;
public byte bConfigurationValue;
public byte iConfiguration;
public byte bmAttributes;
public byte MaxPower;
public IntPtr iface;
public IntPtr extra; /* Extra descriptors */
public int extralen;
public usb_interface Interface {
get {
if (iface == IntPtr.Zero) {
return new usb_interface();
}
return (usb_interface)Marshal.PtrToStructure(iface, typeof(usb_interface));
}
}
public override string ToString()
{
return String.Format("[usb_config_descriptor: bConfigurationValue = {0}, bDescriptorType = {1}, bLength = {2}, bmAttributes = {3}, bNumInterfaces = {4}, extra = {5}, extralen = {6}, iConfiguration = {7}, iface = {8}, MaxPower = {9}, wTotalLength = {10}]",
bConfigurationValue,
bDescriptorType,
bLength,
bmAttributes,
bNumInterfaces,
extra,
extralen,
iConfiguration,
iface,
MaxPower,
wTotalLength);
}
};
/* Device descriptor */
[StructLayout(LayoutKind.Sequential)]
internal struct usb_device_descriptor
{
public byte bLength;
public byte bDescriptorType;
public ushort bcdUSB;
public byte bDeviceClass;
public byte bDeviceSubClass;
public byte bDeviceProtocol;
public byte bMaxPacketSize0;
public ushort idVendor;
public ushort idProduct;
public ushort bcdDevice;
public byte iManufacturer;
public byte iProduct;
public byte iSerialNumber;
public byte bNumConfigurations;
public override string ToString()
{
return String.Format("[usb_device_descriptor: bcdDevice = {0}, bcdUSB = {1}, bDescriptorType = {2}, bDeviceClass = {3}, bDeviceProtocol = {4}, bDeviceSubClass = {5}, bLength = {6}, bMaxPacketSize0 = {7}, bNumConfigurations = {8}, idProduct = {9}, idVendor = {10}, iManufacturer = {11}, iProduct = {12}, iSerialNumber = {13}]",
bcdDevice,
bcdUSB,
bDescriptorType,
bDeviceClass,
bDeviceProtocol,
bDeviceSubClass,
bLength,
bMaxPacketSize0,
bNumConfigurations,
idProduct,
idVendor,
iManufacturer,
iProduct,
iSerialNumber);
}
};
[StructLayout(LayoutKind.Sequential)]
internal struct usb_ctrl_setup
{
public byte bRequestType;
public byte bRequest;
public ushort wValue;
public ushort wIndex;
public ushort wLength;
public override string ToString()
{
return String.Format("[usb_ctrl_setup: bRequest = {0}, bRequestType = {1}, wIndex = {2}, wLength = {3}, wValue = {4}]",
bRequest,
bRequestType,
wIndex,
wLength,
wValue);
}
};
[StructLayout(LayoutKind.Sequential)]
internal class usb_device
{
public IntPtr next = IntPtr.Zero;
public IntPtr prev = IntPtr.Zero;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = NativeMethods.LIBUSB_PATH_MAX)]
public string filename = String.Empty;
public IntPtr bus = IntPtr.Zero;
public usb_device_descriptor descriptor = new usb_device_descriptor();
public IntPtr config = IntPtr.Zero;
public IntPtr dev = IntPtr.Zero; // Darwin support
public override string ToString()
{
return String.Format("[usb_device: filename={0}, next={1}, prev={2}, bus={3}, descriptor={4}, config={5}, dev={6}]",
filename,
next,
prev,
bus,
descriptor,
config,
dev);
}
public usb_device Next {
get {
if (next == IntPtr.Zero) {
return null;
}
return (usb_device)Marshal.PtrToStructure(next, typeof(usb_device));
}
}
public usb_device Prev {
get {
if (prev == IntPtr.Zero) {
return null;
}
return (usb_device)Marshal.PtrToStructure(prev, typeof(usb_device));
}
}
public usb_bus Bus {
get {
if (bus == IntPtr.Zero) {
return null;
}
return (usb_bus)Marshal.PtrToStructure(bus, typeof(usb_bus));
}
}
// public usb_device_descriptor Descriptor {
// get {
// return (usb_device_descriptor)Marshal.PtrToStructure(bus, typeof(usb_device_descriptor));
// }
// }
//
public usb_config_descriptor GetConfig(int number)
{
if (config == IntPtr.Zero) {
return new usb_config_descriptor();
}
IntPtr configPtr = new IntPtr(config.ToInt64() + number * Marshal.SizeOf(typeof(usb_config_descriptor)));
return (usb_config_descriptor)Marshal.PtrToStructure(configPtr, typeof(usb_config_descriptor));
}
};
[StructLayout(LayoutKind.Sequential)]
internal class usb_bus
{
public IntPtr next = IntPtr.Zero;
public IntPtr prev = IntPtr.Zero;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = NativeMethods.LIBUSB_PATH_MAX)]
public string dirname = String.Empty;
public IntPtr devices= IntPtr.Zero;
public uint location = 0;
public usb_bus Next {
get {
if (next == IntPtr.Zero) {
return null;
}
return (usb_bus)Marshal.PtrToStructure(next, typeof(usb_bus));
}
}
public usb_bus Prev {
get {
if (prev == IntPtr.Zero) {
return null;
}
return (usb_bus)Marshal.PtrToStructure(prev, typeof(usb_bus));
}
}
public usb_device Devices {
get {
if (devices == IntPtr.Zero) {
return null;
}
return (usb_device)Marshal.PtrToStructure(devices, typeof(usb_device));
}
}
public override string ToString()
{
return String.Format("[usb_bus: dirname={0}, next={1}, prev={2}, Devices={3}, location={4}]",
dirname,
next,
prev,
Devices,
location);
}
};
internal sealed class NativeMethods
{
// Standard requests
public const int USB_REQ_GET_STATUS = 0x00;
public const int USB_REQ_CLEAR_FEATURE = 0x01;
// 0x02 is reserved
public const int USB_REQ_SET_FEATURE = 0x03;
// 0x04 is reserved
public const int USB_REQ_SET_ADDRESS = 0x05;
public const int USB_REQ_GET_DESCRIPTOR = 0x06;
public const int USB_REQ_SET_DESCRIPTOR = 0x07;
public const int USB_REQ_GET_CONFIGURATION = 0x08;
public const int USB_REQ_SET_CONFIGURATION = 0x09;
public const int USB_REQ_GET_INTERFACE = 0x0A;
public const int USB_REQ_SET_INTERFACE = 0x0B;
public const int USB_REQ_SYNCH_FRAME = 0x0C;
public const int USB_TYPE_STANDARD = (0x00 << 5);
public const int USB_TYPE_CLASS = (0x01 << 5);
public const int USB_TYPE_VENDOR = (0x02 << 5);
public const int USB_TYPE_RESERVED = (0x03 << 5);
public const int USB_RECIP_DEVICE = 0x00;
public const int USB_RECIP_INTERFACE = 0x01;
public const int USB_RECIP_ENDPOINT = 0x02;
public const int USB_RECIP_OTHER = 0x03;
// Various libusb API related stuff
public const int USB_ENDPOINT_IN = 0x80;
public const int USB_ENDPOINT_OUT = 0x00;
// Error codes
public const int USB_ERROR_BEGIN = 500000;
const CallingConvention CALLING_CONVENTION = CallingConvention.Cdecl;
#if WIN32
const string LIBUSB_NATIVE_LIBRARY = "libusb0.dll";
public const int LIBUSB_PATH_MAX = 512;
#else
const string LIBUSB_NATIVE_LIBRARY = "libusb";
public const int LIBUSB_PATH_MAX = 4096 + 1;
#endif
// usb.c
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern IntPtr usb_open(usb_device dev);
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern int usb_close(IntPtr dev);
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern int usb_get_string(IntPtr dev, int index, int langid, StringBuilder buf, int buflen);
public static int usb_get_string(IntPtr dev, int index, int langid, StringBuilder buf)
{
return usb_get_string(dev, index, langid, buf, buf == null ? 0 : buf.Capacity);
}
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern int usb_get_string_simple(IntPtr dev, int index, StringBuilder buf, int buflen);
public static int usb_get_string_simple(IntPtr dev, int index, StringBuilder buf)
{
return usb_get_string_simple(dev, index, buf, buf == null ? 0 : buf.Capacity);
}
// descriptors.c
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern int usb_get_descriptor_by_endpoint(IntPtr udev, int ep, byte type, byte index, IntPtr buf, int size);
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern int usb_get_descriptor(IntPtr udev, byte type, byte index, IntPtr buf, int size);
// <arch>.c
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern int usb_bulk_write(IntPtr dev, int ep, byte[] bytes, int size, int timeout);
public static int usb_bulk_write(IntPtr dev, int ep, byte[] bytes, int timeout)
{
return usb_bulk_write(dev, ep, bytes, bytes == null ? 0 : bytes.Length, timeout);
}
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern int usb_bulk_read(IntPtr dev, int ep, byte[] bytes, int size, int timeout);
public static int usb_bulk_read(IntPtr dev, int ep, byte[] bytes, int timeout)
{
return usb_bulk_read(dev, ep, bytes, bytes == null ? 0 : bytes.Length, timeout);
}
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern int usb_interrupt_write(IntPtr dev, int ep, byte[] bytes, int size, int timeout);
public static int usb_interrupt_write(IntPtr dev, int ep, byte[] bytes, int timeout)
{
return usb_interrupt_write(dev, ep, bytes, bytes == null ? 0 : bytes.Length, timeout);
}
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern int usb_interrupt_read(IntPtr dev, int ep, byte[] bytes, int size, int timeout);
public static int usb_interrupt_read(IntPtr dev, int ep, byte[] bytes, int timeout)
{
return usb_interrupt_read(dev, ep, bytes, bytes == null ? 0 : bytes.Length, timeout);
}
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern int usb_control_msg(IntPtr dev, int requesttype, int request, int value, int index, byte[] bytes, int size, int timeout);
public static int usb_control_msg(IntPtr dev, int requesttype, int request, int value, byte[] bytes, int timeout)
{
return usb_control_msg(dev, requesttype, request, value, 0, bytes, bytes == null ? 0 : bytes.Length, timeout);
}
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern int usb_set_configuration(IntPtr dev, int configuration);
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern int usb_claim_interface(IntPtr dev, int interfaceNum);
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern int usb_release_interface(IntPtr dev, int interfaceNum);
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern int usb_set_altinterface(IntPtr dev, int alternate);
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern int usb_resetep(IntPtr dev, uint ep);
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern int usb_clear_halt(IntPtr dev, uint ep);
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern int usb_reset(IntPtr dev);
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern string usb_strerror();
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern void usb_init();
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern void usb_set_debug(int level);
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern int usb_find_busses();
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern int usb_find_devices();
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern usb_device usb_device(IntPtr dev);
[DllImport(LIBUSB_NATIVE_LIBRARY, CallingConvention = CALLING_CONVENTION, ExactSpelling = true), SuppressUnmanagedCodeSecurity]
public static extern usb_bus usb_get_busses();
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.11.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyInteger
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Models;
public static partial class IntModelExtensions
{
/// <summary>
/// Get null Int value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static int? GetNull(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetNullAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get null Int value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<int?> GetNullAsync( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<int?> result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Get invalid Int value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static int? GetInvalid(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetInvalidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get invalid Int value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<int?> GetInvalidAsync( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<int?> result = await operations.GetInvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Get overflow Int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static int? GetOverflowInt32(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetOverflowInt32Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get overflow Int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<int?> GetOverflowInt32Async( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<int?> result = await operations.GetOverflowInt32WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Get underflow Int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static int? GetUnderflowInt32(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetUnderflowInt32Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get underflow Int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<int?> GetUnderflowInt32Async( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<int?> result = await operations.GetUnderflowInt32WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Get overflow Int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static long? GetOverflowInt64(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetOverflowInt64Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get overflow Int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<long?> GetOverflowInt64Async( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<long?> result = await operations.GetOverflowInt64WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Get underflow Int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static long? GetUnderflowInt64(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetUnderflowInt64Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get underflow Int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<long?> GetUnderflowInt64Async( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<long?> result = await operations.GetUnderflowInt64WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Put max int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
public static void PutMax32(this IIntModel operations, int? intBody)
{
Task.Factory.StartNew(s => ((IIntModel)s).PutMax32Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put max int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutMax32Async( this IIntModel operations, int? intBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutMax32WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Put max int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
public static void PutMax64(this IIntModel operations, long? intBody)
{
Task.Factory.StartNew(s => ((IIntModel)s).PutMax64Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put max int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutMax64Async( this IIntModel operations, long? intBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutMax64WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Put min int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
public static void PutMin32(this IIntModel operations, int? intBody)
{
Task.Factory.StartNew(s => ((IIntModel)s).PutMin32Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put min int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutMin32Async( this IIntModel operations, int? intBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutMin32WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Put min int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
public static void PutMin64(this IIntModel operations, long? intBody)
{
Task.Factory.StartNew(s => ((IIntModel)s).PutMin64Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put min int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutMin64Async( this IIntModel operations, long? intBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutMin64WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false);
}
}
}
| |
// <copyright file=Polygon.cs
// <copyright>
// Copyright (c) 2016, University of Stuttgart
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software),
// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
// <license>MIT License</license>
// <main contributors>
// Markus Funk, Thomas Kosch, Sven Mayer
// </main contributors>
// <co-contributors>
// Paul Brombosch, Mai El-Komy, Juana Heusler,
// Matthias Hoppe, Robert Konrad, Alexander Martin
// </co-contributors>
// <patent information>
// We are aware that this software implements patterns and ideas,
// which might be protected by patents in your country.
// Example patents in Germany are:
// Patent reference number: DE 103 20 557.8
// Patent reference number: DE 10 2013 220 107.9
// Please make sure when using this software not to violate any existing patents in your country.
// </patent information>
// <date> 11/2/2016 12:25:57 PM</date>
using HciLab.Utilities.Mathematics.Core;
using System;
using System.ComponentModel;
using System.Linq;
using System.Runtime.Serialization;
namespace HciLab.Utilities.Mathematics.Geometry2D
{
/// <summary>
/// Represents a polygon in 2 dimentional space.
/// </summary>
[Serializable()]
public class Polygon : DataBaseClass, ISerializable, ICloneable
{
/// <summary>
/// ISerialization Version
/// </summary>
private int m_SerVersion = 1;
#region Private fields
//private Vector2DArrayList m_Points = new Vector2DArrayList();
private CollectionWithItemNotify<Vector2> m_Points = new CollectionWithItemNotify<Vector2>();
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Polygon"/> class.
/// </summary>
public Polygon()
: base()
{
initListener();
}
/// <summary>
/// Initializes a new instance of the <see cref="Polygon"/> class using an array of coordinates.
/// </summary>
/// <param name="pPoints">An <see cref="Vector2DArrayList"/> instance.</param>
public Polygon(Vector2DArrayList pPoints)
: base()
{
foreach(Vector2 v in pPoints.ToArray())
m_Points.Add(v);
initListener();
}
/// <summary>
/// Initializes a new instance of the <see cref="Polygon"/> class using an array of coordinates.
/// </summary>
/// <param name="pPoints">An array of <see cref="Vector2"/> coordniates.</param>
public Polygon(Vector2[] pPoints)
: base()
{
foreach (Vector2 v in pPoints)
m_Points.Add(v);
initListener();
}
/// <summary>
/// Initializes a new instance of the <see cref="Polygon"/> class using coordinates from another instance.
/// </summary>
/// <param name="polygon">A <see cref="Polygon"/> instance.</param>
public Polygon(Polygon polygon)
: base()
{
foreach (Vector2 v in polygon.Points)
m_Points.Add(new Vector2(v.X, v.Y));
initListener();
}
public Polygon(System.Collections.Generic.List<Vector2> pList)
: base()
{
foreach (Vector2 v in pList)
m_Points.Add(v);
initListener();
}
private void initListener()
{
if (m_Points == null)
return;
m_Points.ItemPropertyChanged += Points_PropertyChanged;
m_Points.CollectionChanged += Points_CollectionChanged;
//m_Points.ItemsPropertyChanged += Points_ItemsPropertyChanged;
}
/// <summary>
/// Initializes a new instance of the <see cref="Polygon"/> class with serialized data.
/// </summary>
/// <param name="pInfo">The object that holds the serialized object data.</param>
/// <param name="pContext">The contextual information about the source or destination.</param>
protected Polygon(SerializationInfo pInfo, StreamingContext pContext)
: base(pInfo, pContext)
{
int pSerVersion = pInfo.GetInt32("m_SerVersion");
if (m_SerVersion >= 1)
{
m_Points = (CollectionWithItemNotify<Vector2>)pInfo.GetValue("m_Points", typeof(CollectionWithItemNotify<Vector2>));
}
initListener();
}
#endregion
#region Public Properties
public CollectionWithItemNotify<Vector2> Points
{
get {
return m_Points;
}
set {
m_Points = value;
initListener();
}
}
void Points_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
NotifyPropertyChanged();
}
void Points_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
NotifyPropertyChanged();
}
#endregion
#region ICloneable Members
/// <summary>
/// Creates an exact copy of this <see cref="Polygon"/> object.
/// </summary>
/// <returns>The <see cref="Polygon"/> object this method creates, cast as an object.</returns>
object ICloneable.Clone()
{
return new Polygon(this);
}
/// <summary>
/// Creates an exact copy of this <see cref="Polygon"/> object.
/// </summary>
/// <returns>The <see cref="Polygon"/> object this method creates.</returns>
public Polygon Clone()
{
return new Polygon(this);
}
#endregion
#region ISerializable Members
/// <summary>
/// Populates a <see cref="SerializationInfo"/> with the data needed to serialize this object.
/// </summary>
/// <param name="pInfo">The <see cref="SerializationInfo"/> to populate with data. </param>
/// <param name="pContext">The destination (see <see cref="StreamingContext"/>) for this serialization.</param>
//[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter=true)]
public void GetObjectData(SerializationInfo pInfo, StreamingContext pContext)
{
base.GetObjectData(pInfo, pContext);
pInfo.AddValue("m_SerVersion", m_SerVersion);
pInfo.AddValue("m_Points", m_Points);
}
#endregion
#region Public Methods
/// <summary>
/// Flips the polygon.
/// </summary>
public void Flip()
{
m_Points = new CollectionWithItemNotify<Vector2>(m_Points.Reverse());
}
#endregion
#region Public Properties
/// <summary>
/// Gets the polygon's vertex count.
/// </summary>
public int VertexCount
{
get { return m_Points.Count; }
}
#endregion
public HelixToolkit.Wpf.Polygon ToHelixToolkit()
{
HelixToolkit.Wpf.Polygon p = new HelixToolkit.Wpf.Polygon();
foreach (HciLab.Utilities.Mathematics.Core.Vector2 v in Points)
p.Points.Add(new System.Windows.Point(v.X, v.Y));
return p;
}
public HelixToolkit.Wpf.Polygon3D ToHelixToolkit3D(double pOffset = 0)
{
HelixToolkit.Wpf.Polygon3D p = new HelixToolkit.Wpf.Polygon3D();
foreach (HciLab.Utilities.Mathematics.Core.Vector2 v in Points)
p.Points.Add(new System.Windows.Media.Media3D.Point3D(v.X, v.Y, pOffset));
return p;
}
}
}
| |
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
namespace MaterialDesignThemes.Wpf
{
/// <summary>
/// Helper properties for working with text fields.
/// </summary>
public static class TextFieldAssist
{
/// <summary>
/// The text box view margin property
/// </summary>
public static readonly DependencyProperty TextBoxViewMarginProperty = DependencyProperty.RegisterAttached(
"TextBoxViewMargin",
typeof(Thickness),
typeof(TextFieldAssist),
new FrameworkPropertyMetadata(new Thickness(double.NegativeInfinity), FrameworkPropertyMetadataOptions.Inherits, TextBoxViewMarginPropertyChangedCallback));
/// <summary>
/// Sets the text box view margin.
/// </summary>
/// <param name="element">The element.</param>
/// <param name="value">The value.</param>
public static void SetTextBoxViewMargin(DependencyObject element, Thickness value)
{
element.SetValue(TextBoxViewMarginProperty, value);
}
/// <summary>
/// Gets the text box view margin.
/// </summary>
/// <param name="element">The element.</param>
/// <returns>
/// The <see cref="Thickness" />.
/// </returns>
public static Thickness GetTextBoxViewMargin(DependencyObject element)
{
return (Thickness)element.GetValue(TextBoxViewMarginProperty);
}
/// <summary>
/// Controls the visibility of the underline decoration.
/// </summary>
public static readonly DependencyProperty DecorationVisibilityProperty = DependencyProperty.RegisterAttached(
"DecorationVisibility", typeof(Visibility), typeof(TextFieldAssist), new PropertyMetadata(default(Visibility)));
/// <summary>
/// Controls the visibility of the underline decoration.
/// </summary>
public static void SetDecorationVisibility(DependencyObject element, Visibility value)
{
element.SetValue(DecorationVisibilityProperty, value);
}
/// <summary>
/// Controls the visibility of the underline decoration.
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
public static Visibility GetDecorationVisibility(DependencyObject element)
{
return (Visibility)element.GetValue(DecorationVisibilityProperty);
}
/// <summary>
/// Automatially inserts spelling suggestions into the text box context menu.
/// </summary>
public static readonly DependencyProperty IncludeSpellingSuggestionsProperty = DependencyProperty.RegisterAttached(
"IncludeSpellingSuggestions", typeof(bool), typeof(TextFieldAssist), new PropertyMetadata(default(bool), IncludeSpellingSuggestionsChanged));
public static void SetIncludeSpellingSuggestions(TextBoxBase element, bool value)
{
element.SetValue(IncludeSpellingSuggestionsProperty, value);
}
public static bool GetIncludeSpellingSuggestions(TextBoxBase element)
{
return (bool)element.GetValue(IncludeSpellingSuggestionsProperty);
}
private static void IncludeSpellingSuggestionsChanged(DependencyObject element, DependencyPropertyChangedEventArgs e)
{
var textBox = element as TextBoxBase;
if (textBox != null)
{
if ((bool)e.NewValue)
{
textBox.ContextMenuOpening += TextBoxOnContextMenuOpening;
textBox.ContextMenuClosing += TextBoxOnContextMenuClosing;
}
else
{
textBox.ContextMenuOpening -= TextBoxOnContextMenuOpening;
textBox.ContextMenuClosing -= TextBoxOnContextMenuClosing;
}
}
}
private static void TextBoxOnContextMenuOpening(object sender, ContextMenuEventArgs e)
{
var textBoxBase = sender as TextBoxBase;
ContextMenu contextMenu = textBoxBase?.ContextMenu;
if (contextMenu == null) return;
RemoveSpellingSuggestions(contextMenu);
if (!SpellCheck.GetIsEnabled(textBoxBase)) return;
SpellingError spellingError = GetSpellingError(textBoxBase);
if (spellingError != null)
{
Style spellingSuggestionStyle =
contextMenu.TryFindResource(Spelling.SuggestionMenuItemStyleKey) as Style;
int insertionIndex = 0;
bool hasSuggestion = false;
foreach (string suggestion in spellingError.Suggestions)
{
hasSuggestion = true;
var menuItem = new MenuItem
{
CommandTarget = textBoxBase,
Command = EditingCommands.CorrectSpellingError,
CommandParameter = suggestion,
Style = spellingSuggestionStyle,
Tag = typeof(Spelling)
};
contextMenu.Items.Insert(insertionIndex++, menuItem);
}
if (!hasSuggestion)
{
contextMenu.Items.Insert(insertionIndex++, new MenuItem
{
Style = contextMenu.TryFindResource(Spelling.NoSuggestionsMenuItemStyleKey) as Style,
Tag = typeof(Spelling)
});
}
contextMenu.Items.Insert(insertionIndex++, new Separator
{
Style = contextMenu.TryFindResource(Spelling.SeparatorStyleKey) as Style,
Tag = typeof(Spelling)
});
contextMenu.Items.Insert(insertionIndex++, new MenuItem
{
Command = EditingCommands.IgnoreSpellingError,
CommandTarget = textBoxBase,
Style = contextMenu.TryFindResource(Spelling.IgnoreAllMenuItemStyleKey) as Style,
Tag = typeof(Spelling)
});
contextMenu.Items.Insert(insertionIndex, new Separator
{
Style = contextMenu.TryFindResource(Spelling.SeparatorStyleKey) as Style,
Tag = typeof(Spelling)
});
}
}
private static SpellingError GetSpellingError(TextBoxBase textBoxBase)
{
var textBox = textBoxBase as TextBox;
if (textBox != null)
{
return textBox.GetSpellingError(textBox.CaretIndex);
}
var richTextBox = textBoxBase as RichTextBox;
if (richTextBox != null)
{
return richTextBox.GetSpellingError(richTextBox.CaretPosition);
}
return null;
}
private static void TextBoxOnContextMenuClosing(object sender, ContextMenuEventArgs e)
{
var contextMenu = (sender as TextBoxBase)?.ContextMenu;
if (contextMenu != null)
{
RemoveSpellingSuggestions(contextMenu);
}
}
private static void RemoveSpellingSuggestions(ContextMenu menu)
{
foreach (FrameworkElement item in (from item in menu.Items.OfType<FrameworkElement>()
where ReferenceEquals(item.Tag, typeof(Spelling))
select item).ToList())
{
menu.Items.Remove(item);
}
}
#region Methods
/// <summary>
/// Applies the text box view margin.
/// </summary>
/// <param name="textBox">The text box.</param>
/// <param name="margin">The margin.</param>
private static void ApplyTextBoxViewMargin(Control textBox, Thickness margin)
{
if (margin.Equals(new Thickness(double.NegativeInfinity)))
{
return;
}
var frameworkElement = (textBox.Template.FindName("PART_ContentHost", textBox) as ScrollViewer)?.Content as FrameworkElement;
if (frameworkElement != null)
{
frameworkElement.Margin = margin;
}
}
/// <summary>
/// The text box view margin property changed callback.
/// </summary>
/// <param name="dependencyObject">The dependency object.</param>
/// <param name="dependencyPropertyChangedEventArgs">The dependency property changed event args.</param>
private static void TextBoxViewMarginPropertyChangedCallback(
DependencyObject dependencyObject,
DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
var box = dependencyObject as Control; //could be a text box or password box
if (box == null)
{
return;
}
if (box.IsLoaded)
{
ApplyTextBoxViewMargin(box, (Thickness)dependencyPropertyChangedEventArgs.NewValue);
}
box.Loaded += (sender, args) =>
{
var textBox = (Control)sender;
ApplyTextBoxViewMargin(textBox, GetTextBoxViewMargin(textBox));
};
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Security.Claims
{
public partial class Claim
{
public Claim(System.IO.BinaryReader reader) { }
public Claim(System.IO.BinaryReader reader, System.Security.Claims.ClaimsIdentity subject) { }
protected Claim(System.Security.Claims.Claim other) { }
protected Claim(System.Security.Claims.Claim other, System.Security.Claims.ClaimsIdentity subject) { }
public Claim(string type, string value) { }
public Claim(string type, string value, string valueType) { }
public Claim(string type, string value, string valueType, string issuer) { }
public Claim(string type, string value, string valueType, string issuer, string originalIssuer) { }
public Claim(string type, string value, string valueType, string issuer, string originalIssuer, System.Security.Claims.ClaimsIdentity subject) { }
protected virtual byte[] CustomSerializationData { get { return default(byte[]); } }
public string Issuer { get { return default(string); } }
public string OriginalIssuer { get { return default(string); } }
public System.Collections.Generic.IDictionary<string, string> Properties { get { return default(System.Collections.Generic.IDictionary<string, string>); } }
public System.Security.Claims.ClaimsIdentity Subject { get { return default(System.Security.Claims.ClaimsIdentity); } }
public string Type { get { return default(string); } }
public string Value { get { return default(string); } }
public string ValueType { get { return default(string); } }
public virtual System.Security.Claims.Claim Clone() { return default(System.Security.Claims.Claim); }
public virtual System.Security.Claims.Claim Clone(System.Security.Claims.ClaimsIdentity identity) { return default(System.Security.Claims.Claim); }
public override string ToString() { return default(string); }
public virtual void WriteTo(System.IO.BinaryWriter writer) { }
protected virtual void WriteTo(System.IO.BinaryWriter writer, byte[] userData) { }
}
public partial class ClaimsIdentity : System.Security.Principal.IIdentity
{
public const string DefaultIssuer = "LOCAL AUTHORITY";
public const string DefaultNameClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name";
public const string DefaultRoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role";
public ClaimsIdentity() { }
public ClaimsIdentity(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims) { }
public ClaimsIdentity(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims, string authenticationType) { }
public ClaimsIdentity(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims, string authenticationType, string nameType, string roleType) { }
public ClaimsIdentity(System.IO.BinaryReader reader) { }
protected ClaimsIdentity(System.Security.Claims.ClaimsIdentity other) { }
public ClaimsIdentity(System.Security.Principal.IIdentity identity) { }
public ClaimsIdentity(System.Security.Principal.IIdentity identity, System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims) { }
public ClaimsIdentity(System.Security.Principal.IIdentity identity, System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims, string authenticationType, string nameType, string roleType) { }
public ClaimsIdentity(string authenticationType) { }
public ClaimsIdentity(string authenticationType, string nameType, string roleType) { }
public System.Security.Claims.ClaimsIdentity Actor { get { return default(System.Security.Claims.ClaimsIdentity); } set { } }
public virtual string AuthenticationType { get { return default(string); } }
public object BootstrapContext { get { return default(object); }[System.Security.SecurityCriticalAttribute]set { } }
public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> Claims { get { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); } }
protected virtual byte[] CustomSerializationData { get { return default(byte[]); } }
public virtual bool IsAuthenticated { get { return default(bool); } }
public string Label { get { return default(string); } set { } }
public virtual string Name { get { return default(string); } }
public string NameClaimType { get { return default(string); } }
public string RoleClaimType { get { return default(string); } }
[System.Security.SecurityCriticalAttribute]
public virtual void AddClaim(System.Security.Claims.Claim claim) { }
[System.Security.SecurityCriticalAttribute]
public virtual void AddClaims(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims) { }
public virtual System.Security.Claims.ClaimsIdentity Clone() { return default(System.Security.Claims.ClaimsIdentity); }
protected virtual System.Security.Claims.Claim CreateClaim(System.IO.BinaryReader reader) { return default(System.Security.Claims.Claim); }
public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> FindAll(System.Predicate<System.Security.Claims.Claim> match) { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); }
public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> FindAll(string type) { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); }
public virtual System.Security.Claims.Claim FindFirst(System.Predicate<System.Security.Claims.Claim> match) { return default(System.Security.Claims.Claim); }
public virtual System.Security.Claims.Claim FindFirst(string type) { return default(System.Security.Claims.Claim); }
public virtual bool HasClaim(System.Predicate<System.Security.Claims.Claim> match) { return default(bool); }
public virtual bool HasClaim(string type, string value) { return default(bool); }
[System.Security.SecurityCriticalAttribute]
public virtual void RemoveClaim(System.Security.Claims.Claim claim) { }
[System.Security.SecurityCriticalAttribute]
public virtual bool TryRemoveClaim(System.Security.Claims.Claim claim) { return default(bool); }
public virtual void WriteTo(System.IO.BinaryWriter writer) { }
protected virtual void WriteTo(System.IO.BinaryWriter writer, byte[] userData) { }
}
public partial class ClaimsPrincipal : System.Security.Principal.IPrincipal
{
public ClaimsPrincipal() { }
public ClaimsPrincipal(System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity> identities) { }
public ClaimsPrincipal(System.IO.BinaryReader reader) { }
public ClaimsPrincipal(System.Security.Principal.IIdentity identity) { }
public ClaimsPrincipal(System.Security.Principal.IPrincipal principal) { }
public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> Claims { get { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); } }
public static System.Func<System.Security.Claims.ClaimsPrincipal> ClaimsPrincipalSelector { get { return default(System.Func<System.Security.Claims.ClaimsPrincipal>); }[System.Security.SecurityCriticalAttribute]set { } }
public static System.Security.Claims.ClaimsPrincipal Current { get { return default(System.Security.Claims.ClaimsPrincipal); } }
protected virtual byte[] CustomSerializationData { get { return default(byte[]); } }
public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity> Identities { get { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity>); } }
public virtual System.Security.Principal.IIdentity Identity { get { return default(System.Security.Principal.IIdentity); } }
public static System.Func<System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity>, System.Security.Claims.ClaimsIdentity> PrimaryIdentitySelector { get { return default(System.Func<System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity>, System.Security.Claims.ClaimsIdentity>); }[System.Security.SecurityCriticalAttribute]set { } }
[System.Security.SecurityCriticalAttribute]
public virtual void AddIdentities(System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity> identities) { }
[System.Security.SecurityCriticalAttribute]
public virtual void AddIdentity(System.Security.Claims.ClaimsIdentity identity) { }
public virtual System.Security.Claims.ClaimsPrincipal Clone() { return default(System.Security.Claims.ClaimsPrincipal); }
protected virtual System.Security.Claims.ClaimsIdentity CreateClaimsIdentity(System.IO.BinaryReader reader) { return default(System.Security.Claims.ClaimsIdentity); }
public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> FindAll(System.Predicate<System.Security.Claims.Claim> match) { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); }
public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> FindAll(string type) { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); }
public virtual System.Security.Claims.Claim FindFirst(System.Predicate<System.Security.Claims.Claim> match) { return default(System.Security.Claims.Claim); }
public virtual System.Security.Claims.Claim FindFirst(string type) { return default(System.Security.Claims.Claim); }
public virtual bool HasClaim(System.Predicate<System.Security.Claims.Claim> match) { return default(bool); }
public virtual bool HasClaim(string type, string value) { return default(bool); }
public virtual bool IsInRole(string role) { return default(bool); }
public virtual void WriteTo(System.IO.BinaryWriter writer) { }
protected virtual void WriteTo(System.IO.BinaryWriter writer, byte[] userData) { }
}
public static partial class ClaimTypes
{
public const string Actor = "http://schemas.xmlsoap.org/ws/2009/09/identity/claims/actor";
public const string Anonymous = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/anonymous";
public const string Authentication = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/authentication";
public const string AuthenticationInstant = "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant";
public const string AuthenticationMethod = "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod";
public const string AuthorizationDecision = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/authorizationdecision";
public const string CookiePath = "http://schemas.microsoft.com/ws/2008/06/identity/claims/cookiepath";
public const string Country = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/country";
public const string DateOfBirth = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth";
public const string DenyOnlyPrimaryGroupSid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlyprimarygroupsid";
public const string DenyOnlyPrimarySid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlyprimarysid";
public const string DenyOnlySid = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/denyonlysid";
public const string DenyOnlyWindowsDeviceGroup = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlywindowsdevicegroup";
public const string Dns = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dns";
public const string Dsa = "http://schemas.microsoft.com/ws/2008/06/identity/claims/dsa";
public const string Email = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress";
public const string Expiration = "http://schemas.microsoft.com/ws/2008/06/identity/claims/expiration";
public const string Expired = "http://schemas.microsoft.com/ws/2008/06/identity/claims/expired";
public const string Gender = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/gender";
public const string GivenName = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname";
public const string GroupSid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid";
public const string Hash = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/hash";
public const string HomePhone = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/homephone";
public const string IsPersistent = "http://schemas.microsoft.com/ws/2008/06/identity/claims/ispersistent";
public const string Locality = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality";
public const string MobilePhone = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/mobilephone";
public const string Name = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name";
public const string NameIdentifier = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier";
public const string OtherPhone = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/otherphone";
public const string PostalCode = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/postalcode";
public const string PrimaryGroupSid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarygroupsid";
public const string PrimarySid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid";
public const string Role = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role";
public const string Rsa = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/rsa";
public const string SerialNumber = "http://schemas.microsoft.com/ws/2008/06/identity/claims/serialnumber";
public const string Sid = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/sid";
public const string Spn = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/spn";
public const string StateOrProvince = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/stateorprovince";
public const string StreetAddress = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/streetaddress";
public const string Surname = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname";
public const string System = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/system";
public const string Thumbprint = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/thumbprint";
public const string Upn = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn";
public const string Uri = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/uri";
public const string UserData = "http://schemas.microsoft.com/ws/2008/06/identity/claims/userdata";
public const string Version = "http://schemas.microsoft.com/ws/2008/06/identity/claims/version";
public const string Webpage = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/webpage";
public const string WindowsAccountName = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname";
public const string WindowsDeviceClaim = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsdeviceclaim";
public const string WindowsDeviceGroup = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsdevicegroup";
public const string WindowsFqbnVersion = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsfqbnversion";
public const string WindowsSubAuthority = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowssubauthority";
public const string WindowsUserClaim = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsuserclaim";
public const string X500DistinguishedName = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/x500distinguishedname";
}
public static partial class ClaimValueTypes
{
public const string Base64Binary = "http://www.w3.org/2001/XMLSchema#base64Binary";
public const string Base64Octet = "http://www.w3.org/2001/XMLSchema#base64Octet";
public const string Boolean = "http://www.w3.org/2001/XMLSchema#boolean";
public const string Date = "http://www.w3.org/2001/XMLSchema#date";
public const string DateTime = "http://www.w3.org/2001/XMLSchema#dateTime";
public const string DaytimeDuration = "http://www.w3.org/TR/2002/WD-xquery-operators-20020816#dayTimeDuration";
public const string DnsName = "http://schemas.xmlsoap.org/claims/dns";
public const string Double = "http://www.w3.org/2001/XMLSchema#double";
public const string DsaKeyValue = "http://www.w3.org/2000/09/xmldsig#DSAKeyValue";
public const string Email = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress";
public const string Fqbn = "http://www.w3.org/2001/XMLSchema#fqbn";
public const string HexBinary = "http://www.w3.org/2001/XMLSchema#hexBinary";
public const string Integer = "http://www.w3.org/2001/XMLSchema#integer";
public const string Integer32 = "http://www.w3.org/2001/XMLSchema#integer32";
public const string Integer64 = "http://www.w3.org/2001/XMLSchema#integer64";
public const string KeyInfo = "http://www.w3.org/2000/09/xmldsig#KeyInfo";
public const string Rfc822Name = "urn:oasis:names:tc:xacml:1.0:data-type:rfc822Name";
public const string Rsa = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/rsa";
public const string RsaKeyValue = "http://www.w3.org/2000/09/xmldsig#RSAKeyValue";
public const string Sid = "http://www.w3.org/2001/XMLSchema#sid";
public const string String = "http://www.w3.org/2001/XMLSchema#string";
public const string Time = "http://www.w3.org/2001/XMLSchema#time";
public const string UInteger32 = "http://www.w3.org/2001/XMLSchema#uinteger32";
public const string UInteger64 = "http://www.w3.org/2001/XMLSchema#uinteger64";
public const string UpnName = "http://schemas.xmlsoap.org/claims/UPN";
public const string X500Name = "urn:oasis:names:tc:xacml:1.0:data-type:x500Name";
public const string YearMonthDuration = "http://www.w3.org/TR/2002/WD-xquery-operators-20020816#yearMonthDuration";
}
}
namespace System.Security.Principal
{
public partial class GenericIdentity : System.Security.Claims.ClaimsIdentity
{
protected GenericIdentity(System.Security.Principal.GenericIdentity identity) { }
public GenericIdentity(string name) { }
public GenericIdentity(string name, string type) { }
public override string AuthenticationType { get { return default(string); } }
public override System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> Claims { get { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); } }
public override bool IsAuthenticated { get { return default(bool); } }
public override string Name { get { return default(string); } }
public override System.Security.Claims.ClaimsIdentity Clone() { return default(System.Security.Claims.ClaimsIdentity); }
}
public partial class GenericPrincipal : System.Security.Claims.ClaimsPrincipal
{
public GenericPrincipal(System.Security.Principal.IIdentity identity, string[] roles) { }
public override System.Security.Principal.IIdentity Identity { get { return default(System.Security.Principal.IIdentity); } }
public override bool IsInRole(string role) { return default(bool); }
}
}
| |
// 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.
using UnityEngine;
using UnityEngine.EventSystems;
using Gvr.Internal;
using System;
using System.Collections;
using System.Collections.Generic;
// Events to update the keyboard.
// These values depend on C API keyboard values
public enum GvrKeyboardEvent {
/// Unknown error.
GVR_KEYBOARD_ERROR_UNKNOWN = 0,
/// The keyboard service could not be connected. This is usually due to the
/// keyboard service not being installed.
GVR_KEYBOARD_ERROR_SERVICE_NOT_CONNECTED = 1,
/// No locale was found in the keyboard service.
GVR_KEYBOARD_ERROR_NO_LOCALES_FOUND = 2,
/// The keyboard SDK tried to load dynamically but failed. This is usually due
/// to the keyboard service not being installed or being out of date.
GVR_KEYBOARD_ERROR_SDK_LOAD_FAILED = 3,
/// Keyboard becomes visible.
GVR_KEYBOARD_SHOWN = 4,
/// Keyboard becomes hidden.
GVR_KEYBOARD_HIDDEN = 5,
/// Text has been updated.
GVR_KEYBOARD_TEXT_UPDATED = 6,
/// Text has been committed.
GVR_KEYBOARD_TEXT_COMMITTED = 7,
};
// These values depend on C API keyboard values.
public enum GvrKeyboardError {
UNKNOWN = 0,
SERVICE_NOT_CONNECTED = 1,
NO_LOCALES_FOUND = 2,
SDK_LOAD_FAILED = 3
};
// These values depend on C API keyboard values.
public enum GvrKeyboardInputMode {
DEFAULT = 0,
NUMERIC = 1
};
// Handles keyboard state management such as hiding and displaying
// the keyboard, directly modifying text and stereoscopic rendering.
public class GvrKeyboard : MonoBehaviour {
private static GvrKeyboard instance;
private static IKeyboardProvider keyboardProvider;
private KeyboardState keyboardState = new KeyboardState();
private IEnumerator keyboardUpdate;
// Keyboard delegate types.
public delegate void StandardCallback();
public delegate void EditTextCallback(string edit_text);
public delegate void ErrorCallback(GvrKeyboardError err);
public delegate void KeyboardCallback(IntPtr closure, GvrKeyboardEvent evt);
// Private data and callbacks.
private ErrorCallback errorCallback = null;
private StandardCallback showCallback = null;
private StandardCallback hideCallback = null;
private EditTextCallback updateCallback = null;
private EditTextCallback enterCallback = null;
#if UNITY_ANDROID
// Which eye is currently being rendered.
private bool isRight = false;
#endif // UNITY_ANDROID
private bool isKeyboardHidden = false;
private const float kExecuterWait = 0.01f;
private static List<GvrKeyboardEvent> threadSafeCallbacks =
new List<GvrKeyboardEvent>();
private static System.Object callbacksLock = new System.Object();
// Public parameters.
public GvrKeyboardDelegateBase keyboardDelegate = null;
public GvrKeyboardInputMode inputMode = GvrKeyboardInputMode.DEFAULT;
public bool useRecommended = true;
public float distance = 0;
public string EditorText {
get { return instance != null ? instance.keyboardState.editorText : string.Empty; }
}
public GvrKeyboardInputMode Mode {
get { return instance != null ? instance.keyboardState.mode : GvrKeyboardInputMode.DEFAULT; }
}
public bool IsValid {
get { return instance != null ? instance.keyboardState.isValid : false; }
}
public bool IsReady {
get { return instance != null ? instance.keyboardState.isReady : false; }
}
public Matrix4x4 WorldMatrix {
get { return instance != null ? instance.keyboardState.worldMatrix : Matrix4x4.zero; }
}
void Awake() {
if (instance != null) {
Debug.LogError("More than one GvrKeyboard instance was found in your scene. "
+ "Ensure that there is only one GvrKeyboard.");
enabled = false;
return;
}
instance = this;
if (keyboardProvider == null) {
keyboardProvider = KeyboardProviderFactory.CreateKeyboardProvider(this);
}
}
void OnDestroy() {
instance = null;
}
// Use this for initialization.
void Start() {
if (keyboardDelegate != null) {
errorCallback = keyboardDelegate.OnKeyboardError;
showCallback = keyboardDelegate.OnKeyboardShow;
hideCallback = keyboardDelegate.OnKeyboardHide;
updateCallback = keyboardDelegate.OnKeyboardUpdate;
enterCallback = keyboardDelegate.OnKeyboardEnterPressed;
keyboardDelegate.KeyboardHidden += KeyboardDelegate_KeyboardHidden;
keyboardDelegate.KeyboardShown += KeyboardDelegate_KeyboardShown;
}
keyboardProvider.ReadState(keyboardState);
if (IsValid) {
if (keyboardProvider.Create(OnKeyboardCallback)) {
keyboardProvider.SetInputMode(inputMode);
}
} else {
Debug.LogError("Could not validate keyboard");
}
}
// Update per-frame data.
void Update() {
if (keyboardProvider == null) {
return;
}
keyboardProvider.ReadState(keyboardState);
if (IsReady) {
// Reset position of keyboard.
if (transform.hasChanged) {
Show();
transform.hasChanged = false;
}
keyboardProvider.UpdateData();
}
}
// Use this function for procedural rendering
// Gets called twice per frame, once for each eye.
// On each frame, left eye renders before right eye so
// we keep track of a boolean that toggles back and forth
// between each eye.
void OnRenderObject() {
if (keyboardProvider == null || !IsReady) {
return;
}
#if UNITY_ANDROID
Camera camera = Camera.current;
if (camera && camera == Camera.main) {
// Get current eye.
Camera.StereoscopicEye camEye = isRight ? Camera.StereoscopicEye.Right : Camera.StereoscopicEye.Left;
// Camera matrices.
Matrix4x4 proj = camera.GetStereoProjectionMatrix(camEye);
Matrix4x4 modelView = camera.GetStereoViewMatrix(camEye);
// Camera viewport.
Rect viewport = camera.pixelRect;
// Render keyboard.
keyboardProvider.Render((int) camEye, modelView, proj, viewport);
// Swap.
isRight = !isRight;
}
#endif // !UNITY_ANDROID
}
// Resets keyboard text.
public void ClearText() {
if (keyboardProvider != null) {
keyboardProvider.EditorText = string.Empty;
}
}
public void Show() {
if (keyboardProvider == null) {
return;
}
// Get user matrix.
Quaternion fixRot = new Quaternion(transform.rotation.x * -1, transform.rotation.y * -1,
transform.rotation.z, transform.rotation.w);
Matrix4x4 modelMatrix = Matrix4x4.TRS(transform.position, fixRot, Vector3.one);
Matrix4x4 mat = Matrix4x4.identity;
Vector3 position = gameObject.transform.position;
if (position.x == 0 && position.y == 0 && position.z == 0 && !useRecommended) {
// Force use recommended to be true, otherwise keyboard won't show up.
keyboardProvider.Show(mat, true, distance, modelMatrix);
return;
}
// Matrix needs to be set only if we're not using the recommended one.
// Uses the values of the keyboard gameobject transform as reported by Unity. If this is
// the zero vector, parent it under another gameobject instead.
if (!useRecommended) {
mat = GetKeyboardObjectMatrix(position);
}
keyboardProvider.Show(mat, useRecommended, distance, modelMatrix);
}
public void Hide() {
if (keyboardProvider != null) {
keyboardProvider.Hide();
}
}
public void OnPointerClick(BaseEventData data) {
if (isKeyboardHidden) {
Show();
}
}
void OnEnable() {
keyboardUpdate = Executer();
StartCoroutine(keyboardUpdate);
}
void OnDisable() {
StopCoroutine(keyboardUpdate);
}
void OnApplicationPause(bool paused) {
if (null == keyboardProvider) return;
if (paused) {
keyboardProvider.OnPause();
} else {
keyboardProvider.OnResume();
}
}
IEnumerator Executer() {
while (true) {
yield return new WaitForSeconds(kExecuterWait);
while (threadSafeCallbacks.Count > 0) {
GvrKeyboardEvent keyboardEvent = threadSafeCallbacks[0];
PoolKeyboardCallbacks(keyboardEvent);
lock (callbacksLock) {
threadSafeCallbacks.RemoveAt(0);
}
}
}
}
private void PoolKeyboardCallbacks(GvrKeyboardEvent keyboardEvent) {
switch (keyboardEvent) {
case GvrKeyboardEvent.GVR_KEYBOARD_ERROR_UNKNOWN:
errorCallback(GvrKeyboardError.UNKNOWN);
break;
case GvrKeyboardEvent.GVR_KEYBOARD_ERROR_SERVICE_NOT_CONNECTED:
errorCallback(GvrKeyboardError.SERVICE_NOT_CONNECTED);
break;
case GvrKeyboardEvent.GVR_KEYBOARD_ERROR_NO_LOCALES_FOUND:
errorCallback(GvrKeyboardError.NO_LOCALES_FOUND);
break;
case GvrKeyboardEvent.GVR_KEYBOARD_ERROR_SDK_LOAD_FAILED:
errorCallback(GvrKeyboardError.SDK_LOAD_FAILED);
break;
case GvrKeyboardEvent.GVR_KEYBOARD_SHOWN:
showCallback();
break;
case GvrKeyboardEvent.GVR_KEYBOARD_HIDDEN:
hideCallback();
break;
case GvrKeyboardEvent.GVR_KEYBOARD_TEXT_UPDATED:
updateCallback(keyboardProvider.EditorText);
break;
case GvrKeyboardEvent.GVR_KEYBOARD_TEXT_COMMITTED:
enterCallback(keyboardProvider.EditorText);
break;
}
}
private static void OnKeyboardCallback(IntPtr closure, GvrKeyboardEvent keyboardEvent) {
lock (callbacksLock) {
threadSafeCallbacks.Add(keyboardEvent);
}
}
private void KeyboardDelegate_KeyboardShown(object sender, System.EventArgs e) {
isKeyboardHidden = false;
}
private void KeyboardDelegate_KeyboardHidden(object sender, System.EventArgs e) {
isKeyboardHidden = true;
}
// Returns a matrix populated by the keyboard's gameobject position. If the position is not
// zero, but comes back as zero, parent this under another gameobject instead.
private Matrix4x4 GetKeyboardObjectMatrix(Vector3 position) {
// Set keyboard position based on this gameObject's position.
float angleX = Mathf.Atan2(position.y, position.x);
float kTanAngleX = Mathf.Tan(angleX);
float newPosX = kTanAngleX * position.x;
float angleY = Mathf.Atan2(position.x, position.y);
float kTanAngleY = Mathf.Tan(angleY);
float newPosY = kTanAngleY * position.y;
float angleZ = Mathf.Atan2(position.y, position.z);
float kTanAngleZ = Mathf.Tan(angleZ);
float newPosZ = kTanAngleZ * position.z;
Vector3 keyboardPosition = new Vector3(newPosX, newPosY, newPosZ);
Vector3 lookPosition = Camera.main.transform.position;
Quaternion rotation = Quaternion.LookRotation(lookPosition);
Matrix4x4 mat = new Matrix4x4();
mat.SetTRS(keyboardPosition, rotation, position);
// Set diagonal to identity if any of them are zero.
if (mat[0, 0] == 0) {
Vector4 row0 = mat.GetRow(0);
mat.SetRow(0, new Vector4(1, row0.y, row0.z, row0.w));
}
if (mat[1, 1] == 0) {
Vector4 row1 = mat.GetRow(1);
mat.SetRow(1, new Vector4(row1.x, 1, row1.z, row1.w));
}
if (mat[2, 2] == 0) {
Vector4 row2 = mat.GetRow(2);
mat.SetRow(2, new Vector4(row2.x, row2.y, 1, row2.w));
}
return mat;
}
}
| |
// 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.ServiceModel.Channels;
namespace System.ServiceModel.Dispatcher
{
internal static class ListenerBinder
{
internal static IListenerBinder GetBinder(IChannelListener listener, MessageVersion messageVersion)
{
IChannelListener<IInputChannel> input = listener as IChannelListener<IInputChannel>;
if (input != null)
return new InputListenerBinder(input, messageVersion);
IChannelListener<IInputSessionChannel> inputSession = listener as IChannelListener<IInputSessionChannel>;
if (inputSession != null)
return new InputSessionListenerBinder(inputSession, messageVersion);
IChannelListener<IReplyChannel> reply = listener as IChannelListener<IReplyChannel>;
if (reply != null)
return new ReplyListenerBinder(reply, messageVersion);
IChannelListener<IReplySessionChannel> replySession = listener as IChannelListener<IReplySessionChannel>;
if (replySession != null)
return new ReplySessionListenerBinder(replySession, messageVersion);
IChannelListener<IDuplexChannel> duplex = listener as IChannelListener<IDuplexChannel>;
if (duplex != null)
return new DuplexListenerBinder(duplex, messageVersion);
IChannelListener<IDuplexSessionChannel> duplexSession = listener as IChannelListener<IDuplexSessionChannel>;
if (duplexSession != null)
return new DuplexSessionListenerBinder(duplexSession, messageVersion);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.UnknownListenerType1, listener.Uri.AbsoluteUri)));
}
// ------------------------------------------------------------------------------------------------------------
// Listener Binders
internal class DuplexListenerBinder : IListenerBinder
{
private IRequestReplyCorrelator _correlator;
private IChannelListener<IDuplexChannel> _listener;
private MessageVersion _messageVersion;
internal DuplexListenerBinder(IChannelListener<IDuplexChannel> listener, MessageVersion messageVersion)
{
_correlator = new RequestReplyCorrelator();
_listener = listener;
_messageVersion = messageVersion;
}
public IChannelListener Listener
{
get { return _listener; }
}
public MessageVersion MessageVersion
{
get { return _messageVersion; }
}
public IChannelBinder Accept(TimeSpan timeout)
{
IDuplexChannel channel = _listener.AcceptChannel(timeout);
if (channel == null)
return null;
return new DuplexChannelBinder(channel, _correlator, _listener.Uri);
}
public IAsyncResult BeginAccept(TimeSpan timeout, AsyncCallback callback, object state)
{
return _listener.BeginAcceptChannel(timeout, callback, state);
}
public IChannelBinder EndAccept(IAsyncResult result)
{
IDuplexChannel channel = _listener.EndAcceptChannel(result);
if (channel == null)
return null;
return new DuplexChannelBinder(channel, _correlator, _listener.Uri);
}
}
internal class DuplexSessionListenerBinder : IListenerBinder
{
private IRequestReplyCorrelator _correlator;
private IChannelListener<IDuplexSessionChannel> _listener;
private MessageVersion _messageVersion;
internal DuplexSessionListenerBinder(IChannelListener<IDuplexSessionChannel> listener, MessageVersion messageVersion)
{
_correlator = new RequestReplyCorrelator();
_listener = listener;
_messageVersion = messageVersion;
}
public IChannelListener Listener
{
get { return _listener; }
}
public MessageVersion MessageVersion
{
get { return _messageVersion; }
}
public IChannelBinder Accept(TimeSpan timeout)
{
IDuplexSessionChannel channel = _listener.AcceptChannel(timeout);
if (channel == null)
return null;
return new DuplexChannelBinder(channel, _correlator, _listener.Uri);
}
public IAsyncResult BeginAccept(TimeSpan timeout, AsyncCallback callback, object state)
{
return _listener.BeginAcceptChannel(timeout, callback, state);
}
public IChannelBinder EndAccept(IAsyncResult result)
{
IDuplexSessionChannel channel = _listener.EndAcceptChannel(result);
if (channel == null)
return null;
return new DuplexChannelBinder(channel, _correlator, _listener.Uri);
}
}
internal class InputListenerBinder : IListenerBinder
{
private IChannelListener<IInputChannel> _listener;
private MessageVersion _messageVersion;
internal InputListenerBinder(IChannelListener<IInputChannel> listener, MessageVersion messageVersion)
{
_listener = listener;
_messageVersion = messageVersion;
}
public IChannelListener Listener
{
get { return _listener; }
}
public MessageVersion MessageVersion
{
get { return _messageVersion; }
}
public IChannelBinder Accept(TimeSpan timeout)
{
IInputChannel channel = _listener.AcceptChannel(timeout);
if (channel == null)
return null;
return new InputChannelBinder(channel, _listener.Uri);
}
public IAsyncResult BeginAccept(TimeSpan timeout, AsyncCallback callback, object state)
{
return _listener.BeginAcceptChannel(timeout, callback, state);
}
public IChannelBinder EndAccept(IAsyncResult result)
{
IInputChannel channel = _listener.EndAcceptChannel(result);
if (channel == null)
return null;
return new InputChannelBinder(channel, _listener.Uri);
}
}
internal class InputSessionListenerBinder : IListenerBinder
{
private IChannelListener<IInputSessionChannel> _listener;
private MessageVersion _messageVersion;
internal InputSessionListenerBinder(IChannelListener<IInputSessionChannel> listener, MessageVersion messageVersion)
{
_listener = listener;
_messageVersion = messageVersion;
}
public IChannelListener Listener
{
get { return _listener; }
}
public MessageVersion MessageVersion
{
get { return _messageVersion; }
}
public IChannelBinder Accept(TimeSpan timeout)
{
IInputSessionChannel channel = _listener.AcceptChannel(timeout);
if (null == channel)
return null;
return new InputChannelBinder(channel, _listener.Uri);
}
public IAsyncResult BeginAccept(TimeSpan timeout, AsyncCallback callback, object state)
{
return _listener.BeginAcceptChannel(timeout, callback, state);
}
public IChannelBinder EndAccept(IAsyncResult result)
{
IInputSessionChannel channel = _listener.EndAcceptChannel(result);
if (channel == null)
return null;
return new InputChannelBinder(channel, _listener.Uri);
}
}
internal class ReplyListenerBinder : IListenerBinder
{
private IChannelListener<IReplyChannel> _listener;
private MessageVersion _messageVersion;
internal ReplyListenerBinder(IChannelListener<IReplyChannel> listener, MessageVersion messageVersion)
{
_listener = listener;
_messageVersion = messageVersion;
}
public IChannelListener Listener
{
get { return _listener; }
}
public MessageVersion MessageVersion
{
get { return _messageVersion; }
}
public IChannelBinder Accept(TimeSpan timeout)
{
IReplyChannel channel = _listener.AcceptChannel(timeout);
if (channel == null)
return null;
return new ReplyChannelBinder(channel, _listener.Uri);
}
public IAsyncResult BeginAccept(TimeSpan timeout, AsyncCallback callback, object state)
{
return _listener.BeginAcceptChannel(timeout, callback, state);
}
public IChannelBinder EndAccept(IAsyncResult result)
{
IReplyChannel channel = _listener.EndAcceptChannel(result);
if (channel == null)
return null;
return new ReplyChannelBinder(channel, _listener.Uri);
}
}
internal class ReplySessionListenerBinder : IListenerBinder
{
private IChannelListener<IReplySessionChannel> _listener;
private MessageVersion _messageVersion;
internal ReplySessionListenerBinder(IChannelListener<IReplySessionChannel> listener, MessageVersion messageVersion)
{
_listener = listener;
_messageVersion = messageVersion;
}
public IChannelListener Listener
{
get { return _listener; }
}
public MessageVersion MessageVersion
{
get { return _messageVersion; }
}
public IChannelBinder Accept(TimeSpan timeout)
{
IReplySessionChannel channel = _listener.AcceptChannel(timeout);
if (channel == null)
return null;
return new ReplyChannelBinder(channel, _listener.Uri);
}
public IAsyncResult BeginAccept(TimeSpan timeout, AsyncCallback callback, object state)
{
return _listener.BeginAcceptChannel(timeout, callback, state);
}
public IChannelBinder EndAccept(IAsyncResult result)
{
IReplySessionChannel channel = _listener.EndAcceptChannel(result);
if (channel == null)
return null;
return new ReplyChannelBinder(channel, _listener.Uri);
}
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Text;
using Umbraco.Core.Configuration;
using Umbraco.Core.IO;
namespace Umbraco.Core
{
/// <summary>
/// Provides extension methods to <see cref="Uri"/>.
/// </summary>
public static class UriExtensions
{
/// <summary>
/// Checks if the current uri is a back office request
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
internal static bool IsBackOfficeRequest(this Uri url)
{
var authority = url.GetLeftPart(UriPartial.Authority);
var afterAuthority = url.GetLeftPart(UriPartial.Query)
.TrimStart(authority)
.TrimStart("/");
//check if this is in the umbraco back office
return afterAuthority.InvariantStartsWith(GlobalSettings.Path.TrimStart("/"));
}
/// <summary>
/// Checks if the current uri is an install request
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
internal static bool IsInstallerRequest(this Uri url)
{
var authority = url.GetLeftPart(UriPartial.Authority);
var afterAuthority = url.GetLeftPart(UriPartial.Query)
.TrimStart(authority)
.TrimStart("/");
//check if this is in the umbraco back office
return afterAuthority.InvariantStartsWith(IOHelper.ResolveUrl("~/install").TrimStart("/"));
}
/// <summary>
/// This is a performance tweak to check if this is a .css, .js or .ico, .jpg, .jpeg, .png, .gif file request since
/// .Net will pass these requests through to the module when in integrated mode.
/// We want to ignore all of these requests immediately.
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
internal static bool IsClientSideRequest(this Uri url)
{
var toIgnore = new[] { ".js", ".css", ".ico", ".png", ".jpg", ".jpeg", ".gif", ".html", ".svg" };
return toIgnore.Any(x => Path.GetExtension(url.LocalPath).InvariantEquals(x));
}
/// <summary>
/// Rewrites the path of uri.
/// </summary>
/// <param name="uri">The uri.</param>
/// <param name="path">The new path, which must begin with a slash.</param>
/// <returns>The rewritten uri.</returns>
/// <remarks>Everything else remains unchanged, except for the fragment which is removed.</remarks>
public static Uri Rewrite(this Uri uri, string path)
{
if (!path.StartsWith("/"))
throw new ArgumentException("Path must start with a slash.", "path");
return uri.IsAbsoluteUri
? new Uri(uri.GetLeftPart(UriPartial.Authority) + path + uri.Query)
: new Uri(path + uri.GetSafeQuery(), UriKind.Relative);
}
/// <summary>
/// Rewrites the path and query of a uri.
/// </summary>
/// <param name="uri">The uri.</param>
/// <param name="path">The new path, which must begin with a slash.</param>
/// <param name="query">The new query, which must be empty or begin with a question mark.</param>
/// <returns>The rewritten uri.</returns>
/// <remarks>Everything else remains unchanged, except for the fragment which is removed.</remarks>
public static Uri Rewrite(this Uri uri, string path, string query)
{
if (!path.StartsWith("/"))
throw new ArgumentException("Path must start with a slash.", "path");
if (query.Length > 0 && !query.StartsWith("?"))
throw new ArgumentException("Query must start with a question mark.", "query");
if (query == "?")
query = "";
return uri.IsAbsoluteUri
? new Uri(uri.GetLeftPart(UriPartial.Authority) + path + query)
: new Uri(path + query, UriKind.Relative);
}
/// <summary>
/// Gets the absolute path of the uri, even if the uri is relative.
/// </summary>
/// <param name="uri">The uri.</param>
/// <returns>The absolute path of the uri.</returns>
/// <remarks>Default uri.AbsolutePath does not support relative uris.</remarks>
public static string GetSafeAbsolutePath(this Uri uri)
{
if (uri.IsAbsoluteUri)
return uri.AbsolutePath;
// cannot get .AbsolutePath on relative uri (InvalidOperation)
var s = uri.OriginalString;
var posq = s.IndexOf("?", StringComparison.Ordinal);
var posf = s.IndexOf("#", StringComparison.Ordinal);
var pos = posq > 0 ? posq : (posf > 0 ? posf : 0);
var path = pos > 0 ? s.Substring(0, pos) : s;
return path;
}
/// <summary>
/// Gets the decoded, absolute path of the uri.
/// </summary>
/// <param name="uri">The uri.</param>
/// <returns>The absolute path of the uri.</returns>
/// <remarks>Only for absolute uris.</remarks>
public static string GetAbsolutePathDecoded(this Uri uri)
{
return System.Web.HttpUtility.UrlDecode(uri.AbsolutePath);
}
/// <summary>
/// Gets the decoded, absolute path of the uri, even if the uri is relative.
/// </summary>
/// <param name="uri">The uri.</param>
/// <returns>The absolute path of the uri.</returns>
/// <remarks>Default uri.AbsolutePath does not support relative uris.</remarks>
public static string GetSafeAbsolutePathDecoded(this Uri uri)
{
return System.Web.HttpUtility.UrlDecode(uri.GetSafeAbsolutePath());
}
/// <summary>
/// Rewrites the path of the uri so it ends with a slash.
/// </summary>
/// <param name="uri">The uri.</param>
/// <returns>The rewritten uri.</returns>
/// <remarks>Everything else remains unchanged.</remarks>
public static Uri EndPathWithSlash(this Uri uri)
{
var path = uri.GetSafeAbsolutePath();
if (uri.IsAbsoluteUri)
{
if (path != "/" && !path.EndsWith("/"))
uri = new Uri(uri.GetLeftPart(UriPartial.Authority) + path + "/" + uri.Query);
return uri;
}
else
{
if (path != "/" && !path.EndsWith("/"))
uri = new Uri(path + "/" + uri.Query, UriKind.Relative);
}
return uri;
}
/// <summary>
/// Rewrites the path of the uri so it does not end with a slash.
/// </summary>
/// <param name="uri">The uri.</param>
/// <returns>The rewritten uri.</returns>
/// <remarks>Everything else remains unchanged.</remarks>
public static Uri TrimPathEndSlash(this Uri uri)
{
var path = uri.GetSafeAbsolutePath();
if (uri.IsAbsoluteUri)
{
if (path != "/")
uri = new Uri(uri.GetLeftPart(UriPartial.Authority) + path.TrimEnd('/') + uri.Query);
}
else
{
if (path != "/")
uri = new Uri(path.TrimEnd('/') + uri.Query, UriKind.Relative);
}
return uri;
}
/// <summary>
/// Transforms a relative uri into an absolute uri.
/// </summary>
/// <param name="uri">The relative uri.</param>
/// <param name="baseUri">The base absolute uri.</param>
/// <returns>The absolute uri.</returns>
public static Uri MakeAbsolute(this Uri uri, Uri baseUri)
{
if (uri.IsAbsoluteUri)
throw new ArgumentException("Uri is already absolute.", "uri");
return new Uri(baseUri.GetLeftPart(UriPartial.Authority) + uri.GetSafeAbsolutePath() + uri.GetSafeQuery());
}
static string GetSafeQuery(this Uri uri)
{
if (uri.IsAbsoluteUri)
return uri.Query;
// cannot get .Query on relative uri (InvalidOperation)
var s = uri.OriginalString;
var posq = s.IndexOf("?", StringComparison.Ordinal);
var posf = s.IndexOf("#", StringComparison.Ordinal);
var query = posq < 0 ? null : (posf < 0 ? s.Substring(posq) : s.Substring(posq, posf - posq));
return query;
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="ReferentialConstraint.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.EntityModel.SchemaObjectModel
{
using System.Data.Metadata.Edm;
using System.Diagnostics;
using System.Xml;
/// <summary>
/// Represents an referential constraint on a relationship
/// </summary>
internal sealed class ReferentialConstraint : SchemaElement
{
private const char KEY_DELIMITER = ' ';
private ReferentialConstraintRoleElement _principalRole;
private ReferentialConstraintRoleElement _dependentRole;
/// <summary>
/// construct a Referential constraint
/// </summary>
/// <param name="relationship"></param>
public ReferentialConstraint(Relationship relationship)
: base(relationship)
{
}
/// <summary>
/// Validate this referential constraint
/// </summary>
internal override void Validate()
{
base.Validate();
_principalRole.Validate();
_dependentRole.Validate();
if (ReadyForFurtherValidation(_principalRole) && ReadyForFurtherValidation(_dependentRole))
{
// Validate the to end and from end of the referential constraint
IRelationshipEnd principalRoleEnd = _principalRole.End;
IRelationshipEnd dependentRoleEnd = _dependentRole.End;
bool isPrinicipalRoleKeyProperty, isDependentRoleKeyProperty;
bool areAllPrinicipalRolePropertiesNullable, areAllDependentRolePropertiesNullable;
bool isDependentRolePropertiesSubsetofKeyProperties, isPrinicipalRolePropertiesSubsetofKeyProperties;
bool isAnyPrinicipalRolePropertyNullable, isAnyDependentRolePropertyNullable;
// Validate the role name to be different
if (_principalRole.Name == _dependentRole.Name)
{
AddError(ErrorCode.SameRoleReferredInReferentialConstraint,
EdmSchemaErrorSeverity.Error,
System.Data.Entity.Strings.SameRoleReferredInReferentialConstraint(this.ParentElement.Name));
}
// Resolve all the property in the ToProperty attribute. Also checks whether this is nullable or not and
// whether the properties are the keys for the type in the ToRole
IsKeyProperty(_dependentRole, dependentRoleEnd.Type,
out isPrinicipalRoleKeyProperty,
out areAllDependentRolePropertiesNullable,
out isAnyDependentRolePropertyNullable,
out isDependentRolePropertiesSubsetofKeyProperties);
// Resolve all the property in the ToProperty attribute. Also checks whether this is nullable or not and
// whether the properties are the keys for the type in the ToRole
IsKeyProperty(_principalRole, principalRoleEnd.Type,
out isDependentRoleKeyProperty,
out areAllPrinicipalRolePropertiesNullable,
out isAnyPrinicipalRolePropertyNullable,
out isPrinicipalRolePropertiesSubsetofKeyProperties);
Debug.Assert(_principalRole.RoleProperties.Count != 0, "There should be some ref properties in Principal Role");
Debug.Assert(_dependentRole.RoleProperties.Count != 0, "There should be some ref properties in Dependent Role");
// The properties in the PrincipalRole must be the key of the Entity type referred to by the principal role
if (!isDependentRoleKeyProperty)
{
AddError(ErrorCode.InvalidPropertyInRelationshipConstraint,
EdmSchemaErrorSeverity.Error,
System.Data.Entity.Strings.InvalidFromPropertyInRelationshipConstraint(
PrincipalRole.Name, principalRoleEnd.Type.FQName, this.ParentElement.FQName));
}
else
{
bool v1Behavior = Schema.SchemaVersion <= XmlConstants.EdmVersionForV1_1;
// Determine expected multiplicities
RelationshipMultiplicity expectedPrincipalMultiplicity = (v1Behavior
? areAllPrinicipalRolePropertiesNullable
: isAnyPrinicipalRolePropertyNullable)
? RelationshipMultiplicity.ZeroOrOne
: RelationshipMultiplicity.One;
RelationshipMultiplicity expectedDependentMultiplicity = (v1Behavior
? areAllDependentRolePropertiesNullable
: isAnyDependentRolePropertyNullable)
? RelationshipMultiplicity.ZeroOrOne
: RelationshipMultiplicity.Many;
principalRoleEnd.Multiplicity = principalRoleEnd.Multiplicity ?? expectedPrincipalMultiplicity;
dependentRoleEnd.Multiplicity = dependentRoleEnd.Multiplicity ?? expectedDependentMultiplicity;
// Since the FromProperty must be the key of the FromRole, the FromRole cannot be '*' as multiplicity
// Also the lower bound of multiplicity of FromRole can be zero if and only if all the properties in
// ToProperties are nullable
// for v2+
if (principalRoleEnd.Multiplicity == RelationshipMultiplicity.Many)
{
AddError(ErrorCode.InvalidMultiplicityInRoleInRelationshipConstraint,
EdmSchemaErrorSeverity.Error,
System.Data.Entity.Strings.InvalidMultiplicityFromRoleUpperBoundMustBeOne(_principalRole.Name, this.ParentElement.Name));
}
else if (areAllDependentRolePropertiesNullable
&& principalRoleEnd.Multiplicity == RelationshipMultiplicity.One)
{
string message = System.Data.Entity.Strings.InvalidMultiplicityFromRoleToPropertyNullableV1(_principalRole.Name, this.ParentElement.Name);
AddError(ErrorCode.InvalidMultiplicityInRoleInRelationshipConstraint,
EdmSchemaErrorSeverity.Error,
message);
}
else if ((
(v1Behavior && !areAllDependentRolePropertiesNullable) ||
(!v1Behavior && !isAnyDependentRolePropertyNullable)
)
&& principalRoleEnd.Multiplicity != RelationshipMultiplicity.One)
{
string message;
if (v1Behavior)
{
message = System.Data.Entity.Strings.InvalidMultiplicityFromRoleToPropertyNonNullableV1(_principalRole.Name, this.ParentElement.Name);
}
else
{
message = System.Data.Entity.Strings.InvalidMultiplicityFromRoleToPropertyNonNullableV2(_principalRole.Name, this.ParentElement.Name);
}
AddError(ErrorCode.InvalidMultiplicityInRoleInRelationshipConstraint,
EdmSchemaErrorSeverity.Error,
message);
}
// If the ToProperties form the key of the type in ToRole, then the upper bound of the multiplicity
// of the ToRole must be '1'. The lower bound must always be zero since there can be entries in the from
// column which are not related to child columns.
if (dependentRoleEnd.Multiplicity == RelationshipMultiplicity.One && Schema.DataModel == SchemaDataModelOption.ProviderDataModel)
{
AddError(ErrorCode.InvalidMultiplicityInRoleInRelationshipConstraint,
EdmSchemaErrorSeverity.Error,
System.Data.Entity.Strings.InvalidMultiplicityToRoleLowerBoundMustBeZero(_dependentRole.Name, this.ParentElement.Name));
}
// Need to constrain the dependent role in CSDL to Key properties if this is not a IsForeignKey
// relationship.
if ((!isDependentRolePropertiesSubsetofKeyProperties) &&
(!this.ParentElement.IsForeignKey) &&
(Schema.DataModel == SchemaDataModelOption.EntityDataModel))
{
AddError(ErrorCode.InvalidPropertyInRelationshipConstraint,
EdmSchemaErrorSeverity.Error,
System.Data.Entity.Strings.InvalidToPropertyInRelationshipConstraint(
DependentRole.Name, dependentRoleEnd.Type.FQName, this.ParentElement.FQName));
}
// If the ToProperty is a key property, then the upper bound must be 1 i.e. every parent (from property) can
// have exactly one child
if (isPrinicipalRoleKeyProperty)
{
if (dependentRoleEnd.Multiplicity == RelationshipMultiplicity.Many)
{
AddError(ErrorCode.InvalidMultiplicityInRoleInRelationshipConstraint,
EdmSchemaErrorSeverity.Error,
System.Data.Entity.Strings.InvalidMultiplicityToRoleUpperBoundMustBeOne(dependentRoleEnd.Name, this.ParentElement.Name));
}
}
// if the ToProperty is not the key, then the upper bound must be many i.e every parent (from property) can
// be related to many childs
else if (dependentRoleEnd.Multiplicity != RelationshipMultiplicity.Many)
{
AddError(ErrorCode.InvalidMultiplicityInRoleInRelationshipConstraint,
EdmSchemaErrorSeverity.Error,
System.Data.Entity.Strings.InvalidMultiplicityToRoleUpperBoundMustBeMany(dependentRoleEnd.Name, this.ParentElement.Name));
}
if (_dependentRole.RoleProperties.Count != _principalRole.RoleProperties.Count)
{
AddError(ErrorCode.MismatchNumberOfPropertiesInRelationshipConstraint,
EdmSchemaErrorSeverity.Error,
System.Data.Entity.Strings.MismatchNumberOfPropertiesinRelationshipConstraint);
}
else
{
for (int i = 0; i < _dependentRole.RoleProperties.Count; i++)
{
if (_dependentRole.RoleProperties[i].Property.Type != _principalRole.RoleProperties[i].Property.Type)
{
AddError(ErrorCode.TypeMismatchRelationshipConstaint,
EdmSchemaErrorSeverity.Error,
System.Data.Entity.Strings.TypeMismatchRelationshipConstaint(
_dependentRole.RoleProperties[i].Name,
_dependentRole.End.Type.Identity,
_principalRole.RoleProperties[i].Name,
_principalRole.End.Type.Identity,
this.ParentElement.Name
));
}
}
}
}
}
}
private static bool ReadyForFurtherValidation(ReferentialConstraintRoleElement role)
{
if (role == null)
return false;
if(role.End == null)
return false;
if(role.RoleProperties.Count == 0)
return false;
foreach(PropertyRefElement propRef in role.RoleProperties)
{
if(propRef.Property == null)
return false;
}
return true;
}
/// <summary>
/// Resolves the given property names to the property in the item
/// Also checks whether the properties form the key for the given type and whether all the properties are nullable or not
/// </summary>
/// <param name="roleElement"></param>
/// <param name="itemType"></param>
/// <param name="isKeyProperty"></param>
/// <param name="areAllPropertiesNullable"></param>
/// <param name="isSubsetOfKeyProperties"></param>
private static void IsKeyProperty(ReferentialConstraintRoleElement roleElement, SchemaEntityType itemType,
out bool isKeyProperty,
out bool areAllPropertiesNullable,
out bool isAnyPropertyNullable,
out bool isSubsetOfKeyProperties)
{
isKeyProperty = true;
areAllPropertiesNullable = true;
isAnyPropertyNullable = false;
isSubsetOfKeyProperties = true;
if (itemType.KeyProperties.Count != roleElement.RoleProperties.Count)
{
isKeyProperty = false;
}
// Checking that ToProperties must be the key properties in the entity type referred by the ToRole
for (int i = 0; i < roleElement.RoleProperties.Count; i++)
{
// Once we find that the properties in the constraint are not a subset of the
// Key, one need not search for it every time
if (isSubsetOfKeyProperties)
{
bool foundKeyProperty = false;
// All properties that are defined in ToProperties must be the key property on the entity type
for (int j = 0; j < itemType.KeyProperties.Count; j++)
{
if (itemType.KeyProperties[j].Property == roleElement.RoleProperties[i].Property)
{
foundKeyProperty = true;
break;
}
}
if (!foundKeyProperty)
{
isKeyProperty = false;
isSubsetOfKeyProperties = false;
}
}
areAllPropertiesNullable &= roleElement.RoleProperties[i].Property.Nullable;
isAnyPropertyNullable |= roleElement.RoleProperties[i].Property.Nullable;
}
}
protected override bool HandleAttribute(XmlReader reader)
{
return false;
}
protected override bool HandleElement(XmlReader reader)
{
if (base.HandleElement(reader))
{
return true;
}
else if (CanHandleElement(reader, XmlConstants.PrincipalRole))
{
HandleReferentialConstraintPrincipalRoleElement(reader);
return true;
}
else if (CanHandleElement(reader, XmlConstants.DependentRole))
{
HandleReferentialConstraintDependentRoleElement(reader);
return true;
}
return false;
}
internal void HandleReferentialConstraintPrincipalRoleElement(XmlReader reader)
{
_principalRole = new ReferentialConstraintRoleElement(this);
_principalRole.Parse(reader);
}
internal void HandleReferentialConstraintDependentRoleElement(XmlReader reader)
{
_dependentRole = new ReferentialConstraintRoleElement(this);
_dependentRole.Parse(reader);
}
internal override void ResolveTopLevelNames()
{
_dependentRole.ResolveTopLevelNames();
_principalRole.ResolveTopLevelNames();
}
/// <summary>
/// The parent element as an IRelationship
/// </summary>
internal new IRelationship ParentElement
{
get
{
return (IRelationship)(base.ParentElement);
}
}
internal ReferentialConstraintRoleElement PrincipalRole
{
get
{
return _principalRole;
}
}
internal ReferentialConstraintRoleElement DependentRole
{
get
{
return _dependentRole;
}
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Text;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// PSTuple is a helper class used to create Tuple from an input array.
/// </summary>
internal static class PSTuple
{
/// <summary>
/// ArrayToTuple is a helper method used to create a tuple for the supplied input array.
/// </summary>
/// <param name="inputObjects">Input objects used to create a tuple.</param>
/// <returns>Tuple object.</returns>
internal static object ArrayToTuple(object[] inputObjects)
{
Diagnostics.Assert(inputObjects != null, "inputObjects is null");
Diagnostics.Assert(inputObjects.Length > 0, "inputObjects is empty");
return ArrayToTuple(inputObjects, 0);
}
/// <summary>
/// ArrayToTuple is a helper method used to create a tuple for the supplied input array.
/// </summary>
/// <param name="inputObjects">Input objects used to create a tuple</param>
/// <param name="startIndex">Start index of the array from which the objects have to considered for the tuple creation.</param>
/// <returns>Tuple object.</returns>
internal static object ArrayToTuple(object[] inputObjects, int startIndex)
{
Diagnostics.Assert(inputObjects != null, "inputObjects is null");
Diagnostics.Assert(inputObjects.Length > 0, "inputObjects is empty");
switch (inputObjects.Length - startIndex)
{
case 0:
return null;
case 1:
return Tuple.Create(inputObjects[startIndex]);
case 2:
return Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1]);
case 3:
return Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1], inputObjects[startIndex + 2]);
case 4:
return Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1], inputObjects[startIndex + 2], inputObjects[startIndex + 3]);
case 5:
return Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1], inputObjects[startIndex + 2], inputObjects[startIndex + 3], inputObjects[startIndex + 4]);
case 6:
return Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1], inputObjects[startIndex + 2], inputObjects[startIndex + 3], inputObjects[startIndex + 4],
inputObjects[startIndex + 5]);
case 7:
return Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1], inputObjects[startIndex + 2], inputObjects[startIndex + 3], inputObjects[startIndex + 4],
inputObjects[startIndex + 5], inputObjects[startIndex + 6]);
case 8:
return Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1], inputObjects[startIndex + 2], inputObjects[startIndex + 3], inputObjects[startIndex + 4],
inputObjects[startIndex + 5], inputObjects[startIndex + 6], inputObjects[startIndex + 7]);
default:
return Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1], inputObjects[startIndex + 2], inputObjects[startIndex + 3], inputObjects[startIndex + 4],
inputObjects[startIndex + 5], inputObjects[startIndex + 6], ArrayToTuple(inputObjects, startIndex + 7));
}
}
}
/// <summary>
/// Emitted by Group-Object when the NoElement option is true
/// </summary>
public sealed class GroupInfoNoElement : GroupInfo
{
internal GroupInfoNoElement(OrderByPropertyEntry groupValue)
: base(groupValue)
{
}
internal override void Add(PSObject groupValue)
{
Count++;
}
}
/// <summary>
/// Emitted by Group-Object
/// </summary>
public class GroupInfo
{
internal GroupInfo(OrderByPropertyEntry groupValue)
{
Group = new Collection<PSObject>();
this.Add(groupValue.inputObject);
GroupValue = groupValue;
Name = BuildName(groupValue.orderValues);
}
internal virtual void Add(PSObject groupValue)
{
Group.Add(groupValue);
Count++;
}
private static string BuildName(List<ObjectCommandPropertyValue> propValues)
{
StringBuilder sb = new StringBuilder();
foreach (ObjectCommandPropertyValue propValue in propValues)
{
if (propValue != null && propValue.PropertyValue != null)
{
var propertyValueItems = propValue.PropertyValue as ICollection;
if (propertyValueItems != null)
{
sb.Append("{");
var length = sb.Length;
foreach (object item in propertyValueItems)
{
sb.Append(string.Format(CultureInfo.InvariantCulture, "{0}, ", item.ToString()));
}
sb = sb.Length > length ? sb.Remove(sb.Length - 2, 2) : sb;
sb.Append("}, ");
}
else
{
sb.Append(string.Format(CultureInfo.InvariantCulture, "{0}, ", propValue.PropertyValue.ToString()));
}
}
}
return sb.Length >= 2 ? sb.Remove(sb.Length - 2, 2).ToString() : string.Empty;
}
/// <summary>
///
/// Values of the group
///
/// </summary>
public ArrayList Values
{
get
{
ArrayList values = new ArrayList();
foreach (ObjectCommandPropertyValue propValue in GroupValue.orderValues)
{
values.Add(propValue.PropertyValue);
}
return values;
}
}
/// <summary>
///
/// Number of objects in the group
///
/// </summary>
public int Count { get; internal set; }
/// <summary>
///
/// The list of objects in this group
///
/// </summary>
public Collection<PSObject> Group { get; } = null;
/// <summary>
///
/// The name of the group
///
/// </summary>
public string Name { get; } = null;
/// <summary>
///
/// The OrderByPropertyEntry used to build this group object
///
/// </summary>
internal OrderByPropertyEntry GroupValue { get; } = null;
}
/// <summary>
///
/// Group-Object implementation
///
/// </summary>
[Cmdlet("Group", "Object", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113338", RemotingCapability = RemotingCapability.None)]
[OutputType(typeof(Hashtable), typeof(GroupInfo))]
public class GroupObjectCommand : ObjectBase
{
#region tracer
/// <summary>
/// An instance of the PSTraceSource class used for trace output
/// </summary>
[TraceSourceAttribute(
"GroupObjectCommand",
"Class that has group base implementation")]
private static PSTraceSource s_tracer =
PSTraceSource.GetTracer("GroupObjectCommand",
"Class that has group base implementation");
#endregion tracer
#region Command Line Switches
/// <summary>
///
/// Flatten the groups
///
/// </summary>
/// <value></value>
[Parameter]
public SwitchParameter NoElement
{
get { return _noElement; }
set { _noElement = value; }
}
private bool _noElement;
/// <summary>
/// the AsHashTable parameter
/// </summary>
/// <value></value>
[Parameter(ParameterSetName = "HashTable")]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "HashTable")]
[Alias("AHT")]
public SwitchParameter AsHashTable { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[Parameter(ParameterSetName = "HashTable")]
public SwitchParameter AsString { get; set; }
private List<GroupInfo> _groups = new List<GroupInfo>();
private OrderByProperty _orderByProperty = new OrderByProperty();
private bool _hasProcessedFirstInputObject;
private Dictionary<object, GroupInfo> _tupleToGroupInfoMappingDictionary = new Dictionary<object, GroupInfo>();
private OrderByPropertyComparer _orderByPropertyComparer = null;
#endregion
#region utils
/// <summary>
/// Utility function called by Group-Object to create Groups.
/// </summary>
/// <param name="currentObjectEntry">Input object that needs to be grouped.</param>
/// <param name="noElement">true if we are not accumulating objects</param>
/// <param name="groups">List containing Groups.</param>
/// <param name="groupInfoDictionary">Dictionary used to keep track of the groups with hash of the property values being the key.</param>
/// <param name="orderByPropertyComparer">The Comparer to be used while comparing to check if new group has to be created.</param>
internal static void DoGrouping(OrderByPropertyEntry currentObjectEntry, bool noElement, List<GroupInfo> groups, Dictionary<object, GroupInfo> groupInfoDictionary,
OrderByPropertyComparer orderByPropertyComparer)
{
if (currentObjectEntry != null && currentObjectEntry.orderValues != null && currentObjectEntry.orderValues.Count > 0)
{
object currentTupleObject = PSTuple.ArrayToTuple(currentObjectEntry.orderValues.ToArray());
GroupInfo currentGroupInfo = null;
if (groupInfoDictionary.TryGetValue(currentTupleObject, out currentGroupInfo))
{
if (currentGroupInfo != null)
{
//add this inputObject to an existing group
currentGroupInfo.Add(currentObjectEntry.inputObject);
}
}
else
{
bool isCurrentItemGrouped = false;
for (int groupsIndex = 0; groupsIndex < groups.Count; groupsIndex++)
{
// Check if the current input object can be converted to one of the already known types
// by looking up in the type to GroupInfo mapping.
if (orderByPropertyComparer.Compare(groups[groupsIndex].GroupValue, currentObjectEntry) == 0)
{
groups[groupsIndex].Add(currentObjectEntry.inputObject);
isCurrentItemGrouped = true;
break;
}
}
if (!isCurrentItemGrouped)
{
// create a new group
s_tracer.WriteLine("Create a new group: {0}", currentObjectEntry.orderValues);
GroupInfo newObjGrp = noElement ? new GroupInfoNoElement(currentObjectEntry) : new GroupInfo(currentObjectEntry);
groups.Add(newObjGrp);
groupInfoDictionary.Add(currentTupleObject, newObjGrp);
}
}
}
}
private void WriteNonTerminatingError(Exception exception, string resourceIdAndErrorId,
ErrorCategory category)
{
Exception ex = new Exception(StringUtil.Format(resourceIdAndErrorId), exception);
WriteError(new ErrorRecord(ex, resourceIdAndErrorId, category, null));
}
#endregion utils
/// <summary>
/// Process every input object to group them.
/// </summary>
protected override void ProcessRecord()
{
if (InputObject != null && InputObject != AutomationNull.Value)
{
OrderByPropertyEntry currentEntry = null;
if (!_hasProcessedFirstInputObject)
{
if (Property == null)
{
Property = OrderByProperty.GetDefaultKeyPropertySet(InputObject);
}
_orderByProperty.ProcessExpressionParameter(this, Property);
currentEntry = _orderByProperty.CreateOrderByPropertyEntry(this, InputObject, CaseSensitive, _cultureInfo);
bool[] ascending = new bool[currentEntry.orderValues.Count];
for (int index = 0; index < currentEntry.orderValues.Count; index++)
{
ascending[index] = true;
}
_orderByPropertyComparer = new OrderByPropertyComparer(ascending, _cultureInfo, CaseSensitive);
_hasProcessedFirstInputObject = true;
}
else
{
currentEntry = _orderByProperty.CreateOrderByPropertyEntry(this, InputObject, CaseSensitive, _cultureInfo);
}
DoGrouping(currentEntry, this.NoElement, _groups, _tupleToGroupInfoMappingDictionary, _orderByPropertyComparer);
}
}
/// <summary>
///
/// </summary>
protected override void EndProcessing()
{
s_tracer.WriteLine(_groups.Count);
if (_groups.Count > 0)
{
if (AsHashTable)
{
Hashtable _table = CollectionsUtil.CreateCaseInsensitiveHashtable();
try
{
foreach (GroupInfo _grp in _groups)
{
if (AsString)
{
_table.Add(_grp.Name, _grp.Group);
}
else
{
if (_grp.Values.Count == 1)
{
_table.Add(_grp.Values[0], _grp.Group);
}
else
{
ArgumentException ex = new ArgumentException(UtilityCommonStrings.GroupObjectSingleProperty);
ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidArgument, Property);
ThrowTerminatingError(er);
}
}
}
}
catch (ArgumentException e)
{
WriteNonTerminatingError(e, UtilityCommonStrings.InvalidOperation, ErrorCategory.InvalidArgument);
return;
}
WriteObject(_table);
}
else
{
if (AsString)
{
ArgumentException ex = new ArgumentException(UtilityCommonStrings.GroupObjectWithHashTable);
ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidArgument, AsString);
ThrowTerminatingError(er);
}
else
{
WriteObject(_groups, true);
}
}
}
}
}
}
| |
// 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.Drawing.Printing {
using System;
using System.Security;
using System.Security.Permissions;
using System.IO;
using System.Runtime.Serialization;
using System.Reflection;
using System.Collections;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
/// <include file='doc\PrintingPermission.uex' path='docs/doc[@for="PrintingPermission"]/*' />
/// <devdoc>
/// <para> Controls the ability to use the printer. This class cannot be inherited.</para>
/// </devdoc>
[Serializable]
public sealed class PrintingPermission : CodeAccessPermission, IUnrestrictedPermission {
private PrintingPermissionLevel printingLevel;
/// <include file='doc\PrintingPermission.uex' path='docs/doc[@for="PrintingPermission.PrintingPermission"]/*' />
/// <devdoc>
/// <para>Initializes a new instance of the PrintingPermission class with either fully restricted
/// or unrestricted access, as specified.</para>
/// </devdoc>
public PrintingPermission(PermissionState state) {
if (state == PermissionState.Unrestricted) {
printingLevel = PrintingPermissionLevel.AllPrinting;
}
else if (state == PermissionState.None) {
printingLevel = PrintingPermissionLevel.NoPrinting;
}
else {
throw new ArgumentException(SR.Format(SR.InvalidPermissionState));
}
}
/// <include file='doc\PrintingPermission.uex' path='docs/doc[@for="PrintingPermission.PrintingPermission1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public PrintingPermission(PrintingPermissionLevel printingLevel) {
VerifyPrintingLevel(printingLevel);
this.printingLevel = printingLevel;
}
/// <include file='doc\PrintingPermission.uex' path='docs/doc[@for="PrintingPermission.Level"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public PrintingPermissionLevel Level {
get {
return printingLevel;
}
set {
VerifyPrintingLevel(value);
printingLevel = value;
}
}
private static void VerifyPrintingLevel(PrintingPermissionLevel level) {
if (level < PrintingPermissionLevel.NoPrinting || level > PrintingPermissionLevel.AllPrinting) {
throw new ArgumentException(SR.Format(SR.InvalidPermissionLevel));
}
}
//------------------------------------------------------
//
// CODEACCESSPERMISSION IMPLEMENTATION
//
//------------------------------------------------------
/// <include file='doc\PrintingPermission.uex' path='docs/doc[@for="PrintingPermission.IsUnrestricted"]/*' />
/// <devdoc>
/// <para> Gets a
/// value indicating whether permission is unrestricted.</para>
/// </devdoc>
public bool IsUnrestricted() {
return printingLevel == PrintingPermissionLevel.AllPrinting;
}
//------------------------------------------------------
//
// IPERMISSION IMPLEMENTATION
//
//------------------------------------------------------
/// <include file='doc\PrintingPermission.uex' path='docs/doc[@for="PrintingPermission.IsSubsetOf"]/*' />
/// <devdoc>
/// <para>Determines whether the current permission object is a subset of
/// the specified permission.</para>
/// </devdoc>
public override bool IsSubsetOf(IPermission target) {
if (target == null) {
return printingLevel == PrintingPermissionLevel.NoPrinting;
}
PrintingPermission operand = target as PrintingPermission;
if(operand == null) {
throw new ArgumentException(SR.Format(SR.TargetNotPrintingPermission));
}
return this.printingLevel <= operand.printingLevel;
}
/// <include file='doc\PrintingPermission.uex' path='docs/doc[@for="PrintingPermission.Intersect"]/*' />
/// <devdoc>
/// <para>Creates and returns a permission that is the intersection of the current
/// permission object and a target permission object.</para>
/// </devdoc>
public override IPermission Intersect(IPermission target) {
if (target == null) {
return null;
}
PrintingPermission operand = target as PrintingPermission;
if(operand == null) {
throw new ArgumentException(SR.Format(SR.TargetNotPrintingPermission));
}
PrintingPermissionLevel isectLevels = printingLevel < operand.printingLevel ? printingLevel : operand.printingLevel;
if (isectLevels == PrintingPermissionLevel.NoPrinting)
return null;
else
return new PrintingPermission(isectLevels);
}
/// <include file='doc\PrintingPermission.uex' path='docs/doc[@for="PrintingPermission.Union"]/*' />
/// <devdoc>
/// <para>Creates a permission that is the union of the permission object
/// and the target parameter permission object.</para>
/// </devdoc>
public override IPermission Union(IPermission target) {
if (target == null) {
return this.Copy();
}
PrintingPermission operand = target as PrintingPermission;
if(operand == null) {
throw new ArgumentException(SR.Format(SR.TargetNotPrintingPermission));
}
PrintingPermissionLevel isectLevels = printingLevel > operand.printingLevel ? printingLevel : operand.printingLevel;
if (isectLevels == PrintingPermissionLevel.NoPrinting)
return null;
else
return new PrintingPermission(isectLevels);
}
/// <include file='doc\PrintingPermission.uex' path='docs/doc[@for="PrintingPermission.Copy"]/*' />
/// <devdoc>
/// <para>Creates and returns an identical copy of the current permission
/// object.</para>
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")]
public override IPermission Copy() {
return new PrintingPermission(this.printingLevel);
}
/// <include file='doc\PrintingPermission.uex' path='docs/doc[@for="PrintingPermission.ToXml"]/*' />
/// <devdoc>
/// <para>Creates an XML encoding of the security object and its current
/// state.</para>
/// </devdoc>
public override SecurityElement ToXml() {
SecurityElement securityElement = new SecurityElement("IPermission");
securityElement.AddAttribute("class", this.GetType().FullName + ", " + this.GetType().Module.Assembly.FullName.Replace('\"', '\''));
securityElement.AddAttribute("version", "1");
if (!IsUnrestricted()) {
securityElement.AddAttribute("Level", Enum.GetName(typeof(PrintingPermissionLevel), printingLevel));
}
else {
securityElement.AddAttribute("Unrestricted", "true");
}
return securityElement;
}
/// <include file='doc\PrintingPermission.uex' path='docs/doc[@for="PrintingPermission.FromXml"]/*' />
/// <devdoc>
/// <para>Reconstructs a security object with a specified state from an XML
/// encoding.</para>
/// </devdoc>
[SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes")]
public override void FromXml(SecurityElement esd) {
if (esd == null) {
throw new ArgumentNullException("esd");
}
String className = esd.Attribute("class");
if (className == null || className.IndexOf(this.GetType().FullName) == -1) {
throw new ArgumentException(SR.Format(SR.InvalidClassName));
}
String unrestricted = esd.Attribute("Unrestricted");
if (unrestricted != null && String.Equals(unrestricted, "true", StringComparison.OrdinalIgnoreCase))
{
printingLevel = PrintingPermissionLevel.AllPrinting;
return;
}
printingLevel = PrintingPermissionLevel.NoPrinting;
String printing = esd.Attribute("Level");
if (printing != null)
{
printingLevel = (PrintingPermissionLevel)Enum.Parse(typeof(PrintingPermissionLevel), printing);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
/* Unboxing where a parameter is types as System.ValueType, or System.Enum, and then is unboxed to its scalar type
*/
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
interface X
{
void incCount();
}
interface A : X
{
}
interface B : X
{
}
struct C : A
{
public static int c_count = 1;
public void incCount() { c_count *= 23; }
}
struct D : B
{
public static int d_count = 1;
public void incCount() { d_count *= 31; }
}
struct CSS : A
{
public static int cs_count = 1;
public void incCount() { cs_count *= 37; }
public void readInput(int input) { cs_count = cs_count += input; }
}
struct DSS : B
{
public static int ds_count = 1;
public void incCount() { ds_count *= 41; }
public void readInput(int input) { ds_count = ds_count += input; }
}
enum CS
{
Day = 0, Night = 1
};
enum DS
{
Day = 1, Night = 0
};
struct mainMethod
{
public static bool failed = false;
public static void checkGetTypeValueType(System.ValueType x)
{
if (x.GetType() == typeof(D)) (new D()).incCount();
if (x.GetType() == typeof(C)) (new C()).incCount();
}
public static void checkIsValueType(System.ValueType x)
{
if (x is C) (new C()).incCount();
if (x is D) (new D()).incCount();
}
public static void checkGetTypeValueTypeCast(System.ValueType x)
{
if (x.GetType() == typeof(D)) ((D)x).incCount();
if (x.GetType() == typeof(C)) ((C)x).incCount();
}
public static void checkIsValueTypeCast(System.ValueType x)
{
if (x is C) ((C)x).incCount();
if (x is D) ((D)x).incCount();
}
public static void checkGetTypeEnum(System.Enum x)
{
if (x.GetType() == typeof(DS)) (new DSS()).incCount();
if (x.GetType() == typeof(CS)) (new CSS()).incCount();
}
public static void checkIsEnum(System.Enum x)
{
if (x is CS) (new CSS()).incCount();
if (x is DS) (new DSS()).incCount();
}
public static void checkGetTypeEnumCast(System.Enum x)
{
if (x.GetType() == typeof(DS)) (new DSS()).readInput(Convert.ToInt32(DS.Day));
if (x.GetType() == typeof(CS)) (new CSS()).readInput(Convert.ToInt32(CS.Night));
}
public static void checkIsEnumCast(System.Enum x)
{
if (x is CS) (new CSS()).readInput(Convert.ToInt32(CS.Night));
if (x is DS) (new DSS()).readInput(Convert.ToInt32(DS.Day));
}
public static void checkCount(ref int actual, int expected, string message)
{
if (actual != expected)
{
Console.WriteLine("FAILED: {0}", message);
failed = true;
}
actual = 1;
}
public static void checkAllCounts(ref int x_actual, int ds, int cs, int d, int c, string dsm, string csm, string dm, string cm)
{
/*
int tmp = 1;
printCount(ref DSS.ds_count, ds, dsm);
printCount(ref CSS.cs_count, cs, csm);
printCount(ref D.d_count, d, dm);
printCount(ref C.c_count, c, cm);
printCount(ref tmp, b, bm);
printCount(ref tmp, a, am);
printCount(ref tmp, x, xm);
//printCount(ref B.b_count, b, bm);
//printCount(ref A.a_count, a, am);
//printCount(ref x_actual, x, xm);
*/
checkCount(ref DSS.ds_count, ds, dsm);
checkCount(ref CSS.cs_count, cs, csm);
checkCount(ref D.d_count, d, dm);
checkCount(ref C.c_count, c, cm);
//checkCount(ref B.b_count, b, bm);
//checkCount(ref A.a_count, a, am);
//checkCount(ref x_actual, x, xm);
}
public static void printCount(ref int actual, int expected, string message)
{
Console.Write("{0}, ", actual);
actual = 1;
}
public static void callCheckGetTypeValueType()
{
int i = 0;
int dummy = 1;
checkGetTypeValueType(new C());
checkAllCounts(ref dummy, 1, 1, 1, 23, "DS Count after GetType and typeof", "CS Count after GetType and typeof", "D Count after GetType and typeof", "C Count after GetType and typeof");
Console.WriteLine("-----------{0}", i++);
checkGetTypeValueType(new D());
checkAllCounts(ref dummy, 1, 1, 31, 1, "DS Count after GetType and typeof", "CS Count after GetType and typeof", "D Count after GetType and typeof", "C Count after GetType and typeof");
Console.WriteLine("-----------{0}", i++);
checkGetTypeEnum(new CS());
checkAllCounts(ref dummy, 1, 37, 1, 1, "DS Count after GetType and typeof", "CS Count after GetType and typeof", "D Count after GetType and typeof", "C Count after GetType and typeof");
Console.WriteLine("-----------{0}", i++);
checkGetTypeEnum(new DS());
checkAllCounts(ref dummy, 41, 1, 1, 1, "DS Count after GetType and typeof", "CS Count after GetType and typeof", "D Count after GetType and typeof", "C Count after GetType and typeof");
Console.WriteLine("-----------{0}", i++);
}
public static void callCheckIsValueType()
{
int i = 0;
int dummy = 1;
checkIsValueType(new C());
checkAllCounts(ref dummy, 1, 1, 1, 23, "DS Count after checking is", "CS Count after checking is", "D Count after checking is", "C Count after checking is");
Console.WriteLine("-----------{0}", i++);
checkIsValueType(new D());
checkAllCounts(ref dummy, 1, 1, 31, 1, "DS Count after checking is", "CS Count after checking is", "D Count after checking is", "C Count after checking is");
Console.WriteLine("-----------{0}", i++);
checkIsEnum(new CS());
checkAllCounts(ref dummy, 1, 37, 1, 1, "DS Count after checking is", "CS Count after checking is", "D Count after checking is", "C Count after checking is");
Console.WriteLine("-----------{0}", i++);
checkIsEnum(new DS());
checkAllCounts(ref dummy, 41, 1, 1, 1, "DS Count after checking is", "CS Count after checking is", "D Count after checking is", "C Count after checking is");
Console.WriteLine("-----------{0}", i++);
}
public static void callCheckGetTypeValueTypeCast()
{
int i = 0;
int dummy = 1;
checkGetTypeValueTypeCast(new C());
checkAllCounts(ref dummy, 1, 1, 1, 23, "DS Count after GetType and typeof string cast", "CS Count after GetType and typeof string cast", "D Count after GetType and typeof string cast", "C Count after GetType and typeof string cast");
Console.WriteLine("-----------{0}", i++);
checkGetTypeValueTypeCast(new D());
checkAllCounts(ref dummy, 1, 1, 31, 1, "DS Count after GetType and typeof string cast", "CS Count after GetType and typeof string cast", "D Count after GetType and typeof string cast", "C Count after GetType and typeof string cast");
Console.WriteLine("-----------{0}", i++);
checkGetTypeEnumCast(new CS());
checkAllCounts(ref dummy, 1, 2, 1, 1, "DS Count after GetType and typeof string cast", "CS Count after GetType and typeof string cast", "D Count after GetType and typeof string cast", "C Count after GetType and typeof string cast");
Console.WriteLine("-----------{0}", i++);
checkGetTypeEnumCast(new DS());
checkAllCounts(ref dummy, 2, 1, 1, 1, "DS Count after GetType and typeof string cast", "CS Count after GetType and typeof string cast", "D Count after GetType and typeof string cast", "C Count after GetType and typeof string cast");
Console.WriteLine("-----------{0}", i++);
}
public static void callCheckIsValueTypeCast()
{
int i = 0;
int dummy = 1;
checkIsValueTypeCast(new C());
checkAllCounts(ref dummy, 1, 1, 1, 23, "DS Count after check is string cast ", "CS Count after check is string cast ", "D Count after check is string cast ", "C Count after check is string cast ");
Console.WriteLine("-----------{0}", i++);
checkIsValueTypeCast(new D());
checkAllCounts(ref dummy, 1, 1, 31, 1, "DS Count after check is string cast ", "CS Count after check is string cast ", "D Count after check is string cast ", "C Count after check is string cast ");
Console.WriteLine("-----------{0}", i++);
checkIsEnumCast(new CS());
checkAllCounts(ref dummy, 1, 2, 1, 1, "DS Count after check is string cast ", "CS Count after check is string cast ", "D Count after check is string cast ", "C Count after check is string cast ");
Console.WriteLine("-----------{0}", i++);
checkIsEnumCast(new DS());
checkAllCounts(ref dummy, 2, 1, 1, 1, "DS Count after check is string cast ", "CS Count after check is string cast ", "D Count after check is string cast ", "C Count after check is string cast ");
Console.WriteLine("-----------{0}", i++);
}
public static int Main()
{
callCheckGetTypeValueType();
callCheckIsValueType();
callCheckGetTypeValueTypeCast();
callCheckIsValueTypeCast();
if (failed) return 101; else return 100;
}
}
| |
namespace NArrange.Tests.Core
{
using System;
using NArrange.Core;
using NArrange.Core.CodeElements;
using NUnit.Framework;
/// <summary>
/// Test fixture for the ChainElementArranger class.
/// </summary>
[TestFixture]
public class ChainElementArrangerTests
{
#region Methods
/// <summary>
/// Tests the AddArranger method with a null arranger.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void AddArrangerNullTest()
{
ChainElementArranger chainArranger = new ChainElementArranger();
chainArranger.AddArranger(null);
}
/// <summary>
/// Tests the CanArrange method.
/// </summary>
[Test]
public void CanArrangeTest()
{
ChainElementArranger chain = new ChainElementArranger();
FieldElement fieldElement = new FieldElement();
//
// No arrangers in chain
//
Assert.IsFalse(
chain.CanArrange(fieldElement),
"Empty chain element arranger should not be able to arrange an element.");
//
// Add an arranger that can't arrange the element
//
TestElementArranger disabledArranger = new TestElementArranger(false);
chain.AddArranger(disabledArranger);
Assert.IsFalse(chain.CanArrange(fieldElement), "Unexpected return value from CanArrange.");
//
// Add an arranger that can arrange the element
//
TestElementArranger enabledArranger = new TestElementArranger(true);
chain.AddArranger(enabledArranger);
Assert.IsTrue(chain.CanArrange(fieldElement), "Unexpected return value from CanArrange.");
//
// Null
//
Assert.IsFalse(chain.CanArrange(null), "Unexpected return value from CanArrange.");
}
/// <summary>
/// Tests the Arrange method with an element that cannot be handled.
/// </summary>
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void UnsupportedArrangeNoParentTest()
{
ChainElementArranger chain = new ChainElementArranger();
FieldElement fieldElement = new FieldElement();
//
// Add an arranger that can't arrange the element
//
TestElementArranger disabledArranger = new TestElementArranger(false);
chain.AddArranger(disabledArranger);
Assert.IsFalse(chain.CanArrange(fieldElement), "Unexpected return value from CanArrange.");
chain.ArrangeElement(null, fieldElement);
}
/// <summary>
/// Tests the Arrange method with an element that cannot be handled.
/// </summary>
[Test]
public void UnsupportedArrangeWithParentTest()
{
GroupElement parentElement = new GroupElement();
ChainElementArranger chain = new ChainElementArranger();
FieldElement fieldElement = new FieldElement();
//
// Add an arranger that can't arrange the element
//
TestElementArranger disabledArranger = new TestElementArranger(false);
chain.AddArranger(disabledArranger);
Assert.IsFalse(chain.CanArrange(fieldElement), "Unexpected return value from CanArrange.");
chain.ArrangeElement(parentElement, fieldElement);
Assert.IsTrue(parentElement.Children.Contains(fieldElement));
}
#endregion Methods
#region Nested Types
/// <summary>
/// Test code element arranger.
/// </summary>
private class TestElementArranger : IElementArranger
{
#region Fields
/// <summary>
/// Whether or not arrage was called.
/// </summary>
private bool _arrangeCalled;
/// <summary>
/// Whether or not this arranger can process elements.
/// </summary>
private bool _canArrange;
#endregion Fields
#region Constructors
/// <summary>
/// Creates a test element arranger.
/// </summary>
/// <param name="canArrange">Fixed value for the CanArrange property.</param>
public TestElementArranger(bool canArrange)
{
_canArrange = canArrange;
}
#endregion Constructors
#region Properties
/// <summary>
/// Gets a value indicating whether or not arrange was called.
/// </summary>
public bool ArrangeCalled
{
get
{
return _arrangeCalled;
}
}
#endregion Properties
#region Methods
/// <summary>
/// Arranges the specified element within the parent element.
/// </summary>
/// <param name="parentElement">The parent element.</param>
/// <param name="codeElement">The code element.</param>
public void ArrangeElement(ICodeElement parentElement, ICodeElement codeElement)
{
_arrangeCalled = true;
}
/// <summary>
/// Determines whether or not this arranger can handle arrangement of
/// the specified element.
/// </summary>
/// <param name="codeElement">The code element.</param>
/// <returns>
/// <c>true</c> if this instance can arrange the specified code element; otherwise, <c>false</c>.
/// </returns>
public bool CanArrange(ICodeElement codeElement)
{
return _canArrange;
}
/// <summary>
/// Determines whether or not this arranger can handle arrangement of
/// the specified element.
/// </summary>
/// <param name="parentElement">The parent element.</param>
/// <param name="codeElement">The code element.</param>
/// <returns>
/// <c>true</c> if this instance can arrange the specified parent element; otherwise, <c>false</c>.
/// </returns>
public bool CanArrange(ICodeElement parentElement, ICodeElement codeElement)
{
return _canArrange;
}
#endregion Methods
}
#endregion Nested Types
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle;
namespace System.Net.Http
{
#if HTTP_DLL
internal enum WindowsProxyUsePolicy
#else
public enum WindowsProxyUsePolicy
#endif
{
DoNotUseProxy = 0, // Don't use a proxy at all.
UseWinHttpProxy = 1, // Use configuration as specified by "netsh winhttp" machine config command. Automatic detect not supported.
UseWinInetProxy = 2, // WPAD protocol and PAC files supported.
UseCustomProxy = 3 // Use the custom proxy specified in the Proxy property.
}
#if HTTP_DLL
internal enum CookieUsePolicy
#else
public enum CookieUsePolicy
#endif
{
IgnoreCookies = 0,
UseInternalCookieStoreOnly = 1,
UseSpecifiedCookieContainer = 2
}
#if HTTP_DLL
internal class WinHttpHandler : HttpMessageHandler
#else
public class WinHttpHandler : HttpMessageHandler
#endif
{
private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
private object _lockObject = new object();
private bool _doManualDecompressionCheck = false;
private WinInetProxyHelper _proxyHelper = null;
private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection;
private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections;
private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression;
private CookieUsePolicy _cookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly;
private CookieContainer _cookieContainer = null;
private SslProtocols _sslProtocols = SecurityProtocol.DefaultSecurityProtocols;
private Func<
HttpRequestMessage,
X509Certificate2,
X509Chain,
SslPolicyErrors,
bool> _serverCertificateValidationCallback = null;
private bool _checkCertificateRevocationList = false;
private ClientCertificateOption _clientCertificateOption = ClientCertificateOption.Manual;
private X509Certificate2Collection _clientCertificates = null; // Only create collection when required.
private ICredentials _serverCredentials = null;
private bool _preAuthenticate = false;
private WindowsProxyUsePolicy _windowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinHttpProxy;
private ICredentials _defaultProxyCredentials = CredentialCache.DefaultCredentials;
private IWebProxy _proxy = null;
private int _maxConnectionsPerServer = int.MaxValue;
private TimeSpan _connectTimeout = TimeSpan.FromSeconds(60);
private TimeSpan _sendTimeout = TimeSpan.FromSeconds(30);
private TimeSpan _receiveHeadersTimeout = TimeSpan.FromSeconds(30);
private TimeSpan _receiveDataTimeout = TimeSpan.FromSeconds(30);
private int _maxResponseHeadersLength = 64 * 1024;
private int _maxResponseDrainSize = 64 * 1024;
private volatile bool _operationStarted;
private volatile bool _disposed;
private SafeWinHttpHandle _sessionHandle;
private WinHttpAuthHelper _authHelper = new WinHttpAuthHelper();
private static readonly DiagnosticListener s_diagnosticListener = new DiagnosticListener(HttpHandlerLoggingStrings.DiagnosticListenerName);
public WinHttpHandler()
{
}
#region Properties
public bool AutomaticRedirection
{
get
{
return _automaticRedirection;
}
set
{
CheckDisposedOrStarted();
_automaticRedirection = value;
}
}
public int MaxAutomaticRedirections
{
get
{
return _maxAutomaticRedirections;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxAutomaticRedirections = value;
}
}
public DecompressionMethods AutomaticDecompression
{
get
{
return _automaticDecompression;
}
set
{
CheckDisposedOrStarted();
_automaticDecompression = value;
}
}
public CookieUsePolicy CookieUsePolicy
{
get
{
return _cookieUsePolicy;
}
set
{
if (value != CookieUsePolicy.IgnoreCookies
&& value != CookieUsePolicy.UseInternalCookieStoreOnly
&& value != CookieUsePolicy.UseSpecifiedCookieContainer)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_cookieUsePolicy = value;
}
}
public CookieContainer CookieContainer
{
get
{
return _cookieContainer;
}
set
{
CheckDisposedOrStarted();
_cookieContainer = value;
}
}
public SslProtocols SslProtocols
{
get
{
return _sslProtocols;
}
set
{
SecurityProtocol.ThrowOnNotAllowed(value, allowNone: false);
CheckDisposedOrStarted();
_sslProtocols = value;
}
}
public Func<
HttpRequestMessage,
X509Certificate2,
X509Chain,
SslPolicyErrors,
bool> ServerCertificateValidationCallback
{
get
{
return _serverCertificateValidationCallback;
}
set
{
CheckDisposedOrStarted();
_serverCertificateValidationCallback = value;
}
}
public bool CheckCertificateRevocationList
{
get
{
return _checkCertificateRevocationList;
}
set
{
_checkCertificateRevocationList = value;
}
}
public ClientCertificateOption ClientCertificateOption
{
get
{
return _clientCertificateOption;
}
set
{
if (value != ClientCertificateOption.Manual
&& value != ClientCertificateOption.Automatic)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_clientCertificateOption = value;
}
}
public X509Certificate2Collection ClientCertificates
{
get
{
if (_clientCertificates == null)
{
_clientCertificates = new X509Certificate2Collection();
}
return _clientCertificates;
}
}
public bool PreAuthenticate
{
get
{
return _preAuthenticate;
}
set
{
_preAuthenticate = value;
}
}
public ICredentials ServerCredentials
{
get
{
return _serverCredentials;
}
set
{
_serverCredentials = value;
}
}
public WindowsProxyUsePolicy WindowsProxyUsePolicy
{
get
{
return _windowsProxyUsePolicy;
}
set
{
if (value != WindowsProxyUsePolicy.DoNotUseProxy &&
value != WindowsProxyUsePolicy.UseWinHttpProxy &&
value != WindowsProxyUsePolicy.UseWinInetProxy &&
value != WindowsProxyUsePolicy.UseCustomProxy)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_windowsProxyUsePolicy = value;
}
}
public ICredentials DefaultProxyCredentials
{
get
{
return _defaultProxyCredentials;
}
set
{
CheckDisposedOrStarted();
_defaultProxyCredentials = value;
}
}
public IWebProxy Proxy
{
get
{
return _proxy;
}
set
{
CheckDisposedOrStarted();
_proxy = value;
}
}
public int MaxConnectionsPerServer
{
get
{
return _maxConnectionsPerServer;
}
set
{
if (value < 1)
{
// In WinHTTP, setting this to 0 results in it being reset to 2.
// So, we'll only allow settings above 0.
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxConnectionsPerServer = value;
}
}
public TimeSpan ConnectTimeout
{
get
{
return _connectTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_connectTimeout = value;
}
}
public TimeSpan SendTimeout
{
get
{
return _sendTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_sendTimeout = value;
}
}
public TimeSpan ReceiveHeadersTimeout
{
get
{
return _receiveHeadersTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_receiveHeadersTimeout = value;
}
}
public TimeSpan ReceiveDataTimeout
{
get
{
return _receiveDataTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_receiveDataTimeout = value;
}
}
public int MaxResponseHeadersLength
{
get
{
return _maxResponseHeadersLength;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxResponseHeadersLength = value;
}
}
public int MaxResponseDrainSize
{
get
{
return _maxResponseDrainSize;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxResponseDrainSize = value;
}
}
#endregion
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
_disposed = true;
if (disposing && _sessionHandle != null)
{
SafeWinHttpHandle.DisposeAndClearHandle(ref _sessionHandle);
}
}
base.Dispose(disposing);
}
#if HTTP_DLL
protected internal override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
#else
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
#endif
{
if (request == null)
{
throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest);
}
// Check for invalid combinations of properties.
if (_proxy != null && _windowsProxyUsePolicy != WindowsProxyUsePolicy.UseCustomProxy)
{
throw new InvalidOperationException(SR.net_http_invalid_proxyusepolicy);
}
if (_windowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy && _proxy == null)
{
throw new InvalidOperationException(SR.net_http_invalid_proxy);
}
if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer &&
_cookieContainer == null)
{
throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer);
}
CheckDisposed();
Guid loggingRequestId = s_diagnosticListener.LogHttpRequest(request);
SetOperationStarted();
TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
// Create state object and save current values of handler settings.
var state = new WinHttpRequestState();
state.Tcs = tcs;
state.CancellationToken = cancellationToken;
state.RequestMessage = request;
state.Handler = this;
state.CheckCertificateRevocationList = _checkCertificateRevocationList;
state.ServerCertificateValidationCallback = _serverCertificateValidationCallback;
state.WindowsProxyUsePolicy = _windowsProxyUsePolicy;
state.Proxy = _proxy;
state.ServerCredentials = _serverCredentials;
state.DefaultProxyCredentials = _defaultProxyCredentials;
state.PreAuthenticate = _preAuthenticate;
Task.Factory.StartNew(
s => ((WinHttpRequestState)s).Handler.StartRequest(s),
state,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
s_diagnosticListener.LogHttpResponse(tcs.Task, loggingRequestId);
return tcs.Task;
}
private static bool IsChunkedModeForSend(HttpRequestMessage requestMessage)
{
bool chunkedMode = requestMessage.Headers.TransferEncodingChunked.HasValue &&
requestMessage.Headers.TransferEncodingChunked.Value;
HttpContent requestContent = requestMessage.Content;
if (requestContent != null)
{
if (requestContent.Headers.ContentLength.HasValue)
{
if (chunkedMode)
{
// Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics.
// Current .NET Desktop HttpClientHandler allows both headers to be specified but ends up
// stripping out 'Content-Length' and using chunked semantics. WinHttpHandler will maintain
// the same behavior.
requestContent.Headers.ContentLength = null;
}
}
else
{
if (!chunkedMode)
{
// Neither 'Content-Length' nor 'Transfer-Encoding: chunked' semantics was given.
// Current .NET Desktop HttpClientHandler uses 'Content-Length' semantics and
// buffers the content as well in some cases. But the WinHttpHandler can't access
// the protected internal TryComputeLength() method of the content. So, it
// will use'Transfer-Encoding: chunked' semantics.
chunkedMode = true;
requestMessage.Headers.TransferEncodingChunked = true;
}
}
}
else if (chunkedMode)
{
throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content);
}
return chunkedMode;
}
private static void AddRequestHeaders(
SafeWinHttpHandle requestHandle,
HttpRequestMessage requestMessage,
CookieContainer cookies)
{
var requestHeadersBuffer = new StringBuilder();
// Manually add cookies.
if (cookies != null)
{
string cookieHeader = WinHttpCookieContainerAdapter.GetCookieHeader(requestMessage.RequestUri, cookies);
if (!string.IsNullOrEmpty(cookieHeader))
{
requestHeadersBuffer.AppendLine(cookieHeader);
}
}
// Serialize general request headers.
requestHeadersBuffer.AppendLine(requestMessage.Headers.ToString());
// Serialize entity-body (content) headers.
if (requestMessage.Content != null)
{
// TODO: Content-Length header isn't getting correctly placed using ToString()
// This is a bug in HttpContentHeaders that needs to be fixed.
if (requestMessage.Content.Headers.ContentLength.HasValue)
{
long contentLength = requestMessage.Content.Headers.ContentLength.Value;
requestMessage.Content.Headers.ContentLength = null;
requestMessage.Content.Headers.ContentLength = contentLength;
}
requestHeadersBuffer.AppendLine(requestMessage.Content.Headers.ToString());
}
// Add request headers to WinHTTP request handle.
if (!Interop.WinHttp.WinHttpAddRequestHeaders(
requestHandle,
requestHeadersBuffer,
(uint)requestHeadersBuffer.Length,
Interop.WinHttp.WINHTTP_ADDREQ_FLAG_ADD))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void EnsureSessionHandleExists(WinHttpRequestState state)
{
if (_sessionHandle == null)
{
lock (_lockObject)
{
if (_sessionHandle == null)
{
uint accessType;
// If a custom proxy is specified and it is really the system web proxy
// (initial WebRequest.DefaultWebProxy) then we need to update the settings
// since that object is only a sentinel.
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy)
{
Debug.Assert(state.Proxy != null);
try
{
state.Proxy.GetProxy(state.RequestMessage.RequestUri);
}
catch (PlatformNotSupportedException)
{
// This is the system web proxy.
state.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
state.Proxy = null;
}
}
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.DoNotUseProxy ||
state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy)
{
// Either no proxy at all or a custom IWebProxy proxy is specified.
// For a custom IWebProxy, we'll need to calculate and set the proxy
// on a per request handle basis using the request Uri. For now,
// we set the session handle to have no proxy.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY;
}
else if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinHttpProxy)
{
// Use WinHTTP per-machine proxy settings which are set using the "netsh winhttp" command.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
}
else
{
// Use WinInet per-user proxy settings.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY;
}
_sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
accessType,
Interop.WinHttp.WINHTTP_NO_PROXY_NAME,
Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
if (_sessionHandle.IsInvalid)
{
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_INVALID_PARAMETER)
{
ThrowOnInvalidHandle(_sessionHandle);
}
// We must be running on a platform earlier than Win8.1/Win2K12R2 which doesn't support
// WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY. So, we'll need to read the Wininet style proxy
// settings ourself using our WinInetProxyHelper object.
_proxyHelper = new WinInetProxyHelper();
_sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
_proxyHelper.ManualSettingsOnly ? Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY : Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY,
_proxyHelper.ManualSettingsOnly ? _proxyHelper.Proxy : Interop.WinHttp.WINHTTP_NO_PROXY_NAME,
_proxyHelper.ManualSettingsOnly ? _proxyHelper.ProxyBypass : Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
ThrowOnInvalidHandle(_sessionHandle);
}
uint optionAssuredNonBlockingTrue = 1; // TRUE
if (!Interop.WinHttp.WinHttpSetOption(
_sessionHandle,
Interop.WinHttp.WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS,
ref optionAssuredNonBlockingTrue,
(uint)Marshal.SizeOf<uint>()))
{
// This option is not available on downlevel Windows versions. While it improves
// performance, we can ignore the error that the option is not available.
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION)
{
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
}
}
}
}
private async void StartRequest(object obj)
{
WinHttpRequestState state = (WinHttpRequestState)obj;
bool secureConnection = false;
HttpResponseMessage responseMessage = null;
Exception savedException = null;
SafeWinHttpHandle connectHandle = null;
if (state.CancellationToken.IsCancellationRequested)
{
state.Tcs.TrySetCanceled(state.CancellationToken);
return;
}
try
{
EnsureSessionHandleExists(state);
SetSessionHandleOptions();
// Specify an HTTP server.
connectHandle = Interop.WinHttp.WinHttpConnect(
_sessionHandle,
state.RequestMessage.RequestUri.Host,
(ushort)state.RequestMessage.RequestUri.Port,
0);
ThrowOnInvalidHandle(connectHandle);
connectHandle.SetParentHandle(_sessionHandle);
if (state.RequestMessage.RequestUri.Scheme == UriScheme.Https)
{
secureConnection = true;
}
else
{
secureConnection = false;
}
// Try to use the requested version if a known/supported version was explicitly requested.
// Otherwise, we simply use winhttp's default.
string httpVersion = null;
if (state.RequestMessage.Version == HttpVersion.Version10)
{
httpVersion = "HTTP/1.0";
}
else if (state.RequestMessage.Version == HttpVersion.Version11)
{
httpVersion = "HTTP/1.1";
}
// Create an HTTP request handle.
state.RequestHandle = Interop.WinHttp.WinHttpOpenRequest(
connectHandle,
state.RequestMessage.Method.Method,
state.RequestMessage.RequestUri.PathAndQuery,
httpVersion,
Interop.WinHttp.WINHTTP_NO_REFERER,
Interop.WinHttp.WINHTTP_DEFAULT_ACCEPT_TYPES,
secureConnection ? Interop.WinHttp.WINHTTP_FLAG_SECURE : 0);
ThrowOnInvalidHandle(state.RequestHandle);
state.RequestHandle.SetParentHandle(connectHandle);
// Set callback function.
SetStatusCallback(state.RequestHandle, WinHttpRequestCallback.StaticCallbackDelegate);
// Set needed options on the request handle.
SetRequestHandleOptions(state);
bool chunkedModeForSend = IsChunkedModeForSend(state.RequestMessage);
AddRequestHeaders(
state.RequestHandle,
state.RequestMessage,
_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer ? _cookieContainer : null);
uint proxyAuthScheme = 0;
uint serverAuthScheme = 0;
state.RetryRequest = false;
// The only way to abort pending async operations in WinHTTP is to close the WinHTTP handle.
// We will detect a cancellation request on the cancellation token by registering a callback.
// If the callback is invoked, then we begin the abort process by disposing the handle. This
// will have the side-effect of WinHTTP cancelling any pending I/O and accelerating its callbacks
// on the handle and thus releasing the awaiting tasks in the loop below. This helps to provide
// a more timely, cooperative, cancellation pattern.
using (state.CancellationToken.Register(s => ((WinHttpRequestState)s).RequestHandle.Dispose(), state))
{
do
{
_authHelper.PreAuthenticateRequest(state, proxyAuthScheme);
await InternalSendRequestAsync(state).ConfigureAwait(false);
if (state.RequestMessage.Content != null)
{
await InternalSendRequestBodyAsync(state, chunkedModeForSend).ConfigureAwait(false);
}
bool receivedResponse = await InternalReceiveResponseHeadersAsync(state).ConfigureAwait(false);
if (receivedResponse)
{
// If we're manually handling cookies, we need to add them to the container after
// each response has been received.
if (state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer)
{
WinHttpCookieContainerAdapter.AddResponseCookiesToContainer(state);
}
_authHelper.CheckResponseForAuthentication(
state,
ref proxyAuthScheme,
ref serverAuthScheme);
}
} while (state.RetryRequest);
}
state.CancellationToken.ThrowIfCancellationRequested();
responseMessage = WinHttpResponseParser.CreateResponseMessage(state, _doManualDecompressionCheck);
// Since the headers have been read, set the "receive" timeout to be based on each read
// call of the response body data. WINHTTP_OPTION_RECEIVE_TIMEOUT sets a timeout on each
// lower layer winsock read.
uint optionData = (uint)_receiveDataTimeout.TotalMilliseconds;
SetWinHttpOption(state.RequestHandle, Interop.WinHttp.WINHTTP_OPTION_RECEIVE_TIMEOUT, ref optionData);
}
catch (Exception ex)
{
if (state.SavedException != null)
{
savedException = state.SavedException;
}
else
{
savedException = ex;
}
}
finally
{
SafeWinHttpHandle.DisposeAndClearHandle(ref connectHandle);
}
// Move the main task to a terminal state. This releases any callers of SendAsync() that are awaiting.
if (responseMessage != null)
{
state.Tcs.TrySetResult(responseMessage);
}
else
{
HandleAsyncException(state, savedException);
}
}
private void SetSessionHandleOptions()
{
SetSessionHandleConnectionOptions();
SetSessionHandleTlsOptions();
SetSessionHandleTimeoutOptions();
}
private void SetSessionHandleConnectionOptions()
{
uint optionData = (uint)_maxConnectionsPerServer;
SetWinHttpOption(_sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_SERVER, ref optionData);
SetWinHttpOption(_sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_1_0_SERVER, ref optionData);
}
private void SetSessionHandleTlsOptions()
{
uint optionData = 0;
if ((_sslProtocols & SslProtocols.Tls) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1;
}
if ((_sslProtocols & SslProtocols.Tls11) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1;
}
if ((_sslProtocols & SslProtocols.Tls12) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2;
}
SetWinHttpOption(_sessionHandle, Interop.WinHttp.WINHTTP_OPTION_SECURE_PROTOCOLS, ref optionData);
}
private void SetSessionHandleTimeoutOptions()
{
if (!Interop.WinHttp.WinHttpSetTimeouts(
_sessionHandle,
0,
(int)_connectTimeout.TotalMilliseconds,
(int)_sendTimeout.TotalMilliseconds,
(int)_receiveHeadersTimeout.TotalMilliseconds))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void SetRequestHandleOptions(WinHttpRequestState state)
{
SetRequestHandleProxyOptions(state);
SetRequestHandleDecompressionOptions(state.RequestHandle);
SetRequestHandleRedirectionOptions(state.RequestHandle);
SetRequestHandleCookieOptions(state.RequestHandle);
SetRequestHandleTlsOptions(state.RequestHandle);
SetRequestHandleClientCertificateOptions(state.RequestHandle, state.RequestMessage.RequestUri);
SetRequestHandleCredentialsOptions(state);
SetRequestHandleBufferingOptions(state.RequestHandle);
}
private void SetRequestHandleProxyOptions(WinHttpRequestState state)
{
// We've already set the proxy on the session handle if we're using no proxy or default proxy settings.
// We only need to change it on the request handle if we have a specific IWebProxy or need to manually
// implement Wininet-style auto proxy detection.
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy ||
state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinInetProxy)
{
var proxyInfo = new Interop.WinHttp.WINHTTP_PROXY_INFO();
bool updateProxySettings = false;
Uri uri = state.RequestMessage.RequestUri;
try
{
if (state.Proxy != null)
{
Debug.Assert(state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy);
updateProxySettings = true;
if (state.Proxy.IsBypassed(uri))
{
proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY;
}
else
{
proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY;
Uri proxyUri = state.Proxy.GetProxy(uri);
string proxyString = string.Format(
CultureInfo.InvariantCulture,
"{0}://{1}",
proxyUri.Scheme,
proxyUri.Authority);
proxyInfo.Proxy = Marshal.StringToHGlobalUni(proxyString);
}
}
else if (_proxyHelper != null && _proxyHelper.AutoSettingsUsed)
{
updateProxySettings = true;
_proxyHelper.GetProxyForUrl(_sessionHandle, uri, out proxyInfo);
}
if (updateProxySettings)
{
GCHandle pinnedHandle = GCHandle.Alloc(proxyInfo, GCHandleType.Pinned);
try
{
SetWinHttpOption(
state.RequestHandle,
Interop.WinHttp.WINHTTP_OPTION_PROXY,
pinnedHandle.AddrOfPinnedObject(),
(uint)Marshal.SizeOf(proxyInfo));
}
finally
{
pinnedHandle.Free();
}
}
}
finally
{
Marshal.FreeHGlobal(proxyInfo.Proxy);
Marshal.FreeHGlobal(proxyInfo.ProxyBypass);
}
}
}
private void SetRequestHandleDecompressionOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = 0;
if (_automaticDecompression != DecompressionMethods.None)
{
if ((_automaticDecompression & DecompressionMethods.GZip) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_GZIP;
}
if ((_automaticDecompression & DecompressionMethods.Deflate) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_DEFLATE;
}
try
{
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DECOMPRESSION, ref optionData);
}
catch (WinHttpException ex)
{
if (ex.NativeErrorCode != (int)Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION)
{
throw;
}
// We are running on a platform earlier than Win8.1 for which WINHTTP.DLL
// doesn't support this option. So, we'll have to do the decompression
// manually.
_doManualDecompressionCheck = true;
}
}
}
private void SetRequestHandleRedirectionOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = 0;
if (_automaticRedirection)
{
optionData = (uint)_maxAutomaticRedirections;
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS,
ref optionData);
}
optionData = _automaticRedirection ?
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP :
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_NEVER;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY, ref optionData);
}
private void SetRequestHandleCookieOptions(SafeWinHttpHandle requestHandle)
{
if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer ||
_cookieUsePolicy == CookieUsePolicy.IgnoreCookies)
{
uint optionData = Interop.WinHttp.WINHTTP_DISABLE_COOKIES;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DISABLE_FEATURE, ref optionData);
}
}
private void SetRequestHandleTlsOptions(SafeWinHttpHandle requestHandle)
{
// If we have a custom server certificate validation callback method then
// we need to have WinHTTP ignore some errors so that the callback method
// will have a chance to be called.
uint optionData;
if (_serverCertificateValidationCallback != null)
{
optionData =
Interop.WinHttp.SECURITY_FLAG_IGNORE_UNKNOWN_CA |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_CN_INVALID |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_SECURITY_FLAGS, ref optionData);
}
else if (_checkCertificateRevocationList)
{
// If no custom validation method, then we let WinHTTP do the revocation check itself.
optionData = Interop.WinHttp.WINHTTP_ENABLE_SSL_REVOCATION;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_ENABLE_FEATURE, ref optionData);
}
}
private void SetRequestHandleClientCertificateOptions(SafeWinHttpHandle requestHandle, Uri requestUri)
{
if (requestUri.Scheme != UriScheme.Https)
{
return;
}
X509Certificate2 clientCertificate = null;
if (_clientCertificateOption == ClientCertificateOption.Manual)
{
clientCertificate = WinHttpCertificateHelper.GetEligibleClientCertificate(ClientCertificates);
}
else
{
clientCertificate = WinHttpCertificateHelper.GetEligibleClientCertificate();
}
if (clientCertificate != null)
{
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
clientCertificate.Handle,
(uint)Marshal.SizeOf<Interop.Crypt32.CERT_CONTEXT>());
}
else
{
SetNoClientCertificate(requestHandle);
}
}
internal static void SetNoClientCertificate(SafeWinHttpHandle requestHandle)
{
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
IntPtr.Zero,
0);
}
private void SetRequestHandleCredentialsOptions(WinHttpRequestState state)
{
// Set WinHTTP to send/prevent default credentials for either proxy or server auth.
bool useDefaultCredentials = false;
if (state.ServerCredentials == CredentialCache.DefaultCredentials)
{
useDefaultCredentials = true;
}
else if (state.WindowsProxyUsePolicy != WindowsProxyUsePolicy.DoNotUseProxy)
{
if (state.Proxy == null && _defaultProxyCredentials == CredentialCache.DefaultCredentials)
{
useDefaultCredentials = true;
}
else if (state.Proxy != null && state.Proxy.Credentials == CredentialCache.DefaultCredentials)
{
useDefaultCredentials = true;
}
}
uint optionData = useDefaultCredentials ?
Interop.WinHttp.WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW :
Interop.WinHttp.WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH;
SetWinHttpOption(state.RequestHandle, Interop.WinHttp.WINHTTP_OPTION_AUTOLOGON_POLICY, ref optionData);
}
private void SetRequestHandleBufferingOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = (uint)_maxResponseHeadersLength;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE, ref optionData);
optionData = (uint)_maxResponseDrainSize;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE, ref optionData);
}
private void SetWinHttpOption(SafeWinHttpHandle handle, uint option, ref uint optionData)
{
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
ref optionData))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void SetWinHttpOption(SafeWinHttpHandle handle, uint option, string optionData)
{
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
optionData,
(uint)optionData.Length))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private static void SetWinHttpOption(
SafeWinHttpHandle handle,
uint option,
IntPtr optionData,
uint optionSize)
{
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
optionData,
optionSize))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void HandleAsyncException(WinHttpRequestState state, Exception ex)
{
if (state.CancellationToken.IsCancellationRequested)
{
// If the exception was due to the cancellation token being canceled, throw cancellation exception.
state.Tcs.TrySetCanceled(state.CancellationToken);
}
else if (ex is WinHttpException || ex is IOException)
{
// Wrap expected exceptions as HttpRequestExceptions since this is considered an error during
// execution. All other exception types, including ArgumentExceptions and ProtocolViolationExceptions
// are 'unexpected' or caused by user error and should not be wrapped.
state.Tcs.TrySetException(new HttpRequestException(SR.net_http_client_execution_error, ex));
}
else
{
state.Tcs.TrySetException(ex);
}
}
private void SetOperationStarted()
{
if (!_operationStarted)
{
_operationStarted = true;
}
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_operationStarted)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
private void SetStatusCallback(
SafeWinHttpHandle requestHandle,
Interop.WinHttp.WINHTTP_STATUS_CALLBACK callback)
{
// TODO: Issue #5036. Having the status callback use WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS
// isn't strictly necessary. However, some of the notification flags are required.
// This will be addressed this as part of WinHttpHandler performance improvements.
IntPtr oldCallback = Interop.WinHttp.WinHttpSetStatusCallback(
requestHandle,
callback,
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS,
IntPtr.Zero);
if (oldCallback == new IntPtr(Interop.WinHttp.WINHTTP_INVALID_STATUS_CALLBACK))
{
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_INVALID_HANDLE) // Ignore error if handle was already closed.
{
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
}
private void ThrowOnInvalidHandle(SafeWinHttpHandle handle)
{
if (handle.IsInvalid)
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private Task<bool> InternalSendRequestAsync(WinHttpRequestState state)
{
state.TcsSendRequest = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
lock (state.Lock)
{
if (!Interop.WinHttp.WinHttpSendRequest(
state.RequestHandle,
null,
0,
IntPtr.Zero,
0,
0,
state.ToIntPtr()))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
return state.TcsSendRequest.Task;
}
private async Task InternalSendRequestBodyAsync(WinHttpRequestState state, bool chunkedModeForSend)
{
using (var requestStream = new WinHttpRequestStream(state, chunkedModeForSend))
{
await state.RequestMessage.Content.CopyToAsync(
requestStream,
state.TransportContext).ConfigureAwait(false);
await requestStream.EndUploadAsync(state.CancellationToken).ConfigureAwait(false);
}
}
private Task<bool> InternalReceiveResponseHeadersAsync(WinHttpRequestState state)
{
state.TcsReceiveResponseHeaders =
new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
lock (state.Lock)
{
if (!Interop.WinHttp.WinHttpReceiveResponse(state.RequestHandle, IntPtr.Zero))
{
throw WinHttpException.CreateExceptionUsingLastError();
}
}
return state.TcsReceiveResponseHeaders.Task;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Bond
{
using System;
// Tag types used to annotate Bond schema types via Type attribute
// ReSharper disable InconsistentNaming
// ReSharper disable UnusedTypeParameter
namespace Tag
{
/// <summary>
/// Represents wstring Bond schema type
/// </summary>
public abstract class wstring { }
/// <summary>
/// Represents blob Bond schema type
/// </summary>
public abstract class blob { }
/// <summary>
/// Represents nullable<T> Bond schema type
/// </summary>
public abstract class nullable<T> { }
/// <summary>
/// Represents bonded<T> Bond schema type
/// </summary>
public abstract class bonded<T> { }
/// <summary>
/// Represents a type parameter constrained to value types
/// </summary>
public struct structT { }
/// <summary>
/// Represents unconstrained type parameter
/// </summary>
public abstract class classT { }
}
// ReSharper restore InconsistentNaming
// ReSharper restore UnusedTypeParameter
/// <summary>
/// Specifies that a type represents Bond schema
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface,
Inherited = false)]
public sealed class SchemaAttribute : Attribute
{
}
/// <summary>
/// Specifies namespace of the schema, required only if different than C# namespace of the class
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Enum,
Inherited = false)]
public sealed class NamespaceAttribute : Attribute
{
public NamespaceAttribute(string value)
{
Value = value;
}
internal string Value { get; private set; }
}
/// <summary>
/// Specifies field identifier. Required for all Bond fields
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = false)]
public sealed class IdAttribute : Attribute
{
public IdAttribute(ushort id)
{
Value = id;
}
internal ushort Value { get; private set; }
}
/// <summary>
/// Specifies type of a field in Bond schema
/// </summary>
/// <remarks>
/// If absent the type is inferred from C# type using the following rules:
/// - numeric types map in the obvious way
/// - IList, ICollection -> BT_LIST
/// - IDictionary -> BT_MAP
/// - ISet -> BT_SET
/// - string -> BT_STRING (Utf8)
/// - Bond struct fields initialized to null map to nullable
/// - other fields initialized to null map to default of nothing
/// The Type attribute is necessary in the following cases:
/// - nullable types, e.g. Type[typeof(list<nullable<string>>)]
/// - Utf16 string (BT_WSTRING), e.g. Type[typeof(wstring)]
/// - user specified type aliases
/// </remarks>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = false)]
public sealed class TypeAttribute : Attribute
{
public TypeAttribute(Type type)
{
Value = type;
}
internal Type Value { get; private set; }
}
/// <summary>
/// Specifies the default value of a field
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = false)]
public sealed class DefaultAttribute : Attribute
{
public DefaultAttribute(object value)
{
Value = value;
}
public object Value { get; private set; }
}
/// <summary>
/// Specifies that a field is required
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = false)]
public sealed class RequiredAttribute : Attribute
{
}
/// <summary>
/// Specifies that a field is required_optional
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = false)]
public sealed class RequiredOptionalAttribute : Attribute
{
}
/// <summary>
/// Specifies user defined schema attribute
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum |
AttributeTargets.Interface | AttributeTargets.Field | AttributeTargets.Property,
AllowMultiple = true, Inherited = false)]
public sealed class AttributeAttribute : Attribute
{
public AttributeAttribute(string name, string value)
{
Name = name;
Value = value;
}
public string Name { get; private set; }
public string Value { get; private set; }
}
/// <summary>
/// Applied to protocol readers to indicate the IParser implementation used for parsing the protocol
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)]
public sealed class ParserAttribute : Attribute
{
public ParserAttribute(Type parserType)
{
ParserType = parserType;
}
internal Type ParserType { get; private set; }
}
/// <summary>
/// Applied to protocol writers to indicate the reader type for the protocol
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)]
public sealed class ReaderAttribute : Attribute
{
public ReaderAttribute(Type readerType)
{
ReaderType = readerType;
}
internal Type ReaderType { get; private set; }
}
/// <summary>
/// Applied to protocol writers to indicate the implementation of ISerializerGenerator used to generate serializer
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)]
public sealed class SerializerAttribute : Attribute
{
public SerializerAttribute(Type type)
{
Type = type;
}
internal Type Type { get; private set; }
}
}
| |
/*
Copyright 2012 Michael Edwards
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.
*/
//-CRE-
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Glass.Mapper.Caching;
using Glass.Mapper.Sc.Configuration;
using Glass.Mapper.Sc.Configuration.Attributes;
using NUnit.Framework;
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Globalization;
namespace Glass.Mapper.Sc.Integration
{
[TestFixture]
public class PerformanceTests
{
private string _expected;
private Guid _id;
private Context _context;
private Database _db;
private SitecoreService _service;
private bool _hasRun = false;
private Stopwatch _glassWatch;
private Stopwatch _rawWatch;
private double _glassTotal;
private double _rawTotal;
[SetUp]
public void Setup()
{
if (_hasRun)
{
return;
}
else
_hasRun = true;
_glassWatch = new Stopwatch();
_rawWatch= new Stopwatch();
_expected = "hello world";
_id = new Guid("{59784F74-F830-4BCD-B1F0-1A08616EF726}");
_context = Context.Create(Utilities.CreateStandardResolver());
_context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration"));
_db = Factory.GetDatabase("master");
// service.Profiler = new SimpleProfiler();
_service = new SitecoreService(_db);
var item = _db.GetItem(new ID(_id));
using (new ItemEditing(item, true))
{
item["Field"] = _expected;
}
}
[Test]
public void GetItemByIdvsItemByPath()
{
_glassWatch.Reset();
// Warm up
ID id = new ID(_id);
var item1 = _db.GetItem(id);
string path = item1.Paths.FullPath;
Console.WriteLine(path);
var item2 = _db.GetItem(path);
string itemIdString = _id.ToString();
var item3 = _db.GetItem(itemIdString);
// Start
_glassWatch.Start();
for (var i = 0; i < 10000; i++)
{
_db.GetItem(id);
}
_glassWatch.Stop();
Console.WriteLine("Item by Id: {0}", _glassWatch.ElapsedMilliseconds);
_glassWatch.Reset();
_glassWatch.Start();
for (var i = 0; i < 10000; i++)
{
_db.GetItem(path);
}
_glassWatch.Stop();
Console.WriteLine("Item by Path: {0}", _glassWatch.ElapsedMilliseconds);
_glassWatch.Reset();
_glassWatch.Start();
for (var i = 0; i < 10000; i++)
{
_db.GetItem(itemIdString);
}
_glassWatch.Stop();
Console.WriteLine("Item by Id String: {0}", _glassWatch.ElapsedMilliseconds);
}
[Test]
[Timeout(120000)]
[Repeat(10000)]
public void GetItems(
[Values(1, 1000, 10000, 50000)] int count
)
{
_glassWatch.Reset();
_rawWatch.Reset();
for (int i = 0; i < count; i++)
{
_rawWatch.Start();
var rawItem = _db.GetItem(new ID(_id));
var value1 = rawItem["Field"];
_rawWatch.Stop();
_rawTotal = _rawWatch.ElapsedTicks;
_glassWatch.Start();
var glassItem = _service.GetItem<StubClass>(_id);
var value2 = glassItem.Field;
_glassWatch.Stop();
_glassTotal = _glassWatch.ElapsedTicks;
}
double total = _glassTotal / _rawTotal;
Console.WriteLine("Performance Test Count: {0} Ratio: {1} Average: {2}".Formatted(count, total, _glassTotal/count));
}
[Test]
[Timeout(120000)]
[Repeat(10000)]
public void GetItems_LotsOfProperties(
[Values(1000, 10000, 50000)] int count
)
{
_glassWatch.Reset();
_rawWatch.Reset();
for (int i = 0; i < count; i++)
{
_rawWatch.Start();
var rawItem = _db.GetItem(new ID(_id));
var value1 = rawItem["Field"];
_rawWatch.Stop();
_rawTotal = _rawWatch.ElapsedTicks;
_glassWatch.Start();
var glassItem = _service.GetItem<StubClassWithLotsOfProperties>(_id);
var value2 = glassItem.Field1;
_glassWatch.Stop();
_glassTotal = _glassWatch.ElapsedTicks;
}
double total = _glassTotal / _rawTotal;
Console.WriteLine("Performance Test Count: {0} Ratio: {1} Average: {2}".Formatted(count, total, _glassTotal/count));
}
[Test]
[Timeout(120000)]
public void GetWholeDb()
{
List<Item> items = new List<Item>();
var rawItem = _db.GetItem("/sitecore");
_service.Cast<StubForWholeDb>(rawItem);
foreach (Item child in rawItem.GetChildren())
{
AddChildren(child, items);
}
var count = 0;
_glassWatch.Reset();
_rawWatch.Reset();
foreach (var item in items)
{
_rawWatch.Start();
if (item.Versions.Count > 0)
{
var value1 = rawItem["__DisplayName"];
}
_rawWatch.Stop();
_glassWatch.Start();
var glassItem = _service.Cast<StubForWholeDb>(item);
if (glassItem != null)
{
var value2 = glassItem.Field;
}
_glassWatch.Stop();
count++;
}
_rawTotal += _rawWatch.ElapsedTicks;
_glassTotal = _glassWatch.ElapsedTicks;
double total = _glassTotal / _rawTotal;
Console.WriteLine("Performance Test Count: {0} Ratio: {1} Average: {2}".Formatted(count, total, _glassTotal / count));
Console.WriteLine("Total Items {0}", count);
}
private void AddChildren(Item parent, List<Item> items)
{
items.Add(parent);
if (parent.HasChildren)
{
foreach (Item child in parent.GetChildren())
{
AddChildren(child, items);
}
}
}
[Test]
public void VersionCountsTest()
{
//Arrange
var config = new Config();
IItemVersionHandler versionHandler = new ItemVersionHandler(config);
IItemVersionHandler cachedVersionHandler = new TestCachedItemVersionHandler(new ConcurrentDictionaryCacheManager(), config);
var warmupItem = _db.GetItem(new ID(_id));
bool result1 = false;
bool result2 = false;
//Act
_glassWatch.Start();
var sitecoreItem = _db.GetItem(new ID(_id));
for (var i = 0; i < 10000; i++)
{
result1 = versionHandler.VersionCountEnabledAndHasVersions(sitecoreItem);
}
_glassWatch.Stop();
Console.WriteLine(_glassWatch.ElapsedMilliseconds);
_glassWatch.Reset();
_glassWatch.Start();
for (var i = 0; i < 10000; i++)
{
result2 = cachedVersionHandler.VersionCountEnabledAndHasVersions(sitecoreItem);
}
_glassWatch.Stop();
Console.WriteLine(_glassWatch.ElapsedMilliseconds);
//Assert
Assert.IsTrue(result1);
Assert.IsTrue(result2);
}
[Test]
public void VersionCountsTest_IncorrectLanguage()
{
//Arrange
var config = new Config();
IItemVersionHandler versionHandler = new ItemVersionHandler(config);
IItemVersionHandler cachedVersionHandler = new TestCachedItemVersionHandler(new NetMemoryCacheManager(), config);
var warmupItem = _db.GetItem(new ID(_id));
bool result1 = false;
bool result2 = false;
//Act
_glassWatch.Start();
for (var i = 0; i < 10000; i++)
{
var sitecoreItem = _db.GetItem(new ID(_id), Language.Parse("de-DE"));
result1 = versionHandler.VersionCountEnabledAndHasVersions(sitecoreItem);
}
_glassWatch.Stop();
Console.WriteLine(_glassWatch.ElapsedMilliseconds);
_glassWatch.Reset();
_glassWatch.Start();
for (var i = 0; i < 10000; i++)
{
var sitecoreItem = _db.GetItem(new ID(_id), Language.Parse("de-DE"));
result2 = cachedVersionHandler.VersionCountEnabledAndHasVersions(sitecoreItem);
}
_glassWatch.Stop();
Console.WriteLine(_glassWatch.ElapsedMilliseconds);
//Assert
Assert.IsFalse(result1);
Assert.IsFalse(result2);
}
[Test]
[Timeout(120000)]
public void GetItems_InheritanceTest(
[Values(100, 200, 300)] int count
)
{
string path = "/sitecore/content/Tests/PerformanceTests/InheritanceTest";
for (int i = 0; i < count; i++)
{
_glassWatch.Reset();
_rawWatch.Reset();
_rawWatch.Start();
var glassItem1 = _service.GetItem<StubClassLevel5>(path);
var value1 = glassItem1.Field;
_rawWatch.Stop();
_rawTotal = _rawWatch.ElapsedTicks;
_glassWatch.Start();
var glassItem2 = _service.GetItem<StubClassLevel1>(path);
var value2 = glassItem2.Field;
_glassWatch.Stop();
_glassTotal = _glassWatch.ElapsedTicks;
}
double total = _glassTotal / _rawTotal;
Console.WriteLine("Performance inheritance Test Count: {0}, Single: {1}, 5 Levels: {2}, Ratio: {3}".Formatted(count, _rawTotal, _glassTotal, total));
}
[Test]
[Timeout(120000)]
[Repeat(10000)]
public void CastItems_LotsOfProperties(
[Values(1000, 10000, 50000)] int count
)
{
_glassWatch.Reset();
var sitecoreItem = _db.GetItem(new ID(_id));
var warmup = _service.Cast<StubClassWithLotsOfProperties>(sitecoreItem);
for (int i = 0; i < count; i++)
{
_glassWatch.Start();
var glassItem = _service.Cast<StubClassWithLotsOfProperties>(sitecoreItem);
var value2 = glassItem.Field1;
_glassWatch.Stop();
}
_glassTotal = _glassWatch.ElapsedTicks;
Console.WriteLine("Performance Test Count: {0}".Formatted(_glassTotal));
}
[Test]
[Timeout(120000)]
[Repeat(10000)]
public void CastItems_LotsOfProperties_ServiceEveryTime(
[Values(1000, 10000, 50000)] int count)
{
_glassWatch.Reset();
var sitecoreItem = _db.GetItem(new ID(_id));
var warmup = _service.Cast<StubClassWithLotsOfProperties>(sitecoreItem);
for (int i = 0; i < count; i++)
{
_glassWatch.Start();
var service = new SitecoreService(_db);
var glassItem = service.Cast<StubClassWithLotsOfProperties>(sitecoreItem);
var value2 = glassItem.Field1;
_glassWatch.Stop();
}
_glassTotal = _glassWatch.ElapsedTicks;
Console.WriteLine("Performance Test Count: {0}".Formatted(_glassTotal));
}
[Test]
public void CreateService_Lots(
[Values(1000, 10000, 50000)] int count)
{
_glassWatch.Reset();
for (int i = 0; i < count; i++)
{
_glassWatch.Start();
var service = new SitecoreService(_db);
_glassWatch.Stop();
}
_glassTotal = _glassWatch.ElapsedTicks;
Console.WriteLine("Performance Test Count: {0}".Formatted(_glassTotal));
}
#region Stubs
[SitecoreType]
public class StubClassWithLotsOfProperties
{
[SitecoreField("Field",Setting = SitecoreFieldSettings.RichTextRaw)]
public virtual string Field1 { get; set; }
[SitecoreField("Field", Setting = SitecoreFieldSettings.RichTextRaw)]
public virtual string Field2 { get; set; }
[SitecoreField("Field", Setting = SitecoreFieldSettings.RichTextRaw)]
public virtual string Field3 { get; set; }
[SitecoreField("Field", Setting = SitecoreFieldSettings.RichTextRaw)]
public virtual string Field4 { get; set; }
[SitecoreField("Field", Setting = SitecoreFieldSettings.RichTextRaw)]
public virtual string Field5 { get; set; }
[SitecoreField("Field", Setting = SitecoreFieldSettings.RichTextRaw)]
public virtual string Field6 { get; set; }
[SitecoreField("Field", Setting = SitecoreFieldSettings.RichTextRaw)]
public virtual string Field7 { get; set; }
[SitecoreField("Field", Setting = SitecoreFieldSettings.RichTextRaw)]
public virtual string Field8 { get; set; }
[SitecoreField("Field", Setting = SitecoreFieldSettings.RichTextRaw)]
public virtual string Field9 { get; set; }
[SitecoreField("Field", Setting = SitecoreFieldSettings.RichTextRaw)]
public virtual string Field10 { get; set; }
[SitecoreField("Field", Setting = SitecoreFieldSettings.RichTextRaw)]
public virtual string Field11 { get; set; }
[SitecoreField("Field", Setting = SitecoreFieldSettings.RichTextRaw)]
public virtual string Field12 { get; set; }
[SitecoreField("Field", Setting = SitecoreFieldSettings.RichTextRaw)]
public virtual string Field13 { get; set; }
[SitecoreField("Field", Setting = SitecoreFieldSettings.RichTextRaw)]
public virtual string Field14 { get; set; }
[SitecoreField("Field", Setting = SitecoreFieldSettings.RichTextRaw)]
public virtual string Field15 { get; set; }
[SitecoreField("Field", Setting = SitecoreFieldSettings.RichTextRaw)]
public virtual string Field16 { get; set; }
[SitecoreField("Field", Setting = SitecoreFieldSettings.RichTextRaw)]
public virtual string Field17 { get; set; }
[SitecoreField("Field", Setting = SitecoreFieldSettings.RichTextRaw)]
public virtual string Field18 { get; set; }
[SitecoreField("Field", Setting = SitecoreFieldSettings.RichTextRaw)]
public virtual string Field19 { get; set; }
[SitecoreField("Field", Setting = SitecoreFieldSettings.RichTextRaw)]
public virtual string Field20 { get; set; }
[SitecoreId]
public virtual Guid Id { get; set; }
}
[SitecoreType]
public class StubForWholeDb
{
[SitecoreField("__Display Name")]
public virtual string Field { get; set; }
}
[SitecoreType]
public class StubClass
{
[SitecoreField(Setting = SitecoreFieldSettings.RichTextRaw)]
public virtual string Field { get; set; }
}
[SitecoreType]
public class StubClassLevel1 : StubClassLevel2
{
}
[SitecoreType]
public class StubClassLevel2 : StubClassLevel3
{
}
[SitecoreType]
public class StubClassLevel3 : StubClassLevel4
{
}
[SitecoreType]
public class StubClassLevel4 : StubClassLevel5
{
}
[SitecoreType]
public class StubClassLevel5
{
[SitecoreField(Setting = SitecoreFieldSettings.RichTextRaw)]
public virtual string Field { get; set; }
[SitecoreId]
public virtual Guid Id { get; set; }
}
#endregion
// [Test]
// [Timeout(120000)]
// public void GetItems()
// {
// //Assign
// int[] counts = new int[] {1, 100, 1000, 10000, 50000, 100000, 150000,200000};
// foreach (var count in counts)
// {
// GetItemsTest(count);
// }
// }
// private void GetItemsTest(int count){
// var expected = "hello world";
// var id = new Guid("{59784F74-F830-4BCD-B1F0-1A08616EF726}");
// var context = Context.Create(new SitecoreConfig());
// context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration"));
// var db = Sitecore.Configuration.Factory.GetDatabase("master");
// var service = new SitecoreService(db);
//// service.Profiler = new SimpleProfiler();
// var item = db.GetItem(new ID(id));
// using (new ItemEditing(item, true))
// {
// item["Field"] = expected;
// }
// //Act
// //get Sitecore raw
// var rawTotal = (long)0;
// var watch1 = new Stopwatch();
// for (int i = 0; i < count; i++)
// {
// watch1.Start();
// var rawItem = db.GetItem(new ID(id));
// var value = rawItem["Field"];
// watch1.Stop();
// Assert.AreEqual(expected, value);
// rawTotal += watch1.ElapsedTicks;
// }
// long rawAverage = rawTotal / count;
// //Console.WriteLine("Performance Test - 1000 - Raw - {0}", rawAverage);
// // Console.WriteLine("Raw ElapsedTicks to sec: {0}", rawAverage / (double)Stopwatch.Frequency);
// var glassTotal = (long)0;
// var watch2 = new Stopwatch();
// for (int i = 0; i < count; i++)
// {
// watch2.Start();
// var glassItem = service.GetItem<StubClass>(id);
// var value = glassItem.Field;
// watch2.Stop();
// Assert.AreEqual(expected, value);
// glassTotal += watch2.ElapsedTicks;
// }
// long glassAverage = glassTotal / count;
// // Console.WriteLine("Performance Test - 1000 - Glass - {0}", glassAverage);
// //Console.WriteLine("Glass ElapsedTicks to sec: {0}", glassAverage / (double)Stopwatch.Frequency);
// Console.WriteLine("{1}: Raw/Glass {0}", (double) glassAverage/(double)rawAverage, count);
// //Assert
// //ME - at the moment I am allowing glass to take twice the time. I would hope to reduce this
// //Assert.LessOrEqual(glassAverage, rawAverage*2);
// }
public class TestCachedItemVersionHandler : CachedItemVersionHandler
{
public TestCachedItemVersionHandler(ICacheManager cacheManager, Config config) : base(cacheManager, config)
{
}
protected override bool CanCache()
{
return true;
}
}
}
}
| |
using Shouldly;
using Veggerby.Algorithm.Calculus;
using Veggerby.Algorithm.Calculus.Visitors;
using Xunit;
namespace Veggerby.Algorithm.Tests.Calculus.Visitors
{
public class ComplexityOperandVisitorTests
{
[Fact]
public void Should_return_constant()
{
// arrange
var operand = ValueConstant.One;
var visitor = new ComplexityOperandVisitor();
// act
var actual = operand.Accept(visitor);
// assert
actual.ShouldBe(1);
}
[Fact]
public void Should_return_named_constant()
{
// arrange
var operand = ValueConstant.Pi;
var visitor = new ComplexityOperandVisitor();
// act
var actual = operand.Accept(visitor);
// assert
actual.ShouldBe(1);
}
[Fact]
public void Should_return_variable()
{
// arrange
var operand = Variable.x;
var visitor = new ComplexityOperandVisitor();
// act
var actual = operand.Accept(visitor);
// assert
actual.ShouldBe(2);
}
[Fact]
public void Should_return_fraction()
{
// arrange
var operand = Fraction.Create(1, 2);
var visitor = new ComplexityOperandVisitor();
// act
var actual = operand.Accept(visitor);
// assert
actual.ShouldBe(2);
}
[Fact]
public void Should_return_addition()
{
// arrange
var operand = Addition.Create(ValueConstant.One, Variable.x);
var visitor = new ComplexityOperandVisitor();
// act
var actual = operand.Accept(visitor);
// assert
actual.ShouldBe(4); // 1 + 2 + 1
}
[Fact]
public void Should_return_multiplication()
{
// arrange
var operand = Multiplication.Create(ValueConstant.Create(2), Variable.x);
var visitor = new ComplexityOperandVisitor();
// act
var actual = operand.Accept(visitor);
// assert
actual.ShouldBe(4); // 1 + 2 + 1
}
[Fact]
public void Should_return_subtraction()
{
// arrange
var operand = Subtraction.Create(ValueConstant.Create(2), Variable.x);
var visitor = new ComplexityOperandVisitor();
// act
var actual = operand.Accept(visitor);
// assert
actual.ShouldBe(5); // 1 + 2 + 2
}
[Fact]
public void Should_return_negative()
{
// arrange
var operand = Negative.Create(Variable.x);
var visitor = new ComplexityOperandVisitor();
// act
var actual = operand.Accept(visitor);
// assert
actual.ShouldBe(4); // 2 + 2
}
[Fact]
public void Should_return_division()
{
// arrange
var operand = Division.Create(ValueConstant.Create(2), Variable.x);
var visitor = new ComplexityOperandVisitor();
// act
var actual = operand.Accept(visitor);
// assert
actual.ShouldBe(6); // 1 + 2 + 3
}
[Fact]
public void Should_return_power()
{
// arrange
var operand = Power.Create(ValueConstant.Create(2), Variable.x);
var visitor = new ComplexityOperandVisitor();
// act
var actual = operand.Accept(visitor);
// assert
actual.ShouldBe(6); // 1 + 2 + 3
}
[Fact]
public void Should_return_sine()
{
// arrange
var operand = Sine.Create(ValueConstant.One);
var visitor = new ComplexityOperandVisitor();
// act
var actual = operand.Accept(visitor);
// assert
actual.ShouldBe(3); // 1 + 2
}
[Fact]
public void Should_return_cosine()
{
// arrange
var operand = Cosine.Create(ValueConstant.One);
var visitor = new ComplexityOperandVisitor();
// act
var actual = operand.Accept(visitor);
// assert
actual.ShouldBe(3); // 1 + 2
}
[Fact]
public void Should_return_exponential()
{
// arrange
var operand = Exponential.Create(ValueConstant.One);
var visitor = new ComplexityOperandVisitor();
// act
var actual = operand.Accept(visitor);
// assert
actual.ShouldBe(3); // 1 + 2
}
[Fact]
public void Should_return_logarithm()
{
// arrange
var operand = Logarithm.Create(ValueConstant.One);
var visitor = new ComplexityOperandVisitor();
// act
var actual = operand.Accept(visitor);
// assert
actual.ShouldBe(3); // 1 + 2
}
[Fact]
public void Should_return_logarithm_base()
{
// arrange
var operand = LogarithmBase.Create(10, ValueConstant.One);
var visitor = new ComplexityOperandVisitor();
// act
var actual = operand.Accept(visitor);
// assert
actual.ShouldBe(4); // 1 + 3
}
[Fact]
public void Should_return_tangent()
{
// arrange
var operand = Tangent.Create(ValueConstant.One);
var visitor = new ComplexityOperandVisitor();
// act
var actual = operand.Accept(visitor);
// assert
actual.ShouldBe(4); // 1 + 3
}
[Fact]
public void Should_return_root()
{
// arrange
var operand = Root.Create(3, ValueConstant.Create(2));
var visitor = new ComplexityOperandVisitor();
// act
var actual = operand.Accept(visitor);
// assert
actual.ShouldBe(4); // 1 + 3
}
[Fact]
public void Should_return_factorial()
{
// arrange
var operand = Factorial.Create(ValueConstant.Create(2));
var visitor = new ComplexityOperandVisitor();
// act
var actual = operand.Accept(visitor);
// assert
actual.ShouldBe(5); // 1 + 4
}
[Fact]
public void Should_return_minimum()
{
// arrange
var operand = Minimum.Create(Variable.x, ValueConstant.Create(2));
var visitor = new ComplexityOperandVisitor();
// act
var actual = operand.Accept(visitor);
// assert
actual.ShouldBe(7); // 1 + 2 + 4
}
[Fact]
public void Should_return_maximum()
{
// arrange
var operand = Maximum.Create(Variable.x, ValueConstant.Create(2));
var visitor = new ComplexityOperandVisitor();
// act
var actual = operand.Accept(visitor);
// assert
actual.ShouldBe(7); // 1 + 2 + 4
}
[Fact]
public void Should_return_function()
{
// arrange
var operand = Function.Create("f", ValueConstant.Create(2));
var visitor = new ComplexityOperandVisitor();
// act
var actual = operand.Accept(visitor);
// assert
actual.ShouldBe(3); // 1 + 2
}
[Fact]
public void Should_return_function_reference()
{
// arrange
var operand = FunctionReference.Create("f", ValueConstant.Create(2));
var visitor = new ComplexityOperandVisitor();
// act
var actual = operand.Accept(visitor);
// assert
actual.ShouldBe(3); // 1 + 2
}
[Fact]
public void Should_return_simple_function()
{
// arrange
var operand = Division.Create(
Addition.Create(new [] {
Variable.x, // 2
Sine.Create(Multiplication.Create(ValueConstant.Create(2), Variable.x)), // 2 + (1 + 2 + 1) = 6
Power.Create(ValueConstant.Pi, 2) // 1 + 1 + 3 = 5
}), // 2 + 6 + 5 + 2 = 16
Cosine.Create(Variable.x) // 2 + 2 = 4
); // 15 + 4 + 3 = 22
var visitor = new ComplexityOperandVisitor();
// act
var actual = operand.Accept(visitor);
// assert
actual.ShouldBe(22);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using JetBrains.Application.changes;
using JetBrains.Application.FileSystemTracker;
using JetBrains.Collections;
using JetBrains.Collections.Viewable;
using JetBrains.DataFlow;
using JetBrains.Diagnostics;
using JetBrains.Extension;
using JetBrains.Lifetimes;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Plugins.Unity.Core.ProjectModel;
using JetBrains.Threading;
using JetBrains.Util;
using JetBrains.Util.Logging;
#nullable enable
namespace JetBrains.ReSharper.Plugins.Unity.UnityEditorIntegration.Packages
{
#region Notes
// Empirically, this appears to be the process that Unity goes through when adding a new package:
// 1. Download package
// 2. Extract to tmp folder in global cache dir, e.g. ~/Library/Unity/cache/packages/packages.unity.com
// 3. Rename tmp folder to id@version
// 4. Copy extracted package to tmp folder in project's Library/PackageCache
// 5. Rename tmp folder to id@version
// 6. Modify manifest.json (save to copy and replace)
// 7. Modify packages-lock.json (save to copy and replace) (twice, oddly)
// 8. Refresh assets database/recompile
//
// And when removing:
// 1. Modify manifest.json (save to copy and replace)
// 2. Modify packages-lock.json (save to copy and replace) (twice, oddly)
// 3. Rename Library/PackageCache/id@version to tmp name
// 4. Delete the tmp folder
// 5. Refresh assets database/recompile
//
// Updating:
// 1. Download package
// 2. Extract to tmp folder in global cache dir, e.g. ~/Library/Unity/cache/packages/packages.unity.com
// 3. Rename tmp folder to id@version
// 4. Copy extracted package to tmp folder in project's Library/PackageCache
// 5. Rename tmp folder to id@version
// 6. Modify manifest.json (save to copy and replace)
// 7. Modify packages-lock.json (save to copy and replace) (twice, oddly)
// 8. Rename Library/PackageCache/id@version to tmp name
// 9. Delete the tmp folder
// 10. Refresh assets database/recompile
#endregion
[SolutionComponent]
public class PackageManager
{
private const string DefaultRegistryUrl = "https://packages.unity.com";
private readonly Lifetime myLifetime;
private readonly ISolution mySolution;
private readonly ILogger myLogger;
private readonly UnityVersion myUnityVersion;
private readonly IFileSystemTracker myFileSystemTracker;
private readonly GroupingEvent myDoRefreshGroupingEvent, myWaitForPackagesLockJsonGroupingEvent;
private readonly DictionaryEvents<string, PackageData> myPackagesById;
private readonly Dictionary<string, LifetimeDefinition> myPackageLifetimes;
private readonly VirtualFileSystemPath myPackagesFolder;
private readonly VirtualFileSystemPath myPackagesLockPath;
private readonly VirtualFileSystemPath myManifestPath;
private readonly VirtualFileSystemPath myLocalPackageCacheFolder;
private VirtualFileSystemPath? myLastReadGlobalManifestPath;
private EditorManifestJson? myGlobalManifest;
public PackageManager(Lifetime lifetime, ISolution solution, ILogger logger,
UnitySolutionTracker unitySolutionTracker,
UnityVersion unityVersion,
IFileSystemTracker fileSystemTracker)
{
myLifetime = lifetime;
mySolution = solution;
myLogger = logger;
myUnityVersion = unityVersion;
myFileSystemTracker = fileSystemTracker;
// Refresh the packages in the guarded context, safe from reentrancy
myDoRefreshGroupingEvent = solution.Locks.GroupingEvents.CreateEvent(lifetime, "Unity::PackageManager",
TimeSpan.FromMilliseconds(500), Rgc.Guarded, DoRefresh);
myWaitForPackagesLockJsonGroupingEvent = solution.Locks.GroupingEvents.CreateEvent(lifetime,
"Unity::PackageManager::WaitForPackagesLockJson", TimeSpan.FromMilliseconds(2000), Rgc.Guarded,
DoRefresh);
myPackagesById = new DictionaryEvents<string, PackageData>(lifetime, "Unity::PackageManager");
myPackageLifetimes = new Dictionary<string, LifetimeDefinition>();
myPackagesFolder = mySolution.SolutionDirectory.Combine("Packages");
myPackagesLockPath = myPackagesFolder.Combine("packages-lock.json");
myManifestPath = myPackagesFolder.Combine("manifest.json");
myLocalPackageCacheFolder = mySolution.SolutionDirectory.Combine("Library/PackageCache");
Updating = new Property<bool?>(lifetime, "PackageManger::Update");
// use IsUnityProjectFolder, otherwise frontend would not have packages information, when folder is opened
// and incorrect notification text might be displayed
unitySolutionTracker.IsUnityProjectFolder.AdviseUntil(lifetime, value =>
{
if (!value) return false;
ScheduleRefresh();
// Track changes to the Packages folder, non-recursively. This will handle manifest.json,
// packages-lock.json and any folders that are added/deleted/renamed
fileSystemTracker.AdviseDirectoryChanges(lifetime, myPackagesFolder, false, OnPackagesFolderUpdate);
// We're all set up, terminate the advise
return true;
});
}
public Property<bool?> Updating { get; }
public ViewableProperty<bool> IsInitialUpdateFinished { get; } = new(false);
// DictionaryEvents uses locks internally, so this is thread safe. It gets updated from the guarded reentrancy
// context, so all callbacks also happen within the guarded reentrancy context
public IReadonlyCollectionEvents<KeyValuePair<string, PackageData>> Packages => myPackagesById;
public PackageData? GetPackageById(string id) =>
myPackagesById.TryGetValue(id, out var packageData) ? packageData : null;
public PackageData? GetOwningPackage(VirtualFileSystemPath path)
{
foreach (var packageData in myPackagesById.Values)
{
if (packageData.PackageFolder != null && packageData.PackageFolder.IsPrefixOf(path))
return packageData;
}
return null;
}
public void RefreshPackages() => ScheduleRefresh();
private void ScheduleRefresh()
{
myLogger.Trace("Scheduling package refresh");
myDoRefreshGroupingEvent.FireIncoming();
}
private void OnPackagesFolderUpdate(FileSystemChangeDelta change)
{
var manifestChange = change.FindChangeDelta(myManifestPath) != null;
var lockChange = change.FindChangeDelta(myPackagesLockPath) != null;
if (manifestChange && !lockChange)
{
// We prefer to use packages-lock.json, as it's more accurate than manifest.json. So if the manifest is
// changed without also changing the lock file, fire the delayed refresh event, to give Unity a chance
// to resolve the change changed packages and update the lock file.
// If we get a subsequent notification for the lock file, we'll cancel the delayed refresh and fire the
// normal refresh, and use the more accurate lock file to populate our packages list.
// If we don't get a notification (perhaps Unity isn't running, or the user hasn't yet switched back to
// Unity) the delayed refresh will still update, using the less accurate method based on manifest.json
if (myPackagesLockPath.ExistsFile && myManifestPath.ExistsFile &&
myManifestPath.FileModificationTimeUtc > myPackagesLockPath.FileModificationTimeUtc)
{
myLogger.Trace("manifest.json modified and is newer than packages-lock.json. Scheduling delayed refresh");
myWaitForPackagesLockJsonGroupingEvent.FireIncoming();
}
else
{
myLogger.Trace("manifest.json modified. No need to wait for packages-lock.json. Scheduling normal refresh");
myDoRefreshGroupingEvent.FireIncoming();
}
}
else if (lockChange)
{
myLogger.Trace("packages-lock.json modified. Cancelling delayed refresh. Scheduling normal refresh");
myWaitForPackagesLockJsonGroupingEvent.CancelIncoming();
myDoRefreshGroupingEvent.FireIncoming();
}
else
{
myLogger.Trace("Other file modification in Packages folder. Scheduling normal refresh");
myDoRefreshGroupingEvent.FireIncoming();
}
}
[Guard(Rgc.Guarded)]
private void DoRefresh()
{
myLogger.Trace("DoRefresh");
// We only get null if something has gone wrong, such as invalid or missing files (already logged). If we
// read the files successfully, we'd at least have an empty list. If something is wrong, don't wipe out the
// current list of packages. It's better to show outdated information than nothing at all
var newPackages = GetPackages();
if (newPackages != null)
myLogger.DoActivity("UpdatePackages", null, () => UpdatePackages(newPackages));
}
private void UpdatePackages(IReadOnlyCollection<PackageData> newPackages)
{
if (newPackages.Count == 0)
return;
Updating.Value = true;
try
{
var existingPackages = myPackagesById.Keys.ToJetHashSet();
foreach (var packageData in newPackages)
{
// If the package.json file has been updated, remove the entry and add the new one. This should
// capture all changes to data + metadata. We don't care too much about duplicates, as this is
// invalid JSON and Unity complains. Last write wins, but at least we won't crash
if (myPackagesById.TryGetValue(packageData.Id, out var existingPackageData)
&& existingPackageData.PackageJsonTimestamp != packageData.PackageJsonTimestamp)
{
RemovePackage(packageData.Id);
}
if (!myPackagesById.ContainsKey(packageData.Id))
{
var lifetimeDefinition = myLifetime.CreateNested();
myPackagesById.Add(lifetimeDefinition.Lifetime, packageData.Id, packageData);
// Note that myPackagesLifetimes is only accessed inside this method, so is thread safe
myPackageLifetimes.Add(lifetimeDefinition.Lifetime, packageData.Id, lifetimeDefinition);
// Refresh if any editable package.json is modified, so we pick up changes to e.g. dependencies,
// display name, etc. We don't care if BuiltIn or Registry packages are modified because they're
// not user editable
if (packageData.Source == PackageSource.Local && packageData.PackageFolder != null)
{
myFileSystemTracker.AdviseFileChanges(lifetimeDefinition.Lifetime,
packageData.PackageFolder.Combine("package.json"),
_ => ScheduleRefresh());
}
}
existingPackages.Remove(packageData.Id);
}
// Remove any left overs
foreach (var id in existingPackages)
RemovePackage(id);
}
finally
{
Updating.Value = false;
IsInitialUpdateFinished.Value = true;
}
}
private void RemovePackage(string packageId)
{
if (myPackageLifetimes.TryGetValue(packageId, out var lifetimeDefinition))
lifetimeDefinition.Terminate();
}
private List<PackageData>? GetPackages()
{
return LogEx.WhenVerbose(myLogger).DoCalculation("GetPackages", null,
() => GetPackagesFromPackagesLockJson() ?? GetPackagesFromManifestJson(),
p => p != null ? $"{p.Count} packages" : "Null list of packages. Something went wrong");
}
// Introduced officially in 2019.4, but available behind a switch in manifest.json in 2019.3
// https://forum.unity.com/threads/add-an-option-to-auto-update-packages.730628/#post-4931882
private List<PackageData>? GetPackagesFromPackagesLockJson()
{
if (!myPackagesLockPath.ExistsFile)
{
myLogger.Verbose("packages-lock.json does not exist");
return null;
}
if (myManifestPath.ExistsFile &&
myManifestPath.FileModificationTimeUtc > myPackagesLockPath.FileModificationTimeUtc)
{
myLogger.Info("packages-lock.json is out of date. Skipping");
return null;
}
myLogger.Verbose("Getting packages from packages-lock.json");
var appPath = myUnityVersion.GetActualAppPathForSolution();
var builtInPackagesFolder = UnityInstallationFinder.GetBuiltInPackagesFolder(appPath);
return myLogger.CatchSilent(() =>
{
var packagesLockJson = PackagesLockJson.FromJson(myPackagesLockPath.ReadAllText2().Text);
var packages = new List<PackageData>();
foreach (var (id, details) in packagesLockJson.Dependencies)
packages.Add(GetPackageData(id, details, builtInPackagesFolder));
return packages;
});
}
private List<PackageData>? GetPackagesFromManifestJson()
{
if (!myManifestPath.ExistsFile)
{
// This is not really expected, unless we're on an older Unity that doesn't support package manager
myLogger.Info("manifest.json does not exist");
return null;
}
myLogger.Verbose("Getting packages from manifest.json");
try
{
var projectManifest = ManifestJson.FromJson(myManifestPath.ReadAllText2().Text);
// Now we've deserialised manifest.json, log why we skipped packages-lock.json
LogWhySkippedPackagesLock(projectManifest);
var appPath = myUnityVersion.GetActualAppPathForSolution();
var builtInPackagesFolder = UnityInstallationFinder.GetBuiltInPackagesFolder(appPath);
// Read the editor's default manifest, which gives us the minimum versions for various packages
var globalManifestPath = UnityInstallationFinder.GetPackageManagerDefaultManifest(appPath);
if (globalManifestPath.ExistsFile && myLastReadGlobalManifestPath != globalManifestPath)
{
myLastReadGlobalManifestPath = globalManifestPath;
myGlobalManifest = SafelyReadGlobalManifestFile(globalManifestPath);
}
// TODO: Support registry scopes
// Not massively important. We need the registry for a pre-2018.3 cache folder, which I think predates
// scopes. Post 2018.3, we should get the package from the project local cache
var registry = projectManifest.Registry ?? DefaultRegistryUrl;
var packages = new Dictionary<string, PackageData>();
foreach (var (id, version) in projectManifest.Dependencies)
{
if (version.Equals("exclude", StringComparison.OrdinalIgnoreCase))
continue;
projectManifest.Lock.TryGetValue(id, out var lockDetails);
packages[id] = GetPackageData(id, version, registry, builtInPackagesFolder,
lockDetails);
}
// If a child folder of Packages has a package.json file, then it's a package
foreach (var child in myPackagesFolder.GetChildDirectories())
{
// The folder name is not reliable to act as ID, so we'll use the ID from package.json. All other
// packages get the ID from manifest.json or packages-lock.json. This is assumed to be the same as
// the ID in package.json
var packageData = GetPackageDataFromFolder(null, child, PackageSource.Embedded);
if (packageData != null)
packages[packageData.Id] = packageData;
}
// We currently have the project dependencies. These will usually be the version requested, and will
// therefore have package data, as long as that data exists in the cache. However, a transitive
// dependency might get resolved to a higher version, so the project dependency version won't be in the
// cache, and that package data will be missing.
// Let's calculate the transitive dependencies.
// This is a very naive implementation, initially based on observation. UPM will try to resolve
// dependencies based on a resolution strategy. Note that this is not a conflict resolution strategy. It
// applies to all dependencies, even if there is only usage of that package.
// The default resolution strategy is "lowest". For a single package, this means get that version. For
// multiple packages it means get the lowest version that meets all version requirements, which
// translates to the highest common version.
// With one of the "highest*" resolution strategies, UPM will choose the highest patch, minor or major
// version that's available on the server. E.g. if two packages require dependency A@1.0.0 and A@1.0.5,
// then UPM can resolve this to A@1.0.7 or A@1.1.0 or A@20.0.0. This causes us problems because we don't
// have that information (although it is cached elsewhere on disk). If this dependency is used as a
// project dependency, then it also updates the project dependency.
// We fake "highest*" resolution by getting whatever version is available in Library/PackagesCache.
var packagesToProcess = new List<PackageData>(packages.Values);
while (packagesToProcess.Count > 0)
{
var foundDependencies = GetPackagesFromDependencies(registry, packages, packagesToProcess);
foreach (var package in foundDependencies)
packages[package.Id] = package;
packagesToProcess = foundDependencies;
}
// TODO: Strip unused packages
// There is a chance we have introduced an extra package via a dependency that is subsequently updated.
// E.g. a dependency introduces A@1.0.0 which introduces B@1.0.0. If we have another package that
// depends on A@2.0.0 which no longer uses B, then we have an orphaned package
// This is an unlikely edge case, as it means we'd have to resolve the old version correctly as well as
// the new one. And the worst that can happen is we show an extra package in the UI
return new List<PackageData>(packages.Values);
}
catch (Exception e)
{
myLogger.LogExceptionSilently(e);
return null;
}
}
private void LogWhySkippedPackagesLock(ManifestJson projectManifest)
{
// We know myManifestPath exists
if (myPackagesLockPath.ExistsFile &&
myManifestPath.FileModificationTimeUtc > myPackagesLockPath.FileModificationTimeUtc)
{
if (projectManifest.EnableLockFile.HasValue && !projectManifest.EnableLockFile.Value)
{
myLogger.Info("packages-lock.json is out of date. Lock file is disabled in manifest.json. Old file needs deleting");
}
else if (myUnityVersion.ActualVersionForSolution.Value < new Version(2019, 3))
{
myLogger.Info(
"packages-lock.json is not supported by this version of Unity. Perhaps the file is from a newer version?");
}
myLogger.Info("packages-lock.json out of date. Most likely reason: Unity not running");
}
}
private EditorManifestJson SafelyReadGlobalManifestFile(VirtualFileSystemPath globalManifestPath)
{
try
{
return EditorManifestJson.FromJson(globalManifestPath.ReadAllText2().Text);
}
catch (Exception e)
{
// Even if there's an error, cache an empty file, so we don't continually try to read a broken file
myLogger.LogExceptionSilently(e);
return EditorManifestJson.CreateEmpty();
}
}
private PackageData GetPackageData(string id, PackagesLockDependency details,
VirtualFileSystemPath builtInPackagesFolder)
{
try
{
PackageData? packageData = null;
switch (details.Source)
{
case "embedded":
packageData = GetEmbeddedPackage(id, details.Version);
break;
case "registry":
packageData = GetRegistryPackage(id, details.Version, details.Url ?? DefaultRegistryUrl);
break;
case "builtin":
packageData = GetBuiltInPackage(id, details.Version, builtInPackagesFolder);
break;
case "git":
packageData = GetGitPackage(id, details.Version, details.Hash);
break;
case "local":
packageData = GetLocalPackage(id, details.Version);
break;
case "local-tarball":
packageData = GetLocalTarballPackage(id, details.Version);
break;
}
return packageData ?? PackageData.CreateUnknown(id, details.Version);
}
catch (Exception e)
{
myLogger.Error(e, $"Error resolving package {id}");
return PackageData.CreateUnknown(id, details.Version);
}
}
private PackageData GetPackageData(string id, string version, string registry,
VirtualFileSystemPath builtInPackagesFolder,
ManifestLockDetails? lockDetails)
{
// Order is important here. A package can be listed in manifest.json, but if it also exists in Packages,
// that embedded copy takes precedence. We look for an embedded folder with the same name, but it can be
// under any name - we'll find it again and override it when we look at the other embedded packages.
// Registry packages are the most likely to match, and can't clash with other packages, so check them early.
// The file: protocol is used by local but it can also be a protocol for git, so check git before local.
try
{
return GetEmbeddedPackage(id, id)
?? GetRegistryPackage(id, version, registry)
?? GetGitPackage(id, version, lockDetails?.Hash, lockDetails?.Revision)
?? GetLocalPackage(id, version)
?? GetLocalTarballPackage(id, version)
?? GetBuiltInPackage(id, version, builtInPackagesFolder)
?? PackageData.CreateUnknown(id, version);
}
catch (Exception e)
{
myLogger.Error(e, $"Error resolving package {id}");
return PackageData.CreateUnknown(id, version);
}
}
private PackageData? GetEmbeddedPackage(string id, string filePath)
{
// Embedded packages live in the Packages folder. When reading from manifest.json, filePath is the same as
// ID. When reading from packages-lock.json, we already know it's an embedded folder, and use the version,
// which has a 'file:' prefix
var packageFolder = myPackagesFolder.Combine(filePath.TrimFromStart("file:"));
return GetPackageDataFromFolder(id, packageFolder, PackageSource.Embedded);
}
private PackageData? GetRegistryPackage(string id, string version, string registryUrl)
{
// When parsing manifest.json, version might be a version, or it might even be a URL for a git package
var cacheFolder = RelativePath.TryParse($"{id}@{version}");
if (cacheFolder.IsEmpty)
return null;
// Unity 2018.3 introduced an additional layer of caching for registry based packages, local to the
// project, so that any edits to the files in the package only affect this project. This is primarily
// for the API updater, which would otherwise modify files in the product wide cache
var packageData = GetPackageDataFromFolder(id, myLocalPackageCacheFolder.Combine(cacheFolder),
PackageSource.Registry);
if (packageData != null)
return packageData;
// Fall back to the product wide cache
var packageCacheFolder = UnityCachesFinder.GetPackagesCacheFolder(registryUrl);
if (packageCacheFolder == null || !packageCacheFolder.ExistsDirectory)
return null;
var packageFolder = packageCacheFolder.Combine(cacheFolder);
return GetPackageDataFromFolder(id, packageFolder, PackageSource.Registry);
}
private PackageData? GetBuiltInPackage(string id, string version, VirtualFileSystemPath builtInPackagesFolder)
{
// Starting with Unity 2020.3, modules are copied into the local package cache, and compiled from there.
// This behaviour has been backported to 2019.4 LTS. Make sure we use the cached files, or breakpoints won't
// resolve, because we'll be showing different files to what's in the PDB.
// I don't know why the files are copied - it makes sense for registry packages to be copied so that script
// updater can run on them, or users can make (dangerously transient) changes. But built in packages are,
// well, built in, and should be up to date as far as the script updater is concerned.
var localCacheFolder = myLocalPackageCacheFolder.Combine($"{id}@{version}");
var packageData = GetPackageDataFromFolder(id, localCacheFolder, PackageSource.BuiltIn);
if (packageData == null && builtInPackagesFolder.IsNotEmpty)
packageData = GetPackageDataFromFolder(id, builtInPackagesFolder.Combine(id), PackageSource.BuiltIn);
if (packageData != null)
return packageData;
// We can't find the actual package. If we "know" it's a module/built in package, then mark it as an
// unresolved built in package, rather than just an unresolved package. The Unity Explorer can use this to
// put the unresolved package in the right place, rather than show as a top level unresolved package simply
// because we haven't found the application package cache yet.
// We can rely on an ID starting with "com.unity.modules." as this is the convention Unity uses. Since they
// control the namespace of their own registries, we can be confident that they won't publish normal
// packages with the same naming convention. We can't be sure for third part registries, but if anyone does
// that, they only have themselves to blame.
// If we don't recognise the package as a built in, let someone else handle it
return id.StartsWith("com.unity.modules.")
? PackageData.CreateUnknown(id, version, PackageSource.BuiltIn)
: null;
}
private PackageData? GetGitPackage(string id, string version, string? hash,
string? revision = null)
{
// For older Unity versions, manifest.json will have a hash for any git based package. For newer Unity
// versions, this is stored in packages-lock.json. If the lock file is disabled, then we don't get a hash
// and have to figure it out based on whatever is in Library/PackagesCache. We check the vesion as a git
// URL based on the docs: https://docs.unity3d.com/Manual/upm-git.html
if (hash == null && !IsGitUrl(version))
return null;
// This must be a git package, make sure we return something
try
{
var packageFolder = myLocalPackageCacheFolder.Combine($"{id}@{hash}");
if (!packageFolder.ExistsDirectory && hash != null)
{
var shortHash = hash.Substring(0, Math.Min(hash.Length, 10));
packageFolder = myLocalPackageCacheFolder.Combine($"{id}@{shortHash}");
}
if (!packageFolder.ExistsDirectory)
packageFolder = myLocalPackageCacheFolder.GetChildDirectories($"{id}@*").FirstOrDefault();
if (packageFolder != null && packageFolder.ExistsDirectory)
{
return GetPackageDataFromFolder(id, packageFolder, PackageSource.Git,
new GitDetails(version, hash, revision));
}
return null;
}
catch (Exception e)
{
myLogger.Error(e, "Error resolving git package");
return PackageData.CreateUnknown(id, version);
}
}
private static bool IsGitUrl(string version)
{
return Uri.TryCreate(version, UriKind.Absolute, out var url) &&
(url.Scheme.StartsWith("git+") ||
url.AbsolutePath.EndsWith(".git", StringComparison.InvariantCultureIgnoreCase));
}
private PackageData? GetLocalPackage(string id, string version)
{
// If the version doesn't start with "file:" we know it's not a local package
if (!version.StartsWith("file:"))
return null;
// This might be a local package, or it might be a local tarball. Or a git package (although we'll have
// resolved that before trying local packages), so return null if we can't resolve it
try
{
var path = version.Substring(5);
var packageFolder = myPackagesFolder.Combine(path);
return packageFolder.ExistsDirectory
? GetPackageDataFromFolder(id, packageFolder, PackageSource.Local)
: null;
}
catch (Exception e)
{
myLogger.Error(e, $"Error resolving local package {id} at {version}");
return null;
}
}
private PackageData? GetLocalTarballPackage(string id, string version)
{
if (!version.StartsWith("file:"))
return null;
// This is a package installed from a package.tgz file. The original file is referenced, but not touched.
// It is expanded into Library/PackageCache with a filename of name@{md5-of-path}-{file-modification-in-epoch-ms}
try
{
var path = version.Substring(5);
var tarballPath = myPackagesFolder.Combine(path);
if (tarballPath.ExistsFile)
{
// Note that this is inherently fragile. If the file is touched, but not imported (i.e. Unity isn't
// running), we won't be able to resolve it at all. We also don't have a watch on the file, so we
// have no way of knowing that the package has been updated or imported.
// On the plus side, I have yet to see anyone talk about tarball packages in the wild.
// Also, once it's been imported, we'll refresh and all will be good
var timestamp = (long) (tarballPath.FileModificationTimeUtc - DateTimeEx.UnixEpoch).TotalMilliseconds;
var hash = GetMd5OfString(tarballPath.FullPath).Substring(0, 12).ToLowerInvariant();
var packageFolder = myLocalPackageCacheFolder.Combine($"{id}@{hash}-{timestamp}");
var tarballLocation = tarballPath.StartsWith(mySolution.SolutionDirectory)
? tarballPath.RemovePrefix(mySolution.SolutionDirectory.Parent)
: tarballPath;
return GetPackageDataFromFolder(id, packageFolder, PackageSource.LocalTarball,
tarballLocation: tarballLocation);
}
return null;
}
catch (Exception e)
{
myLogger.Error(e, $"Error resolving local tarball package {version}");
return null;
}
}
private PackageData? GetPackageDataFromFolder(string? id,
VirtualFileSystemPath packageFolder,
PackageSource packageSource,
GitDetails? gitDetails = null,
VirtualFileSystemPath? tarballLocation = null)
{
if (packageFolder.ExistsDirectory)
{
var packageJsonFile = packageFolder.Combine("package.json");
if (packageJsonFile.ExistsFile)
{
try
{
var packageJson = PackageJson.FromJson(packageJsonFile.ReadAllText2().Text);
var packageDetails = PackageDetails.FromPackageJson(packageJson, packageFolder);
return new PackageData(id ?? packageDetails.CanonicalName, packageFolder,
packageJsonFile.FileModificationTimeUtc, packageDetails, packageSource, gitDetails,
tarballLocation);
}
catch (Exception e)
{
myLogger.LogExceptionSilently(e);
return null;
}
}
}
return null;
}
private static string GetMd5OfString(string value)
{
// Use input string to calculate MD5 hash
using var md5 = MD5.Create();
var inputBytes = Encoding.UTF8.GetBytes(value);
var hashBytes = md5.ComputeHash(inputBytes);
// Convert the byte array to hexadecimal string
var sb = new StringBuilder();
foreach (var t in hashBytes)
sb.Append(t.ToString("X2"));
return sb.ToString().PadLeft(32, '0');
}
private List<PackageData> GetPackagesFromDependencies(string registry,
Dictionary<string, PackageData> resolvedPackages,
List<PackageData> packagesToProcess)
{
var dependencies = new Dictionary<string, JetSemanticVersion>();
// Find the highest requested version of each dependency of each package being processed. Check all
// dependencies, even if we've already resolved it, in case we find a higher version
foreach (var packageData in packagesToProcess)
{
foreach (var (id, versionString) in packageData.PackageDetails.Dependencies)
{
if (DoesResolvedPackageTakePrecedence(id, resolvedPackages))
continue;
if (!JetSemanticVersion.TryParse(versionString, out var dependencyVersion))
continue;
var currentMaxVersion = GetCurrentMaxVersion(id, dependencies);
var minimumVersion = GetMinimumVersion(id);
dependencies[id] = Max(dependencyVersion, Max(currentMaxVersion, minimumVersion));
}
}
ICollection<VirtualFileSystemPath>? cachedPackages = null;
var newPackages = new List<PackageData>();
foreach (var (id, version) in dependencies)
{
if (version > GetResolvedVersion(id, resolvedPackages))
{
cachedPackages ??= myLocalPackageCacheFolder.GetChildDirectories();
// We know this is a registry package, so try to get it from the local cache. It might be missing:
// 1) the cache hasn't been built yet
// 2) the package has been resolved with one of the "highest*" strategies and a newer version has
// been downloaded from the UPM server. Check for any "id@" folders, and use that as the version.
// If it's in the local cache, it's the (last) resolved version. If Unity isn't running and the
// manifest is out of date, we can only do a best effort attempt at showing the right packages.
// We need Unity to resolve. We'll refresh once Unity has started again.
// So:
// 1) Check for the exact version in the local cache
// 2) Check for any version in the local cache
// 3) Check for the exact version in the global cache
PackageData? packageData = null;
var exact = $"{id}@{version}";
var prefix = $"{id}@";
foreach (var packageFolder in cachedPackages)
{
if (packageFolder.Name.Equals(exact, StringComparison.InvariantCultureIgnoreCase)
|| packageFolder.Name.StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase))
{
packageData = GetPackageDataFromFolder(id, packageFolder, PackageSource.Registry);
if (packageData != null)
break;
}
}
if (packageData == null)
{
var packageFolder = UnityCachesFinder.GetPackagesCacheFolder(registry)?.Combine(exact);
if (packageFolder != null)
packageData = GetPackageDataFromFolder(id, packageFolder, PackageSource.Registry);
}
if (packageData != null)
newPackages.Add(packageData);
}
}
return newPackages;
}
private static bool DoesResolvedPackageTakePrecedence(string id,
IReadOnlyDictionary<string, PackageData> resolvedPackages)
{
// Some package types take precedence over any requests for another version. Basically any package that is
// built in or pointing at actual files
return resolvedPackages.TryGetValue(id, out var packageData) &&
(packageData.Source == PackageSource.Embedded
|| packageData.Source == PackageSource.BuiltIn
|| packageData.Source == PackageSource.Git
|| packageData.Source == PackageSource.Local
|| packageData.Source == PackageSource.LocalTarball);
}
private static JetSemanticVersion GetCurrentMaxVersion(
string id, IReadOnlyDictionary<string, JetSemanticVersion> dependencies)
{
return dependencies.TryGetValue(id, out var version) ? version : JetSemanticVersion.Empty;
}
private JetSemanticVersion GetMinimumVersion(string id)
{
// Note: do not inline this into the TryGetValue call, because net5's C# compiler complains, and that's what
// we use for CI. Presumably this because it would not be initialised if myGlobalManifest is null. net6's
// compiler doesn't complain.
// error CS0165: Use of unassigned local variable 'editorPackageDetails'
EditorPackageDetails? editorPackageDetails = null;
if (myGlobalManifest?.Packages.TryGetValue(id, out editorPackageDetails) == true
&& JetSemanticVersion.TryParse(editorPackageDetails?.MinimumVersion, out var version))
{
return version;
}
return JetSemanticVersion.Empty;
}
private static JetSemanticVersion GetResolvedVersion(string id, Dictionary<string, PackageData> resolvedPackages)
{
if (resolvedPackages.TryGetValue(id, out var packageData) &&
JetSemanticVersion.TryParse(packageData.PackageDetails.Version, out var version))
{
return version;
}
return JetSemanticVersion.Empty;
}
private static JetSemanticVersion Max(JetSemanticVersion v1, JetSemanticVersion v2) => v1 > v2 ? v1 : v2;
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections;
using System.Reflection;
using log4net.Appender;
using log4net.Layout;
using log4net.Util;
using log4net.Repository;
using log4net.Repository.Hierarchy;
namespace log4net.Config
{
/// <summary>
/// Use this class to quickly configure a <see cref="Hierarchy"/>.
/// </summary>
/// <remarks>
/// <para>
/// Allows very simple programmatic configuration of log4net.
/// </para>
/// <para>
/// Only one appender can be configured using this configurator.
/// The appender is set at the root of the hierarchy and all logging
/// events will be delivered to that appender.
/// </para>
/// <para>
/// Appenders can also implement the <see cref="log4net.Core.IOptionHandler"/> interface. Therefore
/// they would require that the <see cref="M:log4net.Core.IOptionHandler.ActivateOptions()"/> method
/// be called after the appenders properties have been configured.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public sealed class BasicConfigurator
{
#region Private Static Fields
/// <summary>
/// The fully qualified type of the BasicConfigurator class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(BasicConfigurator);
#endregion Private Static Fields
#region Private Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="BasicConfigurator" /> class.
/// </summary>
/// <remarks>
/// <para>
/// Uses a private access modifier to prevent instantiation of this class.
/// </para>
/// </remarks>
private BasicConfigurator()
{
}
#endregion Private Instance Constructors
#region Public Static Methods
#if !NETSTANDARD1_3
/// <summary>
/// Initializes the log4net system with a default configuration.
/// </summary>
/// <remarks>
/// <para>
/// Initializes the log4net logging system using a <see cref="ConsoleAppender"/>
/// that will write to <c>Console.Out</c>. The log messages are
/// formatted using the <see cref="PatternLayout"/> layout object
/// with the <see cref="PatternLayout.DetailConversionPattern"/>
/// layout style.
/// </para>
/// </remarks>
static public ICollection Configure()
{
return BasicConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()));
}
/// <summary>
/// Initializes the log4net system using the specified appenders.
/// </summary>
/// <param name="appenders">The appenders to use to log all logging events.</param>
/// <remarks>
/// <para>
/// Initializes the log4net system using the specified appenders.
/// </para>
/// </remarks>
static public ICollection Configure(params IAppender[] appenders)
{
ArrayList configurationMessages = new ArrayList();
ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly());
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigure(repository, appenders);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
/// <summary>
/// Initializes the log4net system using the specified appender.
/// </summary>
/// <param name="appender">The appender to use to log all logging events.</param>
/// <remarks>
/// <para>
/// Initializes the log4net system using the specified appender.
/// </para>
/// </remarks>
static public ICollection Configure(IAppender appender)
{
return Configure(new IAppender[] { appender });
}
#endif // !NETSTANDARD1_3
/// <summary>
/// Initializes the <see cref="ILoggerRepository"/> with a default configuration.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <remarks>
/// <para>
/// Initializes the specified repository using a <see cref="ConsoleAppender"/>
/// that will write to <c>Console.Out</c>. The log messages are
/// formatted using the <see cref="PatternLayout"/> layout object
/// with the <see cref="PatternLayout.DetailConversionPattern"/>
/// layout style.
/// </para>
/// </remarks>
static public ICollection Configure(ILoggerRepository repository)
{
ArrayList configurationMessages = new ArrayList();
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
// Create the layout
PatternLayout layout = new PatternLayout();
layout.ConversionPattern = PatternLayout.DetailConversionPattern;
layout.ActivateOptions();
// Create the appender
ConsoleAppender appender = new ConsoleAppender();
appender.Layout = layout;
appender.ActivateOptions();
InternalConfigure(repository, appender);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
/// <summary>
/// Initializes the <see cref="ILoggerRepository"/> using the specified appender.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="appender">The appender to use to log all logging events.</param>
/// <remarks>
/// <para>
/// Initializes the <see cref="ILoggerRepository"/> using the specified appender.
/// </para>
/// </remarks>
static public ICollection Configure(ILoggerRepository repository, IAppender appender)
{
return Configure(repository, new IAppender[] { appender });
}
/// <summary>
/// Initializes the <see cref="ILoggerRepository"/> using the specified appenders.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="appenders">The appenders to use to log all logging events.</param>
/// <remarks>
/// <para>
/// Initializes the <see cref="ILoggerRepository"/> using the specified appender.
/// </para>
/// </remarks>
static public ICollection Configure(ILoggerRepository repository, params IAppender[] appenders)
{
ArrayList configurationMessages = new ArrayList();
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigure(repository, appenders);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
static private void InternalConfigure(ILoggerRepository repository, params IAppender[] appenders)
{
IBasicRepositoryConfigurator configurableRepository = repository as IBasicRepositoryConfigurator;
if (configurableRepository != null)
{
configurableRepository.Configure(appenders);
}
else
{
LogLog.Warn(declaringType, "BasicConfigurator: Repository [" + repository + "] does not support the BasicConfigurator");
}
}
#endregion Public Static Methods
}
}
| |
using System;
using NUnit.Framework;
using InTheHand.Net.Bluetooth;
namespace InTheHand.Net.Tests.Sdp2
{
[TestFixture]
public class HeaderByteTests
{
private void DoTest(ElementTypeDescriptor expectedEtd, SizeIndex expectedSizeIndex, byte headerByte)
{
ServiceRecordParser parser = new ServiceRecordParser();
//
// Test the (original) individual methods.
ElementTypeDescriptor resultEtd = ServiceRecordParser.GetElementTypeDescriptor(headerByte);
Assert.AreEqual(expectedEtd, resultEtd);
//
SizeIndex resultSI = ServiceRecordParser.GetSizeIndex(headerByte);
Assert.AreEqual(expectedSizeIndex, resultSI);
//
// Test the single method (which calls each of the individual methods).
ElementTypeDescriptor resultEtd2;
SizeIndex resultSI2;
ServiceRecordParser.SplitHeaderByte(headerByte, out resultEtd2, out resultSI2);
Assert.AreEqual(expectedEtd, resultEtd2);
Assert.AreEqual(expectedSizeIndex, resultSI2);
}
[Test]
public void ZeroNullSize()
{
DoTest((ElementTypeDescriptor)0, 0, 0x00);
}
[Test]
public void OneNullSize()
{
DoTest((ElementTypeDescriptor)1, 0, 0x08);
}
[Test]
public void ThreeNullSize()
{
DoTest((ElementTypeDescriptor)3, 0, 0x18);
}
[Test]
public void ThirtyOneNullSize()
{
DoTest((ElementTypeDescriptor)31, 0, 0xF8);
}
//--
[Test]
public void ZeroMidSize()
{
DoTest((ElementTypeDescriptor)0, (SizeIndex)5, 0x05);
}
[Test]
public void OneMidSize()
{
DoTest((ElementTypeDescriptor)1, (SizeIndex)5, 0x0D);
}
[Test]
public void ThreeMidSize()
{
DoTest((ElementTypeDescriptor)3, (SizeIndex)5, 0x1D);
}
[Test]
public void ThirtyOneMidSize()
{
DoTest((ElementTypeDescriptor)31, (SizeIndex)5, 0xFD);
}
//--
[Test]
public void ZeroFullSize()
{
DoTest((ElementTypeDescriptor)0, (SizeIndex)7, 0x07);
}
[Test]
public void OneFullSize()
{
DoTest((ElementTypeDescriptor)1, (SizeIndex)7, 0x0F);
}
[Test]
public void ThreeFullSize()
{
DoTest((ElementTypeDescriptor)3, (SizeIndex)7, 0x1F);
}
[Test]
public void ThirtyOneFullSize()
{
DoTest((ElementTypeDescriptor)31, (SizeIndex)7, 0xFF);
}
}//class
[TestFixture]
public class HeaderByteLengthEtcTests
{
private void DoTest(int expectedContentLength, int expectedContentOffset, byte[] headerBytes)
{
DoTest(expectedContentLength, expectedContentOffset, headerBytes, 0, headerBytes.Length);
}
private void DoTest(int expectedContentLength, int expectedContentOffset, byte[] headerBytes, int offset, int length)
{
int expectedElementLength = checked(expectedContentLength + expectedContentOffset);
ServiceRecordParser parser = new ServiceRecordParser();
Int32 contentOffset;
Int32 contentLength;
Int32 elementlength = TestableServiceRecordParser.GetElementLength(headerBytes, offset, length, out contentOffset, out contentLength);
Assert.AreEqual(expectedElementLength, elementlength);
Assert.AreEqual(expectedContentOffset, contentOffset);
Assert.AreEqual(expectedContentLength, contentLength);
}
class TestableServiceRecordParser : ServiceRecordParser
{
internal static new Int32 GetElementLength(byte[] buffer, int index, int length,
out int contentOffset, out int contentLength)
{
return ServiceRecordParser.GetElementLength(buffer, index, length,
out contentOffset, out contentLength);
}
internal static Object FakeForArgExceptionCoverage_GetElementLength(byte[] buffer, int index, int length)
{
int contentOffset, contentLength;
return ServiceRecordParser.GetElementLength(buffer, index, length,
out contentOffset, out contentLength);
}
}
//----------------------------
[Test]
public void Nil()
{
DoTest(0, 1, Data_HeaderBytes.Nil);
}
[Test]
public void NilOffsetByTwo()
{
DoTest(0, 1, Data_HeaderBytes.NilOffsetByTwo, 2, 1);
}
[Test]
[ExpectedException(typeof(System.Net.ProtocolViolationException),
ExpectedMessage = ServiceRecordParser.ErrorMsgSizeIndexNotSuitTypeD)]
public void NilBadSizeIndex()
{
DoTest(0, 1, Data_HeaderBytes.NilBadSizeIndex);
}
[Test]
public void OneByte()
{
DoTest(1, 1, Data_HeaderBytes.OneByte);
}
[Test]
public void OneByteOffsetBy9()
{
DoTest(1, 1, Data_HeaderBytes.OneByteOffsetBy9, 9, 1);
}
[Test]
public void TwoByte()
{
DoTest(2, 1, Data_HeaderBytes.TwoByte);
}
[Test]
public void TwoByteOffsetBy9()
{
DoTest(2, 1, Data_HeaderBytes.TwoByteOffsetBy9, 9, 1);
}
[Test]
public void FourByte()
{
DoTest(4, 1, Data_HeaderBytes.FourByte);
}
[Test]
public void FourByteOffset()
{
DoTest(4, 1, Data_HeaderBytes.FourByteOffsetBy9, 9, 1);
}
[Test]
public void EightByte()
{
DoTest(8, 1, Data_HeaderBytes.EightByte);
}
[Test]
public void EightByteOffset()
{
DoTest(8, 1, Data_HeaderBytes.EightByteOffsetBy9, 9, 1);
}
[Test]
public void SixteenByte()
{
DoTest(16, 1, Data_HeaderBytes.SixteenByte);
}
[Test]
public void SixteenByteOffset()
{
DoTest(16, 1, Data_HeaderBytes.SixteenByteOffsetBy9, 9, 1);
}
//-----------------
[Test]
public void OneExtraOneByte()
{
DoTest(1, 2, Data_HeaderBytes.OneExtraOneByte);
}
[Test]
public void OneExtraNineBytes()
{
DoTest(9, 2, Data_HeaderBytes.OneExtraNineBytes);
}
[Test]
public void OneExtraNineBytesOffsetBy9()
{
DoTest(9, 2, Data_HeaderBytes.OneExtraNineBytesOffsetBy9, 9, 2);
}
[Test]
public void OneExtra255Bytes()
{
DoTest(255, 2, Data_HeaderBytes.OneExtraMaxBytes);
}
[Test]
[ExpectedException(typeof(System.Net.ProtocolViolationException), ExpectedMessage = "Header truncated from index 0.")]
public void OneExtraTruncated()
{
DoTest(-1, -1, Data_HeaderBytes.OneExtraTruncated);
}
//-----------------
[Test]
public void TwoExtraOneByte()
{
DoTest(1, 3, Data_HeaderBytes.TwoExtraOneByte);
}
[Test]
public void TwoExtraNineBytes()
{
DoTest(9, 3, Data_HeaderBytes.TwoExtraNineBytes);
}
[Test]
public void TwoExtra0145Bytes()
{
DoTest(0x0145, 3, Data_HeaderBytes.TwoExtra0145Bytes);
}
[Test]
public void TwoExtra0145BytesOffsetBy9()
{
DoTest(0x0145, 3, Data_HeaderBytes.TwoExtra0145BytesOffsetBy9, 9, 3);
}
[Test]
public void TwoExtraMaxBytes()
{
DoTest(65535, 3, Data_HeaderBytes.TwoExtraMaxBytes);
}
[Test]
[ExpectedException(typeof(System.Net.ProtocolViolationException), ExpectedMessage = "Header truncated from index 0.")]
public void TwoExtraTruncatedAll()
{
DoTest(-1, -1, Data_HeaderBytes.TwoExtraTruncatedAll);
}
[Test]
[ExpectedException(typeof(System.Net.ProtocolViolationException), ExpectedMessage = "Header truncated from index 0.")]
public void TwoExtraTruncatedOne()
{
DoTest(-1, -1, Data_HeaderBytes.TwoExtraTruncatedOne);
}
//-----------------
[Test]
public void FourExtraOneByte()
{
DoTest(1, 5, Data_HeaderBytes.FourExtraOneByte);
}
[Test]
public void FourExtraNineBytes()
{
DoTest(9, 5, Data_HeaderBytes.FourExtraNineBytes);
}
[Test]
public void FourExtra01203345Bytes()
{
DoTest(0x01203345, 5, Data_HeaderBytes.FourExtra01203345Bytes);
}
[Test]
public void FourExtra01203345BytesOffsetBy9()
{
DoTest(0x01203345, 5, Data_HeaderBytes.FourExtra01203345BytesOffsetBy9, 9, 5);
}
[Test]
[ExpectedException(typeof(System.Net.ProtocolViolationException), ExpectedMessage = "No support for full sized 32bit length values (index 0).")]
public void FourExtraMaxBytes()
{
DoTest(65535, 5, Data_HeaderBytes.FourExtraMaxBytes);
}
[Test]
public void FourExtraMaxSupportedBytes()
{
Assert.AreEqual(0x7FFFFFFA, 2147483642, "Tests setup");
DoTest(2147483642, 5, Data_HeaderBytes.FourExtraMaxSupportedBytes);
}
[Test]
[ExpectedException(typeof(System.Net.ProtocolViolationException), ExpectedMessage = "Header truncated from index 0.")]
public void FourExtraTruncatedAll()
{
DoTest(-1, -1, Data_HeaderBytes.FourExtraTruncatedAll);
}
[Test]
[ExpectedException(typeof(System.Net.ProtocolViolationException), ExpectedMessage = "Header truncated from index 0.")]
public void FourExtraTruncatedOne()
{
DoTest(-1, -1, Data_HeaderBytes.FourExtraTruncatedOne);
}
[Test]
[ExpectedException(typeof(System.Net.ProtocolViolationException), ExpectedMessage = "Header truncated from index 9.")]
public void FourExtraTruncatedOneOffsetBy9()
{
DoTest(-1, -1, Data_HeaderBytes.FourExtraTruncatedOneOffsetBy9, 9, 4);
}
//---------------
[Test]
public void GetElementLengthArgExCoverage()
{
CoverArgException.CoverStreamLikeReadOrWriteMethod method =
new CoverArgException.CoverStreamLikeReadOrWriteMethod(
TestableServiceRecordParser.FakeForArgExceptionCoverage_GetElementLength);
CoverArgException.CoverStreamLikeReadOrWrite(method);
}
}//class
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace radacode.net.logger
{
public class Logger : ILogger
{
private const string _rdcNetUrl = "https://radacode.net";
//private const string _rdcNetUrl = "http://rdc.net.api.local";
private string _token;
private string _instanceId;
private string _clientId;
public Logger(string login, string password, string instanceId, string clientId)
{
try
{
_clientId = clientId;
var accessTokenAquirer = HttpPostUrlEncoded(
_rdcNetUrl + "/token",
new string[]
{
"grant_type",
"username",
"password",
"client_Id"
},
new string[]
{
"password",
login,
password,
clientId
});
var data = JObject.Parse(accessTokenAquirer.Result);
_token = (string)data.SelectToken("access_token");
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token);
var res = client.GetAsync(_rdcNetUrl + "/api/auth/check").GetAwaiter().GetResult(); ;
if(res.StatusCode != HttpStatusCode.OK)
throw new Exception("Unable to access RDC.NET with aquired token. Check call failed.");
_instanceId = instanceId;
}
catch (Exception ex)
{
throw ex;
}
}
public void Log(string message)
{
var payload = string.Empty;
payload = JsonConvert.SerializeObject(
new
{
message = message,
time = DateTime.Now,
level = 0,
token = _instanceId
});
HttpPostJson(
_rdcNetUrl + "/api/logs/add", payload,
new Dictionary<string,string> { { "Authorization", "Bearer " +_token }} );
}
public void Error(string message, string stackTrace)
{
var payload = string.Empty;
payload = JsonConvert.SerializeObject(
new
{
message = message,
time = DateTime.Now,
level = 2,
token = _instanceId,
stack = stackTrace
});
HttpPostJson(
_rdcNetUrl + "/api/logs/add", payload,
new Dictionary<string, string> { { "Authorization", "Bearer " + _token } });
}
static async Task<string> HttpPostJson(string url, string jsonPayload, Dictionary<string,string> headers)
{
HttpWebRequest req = WebRequest.Create(new Uri(url))
as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/json";
foreach (var header in headers)
{
req.Headers[header.Key] = header.Value;
}
// Encode the parameters as form data:
byte[] formData =
UTF8Encoding.UTF8.GetBytes(jsonPayload);
if (req.Headers.AllKeys.Contains("Content-Length"))
{
req.Headers[HttpRequestHeader.ContentLength] = formData.Length.ToString();
}
// Send the request:
using (Stream dataStream = await req.GetRequestStreamAsync())
{
dataStream.Write(formData, 0, formData.Length);
}
try
{
// Pick up the response:
string result = null;
using (HttpWebResponse resp = await req.GetResponseAsync()
as HttpWebResponse)
{
StreamReader reader =
new StreamReader(resp.GetResponseStream());
result = reader.ReadToEnd();
}
return result;
}
catch (Exception ex)
{
throw;
}
}
static async Task<string> HttpPostUrlEncoded(string url, string[] paramName, string[] paramVal)
{
HttpWebRequest req = WebRequest.Create(new Uri(url))
as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
StringBuilder paramz = new StringBuilder();
for (int i = 0; i < paramName.Length; i++)
{
paramz.Append(paramName[i]);
paramz.Append("=");
paramz.Append(WebUtility.UrlEncode(paramVal[i]));
if(i < (paramName.Length -1)) paramz.Append("&");
}
// Encode the parameters as form data:
byte[] formData =
UTF8Encoding.UTF8.GetBytes(paramz.ToString());
if (req.Headers.AllKeys.Contains("Content-Length"))
{
req.Headers[HttpRequestHeader.ContentLength] = formData.Length.ToString();
}
// Send the request:
using (Stream dataStream = await req.GetRequestStreamAsync())
{
dataStream.Write(formData, 0, formData.Length);
}
try
{
// Pick up the response:
string result = null;
using (HttpWebResponse resp = await req.GetResponseAsync()
as HttpWebResponse)
{
StreamReader reader =
new StreamReader(resp.GetResponseStream());
result = reader.ReadToEnd();
}
return result;
}
catch (Exception ex)
{
throw;
}
}
}
}
| |
using Bridge.Contract;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.TypeSystem;
using System.Linq;
using ICSharpCode.NRefactory.CSharp.Analysis;
namespace Bridge.Translator
{
public class Block : AbstractEmitterBlock
{
public Block(IEmitter emitter, BlockStatement blockStatement)
: base(emitter, blockStatement)
{
this.Emitter = emitter;
this.BlockStatement = blockStatement;
if (blockStatement.Parent is BlockStatement && this.Emitter.IsAsync)
{
this.Emitter.IgnoreBlock = blockStatement;
}
if (this.Emitter.IgnoreBlock == blockStatement || this.Emitter.IsAsync && this.GetAwaiters(blockStatement).Length > 0)
{
this.AsyncNoBraces = true;
}
if (this.Emitter.NoBraceBlock == blockStatement)
{
this.NoBraces = true;
}
}
public BlockStatement BlockStatement
{
get;
set;
}
protected bool AddEndBlock
{
get;
set;
}
public bool AsyncNoBraces
{
get;
set;
}
public bool NoBraces
{
get;
set;
}
public int BeginPosition
{
get;
set;
}
public int SignaturePosition
{
get;
set;
}
public bool IsYield
{
get;
set;
}
public IType ReturnType
{
get;
set;
}
private IType OldReturnType
{
get;
set;
}
public string LoopVar
{
get;
set;
}
public bool? OldReplaceJump
{
get;
set;
}
protected override void DoEmit()
{
this.EmitBlock();
}
protected virtual bool KeepLineAfterBlock(BlockStatement block)
{
var parent = block.Parent;
if (this.AsyncNoBraces || this.NoBraces)
{
return true;
}
if (parent is TryCatchStatement tcs && tcs.TryBlock.Equals(this.BlockStatement))
{
return true;
}
if (parent is CatchClause)
{
return true;
}
if (parent is AnonymousMethodExpression)
{
return true;
}
if (parent is LambdaExpression)
{
return true;
}
if (parent is MethodDeclaration)
{
return true;
}
if (parent is OperatorDeclaration)
{
return true;
}
if (parent is Accessor && (parent.Parent is PropertyDeclaration || parent.Parent is CustomEventDeclaration || parent.Parent is IndexerDeclaration))
{
return true;
}
var loop = parent as DoWhileStatement;
if (loop != null)
{
return true;
}
var ifStatement = parent as IfElseStatement;
if (ifStatement != null && ifStatement.FalseStatement != null && !ifStatement.FalseStatement.IsNull && ifStatement.FalseStatement != block)
{
return true;
}
return false;
}
public void EmitBlock()
{
this.BeginEmitBlock();
this.DoEmitBlock();
this.EndEmitBlock();
}
private bool? isMethodBlock;
public bool IsMethodBlock
{
get
{
if (!this.isMethodBlock.HasValue)
{
this.isMethodBlock = this.BlockStatement.Parent is MethodDeclaration ||
this.BlockStatement.Parent is AnonymousMethodExpression ||
this.BlockStatement.Parent is LambdaExpression ||
this.BlockStatement.Parent is ConstructorDeclaration ||
this.BlockStatement.Parent is OperatorDeclaration ||
this.BlockStatement.Parent is Accessor;
}
return this.isMethodBlock.Value;
}
}
public int OldWrapRestCounter { get; private set; }
public void DoEmitBlock()
{
if (this.BlockStatement.Parent is MethodDeclaration)
{
var methodDeclaration = (MethodDeclaration)this.BlockStatement.Parent;
if (!methodDeclaration.ReturnType.IsNull)
{
var rr = this.Emitter.Resolver.ResolveNode(methodDeclaration.ReturnType, this.Emitter);
this.ReturnType = rr.Type;
}
this.ConvertParamsToReferences(methodDeclaration.Parameters);
}
else if (this.BlockStatement.Parent is AnonymousMethodExpression)
{
var methodDeclaration = (AnonymousMethodExpression)this.BlockStatement.Parent;
var rr = this.Emitter.Resolver.ResolveNode(methodDeclaration, this.Emitter);
this.ReturnType = rr.Type;
this.ConvertParamsToReferences(methodDeclaration.Parameters);
}
else if (this.BlockStatement.Parent is LambdaExpression)
{
var methodDeclaration = (LambdaExpression)this.BlockStatement.Parent;
var rr = this.Emitter.Resolver.ResolveNode(methodDeclaration, this.Emitter);
this.ReturnType = rr.Type;
this.ConvertParamsToReferences(methodDeclaration.Parameters);
}
else if (this.BlockStatement.Parent is ConstructorDeclaration)
{
this.ConvertParamsToReferences(((ConstructorDeclaration)this.BlockStatement.Parent).Parameters);
}
else if (this.BlockStatement.Parent is OperatorDeclaration)
{
this.ConvertParamsToReferences(((OperatorDeclaration)this.BlockStatement.Parent).Parameters);
}
else if (this.BlockStatement.Parent is Accessor)
{
var role = this.BlockStatement.Parent.Role.ToString();
if (role == "Setter")
{
this.ConvertParamsToReferences(new ParameterDeclaration[] { new ParameterDeclaration { Name = "value" } });
}
else if (role == "Getter")
{
var methodDeclaration = (Accessor)this.BlockStatement.Parent;
if (!methodDeclaration.ReturnType.IsNull)
{
var rr = this.Emitter.Resolver.ResolveNode(methodDeclaration.ReturnType, this.Emitter);
this.ReturnType = rr.Type;
}
}
}
if (this.IsMethodBlock && YieldBlock.HasYield(this.BlockStatement))
{
this.IsYield = true;
}
if (this.IsMethodBlock)
{
this.OldReturnType = this.Emitter.ReturnType;
this.Emitter.ReturnType = this.ReturnType;
}
if (this.Emitter.BeforeBlock != null)
{
this.Emitter.BeforeBlock();
this.Emitter.BeforeBlock = null;
}
var ra = ReachabilityAnalysis.Create(this.BlockStatement, this.Emitter.Resolver.Resolver);
this.BlockStatement.Children.ToList().ForEach(child =>
{
var statement = child as Statement;
if (statement != null && !ra.IsReachable(statement))
{
return;
}
child.AcceptVisitor(this.Emitter);
});
}
public void EndEmitBlock()
{
if (this.IsMethodBlock)
{
this.Emitter.ReturnType = this.OldReturnType;
if (this.Emitter.WrapRestCounter > 0)
{
for (int i = 0; i < this.Emitter.WrapRestCounter; i++)
{
this.EndBlock();
this.Write("));");
this.WriteNewLine();
}
}
this.Emitter.WrapRestCounter = this.OldWrapRestCounter;
}
if (!this.NoBraces && (!this.Emitter.IsAsync || (!this.AsyncNoBraces && this.BlockStatement.Parent != this.Emitter.AsyncBlock.Node)))
{
if (this.IsMethodBlock && this.BeginPosition == this.Emitter.Output.Length)
{
this.EndBlock();
this.Emitter.Output.Length = this.SignaturePosition;
this.WriteOpenCloseBrace();
}
else
{
this.EndBlock();
}
}
if (this.AddEndBlock)
{
this.WriteNewLine();
this.EndBlock();
}
if (this.OldReplaceJump.HasValue)
{
this.Emitter.ReplaceJump = this.OldReplaceJump.Value;
}
if (!this.KeepLineAfterBlock(this.BlockStatement))
{
this.WriteNewLine();
}
if (this.IsMethodBlock && !this.Emitter.IsAsync)
{
this.EmitTempVars(this.BeginPosition);
}
this.PopLocals();
}
public void BeginEmitBlock()
{
this.PushLocals();
if (!this.NoBraces && (!this.Emitter.IsAsync || (!this.AsyncNoBraces && this.BlockStatement.Parent != this.Emitter.AsyncBlock.Node)))
{
this.SignaturePosition = this.Emitter.Output.Length;
this.BeginBlock();
}
this.BeginPosition = this.Emitter.Output.Length;
if (this.IsMethodBlock)
{
this.OldWrapRestCounter = this.Emitter.WrapRestCounter;
this.Emitter.WrapRestCounter = 0;
}
}
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Reflection;
using EIDSS.RAM_DB.DBService.Access;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using bv.common.Core;
using bv.tests.AVR.Helpers;
namespace bv.tests.AVR.UnitTests
{
[TestClass]
public class AccessTests
{
private const string TableName = @"tasLayout";
private static string m_DbFilePath;
private static string m_ConnectionString;
[ClassInitialize]
public static void MyClassInitialize(TestContext testContext)
{
Assembly asm = Assembly.GetExecutingAssembly();
string location = Path.GetDirectoryName(Utils.ConvertFileNane(asm.Location)) + @"\AVR";
if (!Directory.Exists(location))
{
int index = location.IndexOf("DevelopersBranch", StringComparison.OrdinalIgnoreCase);
if (index > 0)
{
Directory.CreateDirectory(location);
string realPath = location.Substring(0, index) + @"DevelopersBranch\eidss.main\bin\Debug\AVR\db_test.mdb";
File.Copy(realPath, location + @"\db_test.mdb");
}
}
m_DbFilePath = Utils.GetFilePathNearAssembly(asm, @"AVR\db_test.mdb");
m_ConnectionString = string.Format(@"Data Source={0}; Provider=Microsoft.JET.OLEDB.4.0", m_DbFilePath);
}
[TestMethod]
public void ConnectionTest()
{
Assert.IsTrue(File.Exists(m_DbFilePath), string.Format("File {0} doesn't exists", m_DbFilePath));
using (var connection = new OleDbConnection(m_ConnectionString))
{
connection.Open();
Console.WriteLine(connection.DataSource);
Assert.AreEqual(connection.State, ConnectionState.Open);
}
}
[TestMethod]
public void CreateScriptsTest()
{
DataTable table = DataHelper.GenerateTestTable();
table.TableName = TableName;
string tableCommandText = AccessDataAdapter.CreateTableCommandText(table);
Console.WriteLine(tableCommandText);
Assert.AreEqual(
@"CREATE TABLE [tasLayout](
[sflHC_PatientAge] DOUBLE,
[sflHC_PatientDOB] DATETIME,
[sflHC_CaseID] VARCHAR
)",
tableCommandText);
string selectCommandText = AccessDataAdapter.SelectCommandText(table);
Console.WriteLine(selectCommandText);
Assert.AreEqual(@"SELECT
[sflHC_PatientAge],
[sflHC_PatientDOB],
[sflHC_CaseID]
FROM [tasLayout]", selectCommandText);
string insertCommandText = AccessDataAdapter.InsertCommandText(table);
Console.WriteLine(insertCommandText);
Assert.AreEqual(@"INSERT INTO [tasLayout] (
[sflHC_PatientAge],
[sflHC_PatientDOB],
[sflHC_CaseID])
Values(
?, ?, ?)",
insertCommandText);
}
[TestMethod]
public void ImportTableToAccessInternalTest()
{
using (var connection = new OleDbConnection(m_ConnectionString))
{
DataTable table = DataHelper.GenerateTestTable();
table.TableName = TableName;
connection.Open();
OleDbTransaction transaction = connection.BeginTransaction();
try
{
AccessDataAdapter.DropTableIfExists(connection, transaction, TableName);
DataTable schemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
new object[] {null, null, null, "TABLE"});
Assert.IsNotNull(schemaTable);
Assert.AreEqual(0, schemaTable.Rows.Count);
AccessDataAdapter.CreateTable(connection, transaction, table);
schemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
new object[] {null, null, null, "TABLE"});
Assert.IsNotNull(schemaTable);
Assert.AreEqual(1, schemaTable.Rows.Count);
Assert.AreEqual(TableName, schemaTable.Rows[0]["TABLE_NAME"]);
AccessDataAdapter.InsertData(connection, transaction, table);
var dataSet = new DataSet();
using (var adapter = new OleDbDataAdapter())
{
adapter.SelectCommand = new OleDbCommand(AccessDataAdapter.SelectCommandText(table), connection)
{Transaction = transaction};
adapter.Fill(dataSet);
Assert.AreEqual(1, dataSet.Tables.Count);
Assert.AreEqual(10, dataSet.Tables[0].Rows.Count);
}
AccessDataAdapter.DropTableIfExists(connection, transaction, TableName);
schemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
new object[] {null, null, null, "TABLE"});
Assert.IsNotNull(schemaTable);
Assert.AreEqual(0, schemaTable.Rows.Count);
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
}
[TestMethod]
public void ConvertTableToAccessTest()
{
DataTable table = DataHelper.GenerateTestTable();
table.TableName = TableName;
AddTestColumn(table, "column4", "column3_Caption");
AddTestColumn(table, "column5", "column3_Caption");
AddTestColumn(table, "column6", "column4_Caption");
AddTestColumn(table, "column7", "column3_Caption");
AddTestColumn(table, "column8", "column3_Caption");
DataTable dataTable = AccessDataAdapter.ConvertTable(table);
Assert.AreEqual(8, dataTable.Columns.Count);
Assert.AreEqual("sflHC_CaseID_Caption", dataTable.Columns[2].ColumnName);
Assert.AreEqual("column3_Caption1", dataTable.Columns[3].ColumnName);
Assert.AreEqual("column3_Caption2", dataTable.Columns[4].ColumnName);
Assert.AreEqual("column4_Caption", dataTable.Columns[5].ColumnName);
Assert.AreEqual("column3_Caption3", dataTable.Columns[6].ColumnName);
Assert.AreEqual("column3_Caption4", dataTable.Columns[7].ColumnName);
}
private static void AddTestColumn(DataTable table, string name, string caption)
{
var column = new DataColumn(name) {Caption = caption, DataType = typeof (string)};
table.Columns.Add(column);
}
[TestMethod]
public void ConstructorAccessDataAdapterTest()
{
var adapter = new AccessDataAdapter(m_DbFilePath);
Assert.AreEqual(m_DbFilePath, adapter.DbFileName);
}
[TestMethod]
public void ImportTableToAccessTest()
{
var adapter = new AccessDataAdapter(m_DbFilePath);
Assert.AreEqual(false, adapter.IsTableExistInAccess(TableName));
DataTable table = DataHelper.GenerateTestTable();
table.TableName = TableName;
adapter.ExportTableToAccess(table);
Assert.AreEqual(true, adapter.IsTableExistInAccess(TableName));
using (var connection = new OleDbConnection(m_ConnectionString))
{
connection.Open();
AccessDataAdapter.DropTableIfExists(connection, null, TableName);
}
Assert.AreEqual(false, adapter.IsTableExistInAccess(TableName));
}
[TestMethod]
public void CreateDbTest()
{
string tempDbFilePath = m_DbFilePath.Replace(@"db_test.mdb", @"tmp_unit_test.mdb");
if (File.Exists(tempDbFilePath))
{
File.Delete(tempDbFilePath);
}
AccessDataAdapter.CreateDataBase(string.Format(@"Data Source={0}; Provider=Microsoft.JET.OLEDB.4.0", tempDbFilePath));
Assert.AreEqual(true, File.Exists(tempDbFilePath));
Console.WriteLine(@"Database Created Successfully");
var adapter = new AccessDataAdapter(tempDbFilePath);
DataTable table = DataHelper.GenerateTestTable();
table.TableName = TableName;
adapter.ExportTableToAccess(table);
Assert.AreEqual(true, adapter.IsTableExistInAccess(TableName));
}
}
}
| |
// Copyright (c) 2017 Jan Pluskal, Viliam Letavay
//
//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.
/**
* Autogenerated by Thrift Compiler (0.9.3)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
using System;
using System.Text;
using Thrift.Protocol;
namespace Netfox.SnooperMessenger.Protocol
{
#if !SILVERLIGHT
[Serializable]
#endif
public partial class MNMessagesSyncAppAttributionVisibility : TBase
{
private bool _HideAttribution;
private bool _HideInstallButton;
private bool _HideReplyButton;
private bool _DisableBroadcasting;
private bool _HideAppIcon;
public bool HideAttribution
{
get
{
return _HideAttribution;
}
set
{
__isset.HideAttribution = true;
this._HideAttribution = value;
}
}
public bool HideInstallButton
{
get
{
return _HideInstallButton;
}
set
{
__isset.HideInstallButton = true;
this._HideInstallButton = value;
}
}
public bool HideReplyButton
{
get
{
return _HideReplyButton;
}
set
{
__isset.HideReplyButton = true;
this._HideReplyButton = value;
}
}
public bool DisableBroadcasting
{
get
{
return _DisableBroadcasting;
}
set
{
__isset.DisableBroadcasting = true;
this._DisableBroadcasting = value;
}
}
public bool HideAppIcon
{
get
{
return _HideAppIcon;
}
set
{
__isset.HideAppIcon = true;
this._HideAppIcon = value;
}
}
public Isset __isset;
#if !SILVERLIGHT
[Serializable]
#endif
public struct Isset {
public bool HideAttribution;
public bool HideInstallButton;
public bool HideReplyButton;
public bool DisableBroadcasting;
public bool HideAppIcon;
}
public MNMessagesSyncAppAttributionVisibility() {
}
public void Read (TProtocol iprot)
{
iprot.IncrementRecursionDepth();
try
{
TField field;
iprot.ReadStructBegin();
while (true)
{
field = iprot.ReadFieldBegin();
if (field.Type == TType.Stop) {
break;
}
switch (field.ID)
{
case 1:
if (field.Type == TType.Bool) {
HideAttribution = iprot.ReadBool();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 2:
if (field.Type == TType.Bool) {
HideInstallButton = iprot.ReadBool();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 3:
if (field.Type == TType.Bool) {
HideReplyButton = iprot.ReadBool();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 4:
if (field.Type == TType.Bool) {
DisableBroadcasting = iprot.ReadBool();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 5:
if (field.Type == TType.Bool) {
HideAppIcon = iprot.ReadBool();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
default:
TProtocolUtil.Skip(iprot, field.Type);
break;
}
iprot.ReadFieldEnd();
}
iprot.ReadStructEnd();
}
finally
{
iprot.DecrementRecursionDepth();
}
}
public void Write(TProtocol oprot) {
oprot.IncrementRecursionDepth();
try
{
TStruct struc = new TStruct("MNMessagesSyncAppAttributionVisibility");
oprot.WriteStructBegin(struc);
TField field = new TField();
if (__isset.HideAttribution) {
field.Name = "HideAttribution";
field.Type = TType.Bool;
field.ID = 1;
oprot.WriteFieldBegin(field);
oprot.WriteBool(HideAttribution);
oprot.WriteFieldEnd();
}
if (__isset.HideInstallButton) {
field.Name = "HideInstallButton";
field.Type = TType.Bool;
field.ID = 2;
oprot.WriteFieldBegin(field);
oprot.WriteBool(HideInstallButton);
oprot.WriteFieldEnd();
}
if (__isset.HideReplyButton) {
field.Name = "HideReplyButton";
field.Type = TType.Bool;
field.ID = 3;
oprot.WriteFieldBegin(field);
oprot.WriteBool(HideReplyButton);
oprot.WriteFieldEnd();
}
if (__isset.DisableBroadcasting) {
field.Name = "DisableBroadcasting";
field.Type = TType.Bool;
field.ID = 4;
oprot.WriteFieldBegin(field);
oprot.WriteBool(DisableBroadcasting);
oprot.WriteFieldEnd();
}
if (__isset.HideAppIcon) {
field.Name = "HideAppIcon";
field.Type = TType.Bool;
field.ID = 5;
oprot.WriteFieldBegin(field);
oprot.WriteBool(HideAppIcon);
oprot.WriteFieldEnd();
}
oprot.WriteFieldStop();
oprot.WriteStructEnd();
}
finally
{
oprot.DecrementRecursionDepth();
}
}
public override string ToString() {
StringBuilder __sb = new StringBuilder("MNMessagesSyncAppAttributionVisibility(");
bool __first = true;
if (__isset.HideAttribution) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("HideAttribution: ");
__sb.Append(HideAttribution);
}
if (__isset.HideInstallButton) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("HideInstallButton: ");
__sb.Append(HideInstallButton);
}
if (__isset.HideReplyButton) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("HideReplyButton: ");
__sb.Append(HideReplyButton);
}
if (__isset.DisableBroadcasting) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("DisableBroadcasting: ");
__sb.Append(DisableBroadcasting);
}
if (__isset.HideAppIcon) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("HideAppIcon: ");
__sb.Append(HideAppIcon);
}
__sb.Append(")");
return __sb.ToString();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// This is a C# implementation of the Richards benchmark from:
//
// http://www.cl.cam.ac.uk/~mr10/Bench.html
//
// The benchmark was originally implemented in BCPL by Martin Richards.
#define INTF_FOR_TASK
using Microsoft.Xunit.Performance;
using System;
using System.Collections.Generic;
[assembly: OptimizeForBenchmarks]
[assembly: MeasureInstructionsRetired]
// using System.Diagnostics;
// using System.Text.RegularExpressions;
namespace V8.Richards
{
/// <summary>
/// Support is used for a place to generate any 'miscellaneous' methods generated as part
/// of code generation, (which do not have user-visible names)
/// </summary>
public class Support
{
public static bool runRichards()
{
Scheduler scheduler = new Scheduler();
scheduler.addIdleTask(ID_IDLE, 0, null, COUNT);
Packet queue = new Packet(null, ID_WORKER, KIND_WORK);
queue = new Packet(queue, ID_WORKER, KIND_WORK);
scheduler.addWorkerTask(ID_WORKER, 1000, queue);
queue = new Packet(null, ID_DEVICE_A, KIND_DEVICE);
queue = new Packet(queue, ID_DEVICE_A, KIND_DEVICE);
queue = new Packet(queue, ID_DEVICE_A, KIND_DEVICE);
scheduler.addHandlerTask(ID_HANDLER_A, 2000, queue);
queue = new Packet(null, ID_DEVICE_B, KIND_DEVICE);
queue = new Packet(queue, ID_DEVICE_B, KIND_DEVICE);
queue = new Packet(queue, ID_DEVICE_B, KIND_DEVICE);
scheduler.addHandlerTask(ID_HANDLER_B, 3000, queue);
scheduler.addDeviceTask(ID_DEVICE_A, 4000, null);
scheduler.addDeviceTask(ID_DEVICE_B, 5000, null);
scheduler.schedule();
return ((scheduler.queueCount == EXPECTED_QUEUE_COUNT)
&& (scheduler.holdCount == EXPECTED_HOLD_COUNT));
}
public const int COUNT = 1000;
/**
* These two constants specify how many times a packet is queued and
* how many times a task is put on hold in a correct run of richards.
* They don't have any meaning a such but are characteristic of a
* correct run so if the actual queue or hold count is different from
* the expected there must be a bug in the implementation.
**/
public const int EXPECTED_QUEUE_COUNT = 2322;
public const int EXPECTED_HOLD_COUNT = 928;
public const int ID_IDLE = 0;
public const int ID_WORKER = 1;
public const int ID_HANDLER_A = 2;
public const int ID_HANDLER_B = 3;
public const int ID_DEVICE_A = 4;
public const int ID_DEVICE_B = 5;
public const int NUMBER_OF_IDS = 6;
public const int KIND_DEVICE = 0;
public const int KIND_WORK = 1;
/**
* The task is running and is currently scheduled.
*/
public const int STATE_RUNNING = 0;
/**
* The task has packets left to process.
*/
public const int STATE_RUNNABLE = 1;
/**
* The task is not currently running. The task is not blocked as such and may
* be started by the scheduler.
*/
public const int STATE_SUSPENDED = 2;
/**
* The task is blocked and cannot be run until it is explicitly released.
*/
public const int STATE_HELD = 4;
public const int STATE_SUSPENDED_RUNNABLE = STATE_SUSPENDED | STATE_RUNNABLE;
public const int STATE_NOT_HELD = ~STATE_HELD;
/* --- *
* P a c k e t
* --- */
public const int DATA_SIZE = 4;
public static int Main(String[] args)
{
int n = 1;
if (args.Length > 0)
{
n = Int32.Parse(args[0]);
}
bool result = Measure(n);
return (result ? 100 : -1);
}
public static bool Measure(int n)
{
DateTime start = DateTime.Now;
bool result = true;
for (int i = 0; i < n; i++)
{
result &= runRichards();
}
DateTime end = DateTime.Now;
TimeSpan dur = end - start;
Console.WriteLine("Doing {0} iters of Richards takes {1} ms; {2} us/iter.",
n, dur.TotalMilliseconds, (1000.0 * dur.TotalMilliseconds) / n);
return result;
}
[Benchmark]
public static void Bench()
{
const int Iterations = 5000;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < Iterations; i++)
{
runRichards();
}
}
}
}
}
internal class Scheduler
{
public int queueCount;
public int holdCount;
public TaskControlBlock[] blocks;
public TaskControlBlock list;
public TaskControlBlock currentTcb;
public int currentId;
public Scheduler()
{
this.queueCount = 0;
this.holdCount = 0;
this.blocks = new TaskControlBlock[Support.NUMBER_OF_IDS];
this.list = null;
this.currentTcb = null;
this.currentId = 0;
}
/**
* Add an idle task to this scheduler.
* @param {int} id the identity of the task
* @param {int} priority the task's priority
* @param {Packet} queue the queue of work to be processed by the task
* @param {int} count the number of times to schedule the task
*/
public void addIdleTask(int id, int priority, Packet queue, int count)
{
this.addRunningTask(id, priority, queue,
new IdleTask(this, 1, count));
}
/**
* Add a work task to this scheduler.
* @param {int} id the identity of the task
* @param {int} priority the task's priority
* @param {Packet} queue the queue of work to be processed by the task
*/
public void addWorkerTask(int id, int priority, Packet queue)
{
this.addTask(id, priority, queue,
new WorkerTask(this, Support.ID_HANDLER_A, 0));
}
/**
* Add a handler task to this scheduler.
* @param {int} id the identity of the task
* @param {int} priority the task's priority
* @param {Packet} queue the queue of work to be processed by the task
*/
public void addHandlerTask(int id, int priority, Packet queue)
{
this.addTask(id, priority, queue, new HandlerTask(this));
}
/**
* Add a handler task to this scheduler.
* @param {int} id the identity of the task
* @param {int} priority the task's priority
* @param {Packet} queue the queue of work to be processed by the task
*/
public void addDeviceTask(int id, int priority, Packet queue)
{
this.addTask(id, priority, queue, new DeviceTask(this));
}
/**
* Add the specified task and mark it as running.
* @param {int} id the identity of the task
* @param {int} priority the task's priority
* @param {Packet} queue the queue of work to be processed by the task
* @param {Task} task the task to add
*/
public void addRunningTask(int id, int priority, Packet queue, Task task)
{
this.addTask(id, priority, queue, task);
this.currentTcb.setRunning();
}
/**
* Add the specified task to this scheduler.
* @param {int} id the identity of the task
* @param {int} priority the task's priority
* @param {Packet} queue the queue of work to be processed by the task
* @param {Task} task the task to add
*/
public void addTask(int id, int priority, Packet queue, Task task)
{
this.currentTcb = new TaskControlBlock(this.list, id, priority, queue, task);
this.list = this.currentTcb;
this.blocks[id] = this.currentTcb;
}
/**
* Execute the tasks managed by this scheduler.
*/
public void schedule()
{
this.currentTcb = this.list;
#if TRACEIT
int kkk = 0;
#endif
while (this.currentTcb != null)
{
#if TRACEIT
Console.WriteLine("kkk = {0}", kkk); kkk++;
#endif
if (this.currentTcb.isHeldOrSuspended())
{
#if TRACEIT
Console.WriteLine("held");
#endif
this.currentTcb = this.currentTcb.link;
}
else
{
this.currentId = this.currentTcb.id;
#if TRACEIT
Console.WriteLine("currentId is now...{0}", this.currentId.ToString());
#endif
this.currentTcb = this.currentTcb.run();
}
}
}
/**
* Release a task that is currently blocked and return the next block to run.
* @param {int} id the id of the task to suspend
*/
public TaskControlBlock release(int id)
{
TaskControlBlock tcb = this.blocks[id];
if (tcb == null) return tcb;
tcb.markAsNotHeld();
if (tcb.priority >= this.currentTcb.priority)
{
return tcb;
}
else
{
return this.currentTcb;
}
}
/**
* Block the currently executing task and return the next task control block
* to run. The blocked task will not be made runnable until it is explicitly
* released, even if new work is added to it.
*/
public TaskControlBlock holdCurrent()
{
this.holdCount++;
this.currentTcb.markAsHeld();
return this.currentTcb.link;
}
/**
* Suspend the currently executing task and return the next task control block
* to run. If new work is added to the suspended task it will be made runnable.
*/
public TaskControlBlock suspendCurrent()
{
this.currentTcb.markAsSuspended();
return this.currentTcb;
}
/**
* Add the specified packet to the end of the worklist used by the task
* associated with the packet and make the task runnable if it is currently
* suspended.
* @param {Packet} packet the packet to add
*/
public TaskControlBlock queue(Packet packet)
{
TaskControlBlock t = this.blocks[packet.id];
if (t == null) return t;
this.queueCount++;
packet.link = null;
packet.id = this.currentId;
return t.checkPriorityAdd(this.currentTcb, packet);
}
}
/**
* A task control block manages a task and the queue of work packages associated
* with it.
* @param {TaskControlBlock} link the preceding block in the linked block list
* @param {int} id the id of this block
* @param {int} priority the priority of this block
* @param {Packet} queue the queue of packages to be processed by the task
* @param {Task} task the task
* @constructor
*/
public class TaskControlBlock
{
public TaskControlBlock link;
public int id;
public int priority;
public Packet queue;
public Task task;
public int state;
public TaskControlBlock(TaskControlBlock link, int id, int priority,
Packet queue, Task task)
{
this.link = link;
this.id = id;
this.priority = priority;
this.queue = queue;
this.task = task;
if (queue == null)
{
this.state = Support.STATE_SUSPENDED;
}
else
{
this.state = Support.STATE_SUSPENDED_RUNNABLE;
}
}
public void setRunning()
{
this.state = Support.STATE_RUNNING;
}
public void markAsNotHeld()
{
this.state = this.state & Support.STATE_NOT_HELD;
}
public void markAsHeld()
{
this.state = this.state | Support.STATE_HELD;
}
public bool isHeldOrSuspended()
{
return ((this.state & Support.STATE_HELD) != 0) || (this.state == Support.STATE_SUSPENDED);
}
public void markAsSuspended()
{
this.state = this.state | Support.STATE_SUSPENDED;
}
public void markAsRunnable()
{
this.state = this.state | Support.STATE_RUNNABLE;
}
/**
* Runs this task, if it is ready to be run, and returns the next task to run.
*/
public TaskControlBlock run()
{
Packet packet;
#if TRACEIT
Console.WriteLine(" TCB::run, state = {0}", this.state);
#endif
if (this.state == Support.STATE_SUSPENDED_RUNNABLE)
{
packet = this.queue;
this.queue = packet.link;
if (this.queue == null)
{
this.state = Support.STATE_RUNNING;
}
else
{
this.state = Support.STATE_RUNNABLE;
}
#if TRACEIT
Console.WriteLine(" State is now {0}", this.state);
#endif
}
else
{
#if TRACEIT
Console.WriteLine(" TCB::run, setting packet = Null.");
#endif
packet = null;
}
return this.task.run(packet);
}
/**
* Adds a packet to the worklist of this block's task, marks this as runnable if
* necessary, and returns the next runnable object to run (the one
* with the highest priority).
*/
public TaskControlBlock checkPriorityAdd(TaskControlBlock task, Packet packet)
{
if (this.queue == null)
{
this.queue = packet;
this.markAsRunnable();
if (this.priority >= task.priority) return this;
}
else
{
this.queue = packet.addTo(this.queue);
}
return task;
}
public String toString()
{
return "tcb { " + this.task.toString() + "@" + this.state.ToString() + " }";
}
}
#if INTF_FOR_TASK
// I deliberately ignore the "I" prefix convention here so that we can use Task as a type in both
// cases...
public interface Task
{
TaskControlBlock run(Packet packet);
String toString();
}
#else
public abstract class Task
{
public abstract TaskControlBlock run(Packet packet);
public abstract String toString();
}
#endif
/**
* An idle task doesn't do any work itself but cycles control between the two
* device tasks.
* @param {Scheduler} scheduler the scheduler that manages this task
* @param {int} v1 a seed value that controls how the device tasks are scheduled
* @param {int} count the number of times this task should be scheduled
* @constructor
*/
internal class IdleTask : Task
{
public Scheduler scheduler;
public int _v1;
public int _count;
public IdleTask(Scheduler scheduler, int v1, int count)
{
this.scheduler = scheduler;
this._v1 = v1;
this._count = count;
}
public
#if !INTF_FOR_TASK
override
#endif
TaskControlBlock run(Packet packet)
{
this._count--;
if (this._count == 0) return this.scheduler.holdCurrent();
if ((this._v1 & 1) == 0)
{
this._v1 = this._v1 >> 1;
return this.scheduler.release(Support.ID_DEVICE_A);
}
else
{
this._v1 = (this._v1 >> 1) ^ 0xD008;
return this.scheduler.release(Support.ID_DEVICE_B);
}
}
public
#if !INTF_FOR_TASK
override
#endif
String toString()
{
return "IdleTask";
}
}
/**
* A task that suspends itself after each time it has been run to simulate
* waiting for data from an external device.
* @param {Scheduler} scheduler the scheduler that manages this task
* @constructor
*/
internal class DeviceTask : Task
{
public Scheduler scheduler;
private Packet _v1;
public DeviceTask(Scheduler scheduler)
{
this.scheduler = scheduler;
_v1 = null;
}
public
#if !INTF_FOR_TASK
override
#endif
TaskControlBlock run(Packet packet)
{
if (packet == null)
{
if (_v1 == null) return this.scheduler.suspendCurrent();
Packet v = _v1;
_v1 = null;
return this.scheduler.queue(v);
}
else
{
_v1 = packet;
return this.scheduler.holdCurrent();
}
}
public
#if !INTF_FOR_TASK
override
#endif
String toString()
{
return "DeviceTask";
}
}
/**
* A task that manipulates work packets.
* @param {Scheduler} scheduler the scheduler that manages this task
* @param {int} v1 a seed used to specify how work packets are manipulated
* @param {int} v2 another seed used to specify how work packets are manipulated
* @constructor
*/
internal class WorkerTask : Task
{
public Scheduler scheduler;
public int v1;
public int _v2;
public WorkerTask(Scheduler scheduler, int v1, int v2)
{
this.scheduler = scheduler;
this.v1 = v1;
this._v2 = v2;
}
public
#if !INTF_FOR_TASK
override
#endif
TaskControlBlock run(Packet packet)
{
if (packet == null)
{
return this.scheduler.suspendCurrent();
}
else
{
if (this.v1 == Support.ID_HANDLER_A)
{
this.v1 = Support.ID_HANDLER_B;
}
else
{
this.v1 = Support.ID_HANDLER_A;
}
packet.id = this.v1;
packet.a1 = 0;
for (int i = 0; i < Support.DATA_SIZE; i++)
{
this._v2++;
if (this._v2 > 26) this._v2 = 1;
packet.a2[i] = this._v2;
}
return this.scheduler.queue(packet);
}
}
public
#if !INTF_FOR_TASK
override
#endif
String toString()
{
return "WorkerTask";
}
}
/**
* A task that manipulates work packets and then suspends itself.
* @param {Scheduler} scheduler the scheduler that manages this task
* @constructor
*/
internal class HandlerTask : Task
{
public Scheduler scheduler;
public Packet v1;
public Packet v2;
public HandlerTask(Scheduler scheduler)
{
this.scheduler = scheduler;
this.v1 = null;
this.v2 = null;
}
public
#if !INTF_FOR_TASK
override
#endif
TaskControlBlock run(Packet packet)
{
if (packet != null)
{
if (packet.kind == Support.KIND_WORK)
{
this.v1 = packet.addTo(this.v1);
}
else
{
this.v2 = packet.addTo(this.v2);
}
}
if (this.v1 != null)
{
int count = this.v1.a1;
Packet v;
if (count < Support.DATA_SIZE)
{
if (this.v2 != null)
{
v = this.v2;
this.v2 = this.v2.link;
v.a1 = this.v1.a2[count];
this.v1.a1 = count + 1;
return this.scheduler.queue(v);
}
}
else
{
v = this.v1;
this.v1 = this.v1.link;
return this.scheduler.queue(v);
}
}
return this.scheduler.suspendCurrent();
}
public
#if !INTF_FOR_TASK
override
#endif
String toString()
{
return "HandlerTask";
}
}
/**
* A simple package of data that is manipulated by the tasks. The exact layout
* of the payload data carried by a packet is not importaint, and neither is the
* nature of the work performed on packets by the tasks.
*
* Besides carrying data, packets form linked lists and are hence used both as
* data and worklists.
* @param {Packet} link the tail of the linked list of packets
* @param {int} id an ID for this packet
* @param {int} kind the type of this packet
* @constructor
*/
public class Packet
{
public Packet link;
public int id;
public int kind;
public int a1;
public int[] a2;
public Packet(Packet link, int id, int kind)
{
this.link = link;
this.id = id;
this.kind = kind;
this.a1 = 0;
this.a2 = new int[Support.DATA_SIZE];
}
public Packet addTo(Packet queue)
{
this.link = null;
if (queue == null) return this;
Packet peek;
Packet next = queue;
while ((peek = next.link) != null)
next = peek;
next.link = this;
return queue;
}
public String toString()
{
return "Packet";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Diagnostics
{
internal sealed class PerformanceCounterLib
{
private static string s_computerName;
private PerformanceMonitor _performanceMonitor;
private string _machineName;
private string _perfLcid;
private static Dictionary<String, PerformanceCounterLib> s_libraryTable;
private Dictionary<int, string> _nameTable;
private readonly object _nameTableLock = new Object();
private static Object s_internalSyncObject;
internal PerformanceCounterLib(string machineName, string lcid)
{
_machineName = machineName;
_perfLcid = lcid;
}
/// <internalonly/>
internal static string ComputerName => LazyInitializer.EnsureInitialized(ref s_computerName, ref s_internalSyncObject, () => Interop.Kernel32.GetComputerName());
internal Dictionary<int, string> NameTable
{
get
{
if (_nameTable == null)
{
lock (_nameTableLock)
{
if (_nameTable == null)
_nameTable = GetStringTable(false);
}
}
return _nameTable;
}
}
internal string GetCounterName(int index)
{
string result;
return NameTable.TryGetValue(index, out result) ? result : "";
}
internal static PerformanceCounterLib GetPerformanceCounterLib(string machineName, CultureInfo culture)
{
string lcidString = culture.Name.ToLowerInvariant();
if (machineName.CompareTo(".") == 0)
machineName = ComputerName.ToLowerInvariant();
else
machineName = machineName.ToLowerInvariant();
LazyInitializer.EnsureInitialized(ref s_libraryTable, ref s_internalSyncObject, () => new Dictionary<string, PerformanceCounterLib>());
string libraryKey = machineName + ":" + lcidString;
PerformanceCounterLib library;
if (!PerformanceCounterLib.s_libraryTable.TryGetValue(libraryKey, out library))
{
library = new PerformanceCounterLib(machineName, lcidString);
PerformanceCounterLib.s_libraryTable[libraryKey] = library;
}
return library;
}
internal byte[] GetPerformanceData(string item)
{
if (_performanceMonitor == null)
{
lock (LazyInitializer.EnsureInitialized(ref s_internalSyncObject))
{
if (_performanceMonitor == null)
_performanceMonitor = new PerformanceMonitor(_machineName);
}
}
return _performanceMonitor.GetData(item);
}
private Dictionary<int, string> GetStringTable(bool isHelp)
{
Dictionary<int, string> stringTable;
RegistryKey libraryKey;
libraryKey = Registry.PerformanceData;
try
{
string[] names = null;
int waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins
int waitSleep = 0;
// In some stress situations, querying counter values from
// HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\009
// often returns null/empty data back. We should build fault-tolerance logic to
// make it more reliable because getting null back once doesn't necessarily mean
// that the data is corrupted, most of the time we would get the data just fine
// in subsequent tries.
while (waitRetries > 0)
{
try
{
if (!isHelp)
names = (string[])libraryKey.GetValue("Counter " + _perfLcid);
else
names = (string[])libraryKey.GetValue("Explain " + _perfLcid);
if ((names == null) || (names.Length == 0))
{
--waitRetries;
if (waitSleep == 0)
waitSleep = 10;
else
{
System.Threading.Thread.Sleep(waitSleep);
waitSleep *= 2;
}
}
else
break;
}
catch (IOException)
{
// RegistryKey throws if it can't find the value. We want to return an empty table
// and throw a different exception higher up the stack.
names = null;
break;
}
catch (InvalidCastException)
{
// Unable to cast object of type 'System.Byte[]' to type 'System.String[]'.
// this happens when the registry data store is corrupt and the type is not even REG_MULTI_SZ
names = null;
break;
}
}
if (names == null)
stringTable = new Dictionary<int, string>();
else
{
stringTable = new Dictionary<int, string>(names.Length / 2);
for (int index = 0; index < (names.Length / 2); ++index)
{
string nameString = names[(index * 2) + 1];
if (nameString == null)
nameString = String.Empty;
int key;
if (!Int32.TryParse(names[index * 2], NumberStyles.Integer, CultureInfo.InvariantCulture, out key))
{
if (isHelp)
{
// Category Help Table
throw new InvalidOperationException(SR.Format(SR.CategoryHelpCorrupt, names[index * 2]));
}
else
{
// Counter Name Table
throw new InvalidOperationException(SR.Format(SR.CounterNameCorrupt, names[index * 2]));
}
}
stringTable[key] = nameString;
}
}
}
finally
{
libraryKey.Dispose();
}
return stringTable;
}
internal class PerformanceMonitor
{
private RegistryKey _perfDataKey = null;
private string _machineName;
internal PerformanceMonitor(string machineName)
{
_machineName = machineName;
Init();
}
private void Init()
{
_perfDataKey = Registry.PerformanceData;
}
// Win32 RegQueryValueEx for perf data could deadlock (for a Mutex) up to 2mins in some
// scenarios before they detect it and exit gracefully. In the mean time, ERROR_BUSY,
// ERROR_NOT_READY etc can be seen by other concurrent calls (which is the reason for the
// wait loop and switch case below). We want to wait most certainly more than a 2min window.
// The current wait time of up to 10mins takes care of the known stress deadlock issues. In most
// cases we wouldn't wait for more than 2mins anyways but in worst cases how much ever time
// we wait may not be sufficient if the Win32 code keeps running into this deadlock again
// and again. A condition very rare but possible in theory. We would get back to the user
// in this case with InvalidOperationException after the wait time expires.
internal byte[] GetData(string item)
{
int waitRetries = 17; //2^16*10ms == approximately 10mins
int waitSleep = 0;
byte[] data = null;
int error = 0;
while (waitRetries > 0)
{
try
{
data = (byte[])_perfDataKey.GetValue(item);
return data;
}
catch (IOException e)
{
error = e.HResult;
switch (error)
{
case Interop.Advapi32.RPCStatus.RPC_S_CALL_FAILED:
case Interop.Errors.ERROR_INVALID_HANDLE:
case Interop.Advapi32.RPCStatus.RPC_S_SERVER_UNAVAILABLE:
Init();
goto case Interop.Advapi32.WaitOptions.WAIT_TIMEOUT;
case Interop.Advapi32.WaitOptions.WAIT_TIMEOUT:
case Interop.Errors.ERROR_NOT_READY:
case Interop.Errors.ERROR_LOCK_FAILED:
case Interop.Errors.ERROR_BUSY:
--waitRetries;
if (waitSleep == 0)
{
waitSleep = 10;
}
else
{
System.Threading.Thread.Sleep(waitSleep);
waitSleep *= 2;
}
break;
default:
throw new Win32Exception(error);
}
}
catch (InvalidCastException e)
{
throw new InvalidOperationException(SR.Format(SR.CounterDataCorrupt, _perfDataKey.ToString()), e);
}
}
throw new Win32Exception(error);
}
}
}
}
| |
/*
Copyright 2006 - 2010 Intel 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.IO;
using System.Text;
using System.Threading;
namespace OpenSource.FileHashDB
{
/// <summary>
/// Summary description for DataBlock.
/// </summary>
public class DataBlock
{
private int PendingWrites = 1;
//private int BytesWritten = 0;
private string KEY = "";
internal int OFFSET = -1;
internal int NEXTBLOCK = -1;
internal object _Tag = null;
private FileHashDB f;
private byte[] buffer = new byte[512];
private MemoryStream mstream = new MemoryStream();
public delegate void OnReadHandler(DataBlock sender, string key, byte[] ReadBuffer, object Tag);
public event OnReadHandler OnRead;
public delegate void OnWriteHandler(DataBlock sender, object Tag);
public event OnWriteHandler OnWrite;
private AsyncCallback CB;
internal DataBlock(int BlockOffset, FileHashDB WRITER_sender)
{
CB = new AsyncCallback(WriteBlockSink);
f = WRITER_sender;
OFFSET = BlockOffset;
}
public void Write(string KEY, byte[] DataBuffer, int offset, int count, object Tag)
{
UTF8Encoding U = new UTF8Encoding();
byte[] key = U.GetBytes(KEY);
byte[] keysize = BitConverter.GetBytes((short)key.Length);
byte[] Fill = null;
int DataIDX = 0;
int DataWritten = 0;
int DataWrite = 0;
byte[] BlockSize = null;
byte[] NextBlock = null;
DataBlock OtherBlock = null;
f.SeekLock.WaitOne();
f.fstream.Seek(OFFSET+2,SeekOrigin.Begin);
Interlocked.Increment(ref PendingWrites);
f.fstream.BeginWrite(keysize,0,2,CB,Tag);
Interlocked.Increment(ref PendingWrites);
f.fstream.BeginWrite(key,0,key.Length,CB,Tag);
if(key.Length + 8 < f.MaxBlockSize)
{
// Can fit data here
if(DataBuffer.Length>(f.MaxBlockSize-key.Length-8))
{
DataWrite = f.MaxBlockSize-key.Length-8;
}
else
{
DataWrite = DataBuffer.Length;
}
Interlocked.Increment(ref PendingWrites);
f.fstream.BeginWrite(DataBuffer,0,DataWrite,CB,Tag);
DataWritten += DataWrite;
DataIDX += DataWrite;
Fill = new Byte[(int)f.MaxBlockSize-(DataWrite+key.Length)-8];
if(Fill.Length>0)
{
Interlocked.Increment(ref PendingWrites);
f.fstream.BeginWrite(Fill,0,Fill.Length,CB,Tag);
}
BlockSize = BitConverter.GetBytes((short)(DataWrite + key.Length));
}
else
{
BlockSize = BitConverter.GetBytes((short)key.Length);
}
f.fstream.Seek((long)OFFSET,SeekOrigin.Begin);
Interlocked.Increment(ref PendingWrites);
f.fstream.BeginWrite(BlockSize,0,2,CB,Tag);
if(DataBuffer.Length-DataWrite==0)
{
// No need for more packets;
NextBlock = BitConverter.GetBytes((int)-1);
f.fstream.Seek((long)OFFSET + (long)(f.MaxBlockSize-4),SeekOrigin.Begin);
Interlocked.Increment(ref PendingWrites);
f.fstream.BeginWrite(NextBlock,0,4,CB,Tag);
f.SeekLock.ReleaseMutex();
if(Interlocked.Decrement(ref PendingWrites)==0)
{
if(OnWrite!=null) OnWrite(this,Tag);
}
return;
}
// Need More Blocks
keysize = BitConverter.GetBytes((short)0);
f.SeekLock.ReleaseMutex();
while(DataBuffer.Length-DataWritten!=0)
{
OtherBlock = f.GetFreeBlock();
NextBlock = BitConverter.GetBytes(OtherBlock.OFFSET);
f.SeekLock.WaitOne();
f.fstream.Seek((long)OFFSET+(long)(f.MaxBlockSize-4),SeekOrigin.Begin);
Interlocked.Increment(ref PendingWrites);
f.fstream.BeginWrite(NextBlock,0,4,CB,Tag);
OFFSET = OtherBlock.OFFSET;
f.fstream.Seek((long)OFFSET+2,SeekOrigin.Begin);
Interlocked.Increment(ref PendingWrites);
f.fstream.BeginWrite(keysize,0,2,CB,Tag);
if(DataBuffer.Length-DataWritten>(int)(f.MaxBlockSize-8))
{
DataWrite = f.MaxBlockSize-8;
}
else
{
DataWrite = DataBuffer.Length-DataWritten;
}
Interlocked.Increment(ref PendingWrites);
f.fstream.BeginWrite(DataBuffer,DataIDX,DataWrite,CB,Tag);
DataWritten += DataWrite;
DataIDX += DataWrite;
Fill = new byte[(int)f.MaxBlockSize-DataWrite-8];
if(Fill.Length>0)
{
Interlocked.Increment(ref PendingWrites);
f.fstream.BeginWrite(Fill,0,Fill.Length,CB,Tag);
}
BlockSize = BitConverter.GetBytes((short)DataWrite);
f.fstream.Seek((long)OFFSET,SeekOrigin.Begin);
Interlocked.Increment(ref PendingWrites);
f.fstream.BeginWrite(BlockSize,0,2,CB,Tag);
if(DataBuffer.Length-DataWritten==0)
{
f.fstream.Seek((long)OFFSET+(long)(f.MaxBlockSize-4),SeekOrigin.Begin);
NextBlock = BitConverter.GetBytes((int)-1);
Interlocked.Increment(ref PendingWrites);
f.fstream.BeginWrite(NextBlock,0,4,CB,Tag);
}
f.SeekLock.ReleaseMutex();
}
if(Interlocked.Decrement(ref PendingWrites)==0)
{
if(OnWrite!=null) OnWrite(this,Tag);
}
}
internal DataBlock(FileHashDB READER_sender, int offset, OnReadHandler rCB, object Tag)
{
OnRead += rCB;
_Tag = Tag;
CB = new AsyncCallback(ReadBlockSink);
f = READER_sender;
f.SeekLock.WaitOne();
f.fstream.Seek((long)offset,SeekOrigin.Begin);
f.fstream.BeginRead(buffer,0,512,CB,offset);
f.SeekLock.ReleaseMutex();
}
private void WriteBlockSink(IAsyncResult result)
{
f.fstream.EndWrite(result);
if(Interlocked.Decrement(ref PendingWrites)==0)
{
if(this.OnWrite!=null) OnWrite(this,result.AsyncState);
}
}
private void ReadBlockSink(IAsyncResult result)
{
f.fstream.EndRead(result);
int offset = (int)result.AsyncState;
short BlockSize = BitConverter.ToInt16(buffer,0);
int NextBlock = BitConverter.ToInt32(buffer,f.MaxBlockSize-4);
short KeySize = BitConverter.ToInt16(buffer,2);
if(KeySize!=0)
{
UTF8Encoding U = new UTF8Encoding();
KEY = U.GetString(buffer,4,KeySize);
}
mstream.Write(buffer,4+KeySize,(int)BlockSize-(int)KeySize);
if(NextBlock!=-1)
{
f.SeekLock.WaitOne();
f.fstream.Seek((long)NextBlock,SeekOrigin.Begin);
f.fstream.BeginRead(buffer,0,512,CB,NextBlock);
f.SeekLock.ReleaseMutex();
}
else
{
mstream.Flush();
if(this.OnRead!=null) OnRead(this,KEY,mstream.ToArray(),_Tag);
}
}
}
}
| |
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2004 Scott Willeke (http://scott.willeke.com)
//
// Authors:
// Scott Willeke (scott@willeke.com)
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Threading;
using LessMsi.OleStorage;
using LibMSPackN;
using Microsoft.Tools.WindowsInstallerXml.Msi;
using LessIO;
using Path = LessIO.Path;
namespace LessMsi.Msi
{
public class Wixtracts
{
#region class ExtractionProgress
/// <summary>
/// Provides progress information during an extraction operatation.
/// </summary>
public class ExtractionProgress : IAsyncResult
{
private string _currentFileName;
private ExtractionActivity _activity;
private readonly ManualResetEvent _waitSignal;
private readonly AsyncCallback _callback;
private readonly int _totalFileCount;
private int _filesExtracted;
public ExtractionProgress(AsyncCallback progressCallback, int totalFileCount)
{
_activity = ExtractionActivity.Initializing;
_currentFileName = "";
_callback = progressCallback;
_waitSignal = new ManualResetEvent(false);
_totalFileCount = totalFileCount;
_filesExtracted = 0;
}
internal void ReportProgress(ExtractionActivity activity, string currentFileName, int filesExtractedSoFar)
{
lock (this)
{
_activity = activity;
_currentFileName = currentFileName;
_filesExtracted = filesExtractedSoFar;
if (this.IsCompleted)
_waitSignal.Set();
if (_callback != null)
_callback(this);
}
}
/// <summary>
/// The total number of files to be extracted for this operation.
/// </summary>
public int TotalFileCount
{
get
{
lock (this)
{
return _totalFileCount;
}
}
}
/// <summary>
/// The number of files extracted so far
/// </summary>
public int FilesExtractedSoFar
{
get
{
lock (this)
{
return _filesExtracted;
}
}
}
/// <summary>
/// If <see cref="Activity"/> is <see cref="ExtractionActivity.ExtractingFile"/>, specifies the name of the file being extracted.
/// </summary>
public string CurrentFileName
{
get
{
lock (this)
{
return _currentFileName;
}
}
}
/// <summary>
/// Specifies the current activity.
/// </summary>
public ExtractionActivity Activity
{
get
{
lock (this)
{
return _activity;
}
}
}
#region IAsyncResult Members
object IAsyncResult.AsyncState
{
get
{
lock (this)
{
return this;
}
}
}
bool IAsyncResult.CompletedSynchronously
{
get
{
lock (this)
{
return false;
}
}
}
public WaitHandle AsyncWaitHandle
{
get
{
lock (this)
{
return _waitSignal;
}
}
}
public bool IsCompleted
{
get
{
lock (this)
{
return this.Activity == ExtractionActivity.Complete;
}
}
}
#endregion
}
#endregion
#region enum ExtractionActivity
/// <summary>
/// Specifies the differernt available activities.
/// </summary>
public enum ExtractionActivity
{
Initializing,
Uncompressing,
ExtractingFile,
Complete
}
#endregion
public static void ExtractFiles(Path msi, string outputDir)
{
ExtractFiles(msi, outputDir, new string[0], null);
}
public static void ExtractFiles(Path msi, string outputDir, string[] fileNamesToExtract)
{
var msiFiles = GetMsiFileFromFileNames(msi, fileNamesToExtract);
ExtractFiles(msi, outputDir, msiFiles, null);
}
public static void ExtractFiles(Path msi, string outputDir, string[] fileNamesToExtract, AsyncCallback progressCallback)
{
var msiFiles = GetMsiFileFromFileNames(msi, fileNamesToExtract);
ExtractFiles(msi, outputDir, msiFiles, progressCallback);
}
private static MsiFile[] GetMsiFileFromFileNames(Path msi, string[] fileNamesToExtract)
{
var msiFiles = MsiFile.CreateMsiFilesFromMSI(msi);
Array.Sort(msiFiles, (f1, f2) => string.Compare(f1.LongFileName, f2.LongFileName, StringComparison.InvariantCulture));
var fileNamesToExtractAsMsiFiles = new List<MsiFile>();
foreach (var fileName in fileNamesToExtract)
{
var found = Array.BinarySearch(msiFiles, fileName, FileNameComparer.Default);
if (found >= 0)
fileNamesToExtractAsMsiFiles.Add(msiFiles[found]);
else
Console.WriteLine("File {0} was not found in the msi.", fileName);
}
return fileNamesToExtractAsMsiFiles.ToArray();
}
private sealed class FileNameComparer : IComparer
{
static readonly FileNameComparer _default = new FileNameComparer();
public static FileNameComparer Default
{
get { return _default; }
}
int IComparer.Compare(object x, object y)
{
//expect two MsiFile or one MsiFile and one string:
var getName = new Func<object, string>((object fileOrName) => fileOrName is MsiFile ? ((MsiFile) fileOrName).LongFileName : (string)fileOrName);
var xName = getName(x);
var yName = getName(y);
return string.Compare(xName, yName, StringComparison.InvariantCulture);
}
}
/// <summary>
/// Extracts the compressed files from the specified MSI file to the specified output directory.
/// If specified, the list of <paramref name="filesToExtract"/> objects are the only files extracted.
/// </summary>
/// <param name="filesToExtract">The files to extract or null or empty to extract all files.</param>
/// <param name="progressCallback">Will be called during during the operation with progress information, and upon completion. The argument will be of type <see cref="ExtractionProgress"/>.</param>
public static void ExtractFiles(Path msi, string outputDir, MsiFile[] filesToExtract, AsyncCallback progressCallback)
{
if (msi.IsEmpty)
throw new ArgumentNullException("msi");
if (string.IsNullOrEmpty(outputDir))
throw new ArgumentNullException("outputDir");
int filesExtractedSoFar = 0;
//Refrence on Embedding files: https://msdn.microsoft.com/en-us/library/aa369279.aspx
ExtractionProgress progress = null;
Database msidb = new Database(msi.PathString, OpenDatabase.ReadOnly);
try
{
if (filesToExtract == null || filesToExtract.Length < 1)
filesToExtract = MsiFile.CreateMsiFilesFromMSI(msidb);
progress = new ExtractionProgress(progressCallback, filesToExtract.Length);
if (!FileSystem.Exists(msi))
{
Trace.WriteLine("File \'" + msi + "\' not found.");
progress.ReportProgress(ExtractionActivity.Complete, "", filesExtractedSoFar);
return;
}
progress.ReportProgress(ExtractionActivity.Initializing, "", filesExtractedSoFar);
var outputDirPath = new Path(outputDir);
if (!FileSystem.Exists(outputDirPath)) {
FileSystem.CreateDirectory(outputDirPath);
}
//map short file names to the msi file entry
var fileEntryMap = new Dictionary<string, MsiFile>(filesToExtract.Length, StringComparer.InvariantCulture);
foreach (var fileEntry in filesToExtract)
{
MsiFile existingFile = null;
if (fileEntryMap.TryGetValue(fileEntry.File, out existingFile))
{ //NOTE: This used to be triggered when we ignored case of file, but now we don't ignore case so this is unlikely to occur.
// Differing only by case is not compliant with the msi specification but some installers do it (e.g. python, see issue 28).
Debug.Print("!!Found duplicate file using key {0}. The existing key was {1}", fileEntry.File, existingFile.File);
}
else
{
fileEntryMap.Add(fileEntry.File, fileEntry);
}
}
Debug.Assert(fileEntryMap.Count == filesToExtract.Length, "Duplicate files must have caused some files to not be in the map.");
var cabInfos = CabsFromMsiToDisk(msi, msidb, outputDir);
var cabDecompressors = MergeCabs(cabInfos);
try
{
foreach (MSCabinet decompressor in cabDecompressors)
{
foreach (var compressedFile in decompressor.GetFiles())
{
// if the user didn't select this in the UI for extraction, skip it.
if (!fileEntryMap.ContainsKey(compressedFile.Filename))
continue;
var entry = fileEntryMap[compressedFile.Filename];
progress.ReportProgress(ExtractionActivity.ExtractingFile, entry.LongFileName, filesExtractedSoFar);
string targetDirectoryForFile = GetTargetDirectory(outputDir, entry.Directory);
LessIO.Path destName = LessIO.Path.Combine(targetDirectoryForFile, entry.LongFileName);
if (FileSystem.Exists(destName))
{
Debug.Fail(string.Format("output file '{0}' already exists. We'll make it unique, but this is probably a strange msi or a bug in this program.", destName));
//make unique
// ReSharper disable HeuristicUnreachableCode
Trace.WriteLine(string.Concat("Duplicate file found \'", destName, "\'"));
int duplicateCount = 0;
Path uniqueName;
do
{
uniqueName = new Path(destName + "." + "duplicate" + ++duplicateCount);
} while (FileSystem.Exists(uniqueName));
destName = uniqueName;
// ReSharper restore HeuristicUnreachableCode
}
Trace.WriteLine(string.Concat("Extracting File \'", compressedFile.Filename, "\' to \'", destName, "\'"));
compressedFile.ExtractTo(destName.PathString);
filesExtractedSoFar++;
}
}
}
finally
{ //cleanup the decompressors allocated in MergeCabs
foreach (var decomp in cabDecompressors)
{
decomp.Close(false);
}
// also delete any cabs we copied:
foreach (var cabInf in cabInfos)
{
if (cabInf.DoesNeedDeleted)
{
DeleteFileForcefully(new Path(cabInf.LocalCabFile));
}
}
}
}
finally
{
if (msidb != null)
msidb.Close();
if (progress != null)
progress.ReportProgress(ExtractionActivity.Complete, "", filesExtractedSoFar);
}
}
/// <summary>
/// Deletes a file even if it is readonly.
/// </summary>
private static void DeleteFileForcefully(Path localFilePath)
{
// In github issue #4 found that the cab files in the Win7SDK have the readonly attribute set and File.Delete fails to delete them. Explicitly unsetting that bit before deleting works okay...
FileSystem.RemoveFile(localFilePath, true);
}
/// <summary>
/// Allocates a decompressor for each cab and merges any cabs that need merged.
/// </summary>
/// <param name="cabinets"></param>
/// <returns></returns>
private static IEnumerable<MSCabinet> MergeCabs(IList<CabInfo> cabInfos)
{
/* Sometimes cab files are part of a set. We must merge those into their set before we leave here.
* Otherwise extracting a file that extends beyond the bounds of one cab in the set will fail. This happens in VBRuntime.msi
*
* It can be determined if a cabinet has further parts to load by examining the mscabd_cabinet::flags field:
* if (flags & MSCAB_HDR_PREVCAB) is non-zero, there is a predecessor cabinet to open() and prepend(). Its MS-DOS case-insensitive filename is mscabd_cabinet::prevname
* if (flags & MSCAB_HDR_NEXTCAB) is non-zero, there is a successor cabinet to open() and append(). Its MS-DOS case-insensitive filename is mscabd_cabinet::nextname
*/
var decompressors = new List<MSCabinet>();
for (int i=0; i < cabInfos.Count; i++)
{
CabInfo cab = cabInfos[i];
MSCabinet msCab = null;
try
{
msCab = new MSCabinet(cab.LocalCabFile); // NOTE: Deliberately not disposing. Caller must cleanup.
}
catch (Exception)
{
// As seen in https://github.com/activescott/lessmsi/issues/104, sometimes bogus cabs are inside of a msi but they're not needed to extract any files from. So we should attempt to ignore this failure here:
Debug.Fail(
string.Format("Cab name \"{0}\" could not be read by cab reader. Will attempt to ignore...", cab.CabSourceName)
);
continue;
}
if ((msCab.Flags & MSCabinetFlags.MSCAB_HDR_NEXTCAB) != 0)
{
Debug.Assert(!string.IsNullOrEmpty(msCab.NextName), "Header indcates next cab but new cab not found.");
// load the cab found in NextName:
// Append it to msCab
Debug.Print("Found cabinet set. Nextname: " + msCab.NextName);
var nextCab = FindCabAndRemoveFromList(cabInfos, msCab.NextName);
var msCabNext = new MSCabinet(nextCab.LocalCabFile);
msCab.Append(msCabNext);
decompressors.Add(msCab);
}
else if ((msCab.Flags & MSCabinetFlags.MSCAB_HDR_PREVCAB) != 0)
{
Debug.Assert(!string.IsNullOrEmpty(msCab.PrevName), "Header indcates prev cab but new cab not found.");
Debug.Print("Found cabinet set. PrevName: " + msCab.PrevName);
var prevCabInfo = FindCabAndRemoveFromList(cabInfos, msCab.PrevName);
var msCabPrev = new MSCabinet(prevCabInfo.LocalCabFile);
msCabPrev.Append(msCab);
decompressors.Add(msCabPrev);
}
else
{ // just a simple standalone cab
decompressors.Add(msCab);
}
}
return decompressors;
}
private static CabInfo FindCabAndRemoveFromList(IList<CabInfo> cabInfos, string soughtName)
{
for (var i = 0; i < cabInfos.Count; i++)
{
if (string.Equals(cabInfos[i].CabSourceName, soughtName, StringComparison.InvariantCultureIgnoreCase))
{
var found = cabInfos[i];
cabInfos.RemoveAt(i);
return found;
}
}
throw new Exception("Specified cab not found!");
}
private static string GetTargetDirectory(string rootDirectory, MsiDirectory relativePath)
{
LessIO.Path fullPath = LessIO.Path.Combine(rootDirectory, relativePath.GetPath());
if (!FileSystem.Exists(fullPath))
{
FileSystem.CreateDirectory(fullPath);
}
return fullPath.PathString;
}
/// <summary>
/// Extracts cab files from the specified MSIDB and puts them in the specified outputdir.
/// </summary>
/// <param name="msidb"></param>
/// <param name="outputDir"></param>
/// <returns></returns>
private static List<CabInfo> CabsFromMsiToDisk(Path msi, Database msidb, string outputDir)
{
const string query = "SELECT * FROM `Media`";
var localCabFiles = new List<CabInfo>();
using (View view = msidb.OpenExecuteView(query))
{
Record record;
while (view.Fetch(out record))
{
using (record)
{
const int MsiInterop_Media_Cabinet = 4;
string cabSourceName = record[MsiInterop_Media_Cabinet];
if (string.IsNullOrEmpty(cabSourceName))
{
Debug.Print("Empty Cabinet value in Media table. This happens, but it's rare and it's weird!");
//Debug.Fail("Couldn't find media CAB file inside the MSI (bad media table?).");
continue;
}
if (!string.IsNullOrEmpty(cabSourceName))
{
bool extract = false;
bool doDeleteLater = true;
// NOTE: If the cabinet name is preceded by the number sign, the cabinet is stored as a data stream inside the package. https://docs.microsoft.com/en-us/windows/win32/msi/cabinet
if (cabSourceName.StartsWith("#"))
{
extract = true;
cabSourceName = cabSourceName.Substring(1);
}
Path localCabFile = Path.Combine(outputDir, cabSourceName);
if (extract)
{
// extract cabinet, then explode all of the files to a temp directory
ExtractCabFromPackage(localCabFile, cabSourceName, msidb, msi);
}
else
{
Path originalCabFile = Path.Combine(msi.Parent, cabSourceName);
if (!originalCabFile.Exists)
{
throw ExternalCabNotFoundException.CreateFromCabPath(cabSourceName, msi.Parent.FullPathString);
}
// In cases like https://github.com/activescott/lessmsi/issues/169 the cab file was originally an embedded cab but the user extracted the cab into the same directory as the MSI manually, so it may already be there
if (!originalCabFile.Equals(localCabFile)) {
FileSystem.Copy(originalCabFile, localCabFile);
} else {
doDeleteLater = false;
}
}
/* http://code.google.com/p/lessmsi/issues/detail?id=1
* apparently in some cases a file spans multiple CABs (VBRuntime.msi) so due to that we have get all CAB files out of the MSI and then begin extraction. Then after we extract everything out of all CAbs we need to release the CAB extractors and delete temp files.
* Thanks to Christopher Hamburg for explaining this!
*/
var c = new CabInfo(localCabFile.PathString, cabSourceName, doDeleteLater);
localCabFiles.Add(c);
}
}
}
}
return localCabFiles;
}
class CabInfo
{
/// <summary>
/// Name of the cab in the MSI.
/// </summary>
public string CabSourceName { get; set; }
/// <summary>
/// True if the cab needs deleted later.
/// </summary>
public bool DoesNeedDeleted { get; }
/// <summary>
/// Path of the CAB on local disk after we pop it out of the msi.
/// </summary>
public string LocalCabFile { get; set; } //TODO: Make LocalCabFile use LessIO.Path
public CabInfo(string localCabFile, string cabSourceName, bool doesNeedDeleted)
{
LocalCabFile = localCabFile;
CabSourceName = cabSourceName;
DoesNeedDeleted = doesNeedDeleted;
}
}
public static void ExtractCabFromPackage(Path destCabPath, string cabName, Database inputDatabase, LessIO.Path msiPath)
{
//NOTE: checking inputDatabase.TableExists("_Streams") here is not accurate. It reports that it doesn't exist at times when it is perfectly queryable. So we actually try it and look for a specific exception:
//NOTE: we do want to tryStreams. It is more reliable when available and AFAICT it always /should/ be there according to the docs but isn't.
const bool tryStreams = true;
if (tryStreams)
{
try
{
ExtractCabFromPackageTraditionalWay(destCabPath, cabName, inputDatabase);
// as long as TraditionalWay didn't throw, we'll leave it at that...
return;
}
catch (Exception e)
{
Debug.WriteLine("ExtractCabFromPackageTraditionalWay Exception: {0}", e);
// According to issue #78 (https://github.com/activescott/lessmsi/issues/78), WIX installers sometimes (always?)
// don't have _Streams table yet they still install. Since it appears that msi files generally (BUT NOT ALWAYS - see X86 Debuggers And Tools-x86_en-us.msi) will have only one cab file, we'll try to just find it in the sterams and use it instead:
Trace.WriteLine("MSI File has no _Streams table. Attempting alternate cab file extraction process...");
}
}
using (var stg = new OleStorageFile(msiPath))
{
// MSIs do exist with >1. If we use the ExtractCabFromPackageTraditionalWay (via _Streams table) then it handles that. If we are using this fallback approach, multiple cabs is a bad sign!
Debug.Assert(CountCabs(stg) == 1, string.Format("Expected 1 cab, but found {0}.", CountCabs(stg)));
foreach (var strm in stg.GetStreams())
{
using (var bits = strm.GetStream(FileMode.Open, FileAccess.Read))
{
if (OleStorageFile.IsCabStream(bits))
{
Trace.WriteLine(String.Format("Found CAB bits in stream. Assuming it is for cab {0}.", destCabPath));
Func<byte[], int> streamReader = destBuffer => bits.Read(destBuffer, 0, destBuffer.Length);
CopyStreamToFile(streamReader, destCabPath);
}
}
}
}
}
private static int CountCabs(OleStorageFile stg)
{
return stg.GetStreams().Count(strm => OleStorageFile.IsCabStream((StreamInfo) strm));
}
/// <summary>
/// Write the Cab to disk.
/// </summary>
/// <param name="destCabPath">Specifies the path to the file to contain the stream.</param>
/// <param name="cabName">Specifies the name of the file in the stream.</param>
/// <param name="inputDatabase">The MSI database to get cabs from.</param>
public static void ExtractCabFromPackageTraditionalWay(Path destCabPath, string cabName, Database inputDatabase)
{
using (View view = inputDatabase.OpenExecuteView(String.Concat("SELECT * FROM `_Streams` WHERE `Name` = '", cabName, "'")))
{
Record record;
if (view.Fetch(out record))
{
using (record)
{
Func<byte[], int> streamReader = destBuffer =>
{
const int msiInteropStoragesData = 2; //From wiX:Index to column name Data into Record for row in Msi Table Storages
var bytesWritten = record.GetStream(msiInteropStoragesData, destBuffer, destBuffer.Length);
return bytesWritten;
};
CopyStreamToFile(streamReader, destCabPath);
}
}
}
}
/// <summary>
/// Copies the Stream of bytes from the specified streamReader to the specified destination path.
/// </summary>
/// <param name="streamReader">
/// A callback like this:
/// int StreamReader(byte[] destBuffer)
/// The function should put bytes into the destBuffer and return the number of bytes written to the buffer.
/// </param>
/// <param name="destFile">The file to write the sreamReader's bits to.</param>
private static void CopyStreamToFile(Func<byte[], int> streamReader, Path destFile)
{
using (var writer = new BinaryWriter(FileSystem.CreateFile(destFile)))
{
var buf = new byte[1024 * 1024];
int bytesWritten;
do
{
bytesWritten = streamReader(buf);
if (bytesWritten > 0)
writer.Write(buf, 0, bytesWritten);
} while (bytesWritten > 0);
}
}
}
}
| |
/*************************************************************************
* Project: Dot Map
* Copyright: Shropshire Council (c) 2007
* Purpose: Class to provide access to the data in a convenient form.
* $Author: $
* $Date: 2009-12-10 11:02:25 +0000 (Thu, 10 Dec 2009) $
* $Revision: 92 $
* $HeadURL: https://sbp.svn.cloudforge.com/naturalshropshire/trunk/SCC.Modules.DotMap/Data/DotMapController.cs $
************************************************************************/
using System.Collections;
namespace SCC.Modules.DotMap.Data
{
///<summary>
/// The Controller class for the DotMap
/// </summary>
public class DotMapController//: ISearchable, IPortable
{
#region Constructors
public DotMapController()
{
}
#endregion
#region Public Methods
/// <summary>
/// Get a list of the species available on the module
/// </summary>
/// <param name="moduleId"></param>
/// <param name="EnglishName"></param>
/// <param name="LatinName"></param>
/// <returns></returns>
public ArrayList ListSpecies(int moduleId, string EnglishName, string LatinName)
{
return DotNetNuke.Common.Utilities.CBO.FillCollection(DataProvider.Instance().ListSpecies(moduleId, EnglishName, LatinName), typeof(InfoSighting));
}
/// <summary>
/// Get a list of the sightings of a given species (latin name).
/// </summary>
/// <param name="moduleId"></param>
/// <param name="latinName"></param>
/// <returns></returns>
public ArrayList ListSightings(int moduleId, string latinName)
{
return DotNetNuke.Common.Utilities.CBO.FillCollection(DataProvider.Instance().ListSightings(moduleId, latinName), typeof(InfoSightingLite));
}
/// <summary>
/// Delete all the sightings of a given species, this allows the map owner
/// to remove species that might be threatened somehow and to have complete
/// control over the data that is retained.
/// </summary>
/// <param name="moduleId"></param>
/// <param name="englishName"></param>
public void DeleteSightings(int moduleId, string latinName)
{
DataProvider.Instance().DeleteSightings(moduleId, latinName);
}
/// <summary>
/// Add an individual sighting to the database, the grid references
/// is tetradize both on the way in and the way out to ensure that no
/// detailed data if retained.
/// </summary>
/// <param name="objInfoSighting"></param>
public void AddSighting(InfoSighting objInfoSighting)
{
DataProvider.Instance().AddSighting(objInfoSighting.PortalId,
objInfoSighting.ModuleId, objInfoSighting.EnglishName, objInfoSighting.LatinName,
objInfoSighting.YearSeen, objInfoSighting.GridX, objInfoSighting.GridY);
}
/// <summary>
/// Get the species information for a particular tetrad, this is for one species
/// given in the latin name.
/// </summary>
/// <param name="LatinName"></param>
/// <param name="GridX"></param>
/// <param name="GridY"></param>
/// <returns></returns>
public InfoSighting SpeciesForTetrad(string LatinName, int GridX, int GridY)
{
return (InfoSighting)DotNetNuke.Common.Utilities.CBO.FillObject(DataProvider.Instance().SpeciesForTetrad(LatinName, GridX, GridY), typeof(InfoSighting));
}
public ArrayList ModuleList(int portalId)
{
return DotNetNuke.Common.Utilities.CBO.FillCollection(DataProvider.Instance().ModuleList(portalId), typeof(InfoModule));
}
public ArrayList ListSpeciesForTetrad(int GridX, int GridY, int moduleId)
{
return DotNetNuke.Common.Utilities.CBO.FillCollection(DataProvider.Instance().ListSpeciesForTetrad(GridX, GridY, moduleId), typeof(InfoSighting));
}
public ArrayList SpeciesLists(int portalId)
{
return DotNetNuke.Common.Utilities.CBO.FillCollection(DataProvider.Instance().SpeciesLists(portalId), typeof(InfoList));
}
public ArrayList SpeciesInListForTetrad(int portalId, int speciesListId, int gridX, int gridY)
{
return DotNetNuke.Common.Utilities.CBO.FillCollection(DataProvider.Instance().SpeciesInListForTetrad(portalId, speciesListId, gridX, gridY), typeof(InfoSighting));
}
public ArrayList ListTetrads(int portalId)
{
return DotNetNuke.Common.Utilities.CBO.FillCollection(DataProvider.Instance().ListTetrads(portalId), typeof(InfoPoint));
}
public string EnglishName(string LatinName)
{
return DataProvider.Instance().EnglishName(LatinName);
}
public string LatinName(string EnglishName)
{
return DataProvider.Instance().LatinName(EnglishName);
}
#endregion
#region Optional Interfaces
/*
/// -----------------------------------------------------------------------------
/// <summary>
/// GetSearchItems implements the ISearchable Interface
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="ModInfo">The ModuleInfo for the module to be Indexed</param>
/// <history>
/// </history>
/// -----------------------------------------------------------------------------
public SearchItemInfoCollection GetSearchItems(ModuleInfo ModInfo)
{
SearchItemInfoCollection SearchItemCollection = new SearchItemInfoCollection();
List<DotMapInfo> colDotMaps = GetDotMaps(ModInfo.ModuleID);
foreach (DotMapInfo objDotMap in colDotMaps)
{
if (objDotMap != null)
{
SearchItemInfo SearchItem = new SearchItemInfo(ModInfo.ModuleTitle, objDotMap.Content, objDotMap.CreatedByUser, objDotMap.CreatedDate, ModInfo.ModuleID, objDotMap.ItemId.ToString(), objDotMap.Content, "ItemId=" + objDotMap.ItemId.ToString());
SearchItemCollection.Add(SearchItem);
}
}
return SearchItemCollection;
}
/// -----------------------------------------------------------------------------
/// <summary>
/// ExportModule implements the IPortable ExportModule Interface
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="ModuleID">The Id of the module to be exported</param>
/// <history>
/// </history>
/// -----------------------------------------------------------------------------
public string ExportModule(int ModuleID)
{
string strXML = "";
List<DotMapInfo> colDotMaps = GetDotMaps(ModuleID);
if (colDotMaps.Count != 0)
{
strXML += "<DotMaps>";
foreach (DotMapInfo objDotMap in colDotMaps)
{
strXML += "<DotMap>";
strXML += "<content>" + XmlUtils.XMLEncode(objDotMap.Content) + "</content>";
strXML += "</DotMap>";
}
strXML += "</DotMaps>";
}
return strXML;
}
/// -----------------------------------------------------------------------------
/// <summary>
/// ImportModule implements the IPortable ImportModule Interface
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="ModuleID">The Id of the module to be imported</param>
/// <param name="Content">The content to be imported</param>
/// <param name="Version">The version of the module to be imported</param>
/// <param name="UserId">The Id of the user performing the import</param>
/// <history>
/// </history>
/// -----------------------------------------------------------------------------
public void ImportModule(int ModuleID, string Content, string Version, int UserId)
{
XmlNode xmlDotMaps = Globals.GetContent(Content, "DotMaps");
foreach (XmlNode xmlDotMap in xmlDotMaps.SelectNodes("DotMap"))
{
DotMapInfo objDotMap = new DotMapInfo();
objDotMap.ModuleId = ModuleID;
objDotMap.Content = xmlDotMap.SelectSingleNode("content").InnerText;
objDotMap.CreatedByUser = UserId;
AddDotMap(objDotMap);
}
}
*/
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Activities
{
using System;
using System.Activities.Runtime;
using System.Diagnostics.CodeAnalysis;
using System.Runtime;
using System.Runtime.Serialization;
using System.Transactions;
[Fx.Tag.XamlVisible(false)]
[DataContract]
public sealed class RuntimeTransactionHandle : Handle, IExecutionProperty, IPropertyRegistrationCallback
{
ActivityExecutor executor;
bool isHandleInitialized;
bool doNotAbort;
bool isPropertyRegistered;
bool isSuppressed;
TransactionScope scope;
Transaction rootTransaction;
public RuntimeTransactionHandle()
{
}
// This ctor is used when we want to make a transaction ambient
// without enlisting. This is desirable for scenarios like WorkflowInvoker
public RuntimeTransactionHandle(Transaction rootTransaction)
{
if (rootTransaction == null)
{
throw FxTrace.Exception.ArgumentNull("rootTransaction");
}
this.rootTransaction = rootTransaction;
this.AbortInstanceOnTransactionFailure = false;
}
public bool AbortInstanceOnTransactionFailure
{
get
{
return !this.doNotAbort;
}
set
{
ThrowIfRegistered(SR.CannotChangeAbortInstanceFlagAfterPropertyRegistration);
this.doNotAbort = !value;
}
}
public bool SuppressTransaction
{
get
{
return this.isSuppressed;
}
set
{
ThrowIfRegistered(SR.CannotSuppressAlreadyRegisteredHandle);
this.isSuppressed = value;
}
}
[DataMember(Name = "executor")]
internal ActivityExecutor SerializedExecutor
{
get { return this.executor; }
set { this.executor = value; }
}
[DataMember(EmitDefaultValue = false, Name = "isHandleInitialized")]
internal bool SerializedIsHandleInitialized
{
get { return this.isHandleInitialized; }
set { this.isHandleInitialized = value; }
}
[DataMember(EmitDefaultValue = false, Name = "doNotAbort")]
internal bool SerializedDoNotAbort
{
get { return this.doNotAbort; }
set { this.doNotAbort = value; }
}
[DataMember(EmitDefaultValue = false, Name = "isPropertyRegistered")]
internal bool SerializedIsPropertyRegistered
{
get { return this.isPropertyRegistered; }
set { this.isPropertyRegistered = value; }
}
[DataMember(EmitDefaultValue = false, Name = "isSuppressed")]
internal bool SerializedIsSuppressed
{
get { return this.isSuppressed; }
set { this.isSuppressed = value; }
}
internal bool IsRuntimeOwnedTransaction
{
get { return this.rootTransaction != null; }
}
void ThrowIfRegistered(string message)
{
if (this.isPropertyRegistered)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(message));
}
}
void ThrowIfNotRegistered(string message)
{
if (!this.isPropertyRegistered)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(message));
}
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.ConsiderPassingBaseTypesAsParameters,
Justification = "This method is designed to be called from activities with handle access.")]
public Transaction GetCurrentTransaction(NativeActivityContext context)
{
return GetCurrentTransactionCore(context);
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.ConsiderPassingBaseTypesAsParameters,
Justification = "This method is designed to be called from activities with handle access.")]
public Transaction GetCurrentTransaction(CodeActivityContext context)
{
return GetCurrentTransactionCore(context);
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.ConsiderPassingBaseTypesAsParameters,
Justification = "This method is designed to be called from activities with handle access.")]
public Transaction GetCurrentTransaction(AsyncCodeActivityContext context)
{
return GetCurrentTransactionCore(context);
}
Transaction GetCurrentTransactionCore(ActivityContext context)
{
if (context == null)
{
throw FxTrace.Exception.ArgumentNull("context");
}
context.ThrowIfDisposed();
//If the transaction is a runtime transaction (i.e. an Invoke with ambient transaction case), then
//we do not require that it be registered since the handle created for the root transaction is never registered.
if (this.rootTransaction == null)
{
this.ThrowIfNotRegistered(SR.RuntimeTransactionHandleNotRegisteredAsExecutionProperty("GetCurrentTransaction"));
}
if (!this.isHandleInitialized)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.UnInitializedRuntimeTransactionHandle));
}
if (this.SuppressTransaction)
{
return null;
}
return this.executor.CurrentTransaction;
}
protected override void OnInitialize(HandleInitializationContext context)
{
this.executor = context.Executor;
this.isHandleInitialized = true;
if (this.rootTransaction != null)
{
Fx.Assert(this.Owner == null, "this.rootTransaction should only be set at the root");
this.executor.SetTransaction(this, this.rootTransaction, null, null);
}
base.OnInitialize(context);
}
protected override void OnUninitialize(HandleInitializationContext context)
{
if (this.rootTransaction != null)
{
// If we have a host transaction we're responsible for exiting no persist
this.executor.ExitNoPersist();
}
this.isHandleInitialized = false;
base.OnUninitialize(context);
}
public void RequestTransactionContext(NativeActivityContext context, Action<NativeActivityTransactionContext, object> callback, object state)
{
RequestOrRequireTransactionContextCore(context, callback, state, false);
}
public void RequireTransactionContext(NativeActivityContext context, Action<NativeActivityTransactionContext, object> callback, object state)
{
RequestOrRequireTransactionContextCore(context, callback, state, true);
}
void RequestOrRequireTransactionContextCore(NativeActivityContext context, Action<NativeActivityTransactionContext, object> callback, object state, bool isRequires)
{
if (context == null)
{
throw FxTrace.Exception.ArgumentNull("context");
}
context.ThrowIfDisposed();
if (context.HasRuntimeTransaction)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.RuntimeTransactionAlreadyExists));
}
if (context.IsInNoPersistScope)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.CannotSetRuntimeTransactionInNoPersist));
}
if (!this.isHandleInitialized)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.UnInitializedRuntimeTransactionHandle));
}
if (this.SuppressTransaction)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.RuntimeTransactionIsSuppressed));
}
if (isRequires)
{
if (context.RequiresTransactionContextWaiterExists)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.OnlyOneRequireTransactionContextAllowed));
}
this.ThrowIfNotRegistered(SR.RuntimeTransactionHandleNotRegisteredAsExecutionProperty("RequireTransactionContext"));
}
else
{
this.ThrowIfNotRegistered(SR.RuntimeTransactionHandleNotRegisteredAsExecutionProperty("RequestTransactionContext"));
}
context.RequestTransactionContext(isRequires, this, callback, state);
}
public void CompleteTransaction(NativeActivityContext context)
{
CompleteTransactionCore(context, null);
}
public void CompleteTransaction(NativeActivityContext context, BookmarkCallback callback)
{
if (callback == null)
{
throw FxTrace.Exception.ArgumentNull("callback");
}
CompleteTransactionCore(context, callback);
}
void CompleteTransactionCore(NativeActivityContext context, BookmarkCallback callback)
{
context.ThrowIfDisposed();
if (this.rootTransaction != null)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.CannotCompleteRuntimeOwnedTransaction));
}
if (!context.HasRuntimeTransaction)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.NoRuntimeTransactionExists));
}
if (!this.isHandleInitialized)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.UnInitializedRuntimeTransactionHandle));
}
if (this.SuppressTransaction)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.RuntimeTransactionIsSuppressed));
}
context.CompleteTransaction(this, callback);
}
[Fx.Tag.Throws(typeof(TransactionException), "The transaction for this property is in a state incompatible with TransactionScope.")]
void IExecutionProperty.SetupWorkflowThread()
{
if (this.SuppressTransaction)
{
this.scope = new TransactionScope(TransactionScopeOption.Suppress);
return;
}
if ((this.executor != null) && this.executor.HasRuntimeTransaction)
{
this.scope = TransactionHelper.CreateTransactionScope(this.executor.CurrentTransaction);
}
}
void IExecutionProperty.CleanupWorkflowThread()
{
TransactionHelper.CompleteTransactionScope(ref this.scope);
}
void IPropertyRegistrationCallback.Register(RegistrationContext context)
{
if (!this.isHandleInitialized)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.UnInitializedRuntimeTransactionHandle));
}
RuntimeTransactionHandle handle = (RuntimeTransactionHandle)context.FindProperty(typeof(RuntimeTransactionHandle).FullName);
if (handle != null)
{
if (handle.SuppressTransaction)
{
this.isSuppressed = true;
}
}
this.isPropertyRegistered = true;
}
void IPropertyRegistrationCallback.Unregister(RegistrationContext context)
{
this.isPropertyRegistered = false;
}
}
}
| |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.14.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Google Apps Script Execution API Version v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://developers.google.com/apps-script/execution/rest/v1/scripts/run'>Google Apps Script Execution API</a>
* <tr><th>API Version<td>v1
* <tr><th>API Rev<td>20160801 (578)
* <tr><th>API Docs
* <td><a href='https://developers.google.com/apps-script/execution/rest/v1/scripts/run'>
* https://developers.google.com/apps-script/execution/rest/v1/scripts/run</a>
* <tr><th>Discovery Name<td>script
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Google Apps Script Execution API can be found at
* <a href='https://developers.google.com/apps-script/execution/rest/v1/scripts/run'>https://developers.google.com/apps-script/execution/rest/v1/scripts/run</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.Script.v1
{
/// <summary>The Script Service.</summary>
public class ScriptService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public ScriptService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public ScriptService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
scripts = new ScriptsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "script"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://script.googleapis.com/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return ""; }
}
/// <summary>Available OAuth 2.0 scopes for use with the Google Apps Script Execution API.</summary>
public class Scope
{
/// <summary>View and manage your mail</summary>
public static string MailGoogleCom = "https://mail.google.com/";
/// <summary>Manage your calendars</summary>
public static string WwwGoogleComCalendarFeeds = "https://www.google.com/calendar/feeds";
/// <summary>Manage your contacts</summary>
public static string WwwGoogleComM8Feeds = "https://www.google.com/m8/feeds";
/// <summary>View and manage the provisioning of groups on your domain</summary>
public static string AdminDirectoryGroup = "https://www.googleapis.com/auth/admin.directory.group";
/// <summary>View and manage the provisioning of users on your domain</summary>
public static string AdminDirectoryUser = "https://www.googleapis.com/auth/admin.directory.user";
/// <summary>View and manage the files in your Google Drive</summary>
public static string Drive = "https://www.googleapis.com/auth/drive";
/// <summary>View and manage your forms in Google Drive</summary>
public static string Forms = "https://www.googleapis.com/auth/forms";
/// <summary>View and manage forms that this application has been installed in</summary>
public static string FormsCurrentonly = "https://www.googleapis.com/auth/forms.currentonly";
/// <summary>View and manage your Google Groups</summary>
public static string Groups = "https://www.googleapis.com/auth/groups";
/// <summary>View and manage your spreadsheets in Google Drive</summary>
public static string Spreadsheets = "https://www.googleapis.com/auth/spreadsheets";
/// <summary>View your email address</summary>
public static string UserinfoEmail = "https://www.googleapis.com/auth/userinfo.email";
}
private readonly ScriptsResource scripts;
/// <summary>Gets the Scripts resource.</summary>
public virtual ScriptsResource Scripts
{
get { return scripts; }
}
}
///<summary>A base abstract class for Script requests.</summary>
public abstract class ScriptBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new ScriptBaseServiceRequest instance.</summary>
protected ScriptBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Xgafv { get; set; }
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Alt { get; set; }
/// <summary>OAuth bearer token.</summary>
[Google.Apis.Util.RequestParameterAttribute("bearer_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string BearerToken { get; set; }
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Pretty-print response.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("pp", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> Pp { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes Script parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"bearer_token", new Google.Apis.Discovery.Parameter
{
Name = "bearer_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pp", new Google.Apis.Discovery.Parameter
{
Name = "pp",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "scripts" collection of methods.</summary>
public class ScriptsResource
{
private const string Resource = "scripts";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ScriptsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Runs a function in an Apps Script project that has been deployed for use with the Apps Script
/// Execution API. This method requires authorization with an OAuth 2.0 token that includes at least one of the
/// scopes listed in the [Authentication](#authentication) section; script projects that do not require
/// authorization cannot be executed through this API. To find the correct scopes to include in the
/// authentication token, open the project in the script editor, then select **File > Project properties** and
/// click the **Scopes** tab.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="scriptId">The project key of the script to be executed. To find the project key, open the project in
/// the script editor, then select **File > Project properties**.</param>
public virtual RunRequest Run(Google.Apis.Script.v1.Data.ExecutionRequest body, string scriptId)
{
return new RunRequest(service, body, scriptId);
}
/// <summary>Runs a function in an Apps Script project that has been deployed for use with the Apps Script
/// Execution API. This method requires authorization with an OAuth 2.0 token that includes at least one of the
/// scopes listed in the [Authentication](#authentication) section; script projects that do not require
/// authorization cannot be executed through this API. To find the correct scopes to include in the
/// authentication token, open the project in the script editor, then select **File > Project properties** and
/// click the **Scopes** tab.</summary>
public class RunRequest : ScriptBaseServiceRequest<Google.Apis.Script.v1.Data.Operation>
{
/// <summary>Constructs a new Run request.</summary>
public RunRequest(Google.Apis.Services.IClientService service, Google.Apis.Script.v1.Data.ExecutionRequest body, string scriptId)
: base(service)
{
ScriptId = scriptId;
Body = body;
InitParameters();
}
/// <summary>The project key of the script to be executed. To find the project key, open the project in the
/// script editor, then select **File > Project properties**.</summary>
[Google.Apis.Util.RequestParameterAttribute("scriptId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string ScriptId { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Script.v1.Data.ExecutionRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "run"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/scripts/{scriptId}:run"; }
}
/// <summary>Initializes Run parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"scriptId", new Google.Apis.Discovery.Parameter
{
Name = "scriptId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.Script.v1.Data
{
/// <summary>An object that provides information about the nature of an error in the Apps Script Execution API. If
/// an `run` call succeeds but the script function (or Apps Script itself) throws an exception, the response body's
/// `error` field will contain a `Status` object. The `Status` object's `details` field will contain an array with a
/// single one of these `ExecutionError` objects.</summary>
public class ExecutionError : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The error message thrown by Apps Script, usually localized into the user's language.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("errorMessage")]
public virtual string ErrorMessage { get; set; }
/// <summary>The error type, for example `TypeError` or `ReferenceError`. If the error type is unavailable, this
/// field is not included.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("errorType")]
public virtual string ErrorType { get; set; }
/// <summary>An array of objects that provide a stack trace through the script to show where the execution
/// failed, with the deepest call first.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("scriptStackTraceElements")]
public virtual System.Collections.Generic.IList<ScriptStackTraceElement> ScriptStackTraceElements { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A request to run the function in a script. The script is identified by the specified `script_id`.
/// Executing a function on a script will return results based on the implementation of the script.</summary>
public class ExecutionRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>If `true` and the user is an owner of the script, the script runs at the most recently saved
/// version rather than the version deployed for use with the Execution API. Optional; default is
/// `false`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("devMode")]
public virtual System.Nullable<bool> DevMode { get; set; }
/// <summary>The name of the function to execute in the given script. The name does not include parentheses or
/// parameters.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("function")]
public virtual string Function { get; set; }
/// <summary>The parameters to be passed to the function being executed. The type for each parameter should
/// match the expected type in Apps Script. Parameters cannot be Apps Script-specific objects (such as a
/// `Document` or `Calendar`); they can only be primitive types such as a `string`, `number`, `array`, `object`,
/// or `boolean`. Optional.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("parameters")]
public virtual System.Collections.Generic.IList<object> Parameters { get; set; }
/// <summary>This field is not used.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sessionState")]
public virtual string SessionState { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>An object that provides the return value of a function executed through the Apps Script Execution API.
/// If an `run` call succeeds and the script function returns successfully, the response body's `response` field
/// will contain this `ExecutionResponse` object.</summary>
public class ExecutionResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The return value of the script function. The type will match the type returned in Apps Script.
/// Functions called through the Execution API cannot return Apps Script-specific objects (such as a `Document`
/// or `Calendar`); they can only return primitive types such as a `string`, `number`, `array`, `object`, or
/// `boolean`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("result")]
public virtual object Result { get; set; }
[Newtonsoft.Json.JsonPropertyAttribute("status")]
public virtual string Status { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response will not arrive until the function finishes executing. The maximum runtime is listed in
/// the guide to [limitations in Apps Script](https://developers.google.com/apps-
/// script/guides/services/quotas#current_limitations). If the script function returns successfully, the `response`
/// field will contain an `ExecutionResponse` object with the function's return value in the object's `result`
/// field.
///
/// If the script function (or Apps Script itself) throws an exception, the `error` field will contain a `Status`
/// object. The `Status` object's `details` field will contain an array with a single `ExecutionError` object that
/// provides information about the nature of the error.
///
/// If the `run` call itself fails (for example, because of a malformed request or an authorization error), the
/// method will return an HTTP response code in the 4XX range with a different format for the response body. Client
/// libraries will automatically convert a 4XX response into an exception class.</summary>
public class Operation : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>This field is not used.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("done")]
public virtual System.Nullable<bool> Done { get; set; }
/// <summary>If a `run` call succeeds but the script function (or Apps Script itself) throws an exception, this
/// field will contain a `Status` object. The `Status` object's `details` field will contain an array with a
/// single `ExecutionError` object that provides information about the nature of the error.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("error")]
public virtual Status Error { get; set; }
/// <summary>This field is not used.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("metadata")]
public virtual System.Collections.Generic.IDictionary<string,object> Metadata { get; set; }
/// <summary>This field is not used.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>If the script function returns successfully, this field will contain an `ExecutionResponse` object
/// with the function's return value as the object's `result` field.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("response")]
public virtual System.Collections.Generic.IDictionary<string,object> Response { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A stack trace through the script that shows where the execution failed.</summary>
public class ScriptStackTraceElement : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The name of the function that failed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("function")]
public virtual string Function { get; set; }
/// <summary>The line number where the script failed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("lineNumber")]
public virtual System.Nullable<int> LineNumber { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>If a `run` call succeeds but the script function (or Apps Script itself) throws an exception, the
/// response body's `error` field will contain this `Status` object.</summary>
public class Status : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The status code, which should be an enum value of google.rpc.Code.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual System.Nullable<int> Code { get; set; }
/// <summary>An array that contains a single `ExecutionError` object that provides information about the nature
/// of the error.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("details")]
public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string,object>> Details { get; set; }
/// <summary>A developer-facing error message, which should be in English. Any user-facing error message should
/// be localized and sent in the google.rpc.Status.details field, or localized by the client.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("message")]
public virtual string Message { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
// 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.IO;
using System.Net.Sockets;
using System.Net.Test.Common;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Security.Tests
{
// Callback method that is called when the server receives data from a connected client.
// The callback method should return a byte array and the number of bytes to send from that array.
public delegate void DummyTcpServerReceiveCallback(byte[] bufferReceived, int bytesReceived, Stream stream);
// Provides a dummy TCP/IP server that accepts connections and supports SSL/TLS.
// It normally echoes data received but can be configured to write a byte array
// specified by a callback method.
public class DummyTcpServer : IDisposable
{
private VerboseTestLogging _log;
private TcpListener _listener;
private bool _useSsl;
private SslProtocols _sslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls;
private EncryptionPolicy _sslEncryptionPolicy;
private IPEndPoint _remoteEndPoint;
private DummyTcpServerReceiveCallback _receiveCallback;
private void StartListener(IPEndPoint endPoint)
{
_listener = new TcpListener(endPoint);
_listener.Start(5);
_log.WriteLine("Server {0} listening", endPoint.Address.ToString());
_listener.AcceptTcpClientAsync().ContinueWith(t => OnAccept(t), TaskScheduler.Default);
}
public DummyTcpServer(IPEndPoint endPoint) : this(endPoint, null)
{
}
public DummyTcpServer(IPEndPoint endPoint, EncryptionPolicy? sslEncryptionPolicy)
{
_log = VerboseTestLogging.GetInstance();
if (sslEncryptionPolicy != null)
{
_remoteEndPoint = endPoint;
_useSsl = true;
_sslEncryptionPolicy = (EncryptionPolicy)sslEncryptionPolicy;
}
StartListener(endPoint);
}
public IPEndPoint RemoteEndPoint
{
get { return (IPEndPoint)_listener.LocalEndpoint; }
}
public SslProtocols SslProtocols
{
get { return _sslProtocols; }
set { _sslProtocols = value; }
}
protected DummyTcpServerReceiveCallback ReceiveCallback
{
get { return _receiveCallback; }
set { _receiveCallback = value; }
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_listener.Stop();
}
}
protected virtual void OnClientAccepted(TcpClient client)
{
}
private void OnAuthenticate(Task result, ClientState state)
{
SslStream sslStream = (SslStream)state.Stream;
try
{
result.GetAwaiter().GetResult();
_log.WriteLine("Server authenticated to client with encryption cipher: {0} {1}-bit strength",
sslStream.CipherAlgorithm, sslStream.CipherStrength);
// Start listening for data from the client connection.
sslStream.BeginRead(state.ReceiveBuffer, 0, state.ReceiveBuffer.Length, OnReceive, state);
}
catch (AuthenticationException authEx)
{
_log.WriteLine(
"Server disconnecting from client during authentication. No shared SSL/TLS algorithm. ({0})",
authEx);
}
catch (Exception ex)
{
_log.WriteLine("Server disconnecting from client during authentication. Exception: {0}",
ex.Message);
}
finally
{
state.Dispose();
}
}
private void OnAccept(Task<TcpClient> result)
{
TcpClient client = null;
// Accept current connection
try
{
client = result.Result;
}
catch
{
}
// If we have a connection, then process it
if (client != null)
{
OnClientAccepted(client);
ClientState state;
// Start authentication for SSL?
if (_useSsl)
{
state = new ClientState(client, _sslEncryptionPolicy);
_log.WriteLine("Server: starting SSL authentication.");
SslStream sslStream = null;
X509Certificate2 certificate = TestConfiguration.GetServerCertificate();
try
{
sslStream = (SslStream)state.Stream;
_log.WriteLine("Server: attempting to open SslStream.");
sslStream.AuthenticateAsServerAsync(certificate, false, _sslProtocols, false).ContinueWith(t => OnAuthenticate(t, state), TaskScheduler.Default);
}
catch (Exception ex)
{
_log.WriteLine("Server: Exception: {0}", ex);
state.Dispose(); // close connection to client
}
}
else
{
state = new ClientState(client);
// Start listening for data from the client connection
try
{
state.Stream.BeginRead(state.ReceiveBuffer, 0, state.ReceiveBuffer.Length, OnReceive, state);
}
catch
{
}
}
}
// Listen for more client connections
try
{
_listener.AcceptTcpClientAsync().ContinueWith(t => OnAccept(t), TaskScheduler.Default);
}
catch
{
}
}
private void OnReceive(IAsyncResult result)
{
ClientState state = (ClientState)result.AsyncState;
try
{
int bytesReceived = state.Stream.EndRead(result);
if (bytesReceived == 0)
{
state.Dispose();
return;
}
if (_receiveCallback != null)
{
_receiveCallback(state.ReceiveBuffer, bytesReceived, state.Stream);
}
else
{
// Echo back what we received
state.Stream.Write(state.ReceiveBuffer, 0, bytesReceived);
}
// Read more from client (asynchronous)
state.Stream.BeginRead(state.ReceiveBuffer, 0, state.ReceiveBuffer.Length, OnReceive, state);
}
catch (IOException)
{
state.Dispose();
return;
}
catch (SocketException)
{
state.Dispose();
return;
}
catch (ObjectDisposedException)
{
state.Dispose();
return;
}
}
// The following method is invoked by the RemoteCertificateValidationDelegate.
public static bool AlwaysValidServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true; // allow everything
}
private class ClientState
{
private TcpClient _tcpClient;
private byte[] _receiveBuffer;
private bool _useSsl;
private SslStream _sslStream;
private bool _closed;
public ClientState(TcpClient client)
{
_tcpClient = client;
_receiveBuffer = new byte[1024];
_useSsl = false;
_closed = false;
}
public ClientState(TcpClient client, EncryptionPolicy sslEncryptionPolicy)
{
_tcpClient = client;
_receiveBuffer = new byte[1024];
_useSsl = true;
_sslStream = new SslStream(client.GetStream(), false, AlwaysValidServerCertificate, null, sslEncryptionPolicy);
_closed = false;
}
public void Dispose()
{
if (!_closed)
{
if (_useSsl)
{
_sslStream.Dispose();
}
_tcpClient.Dispose();
_closed = true;
}
}
public TcpClient TcpClient
{
get { return _tcpClient; }
}
public byte[] ReceiveBuffer
{
get { return _receiveBuffer; }
}
public bool UseSsl
{
get { return _useSsl; }
}
public bool Closed
{
get { return _closed; }
}
public Stream Stream
{
get
{
if (_useSsl)
{
return _sslStream;
}
else
{
return _tcpClient.GetStream();
}
}
}
}
}
}
| |
// 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.SpanTests;
using System.Text;
using Xunit;
namespace System.Buffers.Text.Tests
{
public class Base64EncoderUnitTests
{
[Fact]
public void BasicEncodingAndDecoding()
{
var bytes = new byte[byte.MaxValue + 1];
for (int i = 0; i < byte.MaxValue + 1; i++)
{
bytes[i] = (byte)i;
}
for (int value = 0; value < 256; value++)
{
Span<byte> sourceBytes = bytes.AsSpan().Slice(0, value + 1);
Span<byte> encodedBytes = new byte[Base64.GetMaxEncodedToUtf8Length(sourceBytes.Length)];
Assert.Equal(OperationStatus.Done, Base64.EncodeToUtf8(sourceBytes, encodedBytes, out int consumed, out int encodedBytesCount));
Assert.Equal(sourceBytes.Length, consumed);
Assert.Equal(encodedBytes.Length, encodedBytesCount);
string encodedText = Encoding.ASCII.GetString(encodedBytes.ToArray());
string expectedText = Convert.ToBase64String(bytes, 0, value + 1);
Assert.Equal(expectedText, encodedText);
if (encodedBytes.Length % 4 == 0)
{
Span<byte> decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(encodedBytes.Length)];
Assert.Equal(OperationStatus.Done, Base64.DecodeFromUtf8(encodedBytes, decodedBytes, out consumed, out int decodedByteCount));
Assert.Equal(encodedBytes.Length, consumed);
Assert.Equal(sourceBytes.Length, decodedByteCount);
Assert.True(sourceBytes.SequenceEqual(decodedBytes.Slice(0, decodedByteCount)));
}
}
}
[Fact]
public void BasicEncoding()
{
var rnd = new Random(42);
for (int i = 0; i < 10; i++)
{
int numBytes = rnd.Next(100, 1000 * 1000);
Span<byte> source = new byte[numBytes];
Base64TestHelper.InitalizeBytes(source, numBytes);
Span<byte> encodedBytes = new byte[Base64.GetMaxEncodedToUtf8Length(source.Length)];
Assert.Equal(OperationStatus.Done, Base64.EncodeToUtf8(source, encodedBytes, out int consumed, out int encodedBytesCount));
Assert.Equal(source.Length, consumed);
Assert.Equal(encodedBytes.Length, encodedBytesCount);
Assert.True(Base64TestHelper.VerifyEncodingCorrectness(source.Length, encodedBytes.Length, source, encodedBytes));
}
}
[Fact]
public void EncodeEmptySpan()
{
Span<byte> source = Span<byte>.Empty;
Span<byte> encodedBytes = new byte[Base64.GetMaxEncodedToUtf8Length(source.Length)];
Assert.Equal(OperationStatus.Done, Base64.EncodeToUtf8(source, encodedBytes, out int consumed, out int encodedBytesCount));
Assert.Equal(source.Length, consumed);
Assert.Equal(encodedBytes.Length, encodedBytesCount);
Assert.True(Base64TestHelper.VerifyEncodingCorrectness(source.Length, encodedBytes.Length, source, encodedBytes));
}
[Fact]
[OuterLoop]
public void EncodeTooLargeSpan()
{
if (IntPtr.Size < 8)
return;
bool allocatedFirst = false;
bool allocatedSecond = false;
IntPtr memBlockFirst = IntPtr.Zero;
IntPtr memBlockSecond = IntPtr.Zero;
// int.MaxValue - (int.MaxValue % 4) => 2147483644, largest multiple of 4 less than int.MaxValue
// CLR default limit of 2 gigabytes (GB).
// 1610612734, larger than MaximumEncodeLength, requires output buffer of size 2147483648 (which is > int.MaxValue)
const int sourceCount = (int.MaxValue >> 2) * 3 + 1;
const int encodedCount = 2000000000;
try
{
allocatedFirst = AllocationHelper.TryAllocNative((IntPtr)sourceCount, out memBlockFirst);
allocatedSecond = AllocationHelper.TryAllocNative((IntPtr)encodedCount, out memBlockSecond);
if (allocatedFirst && allocatedSecond)
{
unsafe
{
var source = new Span<byte>(memBlockFirst.ToPointer(), sourceCount);
var encodedBytes = new Span<byte>(memBlockSecond.ToPointer(), encodedCount);
Assert.Equal(OperationStatus.DestinationTooSmall, Base64.EncodeToUtf8(source, encodedBytes, out int consumed, out int encodedBytesCount));
Assert.Equal((encodedBytes.Length >> 2) * 3, consumed); // encoding 1500000000 bytes fits into buffer of 2000000000 bytes
Assert.Equal(encodedBytes.Length, encodedBytesCount);
}
}
}
finally
{
if (allocatedFirst)
AllocationHelper.ReleaseNative(ref memBlockFirst);
if (allocatedSecond)
AllocationHelper.ReleaseNative(ref memBlockSecond);
}
}
[Fact]
public void BasicEncodingWithFinalBlockFalse()
{
var rnd = new Random(42);
for (int i = 0; i < 10; i++)
{
int numBytes = rnd.Next(100, 1000 * 1000);
Span<byte> source = new byte[numBytes];
Base64TestHelper.InitalizeBytes(source, numBytes);
Span<byte> encodedBytes = new byte[Base64.GetMaxEncodedToUtf8Length(source.Length)];
int expectedConsumed = source.Length / 3 * 3; // only consume closest multiple of three since isFinalBlock is false
int expectedWritten = source.Length / 3 * 4;
Assert.Equal(OperationStatus.NeedMoreData, Base64.EncodeToUtf8(source, encodedBytes, out int consumed, out int encodedBytesCount, isFinalBlock: false));
Assert.Equal(expectedConsumed, consumed);
Assert.Equal(expectedWritten, encodedBytesCount);
Assert.True(Base64TestHelper.VerifyEncodingCorrectness(expectedConsumed, expectedWritten, source, encodedBytes));
}
}
[Theory]
[InlineData(1, "", 0, 0)]
[InlineData(2, "", 0, 0)]
[InlineData(3, "AQID", 3, 4)]
[InlineData(4, "AQID", 3, 4)]
[InlineData(5, "AQID", 3, 4)]
[InlineData(6, "AQIDBAUG", 6, 8)]
[InlineData(7, "AQIDBAUG", 6, 8)]
public void BasicEncodingWithFinalBlockFalseKnownInput(int numBytes, string expectedText, int expectedConsumed, int expectedWritten)
{
Span<byte> source = new byte[numBytes];
for (int i = 0; i < numBytes; i++)
{
source[i] = (byte)(i + 1);
}
Span<byte> encodedBytes = new byte[Base64.GetMaxEncodedToUtf8Length(source.Length)];
Assert.Equal(OperationStatus.NeedMoreData, Base64.EncodeToUtf8(source, encodedBytes, out int consumed, out int encodedBytesCount, isFinalBlock: false));
Assert.Equal(expectedConsumed, consumed);
Assert.Equal(expectedWritten, encodedBytesCount);
string encodedText = Encoding.ASCII.GetString(encodedBytes.Slice(0, expectedWritten).ToArray());
Assert.Equal(expectedText, encodedText);
}
[Theory]
[InlineData(1, "AQ==", 1, 4)]
[InlineData(2, "AQI=", 2, 4)]
[InlineData(3, "AQID", 3, 4)]
[InlineData(4, "AQIDBA==", 4, 8)]
[InlineData(5, "AQIDBAU=", 5, 8)]
[InlineData(6, "AQIDBAUG", 6, 8)]
[InlineData(7, "AQIDBAUGBw==", 7, 12)]
public void BasicEncodingWithFinalBlockTrueKnownInput(int numBytes, string expectedText, int expectedConsumed, int expectedWritten)
{
Span<byte> source = new byte[numBytes];
for (int i = 0; i < numBytes; i++)
{
source[i] = (byte)(i + 1);
}
Span<byte> encodedBytes = new byte[Base64.GetMaxEncodedToUtf8Length(source.Length)];
Assert.Equal(OperationStatus.Done, Base64.EncodeToUtf8(source, encodedBytes, out int consumed, out int encodedBytesCount, isFinalBlock: true));
Assert.Equal(expectedConsumed, consumed);
Assert.Equal(expectedWritten, encodedBytesCount);
string encodedText = Encoding.ASCII.GetString(encodedBytes.Slice(0, expectedWritten).ToArray());
Assert.Equal(expectedText, encodedText);
}
[Fact]
public void EncodingOutputTooSmall()
{
for (int numBytes = 4; numBytes < 20; numBytes++)
{
Span<byte> source = new byte[numBytes];
Base64TestHelper.InitalizeBytes(source, numBytes);
Span<byte> encodedBytes = new byte[4];
Assert.Equal(OperationStatus.DestinationTooSmall,
Base64.EncodeToUtf8(source, encodedBytes, out int consumed, out int written));
int expectedConsumed = 3;
Assert.Equal(expectedConsumed, consumed);
Assert.Equal(encodedBytes.Length, written);
Assert.True(Base64TestHelper.VerifyEncodingCorrectness(expectedConsumed, encodedBytes.Length, source, encodedBytes));
}
}
[Fact]
public void EncodingOutputTooSmallRetry()
{
Span<byte> source = new byte[750];
Base64TestHelper.InitalizeBytes(source);
int outputSize = 320;
int requiredSize = Base64.GetMaxEncodedToUtf8Length(source.Length);
Span<byte> encodedBytes = new byte[outputSize];
Assert.Equal(OperationStatus.DestinationTooSmall,
Base64.EncodeToUtf8(source, encodedBytes, out int consumed, out int written));
int expectedConsumed = encodedBytes.Length / 4 * 3;
Assert.Equal(expectedConsumed, consumed);
Assert.Equal(encodedBytes.Length, written);
Assert.True(Base64TestHelper.VerifyEncodingCorrectness(expectedConsumed, encodedBytes.Length, source, encodedBytes));
encodedBytes = new byte[requiredSize - outputSize];
source = source.Slice(consumed);
Assert.Equal(OperationStatus.Done,
Base64.EncodeToUtf8(source, encodedBytes, out consumed, out written));
expectedConsumed = encodedBytes.Length / 4 * 3;
Assert.Equal(expectedConsumed, consumed);
Assert.Equal(encodedBytes.Length, written);
Assert.True(Base64TestHelper.VerifyEncodingCorrectness(expectedConsumed, encodedBytes.Length, source, encodedBytes));
}
[Fact]
public void GetMaxEncodedLength()
{
// (int.MaxValue - 4)/(4/3) => 1610612733, otherwise integer overflow
int[] input = { 0, 1, 2, 3, 4, 5, 6, 1610612728, 1610612729, 1610612730, 1610612731, 1610612732, 1610612733 };
int[] expected = { 0, 4, 4, 4, 8, 8, 8, 2147483640, 2147483640, 2147483640, 2147483644, 2147483644, 2147483644 };
for (int i = 0; i < input.Length; i++)
{
Assert.Equal(expected[i], Base64.GetMaxEncodedToUtf8Length(input[i]));
}
// integer overflow
Assert.Throws<ArgumentOutOfRangeException>(() => Base64.GetMaxEncodedToUtf8Length(1610612734));
Assert.Throws<ArgumentOutOfRangeException>(() => Base64.GetMaxEncodedToUtf8Length(int.MaxValue));
// negative input
Assert.Throws<ArgumentOutOfRangeException>(() => Base64.GetMaxEncodedToUtf8Length(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => Base64.GetMaxEncodedToUtf8Length(int.MinValue));
}
[Fact]
public void EncodeInPlace()
{
const int numberOfBytes = 15;
Span<byte> testBytes = new byte[numberOfBytes / 3 * 4]; // slack since encoding inflates the data
Base64TestHelper.InitalizeBytes(testBytes);
for (int numberOfBytesToTest = 0; numberOfBytesToTest <= numberOfBytes; numberOfBytesToTest++)
{
var expectedText = Convert.ToBase64String(testBytes.Slice(0, numberOfBytesToTest).ToArray());
Assert.Equal(OperationStatus.Done, Base64.EncodeToUtf8InPlace(testBytes, numberOfBytesToTest, out int bytesWritten));
Assert.Equal(Base64.GetMaxEncodedToUtf8Length(numberOfBytesToTest), bytesWritten);
var encodedText = Encoding.ASCII.GetString(testBytes.Slice(0, bytesWritten).ToArray());
Assert.Equal(expectedText, encodedText);
}
}
[Fact]
public void EncodeInPlaceOutputTooSmall()
{
byte[] testBytes = { 1, 2, 3 };
for (int numberOfBytesToTest = 1; numberOfBytesToTest <= testBytes.Length; numberOfBytesToTest++)
{
Assert.Equal(OperationStatus.DestinationTooSmall, Base64.EncodeToUtf8InPlace(testBytes, numberOfBytesToTest, out int bytesWritten));
Assert.Equal(0, bytesWritten);
}
}
[Fact]
public void EncodeInPlaceDataLengthTooLarge()
{
byte[] testBytes = { 1, 2, 3 };
Assert.Equal(OperationStatus.DestinationTooSmall, Base64.EncodeToUtf8InPlace(testBytes, testBytes.Length + 1, out int bytesWritten));
Assert.Equal(0, bytesWritten);
}
}
}
| |
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using System.Linq;
using Xunit;
namespace Moq.Tests
{
public class CustomTypeMatchersFixture
{
[Fact]
public void Setup_with_custom_type_matcher()
{
var invocationCount = 0;
var mock = new Mock<IX>();
mock.Setup(x => x.Method<IntOrString>()).Callback(() => invocationCount++);
mock.Object.Method<bool>();
mock.Object.Method<int>();
mock.Object.Method<int>();
mock.Object.Method<object>();
mock.Object.Method<string>();
Assert.Equal(3, invocationCount);
}
[Fact]
public void Verify_with_custom_type_matcher()
{
var mock = new Mock<IX>();
mock.Object.Method<bool>();
mock.Object.Method<int>();
mock.Object.Method<int>();
mock.Object.Method<object>();
mock.Object.Method<string>();
mock.Verify(x => x.Method<IntOrString>(), Times.Exactly(3));
}
[Fact]
public void Cannot_use_type_matcher_with_parameterized_constructor_directly_in_Setup()
{
var mock = new Mock<IX>();
Action setup = () => mock.Setup(x => x.Method<Picky>());
var ex = Assert.Throws<ArgumentException>(setup);
Assert.Contains("Picky does not have a default (public parameterless) constructor", ex.Message);
}
[Fact]
public void Cannot_use_type_matcher_with_parameterized_constructor_directly_in_Verify()
{
var mock = new Mock<IX>();
Action verify = () => mock.Verify(x => x.Method<Picky>(), Times.Never);
var ex = Assert.Throws<ArgumentException>(verify);
Assert.Contains("Picky does not have a default (public parameterless) constructor", ex.Message);
}
[Fact]
public void Can_use_type_matcher_derived_from_one_having_a_parameterized_constructor()
{
var mock = new Mock<IX>();
mock.Object.Method<bool>();
mock.Object.Method<int>();
mock.Object.Method<object>();
mock.Object.Method<string>();
mock.Object.Method<string>();
mock.Verify(x => x.Method<PickyIntOrString>(), Times.Exactly(3));
}
[Fact]
public void Can_use_struct_type_matchers()
{
var mock = new Mock<IX>();
mock.Setup(m => m.Method<AnyStruct>());
}
[Fact]
public void Must_use_custom_type_matcher_when_type_constraints_present()
{
var mock = new Mock<IY>();
//mock.Setup(y => y.Method<It.IsAnyType>()); // wouldn't work because of the type constraint
mock.Setup(y => y.Method<AnyException>());
mock.Object.Method<ArgumentException>();
mock.VerifyAll();
}
[Fact]
public void Must_use_TypeMatcherAttribute_when_type_constraints_present_that_prevents_direct_implementation_of_ITypeMatcher()
{
var mock = new Mock<IZ>();
mock.Setup(z => z.DelegateMethod<AnyDelegate>());
mock.Setup(z => z.EnumMethod<AnyEnum>());
mock.Object.DelegateMethod<Action>();
mock.Object.EnumMethod<AttributeTargets>();
mock.VerifyAll();
}
[Fact]
public void It_IsAny_works_with_custom_matcher()
{
var invocationCount = 0;
var mock = new Mock<IX>();
mock.Setup(m => m.Method(It.IsAny<IntOrString>())).Callback((object arg) => invocationCount++);
mock.Object.Method(true);
mock.Object.Method(42);
mock.Object.Method("42");
mock.Object.Method(new Exception("42"));
mock.Object.Method((string)null);
Assert.Equal(3, invocationCount);
}
[Fact]
public void It_IsNotNull_works_with_custom_matcher()
{
var invocationCount = 0;
var mock = new Mock<IX>();
mock.Setup(m => m.Method(It.IsNotNull<IntOrString>())).Callback((object arg) => invocationCount++);
mock.Object.Method(true);
mock.Object.Method(42);
mock.Object.Method("42");
mock.Object.Method(new Exception("42"));
mock.Object.Method((string)null);
Assert.Equal(2, invocationCount);
}
[Fact]
public void It_Is_works_with_custom_matcher()
{
var acceptableArgs = new object[] { 42, "42" };
var invocationCount = 0;
var mock = new Mock<IX>();
mock.Setup(m => m.Method(It.Is<IntOrString>((arg, _) => acceptableArgs.Contains(arg))))
.Callback((object arg) => invocationCount++);
mock.Object.Method(42);
mock.Object.Method(7);
Assert.Equal(1, invocationCount);
mock.Object.Method("42");
mock.Object.Method("7");
mock.Object.Method((string)null);
Assert.Equal(2, invocationCount);
}
public interface IX
{
void Method<T>();
void Method<T>(T arg);
}
public interface IY
{
void Method<TException>() where TException : Exception;
}
public interface IZ
{
void DelegateMethod<TDelegate>() where TDelegate : Delegate;
void EnumMethod<TEnum>() where TEnum : Enum;
}
[TypeMatcher]
public sealed class IntOrString : ITypeMatcher
{
public bool Matches(Type typeArgument)
{
return typeArgument == typeof(int) || typeArgument == typeof(string);
}
}
public sealed class PickyIntOrString : Picky
{
public PickyIntOrString() : base(typeof(int), typeof(string))
{
}
}
[TypeMatcher]
public class Picky : ITypeMatcher
{
private readonly Type[] types;
public Picky(params Type[] types)
{
this.types = types;
}
public bool Matches(Type typeArgument)
{
return Array.IndexOf(this.types, typeArgument) >= 0;
}
}
[TypeMatcher]
public class AnyException : Exception, ITypeMatcher
{
public bool Matches(Type typeArgument)
{
return true;
}
}
[TypeMatcher(typeof(It.IsAnyType))]
public enum AnyEnum { }
[TypeMatcher(typeof(It.IsAnyType))]
public delegate void AnyDelegate();
[TypeMatcher]
public struct AnyStruct : ITypeMatcher
{
public bool Matches(Type typeArgument) => typeArgument.IsValueType;
}
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using ParentLoadSoftDelete.DataAccess;
using ParentLoadSoftDelete.DataAccess.ERCLevel;
namespace ParentLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// F03_Continent_Child (editable child object).<br/>
/// This is a generated base class of <see cref="F03_Continent_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="F02_Continent"/> collection.
/// </remarks>
[Serializable]
public partial class F03_Continent_Child : BusinessBase<F03_Continent_Child>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int continent_ID1 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Continent_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Continent_Child_NameProperty = RegisterProperty<string>(p => p.Continent_Child_Name, "SubContinents Child Name");
/// <summary>
/// Gets or sets the SubContinents Child Name.
/// </summary>
/// <value>The SubContinents Child Name.</value>
public string Continent_Child_Name
{
get { return GetProperty(Continent_Child_NameProperty); }
set { SetProperty(Continent_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="F03_Continent_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="F03_Continent_Child"/> object.</returns>
internal static F03_Continent_Child NewF03_Continent_Child()
{
return DataPortal.CreateChild<F03_Continent_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="F03_Continent_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="F03_Continent_Child"/> object.</returns>
internal static F03_Continent_Child GetF03_Continent_Child(SafeDataReader dr)
{
F03_Continent_Child obj = new F03_Continent_Child();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="F03_Continent_Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public F03_Continent_Child()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="F03_Continent_Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="F03_Continent_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Continent_Child_NameProperty, dr.GetString("Continent_Child_Name"));
// parent properties
continent_ID1 = dr.GetInt32("Continent_ID1");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="F03_Continent_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(F02_Continent parent)
{
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<IF03_Continent_ChildDal>();
using (BypassPropertyChecks)
{
dal.Insert(
parent.Continent_ID,
Continent_Child_Name
);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="F03_Continent_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(F02_Continent parent)
{
if (!IsDirty)
return;
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<IF03_Continent_ChildDal>();
using (BypassPropertyChecks)
{
dal.Update(
parent.Continent_ID,
Continent_Child_Name
);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="F03_Continent_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(F02_Continent parent)
{
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IF03_Continent_ChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.Continent_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
namespace BooCompiler.Tests
{
using NUnit.Framework;
[TestFixture]
public class OperatorsIntegrationTestFixture : AbstractCompilerTestCase
{
[Test]
public void and_1()
{
RunCompilerTestCase(@"and-1.boo");
}
[Test]
public void and_2()
{
RunCompilerTestCase(@"and-2.boo");
}
[Test]
public void bitwise_and_1()
{
RunCompilerTestCase(@"bitwise-and-1.boo");
}
[Test]
public void bitwise_and_2()
{
RunCompilerTestCase(@"bitwise-and-2.boo");
}
[Test]
public void bitwise_or_1()
{
RunCompilerTestCase(@"bitwise-or-1.boo");
}
[Test]
public void bitwise_or_2()
{
RunCompilerTestCase(@"bitwise-or-2.boo");
}
[Test]
public void cast_1()
{
RunCompilerTestCase(@"cast-1.boo");
}
[Test]
public void cast_2()
{
RunCompilerTestCase(@"cast-2.boo");
}
[Test]
public void cast_3()
{
RunCompilerTestCase(@"cast-3.boo");
}
[Test]
public void cast_4()
{
RunCompilerTestCase(@"cast-4.boo");
}
[Test]
public void cast_5()
{
RunCompilerTestCase(@"cast-5.boo");
}
[Test]
public void cast_6()
{
RunCompilerTestCase(@"cast-6.boo");
}
[Test]
public void cast_7()
{
RunCompilerTestCase(@"cast-7.boo");
}
[Test]
public void cast_8()
{
RunCompilerTestCase(@"cast-8.boo");
}
[Test]
public void cast_9()
{
RunCompilerTestCase(@"cast-9.boo");
}
[Test]
public void conditional_1()
{
RunCompilerTestCase(@"conditional-1.boo");
}
[Test]
public void explode_1()
{
RunCompilerTestCase(@"explode-1.boo");
}
[Test]
public void explode_2()
{
RunCompilerTestCase(@"explode-2.boo");
}
[Test]
public void explode_3()
{
RunCompilerTestCase(@"explode-3.boo");
}
[Test]
public void exponential_1()
{
RunCompilerTestCase(@"exponential-1.boo");
}
[Test]
public void in_1()
{
RunCompilerTestCase(@"in-1.boo");
}
[Test]
public void is_1()
{
RunCompilerTestCase(@"is-1.boo");
}
[Test]
public void is_2()
{
RunCompilerTestCase(@"is-2.boo");
}
[Test]
public void isa_1()
{
RunCompilerTestCase(@"isa-1.boo");
}
[Test]
public void isa_2()
{
RunCompilerTestCase(@"isa-2.boo");
}
[Test]
public void isa_3()
{
RunCompilerTestCase(@"isa-3.boo");
}
[Test]
public void not_1()
{
RunCompilerTestCase(@"not-1.boo");
}
[Test]
public void ones_complement_1()
{
RunCompilerTestCase(@"ones-complement-1.boo");
}
[Test]
public void operators_1()
{
RunCompilerTestCase(@"operators-1.boo");
}
[Test]
public void or_1()
{
RunCompilerTestCase(@"or-1.boo");
}
[Test]
public void or_2()
{
RunCompilerTestCase(@"or-2.boo");
}
[Test]
public void or_3()
{
RunCompilerTestCase(@"or-3.boo");
}
[Test]
public void or_4()
{
RunCompilerTestCase(@"or-4.boo");
}
[Test]
public void post_incdec_1()
{
RunCompilerTestCase(@"post-incdec-1.boo");
}
[Test]
public void post_incdec_2()
{
RunCompilerTestCase(@"post-incdec-2.boo");
}
[Test]
public void post_incdec_3()
{
RunCompilerTestCase(@"post-incdec-3.boo");
}
[Test]
public void post_incdec_4()
{
RunCompilerTestCase(@"post-incdec-4.boo");
}
[Test]
public void post_incdec_5()
{
RunCompilerTestCase(@"post-incdec-5.boo");
}
[Test]
public void post_incdec_6()
{
RunCompilerTestCase(@"post-incdec-6.boo");
}
[Test]
public void post_incdec_7()
{
RunCompilerTestCase(@"post-incdec-7.boo");
}
[Test]
public void shift_1()
{
RunCompilerTestCase(@"shift-1.boo");
}
[Test]
public void slicing_1()
{
RunCompilerTestCase(@"slicing-1.boo");
}
[Test]
public void slicing_10()
{
RunCompilerTestCase(@"slicing-10.boo");
}
[Test]
public void slicing_11()
{
RunCompilerTestCase(@"slicing-11.boo");
}
[Test]
public void slicing_12()
{
RunCompilerTestCase(@"slicing-12.boo");
}
[Test]
public void slicing_13()
{
RunCompilerTestCase(@"slicing-13.boo");
}
[Test]
public void slicing_2()
{
RunCompilerTestCase(@"slicing-2.boo");
}
[Test]
public void slicing_3()
{
RunCompilerTestCase(@"slicing-3.boo");
}
[Test]
public void slicing_4()
{
RunCompilerTestCase(@"slicing-4.boo");
}
[Test]
public void slicing_5()
{
RunCompilerTestCase(@"slicing-5.boo");
}
[Test]
public void slicing_6()
{
RunCompilerTestCase(@"slicing-6.boo");
}
[Test]
public void slicing_7()
{
RunCompilerTestCase(@"slicing-7.boo");
}
[Test]
public void slicing_8()
{
RunCompilerTestCase(@"slicing-8.boo");
}
[Test]
public void slicing_9()
{
RunCompilerTestCase(@"slicing-9.boo");
}
[Test]
public void unary_1()
{
RunCompilerTestCase(@"unary-1.boo");
}
[Test]
public void unary_2()
{
RunCompilerTestCase(@"unary-2.boo");
}
[Test]
public void unary_3()
{
RunCompilerTestCase(@"unary-3.boo");
}
[Test]
public void xor_1()
{
RunCompilerTestCase(@"xor-1.boo");
}
override protected string GetRelativeTestCasesPath()
{
return "integration/operators";
}
}
}
| |
namespace RRLab.PhysiologyWorkbench.Devices
{
partial class FilterWheelPositionControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param genotype="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region 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()
{
this.TableLayout = new System.Windows.Forms.TableLayoutPanel();
this.label1 = new System.Windows.Forms.Label();
this.WheelsBox = new System.Windows.Forms.ListBox();
this.label2 = new System.Windows.Forms.Label();
this.FiltersBox = new System.Windows.Forms.ListBox();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.SetFilterButton = new System.Windows.Forms.Button();
this.TakeControlButton = new System.Windows.Forms.Button();
this.panel1 = new System.Windows.Forms.Panel();
this.ShutterStateComboBox = new System.Windows.Forms.ComboBox();
this.ShutterLabel = new System.Windows.Forms.Label();
this.SetShutterButton = new System.Windows.Forms.Button();
this.TableLayout.SuspendLayout();
this.flowLayoutPanel1.SuspendLayout();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// TableLayout
//
this.TableLayout.ColumnCount = 1;
this.TableLayout.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.TableLayout.Controls.Add(this.label1, 0, 0);
this.TableLayout.Controls.Add(this.WheelsBox, 0, 1);
this.TableLayout.Controls.Add(this.label2, 0, 3);
this.TableLayout.Controls.Add(this.FiltersBox, 0, 4);
this.TableLayout.Controls.Add(this.flowLayoutPanel1, 0, 5);
this.TableLayout.Controls.Add(this.panel1, 0, 2);
this.TableLayout.Dock = System.Windows.Forms.DockStyle.Fill;
this.TableLayout.Location = new System.Drawing.Point(0, 0);
this.TableLayout.Name = "TableLayout";
this.TableLayout.RowCount = 6;
this.TableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.TableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 50F));
this.TableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.TableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.TableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 150F));
this.TableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.TableLayout.Size = new System.Drawing.Size(200, 296);
this.TableLayout.TabIndex = 0;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Dock = System.Windows.Forms.DockStyle.Top;
this.label1.Location = new System.Drawing.Point(3, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(194, 13);
this.label1.TabIndex = 10;
this.label1.Text = "Wheels";
//
// WheelsBox
//
this.WheelsBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.WheelsBox.FormattingEnabled = true;
this.WheelsBox.Location = new System.Drawing.Point(3, 16);
this.WheelsBox.Name = "WheelsBox";
this.WheelsBox.Size = new System.Drawing.Size(194, 43);
this.WheelsBox.TabIndex = 9;
this.WheelsBox.SelectedIndexChanged += new System.EventHandler(this.OnSelectedWheelChanged);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Dock = System.Windows.Forms.DockStyle.Top;
this.label2.Location = new System.Drawing.Point(3, 92);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(194, 13);
this.label2.TabIndex = 8;
this.label2.Text = "Filters";
//
// FiltersBox
//
this.FiltersBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.FiltersBox.FormattingEnabled = true;
this.FiltersBox.Location = new System.Drawing.Point(3, 108);
this.FiltersBox.Name = "FiltersBox";
this.FiltersBox.Size = new System.Drawing.Size(194, 134);
this.FiltersBox.TabIndex = 7;
this.FiltersBox.SelectedIndexChanged += new System.EventHandler(this.OnSelectedFilterChanged);
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.Controls.Add(this.SetFilterButton);
this.flowLayoutPanel1.Controls.Add(this.TakeControlButton);
this.flowLayoutPanel1.FlowDirection = System.Windows.Forms.FlowDirection.RightToLeft;
this.flowLayoutPanel1.Location = new System.Drawing.Point(3, 258);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Size = new System.Drawing.Size(194, 31);
this.flowLayoutPanel1.TabIndex = 11;
//
// SetFilterButton
//
this.SetFilterButton.AutoSize = true;
this.SetFilterButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.SetFilterButton.Location = new System.Drawing.Point(133, 3);
this.SetFilterButton.Name = "SetFilterButton";
this.SetFilterButton.Size = new System.Drawing.Size(58, 23);
this.SetFilterButton.TabIndex = 7;
this.SetFilterButton.Text = "Set Filter";
this.SetFilterButton.UseVisualStyleBackColor = true;
this.SetFilterButton.Click += new System.EventHandler(this.OnSetFilterClicked);
//
// TakeControlButton
//
this.TakeControlButton.AutoSize = true;
this.TakeControlButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.TakeControlButton.Location = new System.Drawing.Point(49, 3);
this.TakeControlButton.Name = "TakeControlButton";
this.TakeControlButton.Size = new System.Drawing.Size(78, 23);
this.TakeControlButton.TabIndex = 8;
this.TakeControlButton.Text = "Take Control";
this.TakeControlButton.UseVisualStyleBackColor = true;
this.TakeControlButton.Click += new System.EventHandler(this.OnTakeControlClicked);
//
// panel1
//
this.panel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.panel1.Controls.Add(this.ShutterStateComboBox);
this.panel1.Controls.Add(this.ShutterLabel);
this.panel1.Controls.Add(this.SetShutterButton);
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point(3, 66);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(194, 23);
this.panel1.TabIndex = 12;
//
// ShutterStateComboBox
//
this.ShutterStateComboBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.ShutterStateComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.ShutterStateComboBox.FormattingEnabled = true;
this.ShutterStateComboBox.Location = new System.Drawing.Point(44, 0);
this.ShutterStateComboBox.Name = "ShutterStateComboBox";
this.ShutterStateComboBox.Size = new System.Drawing.Size(117, 21);
this.ShutterStateComboBox.TabIndex = 1;
//
// ShutterLabel
//
this.ShutterLabel.AutoSize = true;
this.ShutterLabel.Dock = System.Windows.Forms.DockStyle.Left;
this.ShutterLabel.Location = new System.Drawing.Point(0, 0);
this.ShutterLabel.Name = "ShutterLabel";
this.ShutterLabel.Size = new System.Drawing.Size(44, 13);
this.ShutterLabel.TabIndex = 0;
this.ShutterLabel.Text = "Shutter:";
this.ShutterLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// SetShutterButton
//
this.SetShutterButton.AutoSize = true;
this.SetShutterButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.SetShutterButton.Dock = System.Windows.Forms.DockStyle.Right;
this.SetShutterButton.Location = new System.Drawing.Point(161, 0);
this.SetShutterButton.Name = "SetShutterButton";
this.SetShutterButton.Size = new System.Drawing.Size(33, 23);
this.SetShutterButton.TabIndex = 2;
this.SetShutterButton.Text = "Set";
this.SetShutterButton.UseVisualStyleBackColor = true;
this.SetShutterButton.Click += new System.EventHandler(this.OnSetShutterClicked);
//
// FilterWheelPositionControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.TableLayout);
this.Name = "FilterWheelPositionControl";
this.Size = new System.Drawing.Size(200, 296);
this.TableLayout.ResumeLayout(false);
this.TableLayout.PerformLayout();
this.flowLayoutPanel1.ResumeLayout(false);
this.flowLayoutPanel1.PerformLayout();
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TableLayoutPanel TableLayout;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ListBox WheelsBox;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ListBox FiltersBox;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private System.Windows.Forms.Button SetFilterButton;
private System.Windows.Forms.Button TakeControlButton;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.ComboBox ShutterStateComboBox;
private System.Windows.Forms.Label ShutterLabel;
private System.Windows.Forms.Button SetShutterButton;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Pipes.Tests
{
/// <summary>
/// The Specific NamedPipe tests cover edge cases or otherwise narrow cases that
/// show up within particular server/client directional combinations.
/// </summary>
public class NamedPipeTest_Specific : NamedPipeTestBase
{
[Fact]
public void InvalidConnectTimeout_Throws_ArgumentOutOfRangeException()
{
using (NamedPipeClientStream client = new NamedPipeClientStream("client1"))
{
Assert.Throws<ArgumentOutOfRangeException>("timeout", () => client.Connect(-111));
Assert.Throws<ArgumentOutOfRangeException>("timeout", () => { client.ConnectAsync(-111); });
}
}
[Fact]
public async Task ConnectToNonExistentServer_Throws_TimeoutException()
{
using (NamedPipeClientStream client = new NamedPipeClientStream(".", "notthere"))
{
var ctx = new CancellationTokenSource();
Assert.Throws<TimeoutException>(() => client.Connect(60)); // 60 to be over internal 50 interval
await Assert.ThrowsAsync<TimeoutException>(() => client.ConnectAsync(50));
await Assert.ThrowsAsync<TimeoutException>(() => client.ConnectAsync(60, ctx.Token)); // testing Token overload; ctx is not canceled in this test
}
}
[Fact]
public async Task CancelConnectToNonExistentServer_Throws_OperationCanceledException()
{
using (NamedPipeClientStream client = new NamedPipeClientStream(".", "notthere"))
{
var ctx = new CancellationTokenSource();
Task clientConnectToken = client.ConnectAsync(ctx.Token);
ctx.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => clientConnectToken);
ctx.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => client.ConnectAsync(ctx.Token));
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // Unix implementation uses bidirectional sockets
public void ConnectWithConflictingDirections_Throws_UnauthorizedAccessException()
{
string serverName1 = GetUniquePipeName();
using (NamedPipeServerStream server = new NamedPipeServerStream(serverName1, PipeDirection.Out))
using (NamedPipeClientStream client = new NamedPipeClientStream(".", serverName1, PipeDirection.Out))
{
Assert.Throws<UnauthorizedAccessException>(() => client.Connect());
Assert.False(client.IsConnected);
}
string serverName2 = GetUniquePipeName();
using (NamedPipeServerStream server = new NamedPipeServerStream(serverName2, PipeDirection.In))
using (NamedPipeClientStream client = new NamedPipeClientStream(".", serverName2, PipeDirection.In))
{
Assert.Throws<UnauthorizedAccessException>(() => client.Connect());
Assert.False(client.IsConnected);
}
}
[Theory]
[InlineData(PipeOptions.None)]
[InlineData(PipeOptions.Asynchronous)]
[PlatformSpecific(PlatformID.Windows)] // Unix currently doesn't support message mode
public async Task Windows_MessagePipeTransissionMode(PipeOptions serverOptions)
{
byte[] msg1 = new byte[] { 5, 7, 9, 10 };
byte[] msg2 = new byte[] { 2, 4 };
byte[] received1 = new byte[] { 0, 0, 0, 0 };
byte[] received2 = new byte[] { 0, 0 };
byte[] received3 = new byte[] { 0, 0, 0, 0 };
byte[] received4 = new byte[] { 0, 0, 0, 0 };
byte[] received5 = new byte[] { 0, 0 };
byte[] received6 = new byte[] { 0, 0, 0, 0 };
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, serverOptions))
{
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation))
{
server.ReadMode = PipeTransmissionMode.Message;
Assert.Equal(PipeTransmissionMode.Message, server.ReadMode);
Task clientTask = Task.Run(() =>
{
client.Connect();
client.Write(msg1, 0, msg1.Length);
client.Write(msg2, 0, msg2.Length);
client.Write(msg1, 0, msg1.Length);
client.Write(msg1, 0, msg1.Length);
client.Write(msg2, 0, msg2.Length);
client.Write(msg1, 0, msg1.Length);
int serverCount = client.NumberOfServerInstances;
Assert.Equal(1, serverCount);
});
server.WaitForConnection();
int len1 = server.Read(received1, 0, msg1.Length);
Assert.True(server.IsMessageComplete);
Assert.Equal(msg1.Length, len1);
Assert.Equal(msg1, received1);
int len2 = server.Read(received2, 0, msg2.Length);
Assert.True(server.IsMessageComplete);
Assert.Equal(msg2.Length, len2);
Assert.Equal(msg2, received2);
int expectedRead = msg1.Length - 1;
int len3 = server.Read(received3, 0, expectedRead); // read one less than message
Assert.False(server.IsMessageComplete);
Assert.Equal(expectedRead, len3);
for (int i = 0; i < expectedRead; ++i)
{
Assert.Equal(msg1[i], received3[i]);
}
expectedRead = msg1.Length - expectedRead;
Assert.Equal(expectedRead, server.Read(received3, len3, expectedRead));
Assert.True(server.IsMessageComplete);
Assert.Equal(msg1, received3);
Assert.Equal(msg1.Length, await server.ReadAsync(received4, 0, msg1.Length));
Assert.True(server.IsMessageComplete);
Assert.Equal(msg1, received4);
Assert.Equal(msg2.Length, await server.ReadAsync(received5, 0, msg2.Length));
Assert.True(server.IsMessageComplete);
Assert.Equal(msg2, received5);
expectedRead = msg1.Length - 1;
Assert.Equal(expectedRead, await server.ReadAsync(received6, 0, expectedRead)); // read one less than message
Assert.False(server.IsMessageComplete);
for (int i = 0; i < expectedRead; ++i)
{
Assert.Equal(msg1[i], received6[i]);
}
expectedRead = msg1.Length - expectedRead;
Assert.Equal(expectedRead, await server.ReadAsync(received6, msg1.Length - expectedRead, expectedRead));
Assert.True(server.IsMessageComplete);
Assert.Equal(msg1, received6);
await clientTask;
}
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // Unix doesn't support MaxNumberOfServerInstances
public async Task Windows_Get_NumberOfServerInstances_Succeed()
{
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 3))
{
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation))
{
int expectedNumberOfServerInstances;
Task serverTask = server.WaitForConnectionAsync();
client.Connect();
await serverTask;
Assert.True(Interop.TryGetNumberOfServerInstances(client.SafePipeHandle, out expectedNumberOfServerInstances), "GetNamedPipeHandleState failed");
Assert.Equal(expectedNumberOfServerInstances, client.NumberOfServerInstances);
}
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // Win32 P/Invokes to verify the user name
public async Task Windows_GetImpersonationUserName_Succeed()
{
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName))
{
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation))
{
string expectedUserName;
Task serverTask = server.WaitForConnectionAsync();
client.Connect();
await serverTask;
Assert.True(Interop.TryGetImpersonationUserName(server.SafePipeHandle, out expectedUserName), "GetNamedPipeHandleState failed");
Assert.Equal(expectedUserName, server.GetImpersonationUserName());
}
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/1011
[PlatformSpecific(PlatformID.AnyUnix)]
public async Task Unix_GetImpersonationUserName_Succeed()
{
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation))
{
Task serverTask = server.WaitForConnectionAsync();
client.Connect();
await serverTask;
string name = server.GetImpersonationUserName();
Assert.NotNull(name);
Assert.False(string.IsNullOrWhiteSpace(name));
}
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void Unix_MessagePipeTransissionMode()
{
Assert.Throws<PlatformNotSupportedException>(() => new NamedPipeServerStream(GetUniquePipeName(), PipeDirection.InOut, 1, PipeTransmissionMode.Message));
}
[Theory]
[InlineData(PipeDirection.In)]
[InlineData(PipeDirection.Out)]
[InlineData(PipeDirection.InOut)]
[PlatformSpecific(PlatformID.AnyUnix)]
public static void Unix_BufferSizeRoundtripping(PipeDirection direction)
{
int desiredBufferSize = 0;
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
desiredBufferSize = server.OutBufferSize * 2;
}
using (var server = new NamedPipeServerStream(pipeName, direction, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize))
using (var client = new NamedPipeClientStream(".", pipeName, direction == PipeDirection.In ? PipeDirection.Out : PipeDirection.In))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
if ((direction & PipeDirection.Out) != 0)
{
Assert.InRange(server.OutBufferSize, desiredBufferSize, int.MaxValue);
}
if ((direction & PipeDirection.In) != 0)
{
Assert.InRange(server.InBufferSize, desiredBufferSize, int.MaxValue);
}
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public static void Windows_BufferSizeRoundtripping()
{
int desiredBufferSize = 10;
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
Assert.Equal(desiredBufferSize, server.OutBufferSize);
Assert.Equal(desiredBufferSize, client.InBufferSize);
}
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
Assert.Equal(desiredBufferSize, server.InBufferSize);
Assert.Equal(0, client.OutBufferSize);
}
}
[Fact]
public void PipeTransmissionMode_Returns_Byte()
{
using (ServerClientPair pair = CreateServerClientPair())
{
Assert.Equal(PipeTransmissionMode.Byte, pair.writeablePipe.TransmissionMode);
Assert.Equal(PipeTransmissionMode.Byte, pair.readablePipe.TransmissionMode);
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // Unix doesn't currently support message mode
public void Windows_SetReadModeTo__PipeTransmissionModeByte()
{
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
// Throws regardless of connection status for the pipe that is set to PipeDirection.In
Assert.Throws<UnauthorizedAccessException>(() => server.ReadMode = PipeTransmissionMode.Byte);
client.ReadMode = PipeTransmissionMode.Byte;
}
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
// Throws regardless of connection status for the pipe that is set to PipeDirection.In
Assert.Throws<UnauthorizedAccessException>(() => client.ReadMode = PipeTransmissionMode.Byte);
server.ReadMode = PipeTransmissionMode.Byte;
}
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
server.ReadMode = PipeTransmissionMode.Byte;
client.ReadMode = PipeTransmissionMode.Byte;
}
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void Unix_SetReadModeTo__PipeTransmissionModeByte()
{
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
server.ReadMode = PipeTransmissionMode.Byte;
client.ReadMode = PipeTransmissionMode.Byte;
}
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
client.ReadMode = PipeTransmissionMode.Byte;
server.ReadMode = PipeTransmissionMode.Byte;
}
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
server.ReadMode = PipeTransmissionMode.Byte;
client.ReadMode = PipeTransmissionMode.Byte;
}
}
[Theory]
[InlineData(PipeDirection.Out, PipeDirection.In)]
[InlineData(PipeDirection.In, PipeDirection.Out)]
public void InvalidReadMode_Throws_ArgumentOutOfRangeException(PipeDirection serverDirection, PipeDirection clientDirection)
{
string pipeName = GetUniquePipeName();
using (var server = new NamedPipeServerStream(pipeName, serverDirection, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
using (var client = new NamedPipeClientStream(".", pipeName, clientDirection))
{
Task clientConnect = client.ConnectAsync();
server.WaitForConnection();
clientConnect.Wait();
Assert.Throws<ArgumentOutOfRangeException>(() => server.ReadMode = (PipeTransmissionMode)999);
Assert.Throws<ArgumentOutOfRangeException>(() => client.ReadMode = (PipeTransmissionMode)999);
}
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void NameTooLong_MaxLengthPerPlatform()
{
// Increase a name's length until it fails
ArgumentOutOfRangeException e = null;
string name = Path.GetRandomFileName();
for (int i = 0; ; i++)
{
try
{
name += 'c';
using (var s = new NamedPipeServerStream(name))
using (var c = new NamedPipeClientStream(name))
{
Task t = s.WaitForConnectionAsync();
c.Connect();
t.GetAwaiter().GetResult();
}
}
catch (ArgumentOutOfRangeException exc)
{
e = exc;
break;
}
}
Assert.NotNull(e);
Assert.NotNull(e.ActualValue);
// Validate the length was expected
string path = (string)e.ActualValue;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Assert.Equal(108, path.Length);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Assert.Equal(104, path.Length);
}
else
{
Assert.InRange(path.Length, 92, int.MaxValue);
}
}
}
}
| |
#region license
// Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
//
// DO NOT EDIT THIS FILE!
//
// This file was generated automatically by astgen.boo.
//
namespace Boo.Lang.Compiler.Ast
{
using System.Collections;
using System.Runtime.Serialization;
[System.Serializable]
public partial class Field : TypeMember
{
protected TypeReference _type;
protected Expression _initializer;
protected bool _isVolatile;
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public Field CloneNode()
{
return (Field)Clone();
}
/// <summary>
/// <see cref="Node.CleanClone"/>
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public Field CleanClone()
{
return (Field)base.CleanClone();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get { return NodeType.Field; }
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.OnField(this);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Matches(Node node)
{
if (node == null) return false;
if (NodeType != node.NodeType) return false;
var other = ( Field)node;
if (_modifiers != other._modifiers) return NoMatch("Field._modifiers");
if (_name != other._name) return NoMatch("Field._name");
if (!Node.AllMatch(_attributes, other._attributes)) return NoMatch("Field._attributes");
if (!Node.Matches(_type, other._type)) return NoMatch("Field._type");
if (!Node.Matches(_initializer, other._initializer)) return NoMatch("Field._initializer");
if (_isVolatile != other._isVolatile) return NoMatch("Field._isVolatile");
return true;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Replace(Node existing, Node newNode)
{
if (base.Replace(existing, newNode))
{
return true;
}
if (_attributes != null)
{
Attribute item = existing as Attribute;
if (null != item)
{
Attribute newItem = (Attribute)newNode;
if (_attributes.Replace(item, newItem))
{
return true;
}
}
}
if (_type == existing)
{
this.Type = (TypeReference)newNode;
return true;
}
if (_initializer == existing)
{
this.Initializer = (Expression)newNode;
return true;
}
return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
Field clone = (Field)FormatterServices.GetUninitializedObject(typeof(Field));
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
clone._entity = _entity;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
clone._modifiers = _modifiers;
clone._name = _name;
if (null != _attributes)
{
clone._attributes = _attributes.Clone() as AttributeCollection;
clone._attributes.InitializeParent(clone);
}
if (null != _type)
{
clone._type = _type.Clone() as TypeReference;
clone._type.InitializeParent(clone);
}
if (null != _initializer)
{
clone._initializer = _initializer.Clone() as Expression;
clone._initializer.InitializeParent(clone);
}
clone._isVolatile = _isVolatile;
return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
_entity = null;
if (null != _attributes)
{
_attributes.ClearTypeSystemBindings();
}
if (null != _type)
{
_type.ClearTypeSystemBindings();
}
if (null != _initializer)
{
_initializer.ClearTypeSystemBindings();
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public TypeReference Type
{
get { return _type; }
set
{
if (_type != value)
{
_type = value;
if (null != _type)
{
_type.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Expression Initializer
{
get { return _initializer; }
set
{
if (_initializer != value)
{
_initializer = value;
if (null != _initializer)
{
_initializer.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public bool IsVolatile
{
get { return _isVolatile; }
set { _isVolatile = value; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Runtime.ExceptionServices;
using System.Threading;
namespace System.Net.Mime
{
internal class MimeMultiPart : MimeBasePart
{
private Collection<MimeBasePart> _parts;
private static int s_boundary;
private AsyncCallback _mimePartSentCallback;
private bool _allowUnicode;
internal MimeMultiPart(MimeMultiPartType type)
{
MimeMultiPartType = type;
}
internal MimeMultiPartType MimeMultiPartType
{
set
{
if (value > MimeMultiPartType.Related || value < MimeMultiPartType.Mixed)
{
throw new NotSupportedException(value.ToString());
}
SetType(value);
}
}
private void SetType(MimeMultiPartType type)
{
ContentType.MediaType = "multipart" + "/" + type.ToString().ToLower(CultureInfo.InvariantCulture);
ContentType.Boundary = GetNextBoundary();
}
internal Collection<MimeBasePart> Parts
{
get
{
if (_parts == null)
{
_parts = new Collection<MimeBasePart>();
}
return _parts;
}
}
internal void Complete(IAsyncResult result, Exception e)
{
//if we already completed and we got called again,
//it mean's that there was an exception in the callback and we
//should just rethrow it.
MimePartContext context = (MimePartContext)result.AsyncState;
if (context._completed)
{
ExceptionDispatchInfo.Capture(e).Throw();
}
try
{
context._outputStream.Close();
}
catch (Exception ex)
{
if (e == null)
{
e = ex;
}
}
context._completed = true;
context._result.InvokeCallback(e);
}
internal void MimeWriterCloseCallback(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
((MimePartContext)result.AsyncState)._completedSynchronously = false;
try
{
MimeWriterCloseCallbackHandler(result);
}
catch (Exception e)
{
Complete(result, e);
}
}
private void MimeWriterCloseCallbackHandler(IAsyncResult result)
{
MimePartContext context = (MimePartContext)result.AsyncState;
((MimeWriter)context._writer).EndClose(result);
Complete(result, null);
}
internal void MimePartSentCallback(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
((MimePartContext)result.AsyncState)._completedSynchronously = false;
try
{
MimePartSentCallbackHandler(result);
}
catch (Exception e)
{
Complete(result, e);
}
}
private void MimePartSentCallbackHandler(IAsyncResult result)
{
MimePartContext context = (MimePartContext)result.AsyncState;
MimeBasePart part = (MimeBasePart)context._partsEnumerator.Current;
part.EndSend(result);
if (context._partsEnumerator.MoveNext())
{
part = (MimeBasePart)context._partsEnumerator.Current;
IAsyncResult sendResult = part.BeginSend(context._writer, _mimePartSentCallback, _allowUnicode, context);
if (sendResult.CompletedSynchronously)
{
MimePartSentCallbackHandler(sendResult);
}
return;
}
else
{
IAsyncResult closeResult = ((MimeWriter)context._writer).BeginClose(new AsyncCallback(MimeWriterCloseCallback), context);
if (closeResult.CompletedSynchronously)
{
MimeWriterCloseCallbackHandler(closeResult);
}
}
}
internal void ContentStreamCallback(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
((MimePartContext)result.AsyncState)._completedSynchronously = false;
try
{
ContentStreamCallbackHandler(result);
}
catch (Exception e)
{
Complete(result, e);
}
}
private void ContentStreamCallbackHandler(IAsyncResult result)
{
MimePartContext context = (MimePartContext)result.AsyncState;
context._outputStream = context._writer.EndGetContentStream(result);
context._writer = new MimeWriter(context._outputStream, ContentType.Boundary);
if (context._partsEnumerator.MoveNext())
{
MimeBasePart part = (MimeBasePart)context._partsEnumerator.Current;
_mimePartSentCallback = new AsyncCallback(MimePartSentCallback);
IAsyncResult sendResult = part.BeginSend(context._writer, _mimePartSentCallback, _allowUnicode, context);
if (sendResult.CompletedSynchronously)
{
MimePartSentCallbackHandler(sendResult);
}
return;
}
else
{
IAsyncResult closeResult = ((MimeWriter)context._writer).BeginClose(new AsyncCallback(MimeWriterCloseCallback), context);
if (closeResult.CompletedSynchronously)
{
MimeWriterCloseCallbackHandler(closeResult);
}
}
}
internal override IAsyncResult BeginSend(BaseWriter writer, AsyncCallback callback, bool allowUnicode,
object state)
{
_allowUnicode = allowUnicode;
PrepareHeaders(allowUnicode);
writer.WriteHeaders(Headers, allowUnicode);
MimePartAsyncResult result = new MimePartAsyncResult(this, state, callback);
MimePartContext context = new MimePartContext(writer, result, Parts.GetEnumerator());
IAsyncResult contentResult = writer.BeginGetContentStream(new AsyncCallback(ContentStreamCallback), context);
if (contentResult.CompletedSynchronously)
{
ContentStreamCallbackHandler(contentResult);
}
return result;
}
internal class MimePartContext
{
internal MimePartContext(BaseWriter writer, LazyAsyncResult result, IEnumerator<MimeBasePart> partsEnumerator)
{
_writer = writer;
_result = result;
_partsEnumerator = partsEnumerator;
}
internal IEnumerator<MimeBasePart> _partsEnumerator;
internal Stream _outputStream;
internal LazyAsyncResult _result;
internal BaseWriter _writer;
internal bool _completed;
internal bool _completedSynchronously = true;
}
internal override void Send(BaseWriter writer, bool allowUnicode)
{
PrepareHeaders(allowUnicode);
writer.WriteHeaders(Headers, allowUnicode);
Stream outputStream = writer.GetContentStream();
MimeWriter mimeWriter = new MimeWriter(outputStream, ContentType.Boundary);
foreach (MimeBasePart part in Parts)
{
part.Send(mimeWriter, allowUnicode);
}
mimeWriter.Close();
outputStream.Close();
}
internal string GetNextBoundary()
{
int b = Interlocked.Increment(ref s_boundary) - 1;
string boundaryString = "--boundary_" + b.ToString(CultureInfo.InvariantCulture) + "_" + Guid.NewGuid().ToString(null, CultureInfo.InvariantCulture);
return boundaryString;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.AspNetCore.Routing.DecisionTree
{
// This code generates a minimal tree of decision criteria that map known categorical data
// (key-value-pairs) to a set of inputs. Action Selection is the best example of how this
// can be used, so the comments here will describe the process from the point-of-view,
// though the decision tree is generally applicable to like-problems.
//
// Care has been taken here to keep the performance of building the data-structure at a
// reasonable level, as this has an impact on startup cost for action selection. Additionally
// we want to hold on to the minimal amount of memory needed once we've built the tree.
//
// Ex:
// Given actions like the following, create a decision tree that will help action
// selection work efficiently.
//
// Given any set of route data it should be possible to traverse the tree using the
// presence our route data keys (like action), and whether or not they match any of
// the known values for that route data key, to find the set of actions that match
// the route data.
//
// Actions:
//
// { controller = "Home", action = "Index" }
// { controller = "Products", action = "Index" }
// { controller = "Products", action = "Buy" }
// { area = "Admin", controller = "Users", action = "AddUser" }
//
// The generated tree looks like this (json-like-notation):
//
// {
// action : {
// "AddUser" : {
// controller : {
// "Users" : {
// area : {
// "Admin" : match { area = "Admin", controller = "Users", action = "AddUser" }
// }
// }
// }
// },
// "Buy" : {
// controller : {
// "Products" : {
// area : {
// null : match { controller = "Products", action = "Buy" }
// }
// }
// }
// },
// "Index" : {
// controller : {
// "Home" : {
// area : {
// null : match { controller = "Home", action = "Index" }
// }
// }
// "Products" : {
// area : {
// "null" : match { controller = "Products", action = "Index" }
// }
// }
// }
// }
// }
// }
internal static class DecisionTreeBuilder<TItem>
{
public static DecisionTreeNode<TItem> GenerateTree(IReadOnlyList<TItem> items, IClassifier<TItem> classifier)
{
var itemCount = items.Count;
var itemDescriptors = new List<ItemDescriptor<TItem>>(itemCount);
for (var i = 0; i < itemCount; i++)
{
var item = items[i];
itemDescriptors.Add(new ItemDescriptor<TItem>()
{
Criteria = classifier.GetCriteria(item),
Index = i,
Item = item,
});
}
var comparer = new DecisionCriterionValueEqualityComparer(classifier.ValueComparer);
return GenerateNode(
new TreeBuilderContext(),
comparer,
itemDescriptors);
}
private static DecisionTreeNode<TItem> GenerateNode(
TreeBuilderContext context,
DecisionCriterionValueEqualityComparer comparer,
List<ItemDescriptor<TItem>> items)
{
// The extreme use of generics here is intended to reduce the number of intermediate
// allocations of wrapper classes. Performance testing found that building these trees allocates
// significant memory that we can avoid and that it has a real impact on startup.
var criteria = new Dictionary<string, Criterion>(StringComparer.OrdinalIgnoreCase);
// Matches are items that have no remaining criteria - at this point in the tree
// they are considered accepted.
var matches = new List<TItem>();
// For each item in the working set, we want to map it to it's possible criteria-branch
// pairings, then reduce that tree to the minimal set.
foreach (var item in items)
{
var unsatisfiedCriteria = 0;
foreach (var kvp in item.Criteria)
{
// context.CurrentCriteria is the logical 'stack' of criteria that we've already processed
// on this branch of the tree.
if (context.CurrentCriteria.Contains(kvp.Key))
{
continue;
}
unsatisfiedCriteria++;
if (!criteria.TryGetValue(kvp.Key, out var criterion))
{
criterion = new Criterion(comparer);
criteria.Add(kvp.Key, criterion);
}
if (!criterion.TryGetValue(kvp.Value, out var branch))
{
branch = new List<ItemDescriptor<TItem>>();
criterion.Add(kvp.Value, branch);
}
branch.Add(item);
}
// If all of the criteria on item are satisfied by the 'stack' then this item is a match.
if (unsatisfiedCriteria == 0)
{
matches.Add(item.Item);
}
}
// Iterate criteria in order of branchiness to determine which one to explore next. If a criterion
// has no 'new' matches under it then we can just eliminate that part of the tree.
var reducedCriteria = new List<DecisionCriterion<TItem>>();
foreach (var criterion in criteria.OrderByDescending(c => c.Value.Count))
{
var reducedBranches = new Dictionary<object, DecisionTreeNode<TItem>>(comparer.InnerComparer);
foreach (var branch in criterion.Value)
{
bool hasReducedItems = false;
foreach (var item in branch.Value)
{
if (context.MatchedItems.Add(item))
{
hasReducedItems = true;
}
}
if (hasReducedItems)
{
var childContext = new TreeBuilderContext(context);
childContext.CurrentCriteria.Add(criterion.Key);
var newBranch = GenerateNode(childContext, comparer, branch.Value);
reducedBranches.Add(branch.Key.Value, newBranch);
}
}
if (reducedBranches.Count > 0)
{
var newCriterion = new DecisionCriterion<TItem>()
{
Key = criterion.Key,
Branches = reducedBranches,
};
reducedCriteria.Add(newCriterion);
}
}
return new DecisionTreeNode<TItem>()
{
Criteria = reducedCriteria,
Matches = matches,
};
}
private class TreeBuilderContext
{
public TreeBuilderContext()
{
CurrentCriteria = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
MatchedItems = new HashSet<ItemDescriptor<TItem>>();
}
public TreeBuilderContext(TreeBuilderContext other)
{
CurrentCriteria = new HashSet<string>(other.CurrentCriteria, StringComparer.OrdinalIgnoreCase);
MatchedItems = new HashSet<ItemDescriptor<TItem>>();
}
public HashSet<string> CurrentCriteria { get; private set; }
public HashSet<ItemDescriptor<TItem>> MatchedItems { get; private set; }
}
// Subclass just to give a logical name to a mess of generics
private class Criterion : Dictionary<DecisionCriterionValue, List<ItemDescriptor<TItem>>>
{
public Criterion(DecisionCriterionValueEqualityComparer comparer)
: base(comparer)
{
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using AstUtils = System.Management.Automation.Interpreter.Utils;
namespace System.Management.Automation.Interpreter
{
internal static class TypeUtils
{
internal static Type GetNonNullableType(this Type type)
{
if (IsNullableType(type))
{
return type.GetGenericArguments()[0];
}
return type;
}
internal static Type GetNullableType(Type type)
{
Debug.Assert(type != null, "type cannot be null");
if (type.IsValueType && !IsNullableType(type))
{
return typeof(Nullable<>).MakeGenericType(type);
}
return type;
}
internal static bool IsNullableType(Type type)
{
return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
internal static bool IsBool(Type type)
{
return GetNonNullableType(type) == typeof(bool);
}
internal static bool IsNumeric(Type type)
{
type = GetNonNullableType(type);
if (!type.IsEnum)
{
switch (type.GetTypeCode())
{
case TypeCode.Char:
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Double:
case TypeCode.Single:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
}
}
return false;
}
internal static bool IsNumeric(TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.Char:
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Double:
case TypeCode.Single:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
}
return false;
}
internal static bool IsArithmetic(Type type)
{
type = GetNonNullableType(type);
if (!type.IsEnum)
{
switch (type.GetTypeCode())
{
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Double:
case TypeCode.Single:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
}
}
return false;
}
}
internal static class ArrayUtils
{
internal static T[] AddLast<T>(this IList<T> list, T item)
{
T[] res = new T[list.Count + 1];
list.CopyTo(res, 0);
res[list.Count] = item;
return res;
}
}
internal static partial class DelegateHelpers
{
#region Generated Maximum Delegate Arity
// *** BEGIN GENERATED CODE ***
// generated by function: gen_max_delegate_arity from: generate_dynsites.py
private const int MaximumArity = 17;
// *** END GENERATED CODE ***
#endregion
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
internal static Type MakeDelegate(Type[] types)
{
Debug.Assert(types != null && types.Length > 0);
// Can only used predefined delegates if we have no byref types and
// the arity is small enough to fit in Func<...> or Action<...>
if (types.Length > MaximumArity || types.Any(t => t.IsByRef))
{
throw Assert.Unreachable;
// return MakeCustomDelegate(types);
}
Type returnType = types[types.Length - 1];
if (returnType == typeof(void))
{
Array.Resize(ref types, types.Length - 1);
switch (types.Length)
{
case 0: return typeof(Action);
#region Generated Delegate Action Types
// *** BEGIN GENERATED CODE ***
// generated by function: gen_delegate_action from: generate_dynsites.py
case 1: return typeof(Action<>).MakeGenericType(types);
case 2: return typeof(Action<,>).MakeGenericType(types);
case 3: return typeof(Action<,,>).MakeGenericType(types);
case 4: return typeof(Action<,,,>).MakeGenericType(types);
case 5: return typeof(Action<,,,,>).MakeGenericType(types);
case 6: return typeof(Action<,,,,,>).MakeGenericType(types);
case 7: return typeof(Action<,,,,,,>).MakeGenericType(types);
case 8: return typeof(Action<,,,,,,,>).MakeGenericType(types);
case 9: return typeof(Action<,,,,,,,,>).MakeGenericType(types);
case 10: return typeof(Action<,,,,,,,,,>).MakeGenericType(types);
case 11: return typeof(Action<,,,,,,,,,,>).MakeGenericType(types);
case 12: return typeof(Action<,,,,,,,,,,,>).MakeGenericType(types);
case 13: return typeof(Action<,,,,,,,,,,,,>).MakeGenericType(types);
case 14: return typeof(Action<,,,,,,,,,,,,,>).MakeGenericType(types);
case 15: return typeof(Action<,,,,,,,,,,,,,,>).MakeGenericType(types);
case 16: return typeof(Action<,,,,,,,,,,,,,,,>).MakeGenericType(types);
// *** END GENERATED CODE ***
#endregion
}
}
else
{
switch (types.Length)
{
#region Generated Delegate Func Types
// *** BEGIN GENERATED CODE ***
// generated by function: gen_delegate_func from: generate_dynsites.py
case 1: return typeof(Func<>).MakeGenericType(types);
case 2: return typeof(Func<,>).MakeGenericType(types);
case 3: return typeof(Func<,,>).MakeGenericType(types);
case 4: return typeof(Func<,,,>).MakeGenericType(types);
case 5: return typeof(Func<,,,,>).MakeGenericType(types);
case 6: return typeof(Func<,,,,,>).MakeGenericType(types);
case 7: return typeof(Func<,,,,,,>).MakeGenericType(types);
case 8: return typeof(Func<,,,,,,,>).MakeGenericType(types);
case 9: return typeof(Func<,,,,,,,,>).MakeGenericType(types);
case 10: return typeof(Func<,,,,,,,,,>).MakeGenericType(types);
case 11: return typeof(Func<,,,,,,,,,,>).MakeGenericType(types);
case 12: return typeof(Func<,,,,,,,,,,,>).MakeGenericType(types);
case 13: return typeof(Func<,,,,,,,,,,,,>).MakeGenericType(types);
case 14: return typeof(Func<,,,,,,,,,,,,,>).MakeGenericType(types);
case 15: return typeof(Func<,,,,,,,,,,,,,,>).MakeGenericType(types);
case 16: return typeof(Func<,,,,,,,,,,,,,,,>).MakeGenericType(types);
case 17: return typeof(Func<,,,,,,,,,,,,,,,,>).MakeGenericType(types);
// *** END GENERATED CODE ***
#endregion
}
}
throw Assert.Unreachable;
}
}
internal class ScriptingRuntimeHelpers
{
internal static object Int32ToObject(int i)
{
return i;
}
internal static object BooleanToObject(bool b)
{
return b ? True : False;
}
internal static readonly MethodInfo BooleanToObjectMethod = typeof(ScriptingRuntimeHelpers).GetMethod("BooleanToObject");
internal static readonly MethodInfo Int32ToObjectMethod = typeof(ScriptingRuntimeHelpers).GetMethod("Int32ToObject");
internal static object True = true;
internal static object False = false;
internal static object GetPrimitiveDefaultValue(Type type)
{
switch (type.GetTypeCode())
{
case TypeCode.Boolean: return ScriptingRuntimeHelpers.False;
case TypeCode.SByte: return default(SByte);
case TypeCode.Byte: return default(Byte);
case TypeCode.Char: return default(Char);
case TypeCode.Int16: return default(Int16);
case TypeCode.Int32: return ScriptingRuntimeHelpers.Int32ToObject(0);
case TypeCode.Int64: return default(Int64);
case TypeCode.UInt16: return default(UInt16);
case TypeCode.UInt32: return default(UInt32);
case TypeCode.UInt64: return default(UInt64);
case TypeCode.Single: return default(Single);
case TypeCode.Double: return default(Double);
case TypeCode.DateTime: return default(DateTime);
case TypeCode.Decimal: return default(Decimal);
// TypeCode.Empty: null;
// TypeCode.Object: default(object) == null;
// TypeCode.DBNull: default(DBNull) == null;
// TypeCode.String: default(string) == null;
default: return null;
}
}
}
/// <summary>
/// Wraps all arguments passed to a dynamic site with more arguments than can be accepted by a Func/Action delegate.
/// The binder generating a rule for such a site should unwrap the arguments first and then perform a binding to them.
/// </summary>
internal sealed class ArgumentArray
{
private readonly object[] _arguments;
// the index of the first item _arguments that represents an argument:
private readonly int _first;
// the number of items in _arguments that represent the arguments:
internal ArgumentArray(object[] arguments, int first, int count)
{
_arguments = arguments;
_first = first;
Count = count;
}
public int Count { get; }
public object GetArgument(int index)
{
// ContractUtils.RequiresArrayIndex(_arguments, index, "index");
return _arguments[_first + index];
}
public DynamicMetaObject GetMetaObject(Expression parameter, int index)
{
return DynamicMetaObject.Create(
GetArgument(index),
Expression.Call(
s_getArgMethod,
AstUtils.Convert(parameter, typeof(ArgumentArray)),
AstUtils.Constant(index)
)
);
}
// [CLSCompliant(false)]
public static object GetArg(ArgumentArray array, int index)
{
return array._arguments[array._first + index];
}
private static readonly MethodInfo s_getArgMethod = new Func<ArgumentArray, int, object>(GetArg).GetMethodInfo();
}
internal static class ExceptionHelpers
{
private const string prevStackTraces = "PreviousStackTraces";
/// <summary>
/// Updates an exception before it's getting re-thrown so
/// we can present a reasonable stack trace to the user.
/// </summary>
public static Exception UpdateForRethrow(Exception rethrow)
{
#if !SILVERLIGHT
List<StackTrace> prev;
// we don't have any dynamic stack trace data, capture the data we can
// from the raw exception object.
StackTrace st = new StackTrace(rethrow, true);
if (!TryGetAssociatedStackTraces(rethrow, out prev))
{
prev = new List<StackTrace>();
AssociateStackTraces(rethrow, prev);
}
prev.Add(st);
#endif
return rethrow;
}
/// <summary>
/// Returns all the stack traces associates with an exception.
/// </summary>
public static IList<StackTrace> GetExceptionStackTraces(Exception rethrow)
{
List<StackTrace> result;
return TryGetAssociatedStackTraces(rethrow, out result) ? result : null;
}
private static void AssociateStackTraces(Exception e, List<StackTrace> traces)
{
e.Data[prevStackTraces] = traces;
}
private static bool TryGetAssociatedStackTraces(Exception e, out List<StackTrace> traces)
{
traces = e.Data[prevStackTraces] as List<StackTrace>;
return traces != null;
}
}
/// <summary>
/// A hybrid dictionary which compares based upon object identity.
/// </summary>
internal class HybridReferenceDictionary<TKey, TValue> where TKey : class
{
private KeyValuePair<TKey, TValue>[] _keysAndValues;
private Dictionary<TKey, TValue> _dict;
private int _count;
private const int _arraySize = 10;
public HybridReferenceDictionary()
{
}
public HybridReferenceDictionary(int initialCapacity)
{
if (initialCapacity > _arraySize)
{
_dict = new Dictionary<TKey, TValue>(initialCapacity);
}
else
{
_keysAndValues = new KeyValuePair<TKey, TValue>[initialCapacity];
}
}
public bool TryGetValue(TKey key, out TValue value)
{
Debug.Assert(key != null);
if (_dict != null)
{
return _dict.TryGetValue(key, out value);
}
else if (_keysAndValues != null)
{
for (int i = 0; i < _keysAndValues.Length; i++)
{
if (_keysAndValues[i].Key == key)
{
value = _keysAndValues[i].Value;
return true;
}
}
}
value = default(TValue);
return false;
}
public bool Remove(TKey key)
{
Debug.Assert(key != null);
if (_dict != null)
{
return _dict.Remove(key);
}
else if (_keysAndValues != null)
{
for (int i = 0; i < _keysAndValues.Length; i++)
{
if (_keysAndValues[i].Key == key)
{
_keysAndValues[i] = new KeyValuePair<TKey, TValue>();
_count--;
return true;
}
}
}
return false;
}
public bool ContainsKey(TKey key)
{
Debug.Assert(key != null);
if (_dict != null)
{
return _dict.ContainsKey(key);
}
else if (_keysAndValues != null)
{
for (int i = 0; i < _keysAndValues.Length; i++)
{
if (_keysAndValues[i].Key == key)
{
return true;
}
}
}
return false;
}
public int Count
{
get
{
if (_dict != null)
{
return _dict.Count;
}
return _count;
}
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
if (_dict != null)
{
return _dict.GetEnumerator();
}
return GetEnumeratorWorker();
}
private IEnumerator<KeyValuePair<TKey, TValue>> GetEnumeratorWorker()
{
if (_keysAndValues != null)
{
for (int i = 0; i < _keysAndValues.Length; i++)
{
if (_keysAndValues[i].Key != null)
{
yield return _keysAndValues[i];
}
}
}
}
public TValue this[TKey key]
{
get
{
Debug.Assert(key != null);
TValue res;
if (TryGetValue(key, out res))
{
return res;
}
throw new KeyNotFoundException();
}
set
{
Debug.Assert(key != null);
if (_dict != null)
{
_dict[key] = value;
}
else
{
int index;
if (_keysAndValues != null)
{
index = -1;
for (int i = 0; i < _keysAndValues.Length; i++)
{
if (_keysAndValues[i].Key == key)
{
_keysAndValues[i] = new KeyValuePair<TKey, TValue>(key, value);
return;
}
else if (_keysAndValues[i].Key == null)
{
index = i;
}
}
}
else
{
_keysAndValues = new KeyValuePair<TKey, TValue>[_arraySize];
index = 0;
}
if (index != -1)
{
_count++;
_keysAndValues[index] = new KeyValuePair<TKey, TValue>(key, value);
}
else
{
_dict = new Dictionary<TKey, TValue>();
for (int i = 0; i < _keysAndValues.Length; i++)
{
_dict[_keysAndValues[i].Key] = _keysAndValues[i].Value;
}
_keysAndValues = null;
_dict[key] = value;
}
}
}
}
}
/// <summary>
/// Provides a dictionary-like object used for caches which holds onto a maximum
/// number of elements specified at construction time.
///
/// This class is not thread safe.
/// </summary>
internal class CacheDict<TKey, TValue>
{
private readonly Dictionary<TKey, KeyInfo> _dict = new Dictionary<TKey, KeyInfo>();
private readonly LinkedList<TKey> _list = new LinkedList<TKey>();
private readonly int _maxSize;
/// <summary>
/// Creates a dictionary-like object used for caches.
/// </summary>
/// <param name="maxSize">The maximum number of elements to store.</param>
public CacheDict(int maxSize)
{
_maxSize = maxSize;
}
/// <summary>
/// Tries to get the value associated with 'key', returning true if it's found and
/// false if it's not present.
/// </summary>
public bool TryGetValue(TKey key, out TValue value)
{
KeyInfo storedValue;
if (_dict.TryGetValue(key, out storedValue))
{
LinkedListNode<TKey> node = storedValue.List;
if (node.Previous != null)
{
// move us to the head of the list...
_list.Remove(node);
_list.AddFirst(node);
}
value = storedValue.Value;
return true;
}
value = default(TValue);
return false;
}
/// <summary>
/// Adds a new element to the cache, replacing and moving it to the front if the
/// element is already present.
/// </summary>
public void Add(TKey key, TValue value)
{
KeyInfo keyInfo;
if (_dict.TryGetValue(key, out keyInfo))
{
// remove original entry from the linked list
_list.Remove(keyInfo.List);
}
else if (_list.Count == _maxSize)
{
// we've reached capacity, remove the last used element...
LinkedListNode<TKey> node = _list.Last;
_list.RemoveLast();
bool res = _dict.Remove(node.Value);
Debug.Assert(res);
}
// add the new entry to the head of the list and into the dictionary
LinkedListNode<TKey> listNode = new LinkedListNode<TKey>(key);
_list.AddFirst(listNode);
_dict[key] = new CacheDict<TKey, TValue>.KeyInfo(value, listNode);
}
/// <summary>
/// Returns the value associated with the given key, or throws KeyNotFoundException
/// if the key is not present.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public TValue this[TKey key]
{
get
{
TValue res;
if (TryGetValue(key, out res))
{
return res;
}
throw new KeyNotFoundException();
}
set
{
Add(key, value);
}
}
private struct KeyInfo
{
internal readonly TValue Value;
internal readonly LinkedListNode<TKey> List;
internal KeyInfo(TValue value, LinkedListNode<TKey> list)
{
Value = value;
List = list;
}
}
}
internal class ThreadLocal<T>
{
private StorageInfo[] _stores; // array of storage indexed by managed thread ID
private static readonly StorageInfo[] s_updating = Automation.Utils.EmptyArray<StorageInfo>(); // a marker used when updating the array
private readonly bool _refCounted;
public ThreadLocal()
{
}
/// <summary>
/// True if the caller will guarantee that all cleanup happens as the thread
/// unwinds.
///
/// This is typically used in a case where the thread local is surrounded by
/// a try/finally block. The try block pushes some state, the finally block
/// restores the previous state. Therefore when the thread exits the thread
/// local is back to it's original state. This allows the ThreadLocal object
/// to not check the current owning thread on retrieval.
/// </summary>
public ThreadLocal(bool refCounted)
{
_refCounted = refCounted;
}
#region Public API
/// <summary>
/// Gets or sets the value for the current thread.
/// </summary>
public T Value
{
get
{
return GetStorageInfo().Value;
}
set
{
GetStorageInfo().Value = value;
}
}
/// <summary>
/// Gets the current value if its not == null or calls the provided function
/// to create a new value.
/// </summary>
public T GetOrCreate(Func<T> func)
{
Assert.NotNull(func);
StorageInfo si = GetStorageInfo();
T res = si.Value;
if (res == null)
{
si.Value = res = func();
}
return res;
}
/// <summary>
/// Calls the provided update function with the current value and
/// replaces the current value with the result of the function.
/// </summary>
public T Update(Func<T, T> updater)
{
Assert.NotNull(updater);
StorageInfo si = GetStorageInfo();
return si.Value = updater(si.Value);
}
/// <summary>
/// Replaces the current value with a new one and returns the old value.
/// </summary>
public T Update(T newValue)
{
StorageInfo si = GetStorageInfo();
var oldValue = si.Value;
si.Value = newValue;
return oldValue;
}
#endregion
#region Storage implementation
/// <summary>
/// Gets the StorageInfo for the current thread.
/// </summary>
public StorageInfo GetStorageInfo()
{
return GetStorageInfo(_stores);
}
private StorageInfo GetStorageInfo(StorageInfo[] curStorage)
{
int threadId = Thread.CurrentThread.ManagedThreadId;
// fast path if we already have a value in the array
if (curStorage != null && curStorage.Length > threadId)
{
StorageInfo res = curStorage[threadId];
if (res != null && (_refCounted || res.Thread == Thread.CurrentThread))
{
return res;
}
}
return RetryOrCreateStorageInfo(curStorage);
}
/// <summary>
/// Called when the fast path storage lookup fails. if we encountered the Empty storage
/// during the initial fast check then spin until we hit non-empty storage and try the fast
/// path again.
/// </summary>
private StorageInfo RetryOrCreateStorageInfo(StorageInfo[] curStorage)
{
if (curStorage == s_updating)
{
// we need to retry
while ((curStorage = _stores) == s_updating)
{
Thread.Sleep(0);
}
// we now have a non-empty storage info to retry with
return GetStorageInfo(curStorage);
}
// we need to mutate the StorageInfo[] array or create a new StorageInfo
return CreateStorageInfo();
}
/// <summary>
/// Creates the StorageInfo for the thread when one isn't already present.
/// </summary>
private StorageInfo CreateStorageInfo()
{
// we do our own locking, tell hosts this is a bad time to interrupt us.
Thread.BeginCriticalRegion();
StorageInfo[] curStorage = s_updating;
try
{
int threadId = Thread.CurrentThread.ManagedThreadId;
StorageInfo newInfo = new StorageInfo(Thread.CurrentThread);
// set to updating while potentially resizing/mutating, then we'll
// set back to the current value.
while ((curStorage = Interlocked.Exchange(ref _stores, s_updating)) == s_updating)
{
// another thread is already updating...
Thread.Sleep(0);
}
// check and make sure we have a space in the array for our value
if (curStorage == null)
{
curStorage = new StorageInfo[threadId + 1];
}
else if (curStorage.Length <= threadId)
{
StorageInfo[] newStorage = new StorageInfo[threadId + 1];
for (int i = 0; i < curStorage.Length; i++)
{
// leave out the threads that have exited
if (curStorage[i] != null && curStorage[i].Thread.IsAlive)
{
newStorage[i] = curStorage[i];
}
}
curStorage = newStorage;
}
// create our StorageInfo in the array, the empty check ensures we're only here
// when we need to create.
Debug.Assert(curStorage[threadId] == null || curStorage[threadId].Thread != Thread.CurrentThread);
return curStorage[threadId] = newInfo;
}
finally
{
if (curStorage != s_updating)
{
// let others access the storage again
Interlocked.Exchange(ref _stores, curStorage);
}
Thread.EndCriticalRegion();
}
}
/// <summary>
/// Helper class for storing the value. We need to track if a ManagedThreadId
/// has been re-used so we also store the thread which owns the value.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] // TODO
internal sealed class StorageInfo
{
internal readonly Thread Thread; // the thread that owns the StorageInfo
public T Value; // the current value for the owning thread
internal StorageInfo(Thread curThread)
{
Assert.NotNull(curThread);
Thread = curThread;
}
}
#endregion
}
internal static class Assert
{
internal static Exception Unreachable
{
get
{
Debug.Assert(false, "Unreachable");
return new InvalidOperationException("Code supposed to be unreachable");
}
}
[Conditional("DEBUG")]
public static void NotNull(object var)
{
Debug.Assert(var != null);
}
[Conditional("DEBUG")]
public static void NotNull(object var1, object var2)
{
Debug.Assert(var1 != null && var2 != null);
}
[Conditional("DEBUG")]
public static void NotNull(object var1, object var2, object var3)
{
Debug.Assert(var1 != null && var2 != null && var3 != null);
}
[Conditional("DEBUG")]
public static void NotNullItems<T>(IEnumerable<T> items) where T : class
{
Debug.Assert(items != null);
foreach (object item in items)
{
Debug.Assert(item != null);
}
}
[Conditional("DEBUG")]
public static void NotEmpty(string str)
{
Debug.Assert(!string.IsNullOrEmpty(str));
}
}
[Flags]
internal enum ExpressionAccess
{
None = 0,
Read = 1,
Write = 2,
ReadWrite = Read | Write,
}
internal static class Utils
{
internal static Expression Constant(object value)
{
return Expression.Constant(value);
}
private static readonly DefaultExpression s_voidInstance = Expression.Empty();
public static DefaultExpression Empty()
{
return s_voidInstance;
}
public static Expression Void(Expression expression)
{
// ContractUtils.RequiresNotNull(expression, "expression");
if (expression.Type == typeof(void))
{
return expression;
}
return Expression.Block(expression, Utils.Empty());
}
public static DefaultExpression Default(Type type)
{
if (type == typeof(void))
{
return Empty();
}
return Expression.Default(type);
}
public static Expression Convert(Expression expression, Type type)
{
// ContractUtils.RequiresNotNull(expression, "expression");
if (expression.Type == type)
{
return expression;
}
if (expression.Type == typeof(void))
{
return Expression.Block(expression, Utils.Default(type));
}
if (type == typeof(void))
{
return Void(expression);
}
// TODO: this is not the right level for this to be at. It should
// be pushed into languages if they really want this behavior.
if (type == typeof(object))
{
return Box(expression);
}
return Expression.Convert(expression, type);
}
public static Expression Box(Expression expression)
{
MethodInfo m;
if (expression.Type == typeof(int))
{
m = ScriptingRuntimeHelpers.Int32ToObjectMethod;
}
else if (expression.Type == typeof(bool))
{
m = ScriptingRuntimeHelpers.BooleanToObjectMethod;
}
else
{
m = null;
}
return Expression.Convert(expression, typeof(object), m);
}
public static bool IsReadWriteAssignment(this ExpressionType type)
{
switch (type)
{
// unary:
case ExpressionType.PostDecrementAssign:
case ExpressionType.PostIncrementAssign:
case ExpressionType.PreDecrementAssign:
case ExpressionType.PreIncrementAssign:
// binary - compound:
case ExpressionType.AddAssign:
case ExpressionType.AddAssignChecked:
case ExpressionType.AndAssign:
case ExpressionType.DivideAssign:
case ExpressionType.ExclusiveOrAssign:
case ExpressionType.LeftShiftAssign:
case ExpressionType.ModuloAssign:
case ExpressionType.MultiplyAssign:
case ExpressionType.MultiplyAssignChecked:
case ExpressionType.OrAssign:
case ExpressionType.PowerAssign:
case ExpressionType.RightShiftAssign:
case ExpressionType.SubtractAssign:
case ExpressionType.SubtractAssignChecked:
return true;
}
return false;
}
}
internal static class CollectionExtension
{
internal static bool TrueForAll<T>(this IEnumerable<T> collection, Predicate<T> predicate)
{
// ContractUtils.RequiresNotNull(collection, "collection");
// ContractUtils.RequiresNotNull(predicate, "predicate");
foreach (T item in collection)
{
if (!predicate(item)) return false;
}
return true;
}
internal static U[] Map<T, U>(this ICollection<T> collection, Func<T, U> select)
{
int count = collection.Count;
U[] result = new U[count];
count = 0;
foreach (T t in collection)
{
result[count++] = select(t);
}
return result;
}
// We could probably improve the hashing here
internal static int ListHashCode<T>(this IEnumerable<T> list)
{
var cmp = EqualityComparer<T>.Default;
int h = 6551;
foreach (T t in list)
{
h ^= (h << 5) ^ cmp.GetHashCode(t);
}
return h;
}
internal static bool ListEquals<T>(this ICollection<T> first, ICollection<T> second)
{
if (first.Count != second.Count)
{
return false;
}
var cmp = EqualityComparer<T>.Default;
var f = first.GetEnumerator();
var s = second.GetEnumerator();
while (f.MoveNext())
{
s.MoveNext();
if (!cmp.Equals(f.Current, s.Current))
{
return false;
}
}
return true;
}
}
internal sealed class ListEqualityComparer<T> : EqualityComparer<ICollection<T>>
{
internal static readonly ListEqualityComparer<T> Instance = new ListEqualityComparer<T>();
private ListEqualityComparer() { }
// EqualityComparer<T> handles null and object identity for us
public override bool Equals(ICollection<T> x, ICollection<T> y)
{
return x.ListEquals(y);
}
public override int GetHashCode(ICollection<T> obj)
{
return obj.ListHashCode();
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
#if !SILVERLIGHT // ComObject
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices.ComTypes;
using System.Threading;
using ComTypes = System.Runtime.InteropServices.ComTypes;
namespace System.Management.Automation.ComInterop
{
internal class ComTypeDesc : ComTypeLibMemberDesc
{
private string _typeName;
private string _documentation;
//Hashtable is threadsafe for multiple readers single writer.
//Enumerating and writing is mutually exclusive so require locking.
private Hashtable _putRefs;
private ComMethodDesc _getItem;
private ComMethodDesc _setItem;
internal ComTypeDesc(ITypeInfo typeInfo, ComType memberType, ComTypeLibDesc typeLibDesc) : base(memberType)
{
if (typeInfo != null)
{
ComRuntimeHelpers.GetInfoFromType(typeInfo, out _typeName, out _documentation);
}
TypeLib = typeLibDesc;
}
internal static ComTypeDesc FromITypeInfo(ComTypes.ITypeInfo typeInfo, ComTypes.TYPEATTR typeAttr)
{
if (typeAttr.typekind == ComTypes.TYPEKIND.TKIND_COCLASS)
{
return new ComTypeClassDesc(typeInfo, null);
}
else if (typeAttr.typekind == ComTypes.TYPEKIND.TKIND_ENUM)
{
return new ComTypeEnumDesc(typeInfo, null);
}
else if ((typeAttr.typekind == ComTypes.TYPEKIND.TKIND_DISPATCH) ||
(typeAttr.typekind == ComTypes.TYPEKIND.TKIND_INTERFACE))
{
ComTypeDesc typeDesc = new ComTypeDesc(typeInfo, ComType.Interface, null);
return typeDesc;
}
else
{
throw new InvalidOperationException("Attempting to wrap an unsupported enum type.");
}
}
internal static ComTypeDesc CreateEmptyTypeDesc()
{
ComTypeDesc typeDesc = new ComTypeDesc(null, ComType.Interface, null);
typeDesc.Funcs = new Hashtable();
typeDesc.Puts = new Hashtable();
typeDesc._putRefs = new Hashtable();
typeDesc.Events = EmptyEvents;
return typeDesc;
}
internal static Dictionary<string, ComEventDesc> EmptyEvents { get; } = new Dictionary<string, ComEventDesc>();
internal Hashtable Funcs { get; set; }
internal Hashtable Puts { get; set; }
internal Hashtable PutRefs
{
set { _putRefs = value; }
}
internal Dictionary<string, ComEventDesc> Events { get; set; }
internal bool TryGetFunc(string name, out ComMethodDesc method)
{
name = name.ToUpper(System.Globalization.CultureInfo.InvariantCulture);
if (Funcs.ContainsKey(name))
{
method = Funcs[name] as ComMethodDesc;
return true;
}
method = null;
return false;
}
internal void AddFunc(string name, ComMethodDesc method)
{
name = name.ToUpper(System.Globalization.CultureInfo.InvariantCulture);
lock (Funcs)
{
Funcs[name] = method;
}
}
internal bool TryGetPut(string name, out ComMethodDesc method)
{
name = name.ToUpper(System.Globalization.CultureInfo.InvariantCulture);
if (Puts.ContainsKey(name))
{
method = Puts[name] as ComMethodDesc;
return true;
}
method = null;
return false;
}
internal void AddPut(string name, ComMethodDesc method)
{
name = name.ToUpper(System.Globalization.CultureInfo.InvariantCulture);
lock (Puts)
{
Puts[name] = method;
}
}
internal bool TryGetPutRef(string name, out ComMethodDesc method)
{
name = name.ToUpper(System.Globalization.CultureInfo.InvariantCulture);
if (_putRefs.ContainsKey(name))
{
method = _putRefs[name] as ComMethodDesc;
return true;
}
method = null;
return false;
}
internal void AddPutRef(string name, ComMethodDesc method)
{
name = name.ToUpper(System.Globalization.CultureInfo.InvariantCulture);
lock (_putRefs)
{
_putRefs[name] = method;
}
}
internal bool TryGetEvent(string name, out ComEventDesc @event)
{
name = name.ToUpper(System.Globalization.CultureInfo.InvariantCulture);
return Events.TryGetValue(name, out @event);
}
internal string[] GetMemberNames(bool dataOnly)
{
var names = new Dictionary<string, object>();
lock (Funcs)
{
foreach (ComMethodDesc func in Funcs.Values)
{
if (!dataOnly || func.IsDataMember)
{
names.Add(func.Name, null);
}
}
}
if (!dataOnly)
{
lock (Puts)
{
foreach (ComMethodDesc func in Puts.Values)
{
if (!names.ContainsKey(func.Name))
{
names.Add(func.Name, null);
}
}
}
lock (_putRefs)
{
foreach (ComMethodDesc func in _putRefs.Values)
{
if (!names.ContainsKey(func.Name))
{
names.Add(func.Name, null);
}
}
}
if (Events != null && Events.Count > 0)
{
foreach (string name in Events.Keys)
{
if (!names.ContainsKey(name))
{
names.Add(name, null);
}
}
}
}
var keys = names.Keys;
string[] result = new string[keys.Count];
keys.CopyTo(result, 0);
return result;
}
// this property is public - accessed by an AST
public string TypeName
{
get { return _typeName; }
}
internal string Documentation
{
get { return _documentation; }
}
// this property is public - accessed by an AST
public ComTypeLibDesc TypeLib { get; }
internal Guid Guid { get; set; }
internal ComMethodDesc GetItem
{
get { return _getItem; }
}
internal void EnsureGetItem(ComMethodDesc candidate)
{
Interlocked.CompareExchange(ref _getItem, candidate, null);
}
internal ComMethodDesc SetItem
{
get { return _setItem; }
}
internal void EnsureSetItem(ComMethodDesc candidate)
{
Interlocked.CompareExchange(ref _setItem, candidate, null);
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Tests
{
public partial class VersionTests
{
[Fact]
public void Ctor_Default()
{
VerifyVersion(new Version(), 0, 0, -1, -1);
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void Ctor_String(string input, Version expected)
{
Assert.Equal(expected, new Version(input));
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void CtorInvalidVerionString_ThrowsException(string input, Type exceptionType)
{
Assert.Throws(exceptionType, () => new Version(input));
}
[Theory]
[InlineData(0, 0)]
[InlineData(2, 3)]
[InlineData(int.MaxValue, int.MaxValue)]
public static void Ctor_Int_Int(int major, int minor)
{
VerifyVersion(new Version(major, minor), major, minor, -1, -1);
}
[Theory]
[InlineData(0, 0, 0)]
[InlineData(2, 3, 4)]
[InlineData(int.MaxValue, int.MaxValue, int.MaxValue)]
public static void Ctor_Int_Int_Int(int major, int minor, int build)
{
VerifyVersion(new Version(major, minor, build), major, minor, build, -1);
}
[Theory]
[InlineData(0, 0, 0, 0)]
[InlineData(2, 3, 4, 7)]
[InlineData(2, 3, 4, 32767)]
[InlineData(2, 3, 4, 32768)]
[InlineData(2, 3, 4, 65535)]
[InlineData(2, 3, 4, 65536)]
[InlineData(2, 3, 4, 2147483647)]
[InlineData(2, 3, 4, 2147450879)]
[InlineData(2, 3, 4, 2147418112)]
[InlineData(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue)]
public static void Ctor_Int_Int_Int_Int(int major, int minor, int build, int revision)
{
VerifyVersion(new Version(major, minor, build, revision), major, minor, build, revision);
}
[Fact]
public void Ctor_NegativeMajor_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("major", () => new Version(-1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("major", () => new Version(-1, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("major", () => new Version(-1, 0, 0, 0));
}
[Fact]
public void Ctor_NegativeMinor_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("minor", () => new Version(0, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("minor", () => new Version(0, -1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("minor", () => new Version(0, -1, 0, 0));
}
[Fact]
public void Ctor_NegativeBuild_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("build", () => new Version(0, 0, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("build", () => new Version(0, 0, -1, 0));
}
[Fact]
public void Ctor_NegativeRevision_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("revision", () => new Version(0, 0, 0, -1));
}
public static IEnumerable<object[]> Comparison_TestData()
{
foreach (var input in new (Version v1, Version v2, int expectedSign)[]
{
(null, null, 0),
(new Version(1, 2), null, 1),
(new Version(1, 2), new Version(1, 2), 0),
(new Version(1, 2), new Version(1, 3), -1),
(new Version(1, 2), new Version(1, 1), 1),
(new Version(1, 2), new Version(2, 0), -1),
(new Version(1, 2), new Version(1, 2, 1), -1),
(new Version(1, 2), new Version(1, 2, 0, 1), -1),
(new Version(1, 2), new Version(1, 0), 1),
(new Version(1, 2), new Version(1, 0, 1), 1),
(new Version(1, 2), new Version(1, 0, 0, 1), 1),
(new Version(3, 2, 1), null, 1),
(new Version(3, 2, 1), new Version(2, 2, 1), 1),
(new Version(3, 2, 1), new Version(3, 1, 1), 1),
(new Version(3, 2, 1), new Version(3, 2, 0), 1),
(new Version(1, 2, 3, 4), null, 1),
(new Version(1, 2, 3, 4), new Version(1, 2, 3, 4), 0),
(new Version(1, 2, 3, 4), new Version(1, 2, 3, 5), -1),
(new Version(1, 2, 3, 4), new Version(1, 2, 3, 3), 1)
})
{
yield return new object[] { input.v1, input.v2, input.expectedSign };
yield return new object[] { input.v2, input.v1, input.expectedSign * -1 };
}
}
[Theory]
[MemberData(nameof(Comparison_TestData))]
public void CompareTo_ReturnsExpected(Version version1, Version version2, int expectedSign)
{
Assert.Equal(expectedSign, Comparer<Version>.Default.Compare(version1, version2));
if (version1 != null)
{
Assert.Equal(expectedSign, Math.Sign(((IComparable)version1).CompareTo(version2)));
Assert.Equal(expectedSign, Math.Sign(version1.CompareTo((object)version2)));
Assert.Equal(expectedSign, Math.Sign(version1.CompareTo(version2)));
}
}
[ActiveIssue("https://github.com/dotnet/coreclr/pull/23898")]
[Theory]
[MemberData(nameof(Comparison_TestData))]
public void ComparisonOperators_ReturnExpected(Version version1, Version version2, int expectedSign)
{
if (expectedSign < 0)
{
Assert.True(version1 < version2);
Assert.True(version1 <= version2);
Assert.False(version1 == version2);
Assert.False(version1 >= version2);
Assert.False(version1 > version2);
Assert.True(version1 != version2);
}
else if (expectedSign == 0)
{
Assert.False(version1 < version2);
Assert.True(version1 <= version2);
Assert.True(version1 == version2);
Assert.True(version1 >= version2);
Assert.False(version1 > version2);
Assert.False(version1 != version2);
}
else
{
Assert.False(version1 < version2);
Assert.False(version1 <= version2);
Assert.False(version1 == version2);
Assert.True(version1 >= version2);
Assert.True(version1 > version2);
Assert.True(version1 != version2);
}
}
[Theory]
[InlineData(1)]
[InlineData("1.1")]
public void CompareTo_ObjectNotAVersion_ThrowsArgumentException(object other)
{
var version = new Version(1, 1);
AssertExtensions.Throws<ArgumentException>(null, () => version.CompareTo(other));
AssertExtensions.Throws<ArgumentException>(null, () => ((IComparable)version).CompareTo(other));
}
public static IEnumerable<object[]> Equals_TestData()
{
yield return new object[] { new Version(2, 3), new Version(2, 3), true };
yield return new object[] { new Version(2, 3), new Version(2, 4), false };
yield return new object[] { new Version(2, 3), new Version(3, 3), false };
yield return new object[] { new Version(2, 3, 4), new Version(2, 3, 4), true };
yield return new object[] { new Version(2, 3, 4), new Version(2, 3, 5), false };
yield return new object[] { new Version(2, 3, 4), new Version(2, 3), false };
yield return new object[] { new Version(2, 3, 4, 5), new Version(2, 3, 4, 5), true };
yield return new object[] { new Version(2, 3, 4, 5), new Version(2, 3, 4, 6), false };
yield return new object[] { new Version(2, 3, 4, 5), new Version(2, 3), false };
yield return new object[] { new Version(2, 3, 4, 5), new Version(2, 3, 4), false };
yield return new object[] { new Version(2, 3, 0), new Version(2, 3), false };
yield return new object[] { new Version(2, 3, 4, 0), new Version(2, 3, 4), false };
yield return new object[] { new Version(2, 3, 4, 5), new TimeSpan(), false };
yield return new object[] { new Version(2, 3, 4, 5), null, false };
}
[Theory]
[MemberData(nameof(Equals_TestData))]
public static void Equals_Other_ReturnsExpected(Version version1, object obj, bool expected)
{
Version version2 = obj as Version;
Assert.Equal(expected, version1.Equals(version2));
Assert.Equal(expected, version1.Equals(obj));
Assert.Equal(expected, version1 == version2);
Assert.Equal(!expected, version1 != version2);
if (version2 != null)
{
Assert.Equal(expected, version1.GetHashCode().Equals(version2.GetHashCode()));
}
}
public static IEnumerable<object[]> Parse_Valid_TestData()
{
yield return new object[] { "1.2", new Version(1, 2) };
yield return new object[] { "1.2.3", new Version(1, 2, 3) };
yield return new object[] { "1.2.3.4", new Version(1, 2, 3, 4) };
yield return new object[] { "2 .3. 4. \t\r\n15 ", new Version(2, 3, 4, 15) };
yield return new object[] { " 2 .3. 4. \t\r\n15 ", new Version(2, 3, 4, 15) };
yield return new object[] { "+1.+2.+3.+4", new Version(1, 2, 3, 4) };
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void Parse_ValidInput_ReturnsExpected(string input, Version expected)
{
Assert.Equal(expected, Version.Parse(input));
Assert.True(Version.TryParse(input, out Version version));
Assert.Equal(expected, version);
}
public static IEnumerable<object[]> Parse_Invalid_TestData()
{
yield return new object[] { null, typeof(ArgumentNullException) }; // Input is null
yield return new object[] { "", typeof(ArgumentException) }; // Input is empty
yield return new object[] { "1,2,3,4", typeof(ArgumentException) }; // Input contains invalid separator
yield return new object[] { "1", typeof(ArgumentException) }; // Input has fewer than 2 version components
yield return new object[] { "1.2.3.4.5", typeof(ArgumentException) }; // Input has more than 4 version components
yield return new object[] { "-1.2.3.4", typeof(ArgumentOutOfRangeException) }; // Input contains negative value
yield return new object[] { "1.-2.3.4", typeof(ArgumentOutOfRangeException) }; // Input contains negative value
yield return new object[] { "1.2.-3.4", typeof(ArgumentOutOfRangeException) }; // Input contains negative value
yield return new object[] { "1.2.3.-4", typeof(ArgumentOutOfRangeException) }; // Input contains negative value
yield return new object[] { "b.2.3.4", typeof(FormatException) }; // Input contains non-numeric value
yield return new object[] { "1.b.3.4", typeof(FormatException) }; // Input contains non-numeric value
yield return new object[] { "1.2.b.4", typeof(FormatException) }; // Input contains non-numeric value
yield return new object[] { "1.2.3.b", typeof(FormatException) }; // Input contains non-numeric value
yield return new object[] { "2147483648.2.3.4", typeof(OverflowException) }; // Input contains a value > int.MaxValue
yield return new object[] { "1.2147483648.3.4", typeof(OverflowException) }; // Input contains a value > int.MaxValue
yield return new object[] { "1.2.2147483648.4", typeof(OverflowException) }; // Input contains a value > int.MaxValue
yield return new object[] { "1.2.3.2147483648", typeof(OverflowException) }; // Input contains a value > int.MaxValue
// Input contains a value < 0
yield return new object[] { "-1.2.3.4", typeof(ArgumentOutOfRangeException) };
yield return new object[] { "1.-2.3.4", typeof(ArgumentOutOfRangeException) };
yield return new object[] { "1.2.-3.4", typeof(ArgumentOutOfRangeException) };
yield return new object[] { "1.2.3.-4", typeof(ArgumentOutOfRangeException) };
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void Parse_InvalidInput_ThrowsException(string input, Type exceptionType)
{
Assert.Throws(exceptionType, () => Version.Parse(input));
Assert.False(Version.TryParse(input, out Version version));
Assert.Null(version);
}
public static IEnumerable<object[]> ToString_TestData()
{
yield return new object[] { new Version(1, 2), new string[] { "", "1", "1.2" } };
yield return new object[] { new Version(1, 2, 3), new string[] { "", "1", "1.2", "1.2.3" } };
yield return new object[] { new Version(1, 2, 3, 4), new string[] { "", "1", "1.2", "1.2.3", "1.2.3.4" } };
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public static void ToString_Invoke_ReturnsExpected(Version version, string[] expected)
{
for (int i = 0; i < expected.Length; i++)
{
Assert.Equal(expected[i], version.ToString(i));
}
int maxFieldCount = expected.Length - 1;
Assert.Equal(expected[maxFieldCount], version.ToString());
AssertExtensions.Throws<ArgumentException>("fieldCount", () => version.ToString(-1)); // Index < 0
AssertExtensions.Throws<ArgumentException>("fieldCount", () => version.ToString(maxFieldCount + 1)); // Index > version.fieldCount
}
private static void VerifyVersion(Version version, int major, int minor, int build, int revision)
{
Assert.Equal(major, version.Major);
Assert.Equal(minor, version.Minor);
Assert.Equal(build, version.Build);
Assert.Equal(revision, version.Revision);
Assert.Equal((short)(revision >> 16), version.MajorRevision);
Assert.Equal(unchecked((short)(revision & 0xFFFF)), version.MinorRevision);
Version clone = Assert.IsType<Version>(version.Clone());
Assert.NotSame(version, clone);
Assert.Equal(version.Major, clone.Major);
Assert.Equal(version.Minor, clone.Minor);
Assert.Equal(version.Build, clone.Build);
Assert.Equal(version.Revision, clone.Revision);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeFixes
{
using Microsoft.CodeAnalysis.ErrorLogger;
using DiagnosticId = String;
using LanguageKind = String;
[Export(typeof(ICodeFixService))]
internal partial class CodeFixService : ICodeFixService
{
private readonly IDiagnosticAnalyzerService _diagnosticService;
private readonly ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>> _workspaceFixersMap;
private readonly ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>> _projectFixersMap;
// Shared by project fixers and workspace fixers.
private ImmutableDictionary<CodeFixProvider, ImmutableArray<DiagnosticId>> _fixerToFixableIdsMap = ImmutableDictionary<CodeFixProvider, ImmutableArray<DiagnosticId>>.Empty;
private readonly ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>> _fixerPriorityMap;
private readonly ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider> _analyzerReferenceToFixersMap;
private readonly ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>.CreateValueCallback _createProjectCodeFixProvider;
private readonly ImmutableDictionary<LanguageKind, Lazy<ISuppressionFixProvider>> _suppressionProvidersMap;
private readonly IEnumerable<Lazy<IErrorLoggerService>> _errorLoggers;
private ImmutableDictionary<CodeFixProvider, FixAllProviderInfo> _fixAllProviderMap;
[ImportingConstructor]
public CodeFixService(
IDiagnosticAnalyzerService service,
[ImportMany]IEnumerable<Lazy<IErrorLoggerService>> loggers,
[ImportMany]IEnumerable<Lazy<CodeFixProvider, CodeChangeProviderMetadata>> fixers,
[ImportMany]IEnumerable<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>> suppressionProviders)
{
_errorLoggers = loggers;
_diagnosticService = service;
var fixersPerLanguageMap = fixers.ToPerLanguageMapWithMultipleLanguages();
var suppressionProvidersPerLanguageMap = suppressionProviders.ToPerLanguageMapWithMultipleLanguages();
_workspaceFixersMap = GetFixerPerLanguageMap(fixersPerLanguageMap, null);
_suppressionProvidersMap = GetSuppressionProvidersPerLanguageMap(suppressionProvidersPerLanguageMap);
// REVIEW: currently, fixer's priority is statically defined by the fixer itself. might considering making it more dynamic or configurable.
_fixerPriorityMap = GetFixerPriorityPerLanguageMap(fixersPerLanguageMap);
// Per-project fixers
_projectFixersMap = new ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, ImmutableDictionary<string, List<CodeFixProvider>>>();
_analyzerReferenceToFixersMap = new ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>();
_createProjectCodeFixProvider = new ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>.CreateValueCallback(r => new ProjectCodeFixProvider(r));
_fixAllProviderMap = ImmutableDictionary<CodeFixProvider, FixAllProviderInfo>.Empty;
}
public async Task<FirstDiagnosticResult> GetFirstDiagnosticWithFixAsync(Document document, TextSpan range, bool considerSuppressionFixes, CancellationToken cancellationToken)
{
if (document == null || !document.IsOpen())
{
return default(FirstDiagnosticResult);
}
using (var diagnostics = SharedPools.Default<List<DiagnosticData>>().GetPooledObject())
{
var fullResult = await _diagnosticService.TryAppendDiagnosticsForSpanAsync(document, range, diagnostics.Object, cancellationToken).ConfigureAwait(false);
foreach (var diagnostic in diagnostics.Object)
{
cancellationToken.ThrowIfCancellationRequested();
if (!range.IntersectsWith(diagnostic.TextSpan))
{
continue;
}
// REVIEW: 2 possible designs.
// 1. find the first fix and then return right away. if the lightbulb is actually expanded, find all fixes for the line synchronously. or
// 2. kick off a task that finds all fixes for the given range here but return once we find the first one.
// at the same time, let the task to run to finish. if the lightbulb is expanded, we just simply use the task to get all fixes.
//
// first approach is simpler, so I will implement that first. if the first approach turns out to be not good enough, then
// I will try the second approach which will be more complex but quicker
var hasFix = await ContainsAnyFix(document, diagnostic, considerSuppressionFixes, cancellationToken).ConfigureAwait(false);
if (hasFix)
{
return new FirstDiagnosticResult(!fullResult, hasFix, diagnostic);
}
}
return new FirstDiagnosticResult(!fullResult, false, default(DiagnosticData));
}
}
public async Task<IEnumerable<CodeFixCollection>> GetFixesAsync(Document document, TextSpan range, bool includeSuppressionFixes, CancellationToken cancellationToken)
{
// REVIEW: this is the first and simplest design. basically, when ctrl+. is pressed, it asks diagnostic service to give back
// current diagnostics for the given span, and it will use that to get fixes. internally diagnostic service will either return cached information
// (if it is up-to-date) or synchronously do the work at the spot.
//
// this design's weakness is that each side don't have enough information to narrow down works to do. it will most likely always do more works than needed.
// sometimes way more than it is needed. (compilation)
Dictionary<TextSpan, List<DiagnosticData>> aggregatedDiagnostics = null;
foreach (var diagnostic in await _diagnosticService.GetDiagnosticsForSpanAsync(document, range, cancellationToken).ConfigureAwait(false))
{
cancellationToken.ThrowIfCancellationRequested();
aggregatedDiagnostics = aggregatedDiagnostics ?? new Dictionary<TextSpan, List<DiagnosticData>>();
aggregatedDiagnostics.GetOrAdd(diagnostic.TextSpan, _ => new List<DiagnosticData>()).Add(diagnostic);
}
var result = new List<CodeFixCollection>();
if (aggregatedDiagnostics == null)
{
return result;
}
foreach (var spanAndDiagnostic in aggregatedDiagnostics)
{
result = await AppendFixesAsync(document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, result, cancellationToken).ConfigureAwait(false);
}
if (result.Any())
{
// sort the result to the order defined by the fixers
var priorityMap = _fixerPriorityMap[document.Project.Language].Value;
result.Sort((d1, d2) => priorityMap.ContainsKey((CodeFixProvider)d1.Provider) ? (priorityMap.ContainsKey((CodeFixProvider)d2.Provider) ? priorityMap[(CodeFixProvider)d1.Provider] - priorityMap[(CodeFixProvider)d2.Provider] : -1) : 1);
}
if (includeSuppressionFixes)
{
foreach (var spanAndDiagnostic in aggregatedDiagnostics)
{
result = await AppendSuppressionsAsync(document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, result, cancellationToken).ConfigureAwait(false);
}
}
return result;
}
private async Task<List<CodeFixCollection>> AppendFixesAsync(
Document document,
TextSpan span,
IEnumerable<DiagnosticData> diagnosticDataCollection,
List<CodeFixCollection> result,
CancellationToken cancellationToken)
{
Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>> fixerMap;
bool hasAnySharedFixer = _workspaceFixersMap.TryGetValue(document.Project.Language, out fixerMap);
var projectFixersMap = GetProjectFixers(document.Project);
var hasAnyProjectFixer = projectFixersMap.Any();
if (!hasAnySharedFixer && !hasAnyProjectFixer)
{
return result;
}
ImmutableArray<CodeFixProvider> workspaceFixers;
List<CodeFixProvider> projectFixers;
var allFixers = new List<CodeFixProvider>();
foreach (var diagnosticId in diagnosticDataCollection.Select(d => d.Id).Distinct())
{
cancellationToken.ThrowIfCancellationRequested();
if (hasAnySharedFixer && fixerMap.Value.TryGetValue(diagnosticId, out workspaceFixers))
{
allFixers.AddRange(workspaceFixers);
}
if (hasAnyProjectFixer && projectFixersMap.TryGetValue(diagnosticId, out projectFixers))
{
allFixers.AddRange(projectFixers);
}
}
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var diagnostics = diagnosticDataCollection.Select(data => data.ToDiagnostic(tree)).ToImmutableArray();
var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>();
foreach (var fixer in allFixers.Distinct())
{
cancellationToken.ThrowIfCancellationRequested();
Func<Diagnostic, bool> hasFix = (d) => this.GetFixableDiagnosticIds(fixer, extensionManager).Contains(d.Id);
Func<ImmutableArray<Diagnostic>, Task<IEnumerable<CodeFix>>> getFixes =
async (dxs) =>
{
var fixes = new List<CodeFix>();
var context = new CodeFixContext(document, span, dxs,
// TODO: Can we share code between similar lambdas that we pass to this API in BatchFixAllProvider.cs, CodeFixService.cs and CodeRefactoringService.cs?
(a, d) =>
{
// Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from.
lock (fixes)
{
fixes.Add(new CodeFix(a, d));
}
},
verifyArguments: false,
cancellationToken: cancellationToken);
var task = fixer.RegisterCodeFixesAsync(context) ?? SpecializedTasks.EmptyTask;
await task.ConfigureAwait(false);
return fixes;
};
await AppendFixesOrSuppressionsAsync(document, span, diagnostics, result, fixer,
hasFix, getFixes, cancellationToken).ConfigureAwait(false);
}
return result;
}
private async Task<List<CodeFixCollection>> AppendSuppressionsAsync(
Document document, TextSpan span, IEnumerable<DiagnosticData> diagnosticDataCollection, List<CodeFixCollection> result, CancellationToken cancellationToken)
{
Lazy<ISuppressionFixProvider> lazySuppressionProvider;
if (!_suppressionProvidersMap.TryGetValue(document.Project.Language, out lazySuppressionProvider) || lazySuppressionProvider.Value == null)
{
return result;
}
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var diagnostics = diagnosticDataCollection.Select(data => data.ToDiagnostic(tree));
Func<Diagnostic, bool> hasFix = (d) => lazySuppressionProvider.Value.CanBeSuppressed(d);
Func<ImmutableArray<Diagnostic>, Task<IEnumerable<CodeFix>>> getFixes = (dxs) => lazySuppressionProvider.Value.GetSuppressionsAsync(document, span, dxs, cancellationToken);
await AppendFixesOrSuppressionsAsync(document, span, diagnostics, result, lazySuppressionProvider.Value, hasFix, getFixes, cancellationToken).ConfigureAwait(false);
return result;
}
private async Task<List<CodeFixCollection>> AppendFixesOrSuppressionsAsync(
Document document,
TextSpan span,
IEnumerable<Diagnostic> diagnosticsWithSameSpan,
List<CodeFixCollection> result,
object fixer,
Func<Diagnostic, bool> hasFix,
Func<ImmutableArray<Diagnostic>, Task<IEnumerable<CodeFix>>> getFixes,
CancellationToken cancellationToken)
{
var diagnostics = diagnosticsWithSameSpan.Where(d => hasFix(d)).OrderByDescending(d => d.Severity).ToImmutableArray();
if (diagnostics.Length <= 0)
{
// this can happen for suppression case where all diagnostics can't be suppressed
return result;
}
var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>();
var fixes = await extensionManager.PerformFunctionAsync(fixer, () => getFixes(diagnostics)).ConfigureAwait(false);
if (fixes != null && fixes.Any())
{
FixAllCodeActionContext fixAllContext = null;
var codeFixProvider = fixer as CodeFixProvider;
if (codeFixProvider != null)
{
// If the codeFixProvider supports fix all occurrences, then get the corresponding FixAllProviderInfo and fix all context.
var fixAllProviderInfo = extensionManager.PerformFunction(codeFixProvider, () => ImmutableInterlocked.GetOrAdd(ref _fixAllProviderMap, codeFixProvider, FixAllProviderInfo.Create));
if (fixAllProviderInfo != null)
{
fixAllContext = new FixAllCodeActionContext(document, fixAllProviderInfo, codeFixProvider, diagnostics, this.GetDocumentDiagnosticsAsync, this.GetProjectDiagnosticsAsync, cancellationToken);
}
}
result = result ?? new List<CodeFixCollection>();
var codeFix = new CodeFixCollection(fixer, span, fixes, fixAllContext);
result.Add(codeFix);
}
return result;
}
private async Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken)
{
Contract.ThrowIfNull(document);
var solution = document.Project.Solution;
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var diagnostics = await _diagnosticService.GetDiagnosticsForIdsAsync(solution, null, document.Id, diagnosticIds, cancellationToken).ConfigureAwait(false);
Contract.ThrowIfFalse(diagnostics.All(d => d.DocumentId != null));
return diagnostics.Select(d => d.ToDiagnostic(tree));
}
private async Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project, bool includeAllDocumentDiagnostics, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken)
{
Contract.ThrowIfNull(project);
if (includeAllDocumentDiagnostics)
{
// Get all diagnostics for the entire project, including document diagnostics.
var diagnostics = await _diagnosticService.GetDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds: diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false);
var documentIdsToTreeMap = await GetDocumentIdsToTreeMapAsync(project, cancellationToken).ConfigureAwait(false);
return diagnostics.Select(d => d.DocumentId != null ? d.ToDiagnostic(documentIdsToTreeMap[d.DocumentId]) : d.ToDiagnostic(null));
}
else
{
// Get all no-location diagnostics for the project, doesn't include document diagnostics.
var diagnostics = await _diagnosticService.GetProjectDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false);
Contract.ThrowIfFalse(diagnostics.All(d => d.DocumentId == null));
return diagnostics.Select(d => d.ToDiagnostic(null));
}
}
private static async Task<ImmutableDictionary<DocumentId, SyntaxTree>> GetDocumentIdsToTreeMapAsync(Project project, CancellationToken cancellationToken)
{
var builder = ImmutableDictionary.CreateBuilder<DocumentId, SyntaxTree>();
foreach (var document in project.Documents)
{
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
builder.Add(document.Id, tree);
}
return builder.ToImmutable();
}
private async Task<bool> ContainsAnyFix(Document document, DiagnosticData diagnostic, bool considerSuppressionFixes, CancellationToken cancellationToken)
{
ImmutableArray<CodeFixProvider> workspaceFixers = ImmutableArray<CodeFixProvider>.Empty;
List<CodeFixProvider> projectFixers = null;
Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>> fixerMap;
bool hasAnySharedFixer = _workspaceFixersMap.TryGetValue(document.Project.Language, out fixerMap) && fixerMap.Value.TryGetValue(diagnostic.Id, out workspaceFixers);
var hasAnyProjectFixer = GetProjectFixers(document.Project).TryGetValue(diagnostic.Id, out projectFixers);
Lazy<ISuppressionFixProvider> lazySuppressionProvider = null;
var hasSuppressionFixer =
considerSuppressionFixes &&
_suppressionProvidersMap.TryGetValue(document.Project.Language, out lazySuppressionProvider) &&
lazySuppressionProvider.Value != null;
if (!hasAnySharedFixer && !hasAnyProjectFixer && !hasSuppressionFixer)
{
return false;
}
var allFixers = ImmutableArray<CodeFixProvider>.Empty;
if (hasAnySharedFixer)
{
allFixers = workspaceFixers;
}
if (hasAnyProjectFixer)
{
allFixers = allFixers.AddRange(projectFixers);
}
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var dx = diagnostic.ToDiagnostic(tree);
if (hasSuppressionFixer && lazySuppressionProvider.Value.CanBeSuppressed(dx))
{
return true;
}
var fixes = new List<CodeFix>();
var context = new CodeFixContext(document, dx,
// TODO: Can we share code between similar lambdas that we pass to this API in BatchFixAllProvider.cs, CodeFixService.cs and CodeRefactoringService.cs?
(a, d) =>
{
// Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from.
lock (fixes)
{
fixes.Add(new CodeFix(a, d));
}
},
verifyArguments: false,
cancellationToken: cancellationToken);
var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>();
// we do have fixer. now let's see whether it actually can fix it
foreach (var fixer in allFixers)
{
await extensionManager.PerformActionAsync(fixer, () => fixer.RegisterCodeFixesAsync(context) ?? SpecializedTasks.EmptyTask).ConfigureAwait(false);
if (!fixes.Any())
{
continue;
}
return true;
}
return false;
}
private static readonly Func<DiagnosticId, List<CodeFixProvider>> s_createList = _ => new List<CodeFixProvider>();
private ImmutableArray<DiagnosticId> GetFixableDiagnosticIds(CodeFixProvider fixer, IExtensionManager extensionManager)
{
// If we are passed a null extension manager it means we do not have access to a document so there is nothing to
// show the user. In this case we will log any exceptions that occur, but the user will not see them.
if (extensionManager != null)
{
return extensionManager.PerformFunction(
fixer,
() => ImmutableInterlocked.GetOrAdd(ref _fixerToFixableIdsMap, fixer, f => f.FixableDiagnosticIds),
ImmutableArray<DiagnosticId>.Empty);
}
try
{
return ImmutableInterlocked.GetOrAdd(ref _fixerToFixableIdsMap, fixer, f => f.FixableDiagnosticIds);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception e)
{
foreach (var logger in _errorLoggers)
{
logger.Value.LogError(fixer.GetType().Name, e.Message + Environment.NewLine + e.StackTrace);
}
return ImmutableArray<DiagnosticId>.Empty;
}
}
private ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>> GetFixerPerLanguageMap(
Dictionary<LanguageKind, List<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>> fixersPerLanguage,
IExtensionManager extensionManager)
{
var fixerMap = ImmutableDictionary.Create<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>>();
foreach (var languageKindAndFixers in fixersPerLanguage)
{
var lazyMap = new Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>(() =>
{
var mutableMap = new Dictionary<DiagnosticId, List<CodeFixProvider>>();
foreach (var fixer in languageKindAndFixers.Value)
{
foreach (var id in this.GetFixableDiagnosticIds(fixer.Value, extensionManager))
{
if (string.IsNullOrWhiteSpace(id))
{
continue;
}
var list = mutableMap.GetOrAdd(id, s_createList);
list.Add(fixer.Value);
}
}
var immutableMap = ImmutableDictionary.CreateBuilder<DiagnosticId, ImmutableArray<CodeFixProvider>>();
foreach (var diagnosticIdAndFixers in mutableMap)
{
immutableMap.Add(diagnosticIdAndFixers.Key, diagnosticIdAndFixers.Value.AsImmutableOrEmpty());
}
return immutableMap.ToImmutable();
}, isThreadSafe: true);
fixerMap = fixerMap.Add(languageKindAndFixers.Key, lazyMap);
}
return fixerMap;
}
private static ImmutableDictionary<LanguageKind, Lazy<ISuppressionFixProvider>> GetSuppressionProvidersPerLanguageMap(
Dictionary<LanguageKind, List<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>>> suppressionProvidersPerLanguage)
{
var suppressionFixerMap = ImmutableDictionary.Create<LanguageKind, Lazy<ISuppressionFixProvider>>();
foreach (var languageKindAndFixers in suppressionProvidersPerLanguage)
{
var suppressionFixerLazyMap = new Lazy<ISuppressionFixProvider>(() => languageKindAndFixers.Value.SingleOrDefault().Value);
suppressionFixerMap = suppressionFixerMap.Add(languageKindAndFixers.Key, suppressionFixerLazyMap);
}
return suppressionFixerMap;
}
private static ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>> GetFixerPriorityPerLanguageMap(
Dictionary<LanguageKind, List<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>> fixersPerLanguage)
{
var languageMap = ImmutableDictionary.CreateBuilder<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>>();
foreach (var languageAndFixers in fixersPerLanguage)
{
var lazyMap = new Lazy<ImmutableDictionary<CodeFixProvider, int>>(() =>
{
var priorityMap = ImmutableDictionary.CreateBuilder<CodeFixProvider, int>();
var fixers = ExtensionOrderer.Order(languageAndFixers.Value);
for (var i = 0; i < fixers.Count; i++)
{
priorityMap.Add(fixers[i].Value, i);
}
return priorityMap.ToImmutable();
}, isThreadSafe: true);
languageMap.Add(languageAndFixers.Key, lazyMap);
}
return languageMap.ToImmutable();
}
private ImmutableDictionary<DiagnosticId, List<CodeFixProvider>> GetProjectFixers(Project project)
{
return _projectFixersMap.GetValue(project.AnalyzerReferences, pId => ComputeProjectFixers(project));
}
private ImmutableDictionary<DiagnosticId, List<CodeFixProvider>> ComputeProjectFixers(Project project)
{
var extensionManager = project.Solution.Workspace.Services.GetService<IExtensionManager>();
ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Builder builder = null;
foreach (var reference in project.AnalyzerReferences)
{
var projectCodeFixerProvider = _analyzerReferenceToFixersMap.GetValue(reference, _createProjectCodeFixProvider);
foreach (var fixer in projectCodeFixerProvider.GetFixers(project.Language))
{
var fixableIds = this.GetFixableDiagnosticIds(fixer, extensionManager);
foreach (var id in fixableIds)
{
if (string.IsNullOrWhiteSpace(id))
{
continue;
}
builder = builder ?? ImmutableDictionary.CreateBuilder<DiagnosticId, List<CodeFixProvider>>();
var list = builder.GetOrAdd(id, s_createList);
list.Add(fixer);
}
}
}
if (builder == null)
{
return ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Empty;
}
return builder.ToImmutable();
}
}
}
| |
//
// ListView.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using System.ComponentModel;
namespace Xwt
{
[BackendType (typeof(IListViewBackend))]
public class ListView: Widget, IColumnContainer, IScrollableWidget
{
ListViewColumnCollection columns;
IListDataSource dataSource;
SelectionMode mode;
protected new class WidgetBackendHost: Widget.WidgetBackendHost<ListView,IListViewBackend>, IListViewEventSink
{
protected override void OnBackendCreated ()
{
base.OnBackendCreated ();
Parent.columns.Attach (Backend);
}
public void OnSelectionChanged ()
{
Parent.OnSelectionChanged (EventArgs.Empty);
}
public void OnRowActivated (int rowIndex)
{
Parent.OnRowActivated (new ListViewRowEventArgs (rowIndex));
}
public override Size GetDefaultNaturalSize ()
{
return Xwt.Backends.DefaultNaturalSizes.ListView;
}
}
static ListView ()
{
MapEvent (TableViewEvent.SelectionChanged, typeof(ListView), "OnSelectionChanged");
MapEvent (ListViewEvent.RowActivated, typeof(ListView), "OnRowActivated");
}
public ListView (IListDataSource source): this ()
{
VerifyConstructorCall (this);
DataSource = source;
}
public ListView ()
{
columns = new ListViewColumnCollection (this);
VerticalScrollPolicy = HorizontalScrollPolicy = ScrollPolicy.Automatic;
}
protected override BackendHost CreateBackendHost ()
{
return new WidgetBackendHost ();
}
IListViewBackend Backend {
get { return (IListViewBackend) BackendHost.Backend; }
}
public bool BorderVisible
{
get { return Backend.BorderVisible; }
set { Backend.BorderVisible = value; }
}
public GridLines GridLinesVisible
{
get { return Backend.GridLinesVisible; }
set { Backend.GridLinesVisible = value; }
}
public ScrollPolicy VerticalScrollPolicy {
get { return Backend.VerticalScrollPolicy; }
set { Backend.VerticalScrollPolicy = value; }
}
public ScrollPolicy HorizontalScrollPolicy {
get { return Backend.HorizontalScrollPolicy; }
set { Backend.HorizontalScrollPolicy = value; }
}
ScrollControl verticalScrollAdjustment;
public ScrollControl VerticalScrollControl {
get {
if (verticalScrollAdjustment == null)
verticalScrollAdjustment = new ScrollControl (Backend.CreateVerticalScrollControl ());
return verticalScrollAdjustment;
}
}
ScrollControl horizontalScrollAdjustment;
public ScrollControl HorizontalScrollControl {
get {
if (horizontalScrollAdjustment == null)
horizontalScrollAdjustment = new ScrollControl (Backend.CreateHorizontalScrollControl ());
return horizontalScrollAdjustment;
}
}
public ListViewColumnCollection Columns {
get {
return columns;
}
}
public IListDataSource DataSource {
get {
return dataSource;
}
set {
if (dataSource != value) {
Backend.SetSource (value, value is IFrontend ? (IBackend)BackendHost.ToolkitEngine.GetSafeBackend (value) : null);
dataSource = value;
}
}
}
public bool HeadersVisible {
get {
return Backend.HeadersVisible;
}
set {
Backend.HeadersVisible = value;
}
}
public SelectionMode SelectionMode {
get {
return mode;
}
set {
mode = value;
Backend.SetSelectionMode (mode);
}
}
/// <summary>
/// Gets or sets the row the current event applies to.
/// The behavior of this property is undefined when used outside an
/// event that supports it.
/// </summary>
/// <value>
/// The current event row.
/// </value>
public int CurrentEventRow {
get {
return Backend.CurrentEventRow;
}
}
public int SelectedRow {
get {
var items = SelectedRows;
if (items.Length == 0)
return -1;
else
return items [0];
}
}
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public int[] SelectedRows {
get {
return Backend.SelectedRows;
}
}
/// <summary>
/// Gets or sets the focused row.
/// </summary>
/// <value>The row with the keyboard focus.</value>
public int FocusedRow {
get {
return Backend.FocusedRow;
}
set {
Backend.FocusedRow = value;
}
}
public void SelectRow (int row)
{
Backend.SelectRow (row);
}
public void UnselectRow (int row)
{
Backend.UnselectRow (row);
}
public void SelectAll ()
{
Backend.SelectAll ();
}
public void UnselectAll ()
{
Backend.UnselectAll ();
}
public void ScrollToRow (int row)
{
Backend.ScrollToRow (row);
}
/// <summary>
/// Returns the row at the given widget coordinates
/// </summary>
/// <returns>The row index</returns>
/// <param name="x">The x coordinate.</param>
/// <param name="y">The y coordinate.</param>
public int GetRowAtPosition (double x, double y)
{
return GetRowAtPosition (new Point (x, y));
}
/// <summary>
/// Returns the row at the given widget coordinates
/// </summary>
/// <returns>The row index</returns>
/// <param name="p">A position, in widget coordinates</param>
public int GetRowAtPosition (Point p)
{
return Backend.GetRowAtPosition (p);
}
public Rectangle GetCellBounds (int row, CellView cell, bool includeMargin)
{
return Backend.GetCellBounds (row, cell, includeMargin);
}
void IColumnContainer.NotifyColumnsChanged ()
{
}
protected virtual void OnSelectionChanged (EventArgs a)
{
if (selectionChanged != null)
selectionChanged (this, a);
}
EventHandler selectionChanged;
public event EventHandler SelectionChanged {
add {
BackendHost.OnBeforeEventAdd (TableViewEvent.SelectionChanged, selectionChanged);
selectionChanged += value;
}
remove {
selectionChanged -= value;
BackendHost.OnAfterEventRemove (TableViewEvent.SelectionChanged, selectionChanged);
}
}
/// <summary>
/// Raises the row activated event.
/// </summary>
/// <param name="a">The alpha component.</param>
protected virtual void OnRowActivated (ListViewRowEventArgs a)
{
if (rowActivated != null)
rowActivated (this, a);
}
EventHandler<ListViewRowEventArgs> rowActivated;
/// <summary>
/// Occurs when the user double-clicks on a row
/// </summary>
public event EventHandler<ListViewRowEventArgs> RowActivated {
add {
BackendHost.OnBeforeEventAdd (ListViewEvent.RowActivated, rowActivated);
rowActivated += value;
}
remove {
rowActivated -= value;
BackendHost.OnAfterEventRemove (ListViewEvent.RowActivated, rowActivated);
}
}
}
}
| |
/*
* 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 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.IO;
using System.Net;
using System.Text;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using OpenMetaverse;
using log4net;
using Mono.Addins;
using Nini.Config;
using Nwc.XmlRpc;
using OpenSim.Framework;
using OpenSim.Framework.Capabilities;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Caps = OpenSim.Framework.Capabilities.Caps;
namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "VivoxVoiceModule")]
public class VivoxVoiceModule : ISharedRegionModule
{
// channel distance model values
public const int CHAN_DIST_NONE = 0; // no attenuation
public const int CHAN_DIST_INVERSE = 1; // inverse distance attenuation
public const int CHAN_DIST_LINEAR = 2; // linear attenuation
public const int CHAN_DIST_EXPONENT = 3; // exponential attenuation
public const int CHAN_DIST_DEFAULT = CHAN_DIST_LINEAR;
// channel type values
public static readonly string CHAN_TYPE_POSITIONAL = "positional";
public static readonly string CHAN_TYPE_CHANNEL = "channel";
public static readonly string CHAN_TYPE_DEFAULT = CHAN_TYPE_POSITIONAL;
// channel mode values
public static readonly string CHAN_MODE_OPEN = "open";
public static readonly string CHAN_MODE_LECTURE = "lecture";
public static readonly string CHAN_MODE_PRESENTATION = "presentation";
public static readonly string CHAN_MODE_AUDITORIUM = "auditorium";
public static readonly string CHAN_MODE_DEFAULT = CHAN_MODE_OPEN;
// unconstrained default values
public const double CHAN_ROLL_OFF_DEFAULT = 2.0; // rate of attenuation
public const double CHAN_ROLL_OFF_MIN = 1.0;
public const double CHAN_ROLL_OFF_MAX = 4.0;
public const int CHAN_MAX_RANGE_DEFAULT = 80; // distance at which channel is silent
public const int CHAN_MAX_RANGE_MIN = 0;
public const int CHAN_MAX_RANGE_MAX = 160;
public const int CHAN_CLAMPING_DISTANCE_DEFAULT = 10; // distance before attenuation applies
public const int CHAN_CLAMPING_DISTANCE_MIN = 0;
public const int CHAN_CLAMPING_DISTANCE_MAX = 160;
// Infrastructure
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly Object vlock = new Object();
// Capability strings
private static readonly string m_parcelVoiceInfoRequestPath = "0107/";
private static readonly string m_provisionVoiceAccountRequestPath = "0108/";
//private static readonly string m_chatSessionRequestPath = "0109/";
// Control info, e.g. vivox server, admin user, admin password
private static bool m_pluginEnabled = false;
private static bool m_adminConnected = false;
private static string m_vivoxServer;
private static string m_vivoxSipUri;
private static string m_vivoxVoiceAccountApi;
private static string m_vivoxAdminUser;
private static string m_vivoxAdminPassword;
private static string m_authToken = String.Empty;
private static int m_vivoxChannelDistanceModel;
private static double m_vivoxChannelRollOff;
private static int m_vivoxChannelMaximumRange;
private static string m_vivoxChannelMode;
private static string m_vivoxChannelType;
private static int m_vivoxChannelClampingDistance;
private static Dictionary<string,string> m_parents = new Dictionary<string,string>();
private static bool m_dumpXml;
private IConfig m_config;
private object m_Lock;
public void Initialise(IConfigSource config)
{
m_config = config.Configs["VivoxVoice"];
if (null == m_config)
return;
if (!m_config.GetBoolean("enabled", false))
return;
m_Lock = new object();
try
{
// retrieve configuration variables
m_vivoxServer = m_config.GetString("vivox_server", String.Empty);
m_vivoxSipUri = m_config.GetString("vivox_sip_uri", String.Empty);
m_vivoxAdminUser = m_config.GetString("vivox_admin_user", String.Empty);
m_vivoxAdminPassword = m_config.GetString("vivox_admin_password", String.Empty);
m_vivoxChannelDistanceModel = m_config.GetInt("vivox_channel_distance_model", CHAN_DIST_DEFAULT);
m_vivoxChannelRollOff = m_config.GetDouble("vivox_channel_roll_off", CHAN_ROLL_OFF_DEFAULT);
m_vivoxChannelMaximumRange = m_config.GetInt("vivox_channel_max_range", CHAN_MAX_RANGE_DEFAULT);
m_vivoxChannelMode = m_config.GetString("vivox_channel_mode", CHAN_MODE_DEFAULT).ToLower();
m_vivoxChannelType = m_config.GetString("vivox_channel_type", CHAN_TYPE_DEFAULT).ToLower();
m_vivoxChannelClampingDistance = m_config.GetInt("vivox_channel_clamping_distance",
CHAN_CLAMPING_DISTANCE_DEFAULT);
m_dumpXml = m_config.GetBoolean("dump_xml", false);
// Validate against constraints and default if necessary
if (m_vivoxChannelRollOff < CHAN_ROLL_OFF_MIN || m_vivoxChannelRollOff > CHAN_ROLL_OFF_MAX)
{
m_log.WarnFormat("[VivoxVoice] Invalid value for roll off ({0}), reset to {1}.",
m_vivoxChannelRollOff, CHAN_ROLL_OFF_DEFAULT);
m_vivoxChannelRollOff = CHAN_ROLL_OFF_DEFAULT;
}
if (m_vivoxChannelMaximumRange < CHAN_MAX_RANGE_MIN || m_vivoxChannelMaximumRange > CHAN_MAX_RANGE_MAX)
{
m_log.WarnFormat("[VivoxVoice] Invalid value for maximum range ({0}), reset to {1}.",
m_vivoxChannelMaximumRange, CHAN_MAX_RANGE_DEFAULT);
m_vivoxChannelMaximumRange = CHAN_MAX_RANGE_DEFAULT;
}
if (m_vivoxChannelClampingDistance < CHAN_CLAMPING_DISTANCE_MIN ||
m_vivoxChannelClampingDistance > CHAN_CLAMPING_DISTANCE_MAX)
{
m_log.WarnFormat("[VivoxVoice] Invalid value for clamping distance ({0}), reset to {1}.",
m_vivoxChannelClampingDistance, CHAN_CLAMPING_DISTANCE_DEFAULT);
m_vivoxChannelClampingDistance = CHAN_CLAMPING_DISTANCE_DEFAULT;
}
switch (m_vivoxChannelMode)
{
case "open" : break;
case "lecture" : break;
case "presentation" : break;
case "auditorium" : break;
default :
m_log.WarnFormat("[VivoxVoice] Invalid value for channel mode ({0}), reset to {1}.",
m_vivoxChannelMode, CHAN_MODE_DEFAULT);
m_vivoxChannelMode = CHAN_MODE_DEFAULT;
break;
}
switch (m_vivoxChannelType)
{
case "positional" : break;
case "channel" : break;
default :
m_log.WarnFormat("[VivoxVoice] Invalid value for channel type ({0}), reset to {1}.",
m_vivoxChannelType, CHAN_TYPE_DEFAULT);
m_vivoxChannelType = CHAN_TYPE_DEFAULT;
break;
}
m_vivoxVoiceAccountApi = String.Format("http://{0}/api2", m_vivoxServer);
// Admin interface required values
if (String.IsNullOrEmpty(m_vivoxServer) ||
String.IsNullOrEmpty(m_vivoxSipUri) ||
String.IsNullOrEmpty(m_vivoxAdminUser) ||
String.IsNullOrEmpty(m_vivoxAdminPassword))
{
m_log.Error("[VivoxVoice] plugin mis-configured");
m_log.Info("[VivoxVoice] plugin disabled: incomplete configuration");
return;
}
m_log.InfoFormat("[VivoxVoice] using vivox server {0}", m_vivoxServer);
// Get admin rights and cleanup any residual channel definition
DoAdminLogin();
m_pluginEnabled = true;
m_log.Info("[VivoxVoice] plugin enabled");
}
catch (Exception e)
{
m_log.ErrorFormat("[VivoxVoice] plugin initialization failed: {0}", e.Message);
m_log.DebugFormat("[VivoxVoice] plugin initialization failed: {0}", e.ToString());
return;
}
}
public void AddRegion(Scene scene)
{
if (m_pluginEnabled)
{
lock (vlock)
{
string channelId;
string sceneUUID = scene.RegionInfo.RegionID.ToString();
string sceneName = scene.RegionInfo.RegionName;
// Make sure that all local channels are deleted.
// So we have to search for the children, and then do an
// iteration over the set of chidren identified.
// This assumes that there is just one directory per
// region.
if (VivoxTryGetDirectory(sceneUUID + "D", out channelId))
{
m_log.DebugFormat("[VivoxVoice]: region {0}: uuid {1}: located directory id {2}",
sceneName, sceneUUID, channelId);
XmlElement children = VivoxListChildren(channelId);
string count;
if (XmlFind(children, "response.level0.channel-search.count", out count))
{
int cnum = Convert.ToInt32(count);
for (int i = 0; i < cnum; i++)
{
string id;
if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.id", i, out id))
{
if (!IsOK(VivoxDeleteChannel(channelId, id)))
m_log.WarnFormat("[VivoxVoice] Channel delete failed {0}:{1}:{2}", i, channelId, id);
}
}
}
}
else
{
if (!VivoxTryCreateDirectory(sceneUUID + "D", sceneName, out channelId))
{
m_log.WarnFormat("[VivoxVoice] Create failed <{0}:{1}:{2}>",
"*", sceneUUID, sceneName);
channelId = String.Empty;
}
}
// Create a dictionary entry unconditionally. This eliminates the
// need to check for a parent in the core code. The end result is
// the same, if the parent table entry is an empty string, then
// region channels will be created as first-level channels.
lock (m_parents)
{
if (m_parents.ContainsKey(sceneUUID))
{
RemoveRegion(scene);
m_parents.Add(sceneUUID, channelId);
}
else
{
m_parents.Add(sceneUUID, channelId);
}
}
}
// we need to capture scene in an anonymous method
// here as we need it later in the callbacks
scene.EventManager.OnRegisterCaps += delegate(UUID agentID, Caps caps)
{
OnRegisterCaps(scene, agentID, caps);
};
}
}
public void RegionLoaded(Scene scene)
{
// Do nothing.
}
public void RemoveRegion(Scene scene)
{
if (m_pluginEnabled)
{
lock (vlock)
{
string channelId;
string sceneUUID = scene.RegionInfo.RegionID.ToString();
string sceneName = scene.RegionInfo.RegionName;
// Make sure that all local channels are deleted.
// So we have to search for the children, and then do an
// iteration over the set of chidren identified.
// This assumes that there is just one directory per
// region.
if (VivoxTryGetDirectory(sceneUUID + "D", out channelId))
{
m_log.DebugFormat("[VivoxVoice]: region {0}: uuid {1}: located directory id {2}",
sceneName, sceneUUID, channelId);
XmlElement children = VivoxListChildren(channelId);
string count;
if (XmlFind(children, "response.level0.channel-search.count", out count))
{
int cnum = Convert.ToInt32(count);
for (int i = 0; i < cnum; i++)
{
string id;
if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.id", i, out id))
{
if (!IsOK(VivoxDeleteChannel(channelId, id)))
m_log.WarnFormat("[VivoxVoice] Channel delete failed {0}:{1}:{2}", i, channelId, id);
}
}
}
}
if (!IsOK(VivoxDeleteChannel(null, channelId)))
m_log.WarnFormat("[VivoxVoice] Parent channel delete failed {0}:{1}:{2}", sceneName, sceneUUID, channelId);
// Remove the channel umbrella entry
lock (m_parents)
{
if (m_parents.ContainsKey(sceneUUID))
{
m_parents.Remove(sceneUUID);
}
}
}
}
}
public void PostInitialise()
{
// Do nothing.
}
public void Close()
{
if (m_pluginEnabled)
VivoxLogout();
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "VivoxVoiceModule"; }
}
public bool IsSharedModule
{
get { return true; }
}
// <summary>
// OnRegisterCaps is invoked via the scene.EventManager
// everytime OpenSim hands out capabilities to a client
// (login, region crossing). We contribute two capabilities to
// the set of capabilities handed back to the client:
// ProvisionVoiceAccountRequest and ParcelVoiceInfoRequest.
//
// ProvisionVoiceAccountRequest allows the client to obtain
// the voice account credentials for the avatar it is
// controlling (e.g., user name, password, etc).
//
// ParcelVoiceInfoRequest is invoked whenever the client
// changes from one region or parcel to another.
//
// Note that OnRegisterCaps is called here via a closure
// delegate containing the scene of the respective region (see
// Initialise()).
// </summary>
public void OnRegisterCaps(Scene scene, UUID agentID, Caps caps)
{
m_log.DebugFormat("[VivoxVoice] OnRegisterCaps: agentID {0} caps {1}", agentID, caps);
string capsBase = "/CAPS/" + caps.CapsObjectPath;
caps.RegisterHandler(
"ProvisionVoiceAccountRequest",
new RestStreamHandler(
"POST",
capsBase + m_provisionVoiceAccountRequestPath,
(request, path, param, httpRequest, httpResponse)
=> ProvisionVoiceAccountRequest(scene, request, path, param, agentID, caps),
"ProvisionVoiceAccountRequest",
agentID.ToString()));
caps.RegisterHandler(
"ParcelVoiceInfoRequest",
new RestStreamHandler(
"POST",
capsBase + m_parcelVoiceInfoRequestPath,
(request, path, param, httpRequest, httpResponse)
=> ParcelVoiceInfoRequest(scene, request, path, param, agentID, caps),
"ParcelVoiceInfoRequest",
agentID.ToString()));
//caps.RegisterHandler(
// "ChatSessionRequest",
// new RestStreamHandler(
// "POST",
// capsBase + m_chatSessionRequestPath,
// (request, path, param, httpRequest, httpResponse)
// => ChatSessionRequest(scene, request, path, param, agentID, caps),
// "ChatSessionRequest",
// agentID.ToString()));
}
/// <summary>
/// Callback for a client request for Voice Account Details
/// </summary>
/// <param name="scene">current scene object of the client</param>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="agentID"></param>
/// <param name="caps"></param>
/// <returns></returns>
public string ProvisionVoiceAccountRequest(Scene scene, string request, string path, string param,
UUID agentID, Caps caps)
{
try
{
ScenePresence avatar = null;
string avatarName = null;
if (scene == null)
throw new Exception("[VivoxVoice][PROVISIONVOICE]: Invalid scene");
avatar = scene.GetScenePresence(agentID);
while (avatar == null)
{
Thread.Sleep(100);
avatar = scene.GetScenePresence(agentID);
}
avatarName = avatar.Name;
m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: scene = {0}, agentID = {1}", scene, agentID);
m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}",
request, path, param);
XmlElement resp;
bool retry = false;
string agentname = "x" + Convert.ToBase64String(agentID.GetBytes());
string password = new UUID(Guid.NewGuid()).ToString().Replace('-','Z').Substring(0,16);
string code = String.Empty;
agentname = agentname.Replace('+', '-').Replace('/', '_');
do
{
resp = VivoxGetAccountInfo(agentname);
if (XmlFind(resp, "response.level0.status", out code))
{
if (code != "OK")
{
if (XmlFind(resp, "response.level0.body.code", out code))
{
// If the request was recognized, then this should be set to something
switch (code)
{
case "201" : // Account expired
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : expired credentials",
avatarName);
m_adminConnected = false;
retry = DoAdminLogin();
break;
case "202" : // Missing credentials
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : missing credentials",
avatarName);
break;
case "212" : // Not authorized
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : not authorized",
avatarName);
break;
case "300" : // Required parameter missing
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : parameter missing",
avatarName);
break;
case "403" : // Account does not exist
resp = VivoxCreateAccount(agentname,password);
// Note: This REALLY MUST BE status. Create Account does not return code.
if (XmlFind(resp, "response.level0.status", out code))
{
switch (code)
{
case "201" : // Account expired
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : expired credentials",
avatarName);
m_adminConnected = false;
retry = DoAdminLogin();
break;
case "202" : // Missing credentials
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : missing credentials",
avatarName);
break;
case "212" : // Not authorized
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : not authorized",
avatarName);
break;
case "300" : // Required parameter missing
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : parameter missing",
avatarName);
break;
case "400" : // Create failed
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : create failed",
avatarName);
break;
}
}
break;
case "404" : // Failed to retrieve account
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : retrieve failed");
// [AMW] Sleep and retry for a fixed period? Or just abandon?
break;
}
}
}
}
}
while (retry);
if (code != "OK")
{
m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: Get Account Request failed for \"{0}\"", avatarName);
throw new Exception("Unable to execute request");
}
// Unconditionally change the password on each request
VivoxPassword(agentname, password);
LLSDVoiceAccountResponse voiceAccountResponse =
new LLSDVoiceAccountResponse(agentname, password, m_vivoxSipUri, m_vivoxVoiceAccountApi);
string r = LLSDHelpers.SerialiseLLSDReply(voiceAccountResponse);
m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: avatar \"{0}\": {1}", avatarName, r);
return r;
}
catch (Exception e)
{
m_log.ErrorFormat("[VivoxVoice][PROVISIONVOICE]: : {0}, retry later", e.Message);
m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: : {0} failed", e.ToString());
return "<llsd><undef /></llsd>";
}
}
/// <summary>
/// Callback for a client request for ParcelVoiceInfo
/// </summary>
/// <param name="scene">current scene object of the client</param>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="agentID"></param>
/// <param name="caps"></param>
/// <returns></returns>
public string ParcelVoiceInfoRequest(Scene scene, string request, string path, string param,
UUID agentID, Caps caps)
{
ScenePresence avatar = scene.GetScenePresence(agentID);
string avatarName = avatar.Name;
// - check whether we have a region channel in our cache
// - if not:
// create it and cache it
// - send it to the client
// - send channel_uri: as "sip:regionID@m_sipDomain"
try
{
LLSDParcelVoiceInfoResponse parcelVoiceInfo;
string channel_uri;
if (null == scene.LandChannel)
throw new Exception(String.Format("region \"{0}\": avatar \"{1}\": land data not yet available",
scene.RegionInfo.RegionName, avatarName));
// get channel_uri: check first whether estate
// settings allow voice, then whether parcel allows
// voice, if all do retrieve or obtain the parcel
// voice channel
LandData land = scene.GetLandData(avatar.AbsolutePosition);
m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": request: {4}, path: {5}, param: {6}",
scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, request, path, param);
// m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: avatar \"{0}\": location: {1} {2} {3}",
// avatarName, avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y, avatar.AbsolutePosition.Z);
// TODO: EstateSettings don't seem to get propagated...
if (!scene.RegionInfo.EstateSettings.AllowVoice)
{
m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": voice not enabled in estate settings",
scene.RegionInfo.RegionName);
channel_uri = String.Empty;
}
if ((land.Flags & (uint)ParcelFlags.AllowVoiceChat) == 0)
{
m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": voice not enabled for parcel",
scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName);
channel_uri = String.Empty;
}
else
{
channel_uri = RegionGetOrCreateChannel(scene, land);
}
// fill in our response to the client
Hashtable creds = new Hashtable();
creds["channel_uri"] = channel_uri;
parcelVoiceInfo = new LLSDParcelVoiceInfoResponse(scene.RegionInfo.RegionName, land.LocalID, creds);
string r = LLSDHelpers.SerialiseLLSDReply(parcelVoiceInfo);
m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": {4}",
scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, r);
return r;
}
catch (Exception e)
{
m_log.ErrorFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2}, retry later",
scene.RegionInfo.RegionName, avatarName, e.Message);
m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2} failed",
scene.RegionInfo.RegionName, avatarName, e.ToString());
return "<llsd><undef /></llsd>";
}
}
/// <summary>
/// Callback for a client request for a private chat channel
/// </summary>
/// <param name="scene">current scene object of the client</param>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="agentID"></param>
/// <param name="caps"></param>
/// <returns></returns>
public string ChatSessionRequest(Scene scene, string request, string path, string param,
UUID agentID, Caps caps)
{
ScenePresence avatar = scene.GetScenePresence(agentID);
string avatarName = avatar.Name;
m_log.DebugFormat("[VivoxVoice][CHATSESSION]: avatar \"{0}\": request: {1}, path: {2}, param: {3}",
avatarName, request, path, param);
return "<llsd>true</llsd>";
}
private string RegionGetOrCreateChannel(Scene scene, LandData land)
{
string channelUri = null;
string channelId = null;
string landUUID;
string landName;
string parentId;
lock (m_parents)
parentId = m_parents[scene.RegionInfo.RegionID.ToString()];
// Create parcel voice channel. If no parcel exists, then the voice channel ID is the same
// as the directory ID. Otherwise, it reflects the parcel's ID.
if (land.LocalID != 1 && (land.Flags & (uint)ParcelFlags.UseEstateVoiceChan) == 0)
{
landName = String.Format("{0}:{1}", scene.RegionInfo.RegionName, land.Name);
landUUID = land.GlobalID.ToString();
m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}",
landName, land.LocalID, landUUID);
}
else
{
landName = String.Format("{0}:{1}", scene.RegionInfo.RegionName, scene.RegionInfo.RegionName);
landUUID = scene.RegionInfo.RegionID.ToString();
m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}",
landName, land.LocalID, landUUID);
}
lock (vlock)
{
// Added by Adam to help debug channel not availible errors.
if (VivoxTryGetChannel(parentId, landUUID, out channelId, out channelUri))
m_log.DebugFormat("[VivoxVoice] Found existing channel at " + channelUri);
else if (VivoxTryCreateChannel(parentId, landUUID, landName, out channelUri))
m_log.DebugFormat("[VivoxVoice] Created new channel at " + channelUri);
else
throw new Exception("vivox channel uri not available");
m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parent channel id {1}: retrieved parcel channel_uri {2} ",
landName, parentId, channelUri);
}
return channelUri;
}
private static readonly string m_vivoxLoginPath = "http://{0}/api2/viv_signin.php?userid={1}&pwd={2}";
/// <summary>
/// Perform administrative login for Vivox.
/// Returns a hash table containing values returned from the request.
/// </summary>
private XmlElement VivoxLogin(string name, string password)
{
string requrl = String.Format(m_vivoxLoginPath, m_vivoxServer, name, password);
return VivoxCall(requrl, false);
}
private static readonly string m_vivoxLogoutPath = "http://{0}/api2/viv_signout.php?auth_token={1}";
/// <summary>
/// Perform administrative logout for Vivox.
/// </summary>
private XmlElement VivoxLogout()
{
string requrl = String.Format(m_vivoxLogoutPath, m_vivoxServer, m_authToken);
return VivoxCall(requrl, false);
}
private static readonly string m_vivoxGetAccountPath = "http://{0}/api2/viv_get_acct.php?auth_token={1}&user_name={2}";
/// <summary>
/// Retrieve account information for the specified user.
/// Returns a hash table containing values returned from the request.
/// </summary>
private XmlElement VivoxGetAccountInfo(string user)
{
string requrl = String.Format(m_vivoxGetAccountPath, m_vivoxServer, m_authToken, user);
return VivoxCall(requrl, true);
}
private static readonly string m_vivoxNewAccountPath = "http://{0}/api2/viv_adm_acct_new.php?username={1}&pwd={2}&auth_token={3}";
/// <summary>
/// Creates a new account.
/// For now we supply the minimum set of values, which
/// is user name and password. We *can* supply a lot more
/// demographic data.
/// </summary>
private XmlElement VivoxCreateAccount(string user, string password)
{
string requrl = String.Format(m_vivoxNewAccountPath, m_vivoxServer, user, password, m_authToken);
return VivoxCall(requrl, true);
}
private static readonly string m_vivoxPasswordPath = "http://{0}/api2/viv_adm_password.php?user_name={1}&new_pwd={2}&auth_token={3}";
/// <summary>
/// Change the user's password.
/// </summary>
private XmlElement VivoxPassword(string user, string password)
{
string requrl = String.Format(m_vivoxPasswordPath, m_vivoxServer, user, password, m_authToken);
return VivoxCall(requrl, true);
}
private static readonly string m_vivoxChannelPath = "http://{0}/api2/viv_chan_mod.php?mode={1}&chan_name={2}&auth_token={3}";
/// <summary>
/// Create a channel.
/// Once again, there a multitude of options possible. In the simplest case
/// we specify only the name and get a non-persistent cannel in return. Non
/// persistent means that the channel gets deleted if no-one uses it for
/// 5 hours. To accomodate future requirements, it may be a good idea to
/// initially create channels under the umbrella of a parent ID based upon
/// the region name. That way we have a context for side channels, if those
/// are required in a later phase.
///
/// In this case the call handles parent and description as optional values.
/// </summary>
private bool VivoxTryCreateChannel(string parent, string channelId, string description, out string channelUri)
{
string requrl = String.Format(m_vivoxChannelPath, m_vivoxServer, "create", channelId, m_authToken);
if (!string.IsNullOrEmpty(parent))
{
requrl = String.Format("{0}&chan_parent={1}", requrl, parent);
}
if (!string.IsNullOrEmpty(description))
{
requrl = String.Format("{0}&chan_desc={1}", requrl, description);
}
requrl = String.Format("{0}&chan_type={1}", requrl, m_vivoxChannelType);
requrl = String.Format("{0}&chan_mode={1}", requrl, m_vivoxChannelMode);
requrl = String.Format("{0}&chan_roll_off={1}", requrl, m_vivoxChannelRollOff);
requrl = String.Format("{0}&chan_dist_model={1}", requrl, m_vivoxChannelDistanceModel);
requrl = String.Format("{0}&chan_max_range={1}", requrl, m_vivoxChannelMaximumRange);
requrl = String.Format("{0}&chan_clamping_distance={1}", requrl, m_vivoxChannelClampingDistance);
XmlElement resp = VivoxCall(requrl, true);
if (XmlFind(resp, "response.level0.body.chan_uri", out channelUri))
return true;
channelUri = String.Empty;
return false;
}
/// <summary>
/// Create a directory.
/// Create a channel with an unconditional type of "dir" (indicating directory).
/// This is used to create an arbitrary name tree for partitioning of the
/// channel name space.
/// The parent and description are optional values.
/// </summary>
private bool VivoxTryCreateDirectory(string dirId, string description, out string channelId)
{
string requrl = String.Format(m_vivoxChannelPath, m_vivoxServer, "create", dirId, m_authToken);
// if (parent != null && parent != String.Empty)
// {
// requrl = String.Format("{0}&chan_parent={1}", requrl, parent);
// }
if (!string.IsNullOrEmpty(description))
{
requrl = String.Format("{0}&chan_desc={1}", requrl, description);
}
requrl = String.Format("{0}&chan_type={1}", requrl, "dir");
XmlElement resp = VivoxCall(requrl, true);
if (IsOK(resp) && XmlFind(resp, "response.level0.body.chan_id", out channelId))
return true;
channelId = String.Empty;
return false;
}
private static readonly string m_vivoxChannelSearchPath = "http://{0}/api2/viv_chan_search.php?cond_channame={1}&auth_token={2}";
/// <summary>
/// Retrieve a channel.
/// Once again, there a multitude of options possible. In the simplest case
/// we specify only the name and get a non-persistent cannel in return. Non
/// persistent means that the channel gets deleted if no-one uses it for
/// 5 hours. To accomodate future requirements, it may be a good idea to
/// initially create channels under the umbrella of a parent ID based upon
/// the region name. That way we have a context for side channels, if those
/// are required in a later phase.
/// In this case the call handles parent and description as optional values.
/// </summary>
private bool VivoxTryGetChannel(string channelParent, string channelName,
out string channelId, out string channelUri)
{
string count;
string requrl = String.Format(m_vivoxChannelSearchPath, m_vivoxServer, channelName, m_authToken);
XmlElement resp = VivoxCall(requrl, true);
if (XmlFind(resp, "response.level0.channel-search.count", out count))
{
int channels = Convert.ToInt32(count);
// Bug in Vivox Server r2978 where count returns 0
// Found by Adam
if (channels == 0)
{
for (int j=0;j<100;j++)
{
string tmpId;
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.id", j, out tmpId))
break;
channels = j + 1;
}
}
for (int i = 0; i < channels; i++)
{
string name;
string id;
string type;
string uri;
string parent;
// skip if not a channel
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.type", i, out type) ||
(type != "channel" && type != "positional_M"))
{
m_log.Debug("[VivoxVoice] Skipping Channel " + i + " as it's not a channel.");
continue;
}
// skip if not the name we are looking for
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.name", i, out name) ||
name != channelName)
{
m_log.Debug("[VivoxVoice] Skipping Channel " + i + " as it has no name.");
continue;
}
// skip if parent does not match
if (channelParent != null && !XmlFind(resp, "response.level0.channel-search.channels.channels.level4.parent", i, out parent))
{
m_log.Debug("[VivoxVoice] Skipping Channel " + i + "/" + name + " as it's parent doesnt match");
continue;
}
// skip if no channel id available
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.id", i, out id))
{
m_log.Debug("[VivoxVoice] Skipping Channel " + i + "/" + name + " as it has no channel ID");
continue;
}
// skip if no channel uri available
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.uri", i, out uri))
{
m_log.Debug("[VivoxVoice] Skipping Channel " + i + "/" + name + " as it has no channel URI");
continue;
}
channelId = id;
channelUri = uri;
return true;
}
}
else
{
m_log.Debug("[VivoxVoice] No count element?");
}
channelId = String.Empty;
channelUri = String.Empty;
// Useful incase something goes wrong.
//m_log.Debug("[VivoxVoice] Could not find channel in XMLRESP: " + resp.InnerXml);
return false;
}
private bool VivoxTryGetDirectory(string directoryName, out string directoryId)
{
string count;
string requrl = String.Format(m_vivoxChannelSearchPath, m_vivoxServer, directoryName, m_authToken);
XmlElement resp = VivoxCall(requrl, true);
if (XmlFind(resp, "response.level0.channel-search.count", out count))
{
int channels = Convert.ToInt32(count);
for (int i = 0; i < channels; i++)
{
string name;
string id;
string type;
// skip if not a directory
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.type", i, out type) ||
type != "dir")
continue;
// skip if not the name we are looking for
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.name", i, out name) ||
name != directoryName)
continue;
// skip if no channel id available
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.id", i, out id))
continue;
directoryId = id;
return true;
}
}
directoryId = String.Empty;
return false;
}
// private static readonly string m_vivoxChannelById = "http://{0}/api2/viv_chan_mod.php?mode={1}&chan_id={2}&auth_token={3}";
// private XmlElement VivoxGetChannelById(string parent, string channelid)
// {
// string requrl = String.Format(m_vivoxChannelById, m_vivoxServer, "get", channelid, m_authToken);
// if (parent != null && parent != String.Empty)
// return VivoxGetChild(parent, channelid);
// else
// return VivoxCall(requrl, true);
// }
private static readonly string m_vivoxChannelDel = "http://{0}/api2/viv_chan_mod.php?mode={1}&chan_id={2}&auth_token={3}";
/// <summary>
/// Delete a channel.
/// Once again, there a multitude of options possible. In the simplest case
/// we specify only the name and get a non-persistent cannel in return. Non
/// persistent means that the channel gets deleted if no-one uses it for
/// 5 hours. To accomodate future requirements, it may be a good idea to
/// initially create channels under the umbrella of a parent ID based upon
/// the region name. That way we have a context for side channels, if those
/// are required in a later phase.
/// In this case the call handles parent and description as optional values.
/// </summary>
private XmlElement VivoxDeleteChannel(string parent, string channelid)
{
string requrl = String.Format(m_vivoxChannelDel, m_vivoxServer, "delete", channelid, m_authToken);
if (!string.IsNullOrEmpty(parent))
{
requrl = String.Format("{0}&chan_parent={1}", requrl, parent);
}
return VivoxCall(requrl, true);
}
private static readonly string m_vivoxChannelSearch = "http://{0}/api2/viv_chan_search.php?&cond_chanparent={1}&auth_token={2}";
/// <summary>
/// Return information on channels in the given directory
/// </summary>
private XmlElement VivoxListChildren(string channelid)
{
string requrl = String.Format(m_vivoxChannelSearch, m_vivoxServer, channelid, m_authToken);
return VivoxCall(requrl, true);
}
// private XmlElement VivoxGetChild(string parent, string child)
// {
// XmlElement children = VivoxListChildren(parent);
// string count;
// if (XmlFind(children, "response.level0.channel-search.count", out count))
// {
// int cnum = Convert.ToInt32(count);
// for (int i = 0; i < cnum; i++)
// {
// string name;
// string id;
// if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.name", i, out name))
// {
// if (name == child)
// {
// if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.id", i, out id))
// {
// return VivoxGetChannelById(null, id);
// }
// }
// }
// }
// }
// // One we *know* does not exist.
// return VivoxGetChannel(null, Guid.NewGuid().ToString());
// }
/// <summary>
/// This method handles the WEB side of making a request over the
/// Vivox interface. The returned values are tansferred to a has
/// table which is returned as the result.
/// The outcome of the call can be determined by examining the
/// status value in the hash table.
/// </summary>
private XmlElement VivoxCall(string requrl, bool admin)
{
XmlDocument doc = null;
// If this is an admin call, and admin is not connected,
// and the admin id cannot be connected, then fail.
if (admin && !m_adminConnected && !DoAdminLogin())
return null;
doc = new XmlDocument();
// Let's serialize all calls to Vivox. Most of these are driven by
// the clients (CAPs), when the user arrives at the region. We don't
// want to issue many simultaneous http requests to Vivox, because mono
// doesn't like that
lock (m_Lock)
{
try
{
// Otherwise prepare the request
m_log.DebugFormat("[VivoxVoice] Sending request <{0}>", requrl);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(requrl);
// We are sending just parameters, no content
req.ContentLength = 0;
// Send request and retrieve the response
using (HttpWebResponse rsp = (HttpWebResponse)req.GetResponse())
using (Stream s = rsp.GetResponseStream())
using (XmlTextReader rdr = new XmlTextReader(s))
doc.Load(rdr);
}
catch (Exception e)
{
m_log.ErrorFormat("[VivoxVoice] Error in admin call : {0}", e.Message);
}
}
// If we're debugging server responses, dump the whole
// load now
if (m_dumpXml) XmlScanl(doc.DocumentElement,0);
return doc.DocumentElement;
}
/// <summary>
/// Just say if it worked.
/// </summary>
private bool IsOK(XmlElement resp)
{
string status;
XmlFind(resp, "response.level0.status", out status);
return (status == "OK");
}
/// <summary>
/// Login has been factored in this way because it gets called
/// from several places in the module, and we want it to work
/// the same way each time.
/// </summary>
private bool DoAdminLogin()
{
m_log.Debug("[VivoxVoice] Establishing admin connection");
lock (vlock)
{
if (!m_adminConnected)
{
string status = "Unknown";
XmlElement resp = null;
resp = VivoxLogin(m_vivoxAdminUser, m_vivoxAdminPassword);
if (XmlFind(resp, "response.level0.body.status", out status))
{
if (status == "Ok")
{
m_log.Info("[VivoxVoice] Admin connection established");
if (XmlFind(resp, "response.level0.body.auth_token", out m_authToken))
{
if (m_dumpXml) m_log.DebugFormat("[VivoxVoice] Auth Token <{0}>",
m_authToken);
m_adminConnected = true;
}
}
else
{
m_log.WarnFormat("[VivoxVoice] Admin connection failed, status = {0}",
status);
}
}
}
}
return m_adminConnected;
}
/// <summary>
/// The XmlScan routine is provided to aid in the
/// reverse engineering of incompletely
/// documented packets returned by the Vivox
/// voice server. It is only called if the
/// m_dumpXml switch is set.
/// </summary>
private void XmlScanl(XmlElement e, int index)
{
if (e.HasChildNodes)
{
m_log.DebugFormat("<{0}>".PadLeft(index+5), e.Name);
XmlNodeList children = e.ChildNodes;
foreach (XmlNode node in children)
switch (node.NodeType)
{
case XmlNodeType.Element :
XmlScanl((XmlElement)node, index+1);
break;
case XmlNodeType.Text :
m_log.DebugFormat("\"{0}\"".PadLeft(index+5), node.Value);
break;
default :
break;
}
m_log.DebugFormat("</{0}>".PadLeft(index+6), e.Name);
}
else
{
m_log.DebugFormat("<{0}/>".PadLeft(index+6), e.Name);
}
}
private static readonly char[] C_POINT = {'.'};
/// <summary>
/// The Find method is passed an element whose
/// inner text is scanned in an attempt to match
/// the name hierarchy passed in the 'tag' parameter.
/// If the whole hierarchy is resolved, the InnerText
/// value at that point is returned. Note that this
/// may itself be a subhierarchy of the entire
/// document. The function returns a boolean indicator
/// of the search's success. The search is performed
/// by the recursive Search method.
/// </summary>
private bool XmlFind(XmlElement root, string tag, int nth, out string result)
{
if (root == null || tag == null || tag == String.Empty)
{
result = String.Empty;
return false;
}
return XmlSearch(root,tag.Split(C_POINT),0, ref nth, out result);
}
private bool XmlFind(XmlElement root, string tag, out string result)
{
int nth = 0;
if (root == null || tag == null || tag == String.Empty)
{
result = String.Empty;
return false;
}
return XmlSearch(root,tag.Split(C_POINT),0, ref nth, out result);
}
/// <summary>
/// XmlSearch is initially called by XmlFind, and then
/// recursively called by itself until the document
/// supplied to XmlFind is either exhausted or the name hierarchy
/// is matched.
///
/// If the hierarchy is matched, the value is returned in
/// result, and true returned as the function's
/// value. Otherwise the result is set to the empty string and
/// false is returned.
/// </summary>
private bool XmlSearch(XmlElement e, string[] tags, int index, ref int nth, out string result)
{
if (index == tags.Length || e.Name != tags[index])
{
result = String.Empty;
return false;
}
if (tags.Length-index == 1)
{
if (nth == 0)
{
result = e.InnerText;
return true;
}
else
{
nth--;
result = String.Empty;
return false;
}
}
if (e.HasChildNodes)
{
XmlNodeList children = e.ChildNodes;
foreach (XmlNode node in children)
{
switch (node.NodeType)
{
case XmlNodeType.Element :
if (XmlSearch((XmlElement)node, tags, index+1, ref nth, out result))
return true;
break;
default :
break;
}
}
}
result = String.Empty;
return false;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Web;
using DotNetOpenId;
using DotNetOpenId.Provider;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Handlers.Base;
using OpenSim.Services.Interfaces;
using Nini.Config;
using OpenMetaverse;
namespace OpenSim.Server.Handlers.Authentication
{
/// <summary>
/// Temporary, in-memory store for OpenID associations
/// </summary>
public class ProviderMemoryStore : IAssociationStore<AssociationRelyingPartyType>
{
private class AssociationItem
{
public AssociationRelyingPartyType DistinguishingFactor;
public string Handle;
public DateTime Expires;
public byte[] PrivateData;
}
Dictionary<string, AssociationItem> m_store = new Dictionary<string, AssociationItem>();
SortedList<DateTime, AssociationItem> m_sortedStore = new SortedList<DateTime, AssociationItem>();
object m_syncRoot = new object();
#region IAssociationStore<AssociationRelyingPartyType> Members
public void StoreAssociation(AssociationRelyingPartyType distinguishingFactor, Association assoc)
{
AssociationItem item = new AssociationItem();
item.DistinguishingFactor = distinguishingFactor;
item.Handle = assoc.Handle;
item.Expires = assoc.Expires.ToLocalTime();
item.PrivateData = assoc.SerializePrivateData();
lock (m_syncRoot)
{
m_store[item.Handle] = item;
m_sortedStore[item.Expires] = item;
}
}
public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor)
{
lock (m_syncRoot)
{
if (m_sortedStore.Count > 0)
{
AssociationItem item = m_sortedStore.Values[m_sortedStore.Count - 1];
return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData);
}
else
{
return null;
}
}
}
public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor, string handle)
{
AssociationItem item;
bool success = false;
lock (m_syncRoot)
success = m_store.TryGetValue(handle, out item);
if (success)
return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData);
else
return null;
}
public bool RemoveAssociation(AssociationRelyingPartyType distinguishingFactor, string handle)
{
lock (m_syncRoot)
{
for (int i = 0; i < m_sortedStore.Values.Count; i++)
{
AssociationItem item = m_sortedStore.Values[i];
if (item.Handle == handle)
{
m_sortedStore.RemoveAt(i);
break;
}
}
return m_store.Remove(handle);
}
}
public void ClearExpiredAssociations()
{
lock (m_syncRoot)
{
List<AssociationItem> itemsCopy = new List<AssociationItem>(m_sortedStore.Values);
DateTime now = DateTime.Now;
for (int i = 0; i < itemsCopy.Count; i++)
{
AssociationItem item = itemsCopy[i];
if (item.Expires <= now)
{
m_sortedStore.RemoveAt(i);
m_store.Remove(item.Handle);
}
}
}
}
#endregion
}
public class OpenIdStreamHandler : BaseOutputStreamHandler, IStreamHandler
{
#region HTML
/// <summary>Login form used to authenticate OpenID requests</summary>
const string LOGIN_PAGE =
@"<html>
<head><title>OpenSim OpenID Login</title></head>
<body>
<h3>OpenSim Login</h3>
<form method=""post"">
<label for=""first"">First Name:</label> <input readonly type=""text"" name=""first"" id=""first"" value=""{0}""/>
<label for=""last"">Last Name:</label> <input readonly type=""text"" name=""last"" id=""last"" value=""{1}""/>
<label for=""pass"">Password:</label> <input type=""password"" name=""pass"" id=""pass""/>
<input type=""submit"" value=""Login"">
</form>
</body>
</html>";
/// <summary>Page shown for a valid OpenID identity</summary>
const string OPENID_PAGE =
@"<html>
<head>
<title>{2} {3}</title>
<link rel=""openid2.provider openid.server"" href=""{0}://{1}/openid/server/""/>
</head>
<body>OpenID identifier for {2} {3}</body>
</html>
";
/// <summary>Page shown for an invalid OpenID identity</summary>
const string INVALID_OPENID_PAGE =
@"<html><head><title>Identity not found</title></head>
<body>Invalid OpenID identity</body></html>";
/// <summary>Page shown if the OpenID endpoint is requested directly</summary>
const string ENDPOINT_PAGE =
@"<html><head><title>OpenID Endpoint</title></head><body>
This is an OpenID server endpoint, not a human-readable resource.
For more information, see <a href='http://openid.net/'>http://openid.net/</a>.
</body></html>";
#endregion HTML
IAuthenticationService m_authenticationService;
IUserAccountService m_userAccountService;
ProviderMemoryStore m_openidStore = new ProviderMemoryStore();
public override string ContentType { get { return "text/html"; } }
/// <summary>
/// Constructor
/// </summary>
public OpenIdStreamHandler(
string httpMethod, string path, IUserAccountService userService, IAuthenticationService authService)
: base(httpMethod, path, "OpenId", "OpenID stream handler")
{
m_authenticationService = authService;
m_userAccountService = userService;
}
/// <summary>
/// Handles all GET and POST requests for OpenID identifier pages and endpoint
/// server communication
/// </summary>
protected override void ProcessRequest(
string path, Stream request, Stream response, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
Uri providerEndpoint = new Uri(String.Format("{0}://{1}{2}", httpRequest.Url.Scheme, httpRequest.Url.Authority, httpRequest.Url.AbsolutePath));
// Defult to returning HTML content
httpResponse.ContentType = ContentType;
try
{
string forPost;
using(StreamReader sr = new StreamReader(httpRequest.InputStream))
forPost = sr.ReadToEnd();
NameValueCollection postQuery = HttpUtility.ParseQueryString(forPost);
NameValueCollection getQuery = HttpUtility.ParseQueryString(httpRequest.Url.Query);
NameValueCollection openIdQuery = (postQuery.GetValues("openid.mode") != null ? postQuery : getQuery);
OpenIdProvider provider = new OpenIdProvider(m_openidStore, providerEndpoint, httpRequest.Url, openIdQuery);
if (provider.Request != null)
{
if (!provider.Request.IsResponseReady && provider.Request is IAuthenticationRequest)
{
IAuthenticationRequest authRequest = (IAuthenticationRequest)provider.Request;
string[] passwordValues = postQuery.GetValues("pass");
UserAccount account;
if (TryGetAccount(new Uri(authRequest.ClaimedIdentifier.ToString()), out account))
{
// Check for form POST data
if (passwordValues != null && passwordValues.Length == 1)
{
if (account != null &&
(m_authenticationService.Authenticate(account.PrincipalID,Util.Md5Hash(passwordValues[0]), 30) != string.Empty))
authRequest.IsAuthenticated = true;
else
authRequest.IsAuthenticated = false;
}
else
{
// Authentication was requested, send the client a login form
using (StreamWriter writer = new StreamWriter(response))
writer.Write(String.Format(LOGIN_PAGE, account.FirstName, account.LastName));
return;
}
}
else
{
// Cannot find an avatar matching the claimed identifier
authRequest.IsAuthenticated = false;
}
}
// Add OpenID headers to the response
foreach (string key in provider.Request.Response.Headers.Keys)
httpResponse.AddHeader(key, provider.Request.Response.Headers[key]);
string[] contentTypeValues = provider.Request.Response.Headers.GetValues("Content-Type");
if (contentTypeValues != null && contentTypeValues.Length == 1)
httpResponse.ContentType = contentTypeValues[0];
// Set the response code and document body based on the OpenID result
httpResponse.StatusCode = (int)provider.Request.Response.Code;
response.Write(provider.Request.Response.Body, 0, provider.Request.Response.Body.Length);
response.Close();
}
else if (httpRequest.Url.AbsolutePath.Contains("/openid/server"))
{
// Standard HTTP GET was made on the OpenID endpoint, send the client the default error page
using (StreamWriter writer = new StreamWriter(response))
writer.Write(ENDPOINT_PAGE);
}
else
{
// Try and lookup this avatar
UserAccount account;
if (TryGetAccount(httpRequest.Url, out account))
{
using (StreamWriter writer = new StreamWriter(response))
{
// TODO: Print out a full profile page for this avatar
writer.Write(String.Format(OPENID_PAGE, httpRequest.Url.Scheme,
httpRequest.Url.Authority, account.FirstName, account.LastName));
}
}
else
{
// Couldn't parse an avatar name, or couldn't find the avatar in the user server
using (StreamWriter writer = new StreamWriter(response))
writer.Write(INVALID_OPENID_PAGE);
}
}
}
catch (Exception ex)
{
httpResponse.StatusCode = (int)HttpStatusCode.InternalServerError;
using (StreamWriter writer = new StreamWriter(response))
writer.Write(ex.Message);
}
}
/// <summary>
/// Parse a URL with a relative path of the form /users/First_Last and try to
/// retrieve the profile matching that avatar name
/// </summary>
/// <param name="requestUrl">URL to parse for an avatar name</param>
/// <param name="profile">Profile data for the avatar</param>
/// <returns>True if the parse and lookup were successful, otherwise false</returns>
bool TryGetAccount(Uri requestUrl, out UserAccount account)
{
if (requestUrl.Segments.Length == 3 && requestUrl.Segments[1] == "users/")
{
// Parse the avatar name from the path
string username = requestUrl.Segments[requestUrl.Segments.Length - 1];
string[] name = username.Split('_');
if (name.Length == 2)
{
account = m_userAccountService.GetUserAccount(UUID.Zero, name[0], name[1]);
return (account != null);
}
}
account = null;
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Design;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using CslaGenerator.Metadata;
using CslaGenerator.Util;
namespace CslaGenerator.Design
{
/// <summary>
/// Summary description for RefTypeEditor (list of .NET types).
/// Used to get/set an assembly type (TypeInfo.Type).
/// </summary>
public class RefTypeEditor : UITypeEditor, IDisposable
{
public class BaseProperty
{
public Type Type { get; set; }
public string TypeName { get; set; }
public BaseProperty(Type type, string typeName)
{
Type = type;
TypeName = typeName;
}
}
private IWindowsFormsEditorService _editorService;
private ListBox _lstProperties;
private Type _instance;
private List<BaseProperty> _baseTypes;
private List<string> _sizeSortedNamespaces;
public RefTypeEditor()
{
_lstProperties = new ListBox();
_lstProperties.SelectedValueChanged += ValueChanged;
}
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
_editorService = (IWindowsFormsEditorService) provider.GetService(typeof(IWindowsFormsEditorService));
if (_editorService != null)
{
if (context.Instance != null)
{
// CR modifying to accomodate PropertyBag
Type instanceType = null;
object objinfo = null;
ContextHelper.GetTypeInfoContextInstanceObject(context, ref objinfo, ref instanceType);
var obj = (TypeInfo) objinfo;
_instance = objinfo.GetType();
_lstProperties.Items.Clear();
_lstProperties.Items.Add("(None)");
var currentCslaObject = GeneratorController.Current.CurrentCslaObject;
_sizeSortedNamespaces = currentCslaObject.Namespaces.ToList();
_sizeSortedNamespaces.Add(currentCslaObject.ObjectNamespace);
_sizeSortedNamespaces.Add("Csla");
_sizeSortedNamespaces = BusinessRuleTypeEditor.GetSizeSorted(_sizeSortedNamespaces);
// Get Assembly File Path
var assemblyFileInfo = _instance.GetProperty("AssemblyFile");
var assemblyFilePath = (string) assemblyFileInfo.GetValue(objinfo, null);
// If Assembly path is available, use assembly to load a drop down with available types.
if (!string.IsNullOrEmpty(assemblyFilePath))
{
var assembly = Assembly.LoadFrom(assemblyFilePath);
var alltypes = assembly.GetExportedTypes();
if (alltypes.Length > 0)
_baseTypes = new List<BaseProperty>();
var isCustomCriteria = !(obj.IsInheritedType || obj.IsInheritedTypeWinForms);
var numberOfGenericArguments = 1;
if (!isCustomCriteria)
numberOfGenericArguments = currentCslaObject.NumberOfGenericArguments();
foreach (var type in alltypes)
{
if (type.GetInterface("Csla.Core.IBusinessObject") != null ||
type.GetInterface("Csla.Core.IObservableBindingList") != null ||
type.GetInterface("Csla.Core.IExtendedBindingList") != null)
{
// exclude interface classes
if (!type.IsInterface)
{
var listableType = string.Empty;
if (!GeneratorController.Current.CurrentUnit.Params.EnforceGenericInheritance &&
!isCustomCriteria)
listableType = type.ToString();
if (type.IsGenericType)
{
if (type.GetGenericArguments().Length == numberOfGenericArguments)
{
listableType = type.ToString();
listableType = listableType.Substring(0, listableType.LastIndexOf('`'));
foreach (var argument in type.GetGenericArguments())
{
listableType += "<" + argument.Name + ">";
}
listableType = listableType.Replace("><", ",");
}
else
{
listableType = string.Empty;
}
}
if (!string.IsNullOrEmpty(listableType))
{
listableType = BusinessRuleTypeEditor.StripKnownNamespaces(
_sizeSortedNamespaces,
listableType);
_lstProperties.Items.Add(listableType);
_baseTypes.Add(new BaseProperty(type, listableType));
}
}
}
}
_lstProperties.Sorted = true;
}
var entry = BusinessRuleTypeEditor.StripKnownNamespaces(_sizeSortedNamespaces, obj.Type);
if (_lstProperties.Items.Contains(entry))
_lstProperties.SelectedItem = entry;
else
_lstProperties.SelectedItem = "(None)";
_editorService.DropDownControl(_lstProperties);
if (_lstProperties.SelectedIndex < 0 || _lstProperties.SelectedItem.ToString() == "(None)")
{
FillPropertyGrid(obj, _lstProperties.SelectedItem.ToString());
return string.Empty;
}
FillPropertyGrid(obj, _lstProperties.SelectedItem.ToString());
return _lstProperties.SelectedItem.ToString();
}
}
return value;
}
private void FillPropertyGrid(TypeInfo typeInfo, string stringType)
{
Type usedType = null;
if (stringType != "(None)")
{
foreach (var baseType in _baseTypes)
{
if (baseType.TypeName ==
BusinessRuleTypeEditor.StripKnownNamespaces(_sizeSortedNamespaces, stringType))
usedType = baseType.Type;
}
}
if (usedType == null)
typeInfo.IsGenericType = false;
else
typeInfo.IsGenericType = usedType.IsGenericType;
}
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.Modal;
}
private void ValueChanged(object sender, EventArgs e)
{
if (_editorService != null)
{
_editorService.CloseDropDown();
}
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// dispose managed resources
if (_lstProperties != null)
{
_lstProperties.Dispose();
_lstProperties = null;
}
}
// free native resources
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* 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 SignInt16()
{
var test = new SimpleBinaryOpTest__SignInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__SignInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Int16> _fld1;
public Vector256<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__SignInt16 testClass)
{
var result = Avx2.Sign(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__SignInt16 testClass)
{
fixed (Vector256<Int16>* pFld1 = &_fld1)
fixed (Vector256<Int16>* pFld2 = &_fld2)
{
var result = Avx2.Sign(
Avx.LoadVector256((Int16*)(pFld1)),
Avx.LoadVector256((Int16*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector256<Int16> _clsVar1;
private static Vector256<Int16> _clsVar2;
private Vector256<Int16> _fld1;
private Vector256<Int16> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__SignInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
}
public SimpleBinaryOpTest__SignInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.Sign(
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.Sign(
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.Sign(
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Sign), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Sign), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Sign), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.Sign(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Int16>* pClsVar1 = &_clsVar1)
fixed (Vector256<Int16>* pClsVar2 = &_clsVar2)
{
var result = Avx2.Sign(
Avx.LoadVector256((Int16*)(pClsVar1)),
Avx.LoadVector256((Int16*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr);
var result = Avx2.Sign(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx2.Sign(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx2.Sign(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__SignInt16();
var result = Avx2.Sign(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__SignInt16();
fixed (Vector256<Int16>* pFld1 = &test._fld1)
fixed (Vector256<Int16>* pFld2 = &test._fld2)
{
var result = Avx2.Sign(
Avx.LoadVector256((Int16*)(pFld1)),
Avx.LoadVector256((Int16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.Sign(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Int16>* pFld1 = &_fld1)
fixed (Vector256<Int16>* pFld2 = &_fld2)
{
var result = Avx2.Sign(
Avx.LoadVector256((Int16*)(pFld1)),
Avx.LoadVector256((Int16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.Sign(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.Sign(
Avx.LoadVector256((Int16*)(&test._fld1)),
Avx.LoadVector256((Int16*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Int16> op1, Vector256<Int16> op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (right[0] < 0 ? (short)(-left[0]) : (right[0] > 0 ? left[0] : 0)))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (right[i] < 0 ? (short)(-left[i]) : (right[i] > 0 ? left[i] : 0)))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Sign)}<Int16>(Vector256<Int16>, Vector256<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using UMA;
using UMA.CharacterSystem;
using System.Collections.Generic;
using System.IO;
using UMA.Examples;
using UMA.PoseTools;
using static UMA.UMAPackedRecipeBase;
namespace UMA.Editors
{
public class UMAAvatarLoadSaveMenuItems : Editor
{
[UnityEditor.MenuItem("GameObject/UMA/Save Mecanim Avatar to Asset (runtime only)")]
[MenuItem("UMA/Runtime/Save Selected Avatars Mecanim Avatar to Asset", priority = 1)]
public static void SaveMecanimAvatar()
{
if (!Application.isPlaying)
{
EditorUtility.DisplayDialog("Notice", "This function is only available at runtime", "Got it");
return;
}
if (Selection.gameObjects.Length != 1)
{
EditorUtility.DisplayDialog("Notice", "Only one Avatar can be selected.", "OK");
return;
}
var selectedTransform = Selection.gameObjects[0].transform;
var avatar = selectedTransform.GetComponent<UMAAvatarBase>();
if (avatar == null)
{
EditorUtility.DisplayDialog("Notice", "An Avatar must be selected to use this function", "OK");
return;
}
if (avatar.umaData == null)
{
EditorUtility.DisplayDialog("Notice", "The Avatar must be constructed before using this function", "OK");
return;
}
if (avatar.umaData.animator == null)
{
EditorUtility.DisplayDialog("Notice", "Animator has not been assigned!", "OK");
return;
}
if (avatar.umaData.animator.avatar == null)
{
EditorUtility.DisplayDialog("Notice", "Mecanim avatar is null!", "OK");
return;
}
string path = EditorUtility.SaveFilePanelInProject("Save avatar", "CreatedAvatar.asset", "asset", "Save the avatar");
AssetDatabase.CreateAsset(avatar.umaData.animator.avatar, path);
AssetDatabase.SaveAssets();
EditorUtility.DisplayDialog("Saved", "Avatar save to assets as CreatedAvatar", "OK");
}
public static void ConvertToNonUMA(GameObject baseObject, UMAAvatarBase avatar, string Folder, bool ConvertNormalMaps, string CharName, bool AddStandaloneDNA)
{
Folder = Folder + "/" + CharName;
if (!System.IO.Directory.Exists(Folder))
{
System.IO.Directory.CreateDirectory(Folder);
}
SkinnedMeshRenderer[] renderers = avatar.umaData.GetRenderers();
int meshno = 0;
foreach (SkinnedMeshRenderer smr in renderers)
{
Material[] mats = smr.sharedMaterials;
int Material = 0;
foreach (Material m in mats)
{
// get each texture.
// if the texture has been generated (has no path) then we need to convert to Texture2D (if needed) save that asset.
// update the material with that material.
List<Texture> allTexture = new List<Texture>();
Shader shader = m.shader;
for (int i = 0; i < ShaderUtil.GetPropertyCount(shader); i++)
{
if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.TexEnv)
{
string propertyName = ShaderUtil.GetPropertyName(shader, i);
Texture texture = m.GetTexture(propertyName);
if (texture is Texture2D || texture is RenderTexture)
{
bool isNormal = false;
string path = AssetDatabase.GetAssetPath(texture.GetInstanceID());
if (string.IsNullOrEmpty(path))
{
if (ConvertNormalMaps)
{
if (propertyName.ToLower().Contains("bumpmap") || propertyName.ToLower().Contains("normal"))
{
// texture = ConvertNormalMap(texture);
texture = sconvertNormalMap(texture);
isNormal = true;
}
}
string texName = Path.Combine(Folder, CharName + "_Mat_" + Material + propertyName + ".png");
SaveTexture(texture, texName);
AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
if (isNormal)
{
TextureImporter importer = (TextureImporter)TextureImporter.GetAtPath(texName);
importer.isReadable = true;
importer.textureType = TextureImporterType.NormalMap;
importer.maxTextureSize = 1024; // or whatever
importer.textureCompression = TextureImporterCompression.CompressedHQ;
EditorUtility.SetDirty(importer);
importer.SaveAndReimport();
}
Texture2D tex = AssetDatabase.LoadAssetAtPath<Texture2D>(CustomAssetUtility.UnityFriendlyPath(texName));
m.SetTexture(propertyName, tex);
}
}
}
}
string matname = Folder + "/"+CharName+"_Mat_" + Material + ".mat";
CustomAssetUtility.SaveAsset<Material>(m, matname);
Material++;
// Save the material to disk?
// update the SMR
}
string meshName = Folder + "/"+CharName+"_Mesh_" + meshno + ".asset";
meshno++;
// Save Mesh to disk.
CustomAssetUtility.SaveAsset<Mesh>(smr.sharedMesh, meshName);
smr.sharedMaterials = mats;
smr.materials = mats;
}
// save Animator Avatar.
var animator = baseObject.GetComponent<Animator>();
string avatarName = Folder + "/"+CharName+"_Avatar.asset";
CustomAssetUtility.SaveAsset<Avatar>(animator.avatar, avatarName);
DestroyImmediate(avatar);
var lod = baseObject.GetComponent<UMASimpleLOD>();
if (lod != null) DestroyImmediate(lod);
if (AddStandaloneDNA)
{
UMAData uda = baseObject.GetComponent<UMAData>();
StandAloneDNA sda = baseObject.AddComponent<UMA.StandAloneDNA>();
sda.PackedDNA = UMAPackedRecipeBase.GetPackedDNA(uda._umaRecipe);
if (avatar is DynamicCharacterAvatar)
{
DynamicCharacterAvatar avt = avatar as DynamicCharacterAvatar;
sda.avatarDefinition = avt.GetAvatarDefinition(true);
}
sda.umaData = uda;
}
else
{
var ud = baseObject.GetComponent<UMAData>();
if (ud != null) DestroyImmediate(ud);
}
var ue = baseObject.GetComponent<UMAExpressionPlayer>();
if (ue != null) DestroyImmediate(ue);
baseObject.name = CharName;
string prefabName = Folder + "/"+CharName+".prefab";
prefabName = CustomAssetUtility.UnityFriendlyPath(prefabName);
PrefabUtility.SaveAsPrefabAssetAndConnect(baseObject, prefabName, InteractionMode.AutomatedAction);
}
[UnityEditor.MenuItem("GameObject/UMA/Save Atlas Textures (runtime only)")]
[MenuItem("CONTEXT/DynamicCharacterAvatar/Save Selected Avatars generated textures to PNG", false, 10)]
[MenuItem("UMA/Runtime/Save Selected Avatar Atlas Textures")]
public static void SaveSelectedAvatarsPNG()
{
if (Selection.gameObjects.Length != 1)
{
EditorUtility.DisplayDialog("Notice", "Only one Avatar can be selected.", "OK");
return;
}
var selectedTransform = Selection.gameObjects[0].transform;
var avatar = selectedTransform.GetComponent<UMAAvatarBase>();
if (avatar == null)
{
EditorUtility.DisplayDialog("Notice", "An Avatar must be selected to use this function", "OK");
return;
}
SkinnedMeshRenderer smr = avatar.gameObject.GetComponentInChildren<SkinnedMeshRenderer>();
if (smr == null)
{
EditorUtility.DisplayDialog("Warning", "Could not find SkinnedMeshRenderer in Avatar hierarchy", "OK");
return;
}
string path = EditorUtility.SaveFilePanelInProject("Save Texture(s)", "Texture.png", "png", "Base Filename to save PNG files to.");
if (!string.IsNullOrEmpty(path))
{
string basename = System.IO.Path.GetFileNameWithoutExtension(path);
string pathname = System.IO.Path.GetDirectoryName(path);
// save the diffuse texture
for (int i = 0; i < smr.materials.Length; i++)
{
Material mat = smr.materials[i];
string PathBase = System.IO.Path.Combine(pathname, basename + "_material_" + i.ToString());
string[] texNames = mat.GetTexturePropertyNames();
foreach (string tex in texNames)
{
string texname = PathBase + tex + ".PNG";
Texture texture = mat.GetTexture(tex);
if (texture != null) SaveTexture(texture, texname);
}
}
}
}
private static void SaveTexture(Texture texture, string diffuseName, bool isNormal = false)
{
if (texture is RenderTexture)
{
SaveRenderTexture(texture as RenderTexture, diffuseName, isNormal);
return;
}
else if (texture is Texture2D)
{
SaveTexture2D(texture as Texture2D, diffuseName);
return;
}
EditorUtility.DisplayDialog("Error", "Texture is not RenderTexture or Texture2D", "OK");
}
/// <param name="normalMap"></param>
/// <returns></returns>
private static Texture2D sconvertNormalMap(Texture2D normalMap)
{
ComputeShader normalMapConverter = Resources.Load<ComputeShader>("Shader/NormalShader");
int kernel = normalMapConverter.FindKernel("NormalConverter");
RenderTexture normalMapRenderTex = new RenderTexture(normalMap.width, normalMap.height, 24);
normalMapRenderTex.enableRandomWrite = true;
normalMapRenderTex.Create();
normalMapConverter.SetTexture(kernel, "Input", normalMap);
normalMapConverter.SetTexture(kernel, "Result", normalMapRenderTex);
normalMapConverter.Dispatch(kernel, normalMap.width, normalMap.height, 1);
RenderTexture.active = normalMapRenderTex;
Texture2D convertedNormalMap = new Texture2D(normalMap.width, normalMap.height, TextureFormat.RGBA32, false, true);
convertedNormalMap.ReadPixels(new Rect(0, 0, normalMap.width, normalMap.height), 0, 0);
convertedNormalMap.Apply();
DestroyImmediate(normalMapRenderTex);
return convertedNormalMap;
}
private static Texture2D sconvertNormalMap(RenderTexture normalMap)
{
ComputeShader normalMapConverter = Resources.Load<ComputeShader>("Shader/NormalShader");
int kernel = normalMapConverter.FindKernel("NormalConverter");
RenderTexture normalMapRenderTex = new RenderTexture(normalMap.width, normalMap.height, 24);
normalMapRenderTex.enableRandomWrite = true;
normalMapRenderTex.Create();
normalMapConverter.SetTexture(kernel, "Input", normalMap);
normalMapConverter.SetTexture(kernel, "Result", normalMapRenderTex);
normalMapConverter.Dispatch(kernel, normalMap.width, normalMap.height, 1);
RenderTexture.active = normalMapRenderTex;
Texture2D convertedNormalMap = new Texture2D(normalMap.width, normalMap.height, TextureFormat.RGBA32, false, true);
convertedNormalMap.ReadPixels(new Rect(0, 0, normalMap.width, normalMap.height), 0, 0);
convertedNormalMap.Apply();
DestroyImmediate(normalMapRenderTex);
return convertedNormalMap;
}
private static Texture2D sconvertNormalMap2(RenderTexture rt)
{
Texture2D tex = GetRTPixels(rt);
Texture2D result = sconvertNormalMap(tex);
DestroyImmediate(tex);
return result;
}
private static Texture2D sconvertNormalMap(Texture tex)
{
if (tex is RenderTexture)
return sconvertNormalMap(tex as RenderTexture);
return sconvertNormalMap(tex as Texture2D);
}
static public Texture2D GetRTPixels(RenderTexture rt)
{
/// Some goofiness ends up with the texture being too dark unless
/// I send it to a new render texture.
RenderTexture outputMap = new RenderTexture(rt.width, rt.height, 32);
outputMap.enableRandomWrite = true;
outputMap.Create();
RenderTexture.active = outputMap;
GL.Clear(true, true, Color.black);
Graphics.Blit(rt, outputMap);
// Remember currently active render texture
RenderTexture currentActiveRT = RenderTexture.active;
// Set the supplied RenderTexture as the active one
RenderTexture.active = outputMap;
// Create a new Texture2D and read the RenderTexture image into it
Texture2D tex = new Texture2D(rt.width, rt.height, TextureFormat.ARGB32, false, true);
tex.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0);
// Restore previously active render texture
RenderTexture.active = currentActiveRT;
DestroyImmediate(outputMap);
return tex;
}
private static void SaveRenderTexture(RenderTexture texture, string textureName, bool isNormal = false)
{
Texture2D tex;
if (isNormal)
{
tex = sconvertNormalMap(texture);
}
else
{
tex = GetRTPixels(texture);
}
SaveTexture2D(tex, textureName);
}
private static void SaveTexture2D(Texture2D texture, string textureName)
{
if (texture.isReadable)
{
byte[] data = texture.EncodeToPNG();
System.IO.File.WriteAllBytes(textureName, data);
}
else
{
Debug.LogError("Texture: " + texture.name + " is not readable. Skipping.");
}
}
[UnityEditor.MenuItem("CONTEXT/DynamicCharacterAvatar/Save as UMA Preset")]
[UnityEditor.MenuItem("GameObject/UMA/Save as UMA Preset")]
[MenuItem("UMA/Load and Save/Save Selected Avatar as UMA Preset", priority = 1)]
public static void SaveSelectedAvatarsPreset()
{
for (int i = 0; i < Selection.gameObjects.Length; i++)
{
var selectedTransform = Selection.gameObjects[i].transform;
var avatar = selectedTransform.GetComponent<DynamicCharacterAvatar>();
while (avatar == null && selectedTransform.parent != null)
{
selectedTransform = selectedTransform.parent;
avatar = selectedTransform.GetComponent<DynamicCharacterAvatar>();
}
if (avatar != null)
{
var path = EditorUtility.SaveFilePanel("Save avatar preset", "Assets", avatar.name + ".umapreset", "umapreset");
if (path.Length != 0)
{
UMAPreset prs = new UMAPreset();
prs.DefaultColors = avatar.characterColors;
var DNA = avatar.GetDNA();
prs.PredefinedDNA = new UMAPredefinedDNA();
foreach (DnaSetter d in DNA.Values)
{
prs.PredefinedDNA.AddDNA(d.Name, d.Value);
}
prs.DefaultWardrobe = new DynamicCharacterAvatar.WardrobeRecipeList();
foreach (UMATextRecipe utr in avatar.WardrobeRecipes.Values)
{
prs.DefaultWardrobe.recipes.Add(new DynamicCharacterAvatar.WardrobeRecipeListItem(utr));
}
string presetstring = JsonUtility.ToJson(prs);
System.IO.File.WriteAllText(path, presetstring);
}
}
}
}
[UnityEditor.MenuItem("CONTEXT/DynamicCharacterAvatar/Save as Character text file (runtime only)")]
[UnityEditor.MenuItem("GameObject/UMA/Save as Character Text file (runtime only)")]
[MenuItem("UMA/Load and Save/Save Selected Avatar(s) Txt", priority = 1)]
public static void SaveSelectedAvatarsTxt()
{
for (int i = 0; i < Selection.gameObjects.Length; i++)
{
var selectedTransform = Selection.gameObjects[i].transform;
var avatar = selectedTransform.GetComponent<UMAAvatarBase>();
while (avatar == null && selectedTransform.parent != null)
{
selectedTransform = selectedTransform.parent;
avatar = selectedTransform.GetComponent<UMAAvatarBase>();
}
if (avatar != null)
{
var path = EditorUtility.SaveFilePanel("Save serialized Avatar", "Assets", avatar.name + ".txt", "txt");
if (path.Length != 0)
{
var asset = ScriptableObject.CreateInstance<UMATextRecipe>();
//check if Avatar is DCS
if (avatar is UMA.CharacterSystem.DynamicCharacterAvatar)
{
asset.Save(avatar.umaData.umaRecipe, avatar.context, (avatar as DynamicCharacterAvatar).WardrobeRecipes, true);
}
else
{
asset.Save(avatar.umaData.umaRecipe, avatar.context);
}
System.IO.File.WriteAllText(path, asset.recipeString);
UMAUtils.DestroySceneObject(asset);
}
}
}
}
[UnityEditor.MenuItem("GameObject/UMA/Show Mesh Info (runtime only)")]
public static void ShowSelectedAvatarStats()
{
if (Selection.gameObjects.Length == 1)
{
var selectedTransform = Selection.gameObjects[0].transform;
var avatar = selectedTransform.GetComponent<UMAAvatarBase>();
while (avatar == null && selectedTransform.parent != null)
{
selectedTransform = selectedTransform.parent;
avatar = selectedTransform.GetComponent<UMAAvatarBase>();
}
if (avatar != null)
{
SkinnedMeshRenderer sk = avatar.gameObject.GetComponentInChildren<SkinnedMeshRenderer>();
if (sk != null)
{
List<string> info = new List<string>
{
sk.gameObject.name,
"Mesh index type: " + sk.sharedMesh.indexFormat.ToString(),
"VertexLength: " + sk.sharedMesh.vertices.Length,
"Submesh Count: " + sk.sharedMesh.subMeshCount
};
for (int i = 0; i < sk.sharedMesh.subMeshCount; i++)
{
int[] tris = sk.sharedMesh.GetTriangles(i);
info.Add("Submesh " + i + " Tri count: " + tris.Length);
}
Rect R = new Rect(200.0f, 200.0f, 300.0f, 600.0f);
DisplayListWindow.ShowDialog("Mesh Info", R, info);
}
}
}
}
[UnityEditor.MenuItem("GameObject/UMA/Save as Character Asset (runtime only)")]
[UnityEditor.MenuItem("CONTEXT/DynamicCharacterAvatar/Save as Asset (runtime only)")]
[MenuItem("UMA/Load and Save/Save Selected Avatar(s) asset", priority = 1)]
public static void SaveSelectedAvatarsAsset()
{
for (int i = 0; i < Selection.gameObjects.Length; i++)
{
var selectedTransform = Selection.gameObjects[i].transform;
var avatar = selectedTransform.GetComponent<UMAAvatarBase>();
while (avatar == null && selectedTransform.parent != null)
{
selectedTransform = selectedTransform.parent;
avatar = selectedTransform.GetComponent<UMAAvatarBase>();
}
if (avatar != null)
{
var path = EditorUtility.SaveFilePanelInProject("Save serialized Avatar", avatar.name + ".asset", "asset", "Message 2");
if (path.Length != 0)
{
var asset = ScriptableObject.CreateInstance<UMATextRecipe>();
//check if Avatar is DCS
if (avatar is DynamicCharacterAvatar)
{
asset.Save(avatar.umaData.umaRecipe, avatar.context, (avatar as DynamicCharacterAvatar).WardrobeRecipes, true);
}
else
{
asset.Save(avatar.umaData.umaRecipe, avatar.context);
}
AssetDatabase.CreateAsset(asset, path);
AssetDatabase.SaveAssets();
Debug.Log("Recipe size: " + asset.recipeString.Length + " chars");
}
}
}
}
[UnityEditor.MenuItem("GameObject/UMA/Load from Character Text file (runtime only)")]
[UnityEditor.MenuItem("CONTEXT/DynamicCharacterAvatar/Load Avatar from text file (runtime only)")]
[MenuItem("UMA/Load and Save/Load Selected Avatar(s) txt", priority = 1)]
public static void LoadSelectedAvatarsTxt()
{
for (int i = 0; i < Selection.gameObjects.Length; i++)
{
var selectedTransform = Selection.gameObjects[i].transform;
var avatar = selectedTransform.GetComponent<UMAAvatarBase>();
while (avatar == null && selectedTransform.parent != null)
{
selectedTransform = selectedTransform.parent;
avatar = selectedTransform.GetComponent<UMAAvatarBase>();
}
if (avatar != null)
{
var path = EditorUtility.OpenFilePanel("Load serialized Avatar", "Assets", "txt");
if (path.Length != 0)
{
var asset = ScriptableObject.CreateInstance<UMATextRecipe>();
asset.recipeString = FileUtils.ReadAllText(path);
//check if Avatar is DCS
if (avatar is DynamicCharacterAvatar)
{
(avatar as DynamicCharacterAvatar).LoadFromRecipeString(asset.recipeString);
}
else
{
avatar.Load(asset);
}
UMAUtils.DestroySceneObject(asset);
}
}
}
}
[UnityEditor.MenuItem("GameObject/UMA/Load from Character Asset (runtime only)")]
[UnityEditor.MenuItem("CONTEXT/DynamicCharacterAvatar/Load Avatar from Asset (runtime only)")]
[MenuItem("UMA/Load and Save/Load Selected Avatar(s) assets", priority = 1)]
public static void LoadSelectedAvatarsAsset()
{
for (int i = 0; i < Selection.gameObjects.Length; i++)
{
var selectedTransform = Selection.gameObjects[i].transform;
var avatar = selectedTransform.GetComponent<UMAAvatarBase>();
while (avatar == null && selectedTransform.parent != null)
{
selectedTransform = selectedTransform.parent;
avatar = selectedTransform.GetComponent<UMAAvatarBase>();
}
if (avatar != null)
{
var path = EditorUtility.OpenFilePanel("Load serialized Avatar", "Assets", "asset");
if (path.Length != 0)
{
var index = path.IndexOf("/Assets/");
if (index > 0)
{
path = path.Substring(index + 1);
}
var asset = AssetDatabase.LoadMainAssetAtPath(path) as UMARecipeBase;
if (asset != null)
{
//check if Avatar is DCS
if (avatar is DynamicCharacterAvatar)
{
(avatar as DynamicCharacterAvatar).LoadFromRecipe(asset);
}
else
{
avatar.Load(asset);
}
}
else
{
Debug.LogError("Failed To Load Asset \"" + path + "\"\nAssets must be inside the project and descend from the UMARecipeBase type");
}
}
}
}
}
//@jaimi this is the equivalent of your previous JSON save but the resulting file does not need a special load method
[UnityEditor.MenuItem("GameObject/UMA/Save as Optimized Character Text File (runtime only)")]
[UnityEditor.MenuItem("CONTEXT/DynamicCharacterAvatar/Save as Optimized Character Text File")]
[MenuItem("UMA/Load and Save/Save DynamicCharacterAvatar(s) txt (optimized)", priority = 1)]
public static void SaveSelectedAvatarsDCSTxt()
{
if (!Application.isPlaying)
{
EditorUtility.DisplayDialog("Notice", "This function is only available at runtime", "Got it");
return;
}
else
{
EditorUtility.DisplayDialog("Notice", "The optimized save type is only compatible with DynamicCharacterAvatar avatars (or child classes of)", "Continue");
}
for (int i = 0; i < Selection.gameObjects.Length; i++)
{
var selectedTransform = Selection.gameObjects[i].transform;
var avatar = selectedTransform.GetComponent<DynamicCharacterAvatar>();
if (avatar != null)
{
var path = EditorUtility.SaveFilePanel("Save DynamicCharacterAvatar Optimized Text", "Assets", avatar.name + ".txt", "txt");
if (path.Length != 0)
{
avatar.DoSave(false, path);
}
}
}
}
//@jaimi this is the equivalent of your previous JSON save but the resulting file does not need a special load method and the resulting asset can also be inspected and edited
[UnityEditor.MenuItem("GameObject/UMA/Save as Optimized Character Asset (runtime only)")]
[UnityEditor.MenuItem("CONTEXT/DynamicCharacterAvatar/Save as Optimized Character Asset File")]
[MenuItem("UMA/Load and Save/Save DynamicCharacterAvatar(s) asset (optimized)", priority = 1)]
public static void SaveSelectedAvatarsDCSAsset()
{
if (!Application.isPlaying)
{
EditorUtility.DisplayDialog("Notice", "This function is only available at runtime", "Got it");
return;
}
else
{
EditorUtility.DisplayDialog("Notice", "The optimized save type is only compatible with DynamicCharacterAvatar avatars (or child classes of)", "Continue");
}
for (int i = 0; i < Selection.gameObjects.Length; i++)
{
var selectedTransform = Selection.gameObjects[i].transform;
var avatar = selectedTransform.GetComponent<DynamicCharacterAvatar>();
if (avatar != null)
{
var path = EditorUtility.SaveFilePanelInProject("Save DynamicCharacterAvatar Optimized Asset", avatar.name + ".asset", "asset", "Message 2");
if (path.Length != 0)
{
avatar.DoSave(true, path);
}
}
}
}
[UnityEditor.MenuItem("Assets/Add Selected Assets to UMA Global Library")]
public static void AddSelectedToGlobalLibrary()
{
int added = 0;
UMAAssetIndexer UAI = UMAAssetIndexer.Instance;
foreach (Object o in Selection.objects)
{
System.Type type = o.GetType();
if (UAI.IsIndexedType(type))
{
if (UAI.EvilAddAsset(type, o))
added++;
}
}
UAI.ForceSave();
EditorUtility.DisplayDialog("Success", added + " item(s) added to Global Library", "OK");
}
}
public class UmaPrefabSaverWindow : EditorWindow
{
[Tooltip("The character that you want to convert")]
public UMAAvatarBase baseObject;
[Tooltip("Convert Swizzled normal maps back to standard normal maps")]
public bool UnswizzleNormalMaps = true;
[Tooltip("If True, will keep the umaData, and add a Standalone DNA component allowing you to load/save/Deform skeletal DNA")]
public bool AddStandaloneDNA = true;
[Tooltip("The prefab will be named this, and it will be added to all assets saved")]
public string CharacterName;
[Tooltip("The folder where the prefab folder will be created")]
public UnityEngine.Object prefabFolder;
public string CheckFolder(ref UnityEngine.Object folderObject)
{
if (folderObject != null)
{
string destpath = AssetDatabase.GetAssetPath(folderObject);
if (string.IsNullOrEmpty(destpath))
{
folderObject = null;
}
else if (!System.IO.Directory.Exists(destpath))
{
destpath = destpath.Substring(0, destpath.LastIndexOf('/'));
}
return destpath;
}
return null;
}
void OnGUI()
{
EditorGUILayout.LabelField("UMA Prefab Saver", EditorStyles.boldLabel);
EditorGUILayout.HelpBox("This will convert an UMA avatar into a non-UMA prefab. Once converted, it can be reused with little overhead, but all UMA functionality will be lost.", MessageType.None, false);
baseObject = (UMAAvatarBase)EditorGUILayout.ObjectField("UMA Avatar",baseObject, typeof(UMAAvatarBase),true);
UnswizzleNormalMaps = EditorGUILayout.Toggle("Unswizzle Normals", UnswizzleNormalMaps);
AddStandaloneDNA = EditorGUILayout.Toggle("Add Standalone DNA", AddStandaloneDNA);
CharacterName = EditorGUILayout.TextField("Prefab Name", CharacterName);
prefabFolder = EditorGUILayout.ObjectField("Prefab Base Folder", prefabFolder, typeof(UnityEngine.Object), false) as UnityEngine.Object;
string folder = CheckFolder(ref prefabFolder);
if (prefabFolder != null && baseObject != null && !string.IsNullOrEmpty(CharacterName))
{
if (GUILayout.Button("Make Prefab") && prefabFolder != null)
{
UMAAvatarLoadSaveMenuItems.ConvertToNonUMA(baseObject.gameObject, baseObject, folder, UnswizzleNormalMaps, CharacterName,AddStandaloneDNA);
EditorUtility.DisplayDialog("UMA Prefab Saver", "Conversion complete", "OK");
}
}
else
{
if (baseObject == null)
{
EditorGUILayout.HelpBox("A valid character with DynamicCharacterAvatar or DynamicAvatar must be supplied",MessageType.Error);
}
if (string.IsNullOrEmpty(CharacterName))
{
EditorGUILayout.HelpBox("Prefab Name cannot be empty", MessageType.Error);
}
if (prefabFolder == null)
{
EditorGUILayout.HelpBox("A valid base folder must be supplied", MessageType.Error);
}
}
}
[MenuItem("UMA/Prefab Maker", priority = 20)]
public static void OpenUmaPrefabWindow()
{
UmaPrefabSaverWindow window = (UmaPrefabSaverWindow)EditorWindow.GetWindow(typeof(UmaPrefabSaverWindow));
window.titleContent.text = "UMA Prefab Maker";
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Test
{
public class ImmutableQueueTest : SimpleElementImmutablesTestBase
{
private void EnqueueDequeueTestHelper<T>(params T[] items)
{
Contract.Requires(items != null);
var queue = ImmutableQueue<T>.Empty;
int i = 0;
foreach (T item in items)
{
var nextQueue = queue.Enqueue(item);
Assert.NotSame(queue, nextQueue); //, "Enqueue returned this instead of a new instance.");
Assert.Equal(i, queue.Count()); //, "Enqueue mutated the queue.");
Assert.Equal(++i, nextQueue.Count());
queue = nextQueue;
}
i = 0;
foreach (T element in queue)
{
AssertAreSame(items[i++], element);
}
i = 0;
foreach (T element in (System.Collections.IEnumerable)queue)
{
AssertAreSame(items[i++], element);
}
i = items.Length;
foreach (T expectedItem in items)
{
T actualItem = queue.Peek();
AssertAreSame(expectedItem, actualItem);
var nextQueue = queue.Dequeue();
Assert.NotSame(queue, nextQueue); //, "Dequeue returned this instead of a new instance.");
Assert.Equal(i, queue.Count());
Assert.Equal(--i, nextQueue.Count());
queue = nextQueue;
}
}
[Fact]
public void EnumerationOrder()
{
var queue = ImmutableQueue<int>.Empty;
// Push elements onto the backwards stack.
queue = queue.Enqueue(1).Enqueue(2).Enqueue(3);
Assert.Equal(1, queue.Peek());
// Force the backwards stack to be reversed and put into forwards.
queue = queue.Dequeue();
// Push elements onto the backwards stack again.
queue = queue.Enqueue(4).Enqueue(5);
// Now that we have some elements on the forwards and backwards stack,
// 1. enumerate all elements to verify order.
Assert.Equal<int>(new[] { 2, 3, 4, 5 }, queue.ToArray());
// 2. dequeue all elements to verify order
var actual = new int[queue.Count()];
for (int i = 0; i < actual.Length; i++)
{
actual[i] = queue.Peek();
queue = queue.Dequeue();
}
}
[Fact]
public void GetEnumeratorText()
{
var queue = ImmutableQueue.Create(5);
var enumeratorStruct = queue.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumeratorStruct.Current);
Assert.True(enumeratorStruct.MoveNext());
Assert.Equal(5, enumeratorStruct.Current);
Assert.False(enumeratorStruct.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumeratorStruct.Current);
var enumerator = ((IEnumerable<int>)queue).GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(5, enumerator.Current);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(5, enumerator.Current);
Assert.False(enumerator.MoveNext());
enumerator.Dispose();
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var queue = ImmutableQueue.Create(5);
var enumerator = ((IEnumerable<int>)queue).GetEnumerator();
var enumeratorCopy = enumerator;
Assert.True(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
// As pure structs with no disposable reference types inside it,
// we have nothing to track across struct copies, and this just works.
////Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext());
////Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset());
////Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = ((IEnumerable<int>)queue).GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.Equal(queue.Peek(), enumerator.Current);
enumerator.Dispose();
}
[Fact]
public void EnqueueDequeueTest()
{
this.EnqueueDequeueTestHelper(new GenericParameterHelper(1), new GenericParameterHelper(2), new GenericParameterHelper(3));
this.EnqueueDequeueTestHelper<GenericParameterHelper>();
// interface test
IImmutableQueue<GenericParameterHelper> queueInterface = ImmutableQueue.Create<GenericParameterHelper>();
IImmutableQueue<GenericParameterHelper> populatedQueueInterface = queueInterface.Enqueue(new GenericParameterHelper(5));
Assert.Equal(new GenericParameterHelper(5), populatedQueueInterface.Peek());
}
[Fact]
public void DequeueOutValue()
{
var queue = ImmutableQueue<int>.Empty.Enqueue(5).Enqueue(6);
int head;
queue = queue.Dequeue(out head);
Assert.Equal(5, head);
var emptyQueue = queue.Dequeue(out head);
Assert.Equal(6, head);
Assert.True(emptyQueue.IsEmpty);
// Also check that the interface extension method works.
IImmutableQueue<int> interfaceQueue = queue;
Assert.Same(emptyQueue, interfaceQueue.Dequeue(out head));
Assert.Equal(6, head);
}
[Fact]
public void ClearTest()
{
var emptyQueue = ImmutableQueue.Create<GenericParameterHelper>();
AssertAreSame(emptyQueue, emptyQueue.Clear());
var nonEmptyQueue = emptyQueue.Enqueue(new GenericParameterHelper(3));
AssertAreSame(emptyQueue, nonEmptyQueue.Clear());
// Interface test
IImmutableQueue<GenericParameterHelper> queueInterface = nonEmptyQueue;
AssertAreSame(emptyQueue, queueInterface.Clear());
}
[Fact]
public void EqualsTest()
{
Assert.False(ImmutableQueue<int>.Empty.Equals(null));
Assert.False(ImmutableQueue<int>.Empty.Equals("hi"));
Assert.True(ImmutableQueue<int>.Empty.Equals(ImmutableQueue<int>.Empty));
Assert.False(ImmutableQueue<int>.Empty.Enqueue(3).Equals(ImmutableQueue<int>.Empty.Enqueue(3)));
Assert.False(ImmutableQueue<int>.Empty.Enqueue(5).Equals(ImmutableQueue<int>.Empty.Enqueue(3)));
Assert.False(ImmutableQueue<int>.Empty.Enqueue(3).Enqueue(5).Equals(ImmutableQueue<int>.Empty.Enqueue(3)));
Assert.False(ImmutableQueue<int>.Empty.Enqueue(3).Equals(ImmutableQueue<int>.Empty.Enqueue(3).Enqueue(5)));
// Also be sure to compare equality of partially dequeued queues since that moves data to different fields.
Assert.False(ImmutableQueue<int>.Empty.Enqueue(3).Enqueue(1).Enqueue(2).Dequeue().Equals(ImmutableQueue<int>.Empty.Enqueue(1).Enqueue(2)));
}
[Fact]
public void PeekEmptyThrows()
{
Assert.Throws<InvalidOperationException>(() => ImmutableQueue<GenericParameterHelper>.Empty.Peek());
}
[Fact]
public void DequeueEmptyThrows()
{
Assert.Throws<InvalidOperationException>(() => ImmutableQueue<GenericParameterHelper>.Empty.Dequeue());
}
[Fact]
public void Create()
{
ImmutableQueue<int> queue = ImmutableQueue.Create<int>();
Assert.True(queue.IsEmpty);
queue = ImmutableQueue.Create(1);
Assert.False(queue.IsEmpty);
Assert.Equal(new[] { 1 }, queue);
queue = ImmutableQueue.Create(1, 2);
Assert.False(queue.IsEmpty);
Assert.Equal(new[] { 1, 2 }, queue);
queue = ImmutableQueue.CreateRange((IEnumerable<int>)new[] { 1, 2 });
Assert.False(queue.IsEmpty);
Assert.Equal(new[] { 1, 2 }, queue);
Assert.Throws<ArgumentNullException>(() => ImmutableQueue.CreateRange((IEnumerable<int>)null));
Assert.Throws<ArgumentNullException>(() => ImmutableQueue.Create((int[])null));
}
[Fact]
public void Empty()
{
// We already test Create(), so just prove that Empty has the same effect.
Assert.Same(ImmutableQueue.Create<int>(), ImmutableQueue<int>.Empty);
}
protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents)
{
var queue = ImmutableQueue<T>.Empty;
foreach (var item in contents)
{
queue = queue.Enqueue(item);
}
return queue;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Description;
using Augment;
using FluentValidation;
using NerdBudget.Core;
using NerdBudget.Core.Models;
using NerdBudget.Core.Services;
using Newtonsoft.Json;
namespace NerdBudget.Web.ApiControllers
{
/// <summary>
/// Represents a basic controller for Ledger
/// </summary>
[RoutePrefix("api/ledgers")]
public class LedgersController : BaseController
{
#region Members
public class Trx { public string Transactions { get; set; } }
private IAccountService _service;
#endregion
#region Contructors
public LedgersController(IAccountService service)
{
_service = service;
}
#endregion
#region Import Actions
// POST: api/ledger
[HttpPost, Route("{accountId}/import")]
public IHttpActionResult PostImport(string accountId, [FromBody]Trx trx)
{
Account account = GetAccount(accountId);
if (account == null)
{
return NotFound();
}
try
{
account.Ledgers.Import(trx.Transactions);
_service.Save(account.Ledgers);
_service.Save(account.Balances);
_service.Save(account.Maps);
return Ok();
}
catch (ValidationException exp)
{
return BadRequest(exp.Errors);
}
}
#endregion
#region Normal CRUD Actions
// GET: api/ledger/5
[HttpGet, Route("{accountId}/{budgetId}/{date}/weekly"), ResponseType(typeof(Ledger))]
public IHttpActionResult GetLedgers(string accountId, string budgetId, DateTime date)
{
Account account = GetAccount(accountId);
if (account == null)
{
return NotFound();
}
Range<DateTime> range = date.ToWeeklyBudgetRange();
IEnumerable<Ledger> ledgers = account.Ledgers
.Where(x => x.BudgetId == budgetId && range.Contains(x.Date))
.OrderBy(x => x.Date).ThenBy(x => x.Sequence);
JsonSerializerSettings jss = GetPayloadSettings();
return Json(ledgers, jss);
}
// GET: api/ledger/5
[HttpGet, Route("{accountId}/map"), ResponseType(typeof(Ledger))]
public IHttpActionResult Get(string accountId)
{
Account account = GetAccount(accountId);
if (account == null)
{
return NotFound();
}
Ledger ledger = account.Ledgers.MissingBudget().FirstOrDefault();
if (ledger == null)
{
return Ok(new { status = 302, url = Url.Content("~/Analysis/" + account.Id) });
}
JsonSerializerSettings jss = GetPayloadSettings();
return Json(ledger, jss);
}
// GET: api/ledger/5
[HttpGet, Route("{accountId}/{id}/{date}"), ResponseType(typeof(Ledger))]
public IHttpActionResult Get(string accountId, string id, DateTime date)
{
Account account = GetAccount(accountId);
if (account == null)
{
return NotFound();
}
Ledger ledger = account.Ledgers.Find(id, date);
if (ledger == null)
{
return NotFound();
}
JsonSerializerSettings jss = GetPayloadSettings();
var model = new
{
account = account,
budgets = account.Categories.SelectMany(x => x.Budgets),
ledger = ledger
};
return Json(model, jss);
}
// PUT: api/ledger/5
[HttpPut, Route("{accountId}/{id}/{date}")]
public IHttpActionResult Put(string accountId, string id, DateTime date, [FromBody]Ledger ledger)
{
Account account = GetAccount(accountId);
if (account == null)
{
return NotFound();
}
Ledger model = account.Ledgers.Find(id, date);
if (model == null)
{
return NotFound();
}
if (model.BudgetId.IsNullOrEmpty())
{
// need to associate a map
Map map = account.Maps.CreateFor(ledger);
foreach (Ledger x in account.Ledgers.MissingBudget())
{
if (map.IsMatchFor(x))
{
x.BudgetId = map.BudgetId;
}
}
}
else
{
// otherwise we're just moving "this" ledger
model.BudgetId = ledger.BudgetId;
}
try
{
_service.Save(account.Ledgers);
_service.Save(account.Maps);
return Ok();
}
catch (ValidationException ve)
{
return BadRequest(ve.Errors);
}
}
#endregion
#region Verb Actions
//// GET: api/ledger
//[HttpGet, Route("{accountId}/{startDate:datetime}/{endDate:datetime}")]
//public IHttpActionResult GetAll(string accountId, DateTime startDate, DateTime endDate)
//{
// Account account = GetAccount(accountId);
// if (account == null)
// {
// return NotFound();
// }
// Range<DateTime> dateRange = new Range<DateTime>(startDate, endDate);
// IList<Ledger> ledgers = account.Ledgers
// .Where(x => dateRange.Contains(x.Date))
// .OrderBy(x => x.Date)
// .ThenBy(x => x.Sequence)
// .ToList();
// JsonSerializerSettings jss = GetPayloadSettings();
// var model = new
// {
// account = account,
// ledgers = ledgers
// };
// return Json(_service.GetList());
//}
#endregion
#region Helpers
private Account GetAccount(string accountId)
{
return _service.Get(accountId);
}
private JsonSerializerSettings GetPayloadSettings()
{
return PayloadManager
.AddPayload<Account>("Id,Name")
.AddPayload<Budget>("Id,FullName")
.AddStandardPayload<Ledger>()
.ToSettings();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void OrUInt64()
{
var test = new SimpleBinaryOpTest__OrUInt64();
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__OrUInt64
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(UInt64);
private const int Op2ElementCount = VectorSize / sizeof(UInt64);
private const int RetElementCount = VectorSize / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static Vector128<UInt64> _clsVar1;
private static Vector128<UInt64> _clsVar2;
private Vector128<UInt64> _fld1;
private Vector128<UInt64> _fld2;
private SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64> _dataTable;
static SimpleBinaryOpTest__OrUInt64()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__OrUInt64()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64>(_data1, _data2, new UInt64[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Or(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Or(
Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Or(
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt64*)(_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.Or), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Or(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var result = Sse2.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = Sse2.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = Sse2.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__OrUInt64();
var result = Sse2.Or(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.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(Vector128<UInt64> left, Vector128<UInt64> right, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, 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 = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "")
{
if ((ulong)(left[0] | right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((ulong)(left[i] | right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Or)}<UInt64>(Vector128<UInt64>, Vector128<UInt64>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#if FEATURE_ENCODINGNLS
namespace System.Text
{
using System;
using System.Diagnostics.Contracts;
using System.Collections;
using System.Runtime.Remoting;
using System.Globalization;
using System.Threading;
using Win32Native = Microsoft.Win32.Win32Native;
// This class overrides Encoding with the things we need for our NLS Encodings
//
// All of the GetBytes/Chars GetByte/CharCount methods are just wrappers for the pointer
// plus decoder/encoder method that is our real workhorse. Note that this is an internal
// class, so our public classes cannot derive from this class. Because of this, all of the
// GetBytes/Chars GetByte/CharCount wrapper methods are duplicated in all of our public
// encodings, which currently include:
//
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, & UnicodeEncoding
//
// So if you change the wrappers in this class, you must change the wrappers in the other classes
// as well because they should have the same behavior.
//
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
internal abstract class EncodingNLS : Encoding
{
protected EncodingNLS(int codePage) : base(codePage)
{
}
// Returns the number of bytes required to encode a range of characters in
// a character array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
[System.Security.SecuritySafeCritical] // overrides public transparent member
public override unsafe int GetByteCount(char[] chars, int index, int count)
{
// Validate input parameters
if (chars == null)
throw new ArgumentNullException("chars",
Environment.GetResourceString("ArgumentNull_Array"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (chars.Length - index < count)
throw new ArgumentOutOfRangeException("chars",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
// If no input, return 0, avoid fixed empty array problem
if (chars.Length == 0)
return 0;
// Just call the pointer version
fixed (char* pChars = chars)
return GetByteCount(pChars + index, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
[System.Security.SecuritySafeCritical] // overrides public transparent member
public override unsafe int GetByteCount(String s)
{
// Validate input
if (s==null)
throw new ArgumentNullException("s");
Contract.EndContractBlock();
fixed (char* pChars = s)
return GetByteCount(pChars, s.Length, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[System.Security.SecurityCritical] // auto-generated
public override unsafe int GetByteCount(char* chars, int count)
{
// Validate Parameters
if (chars == null)
throw new ArgumentNullException("chars",
Environment.GetResourceString("ArgumentNull_Array"));
if (count < 0)
throw new ArgumentOutOfRangeException("count",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Call it with empty encoder
return GetByteCount(chars, count, null);
}
// Parent method is safe.
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[System.Security.SecuritySafeCritical] // overrides public transparent member
public override unsafe int GetBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
if (s == null || bytes == null)
throw new ArgumentNullException((s == null ? "s" : "bytes"),
Environment.GetResourceString("ArgumentNull_Array"));
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (s.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException("s",
Environment.GetResourceString("ArgumentOutOfRange_IndexCount"));
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException("byteIndex",
Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
int byteCount = bytes.Length - byteIndex;
// Fixed doesn't like empty arrays
if (bytes.Length == 0)
bytes = new byte[1];
fixed (char* pChars = s)
fixed ( byte* pBytes = bytes)
return GetBytes(pChars + charIndex, charCount,
pBytes + byteIndex, byteCount, null);
}
// Encodes a range of characters in a character array into a range of bytes
// in a byte array. An exception occurs if the byte array is not large
// enough to hold the complete encoding of the characters. The
// GetByteCount method can be used to determine the exact number of
// bytes that will be produced for a given range of characters.
// Alternatively, the GetMaxByteCount method can be used to
// determine the maximum number of bytes that will be produced for a given
// number of characters, regardless of the actual character values.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
[System.Security.SecuritySafeCritical] // overrides public transparent member
public override unsafe int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? "chars" : "bytes"),
Environment.GetResourceString("ArgumentNull_Array"));
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException("chars",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException("byteIndex",
Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
// If nothing to encode return 0, avoid fixed problem
if (chars.Length == 0)
return 0;
// Just call pointer version
int byteCount = bytes.Length - byteIndex;
// Fixed doesn't like empty arrays
if (bytes.Length == 0)
bytes = new byte[1];
fixed (char* pChars = chars)
fixed (byte* pBytes = bytes)
// Remember that byteCount is # to decode, not size of array.
return GetBytes(pChars + charIndex, charCount,
pBytes + byteIndex, byteCount, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[System.Security.SecurityCritical] // auto-generated
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars",
Environment.GetResourceString("ArgumentNull_Array"));
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
return GetBytes(chars, charCount, bytes, byteCount, null);
}
// Returns the number of characters produced by decoding a range of bytes
// in a byte array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
[System.Security.SecuritySafeCritical] // overrides public transparent member
public override unsafe int GetCharCount(byte[] bytes, int index, int count)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes",
Environment.GetResourceString("ArgumentNull_Array"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException("bytes",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
// If no input just return 0, fixed doesn't like 0 length arrays
if (bytes.Length == 0)
return 0;
// Just call pointer version
fixed (byte* pBytes = bytes)
return GetCharCount(pBytes + index, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[System.Security.SecurityCritical] // auto-generated
public override unsafe int GetCharCount(byte* bytes, int count)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes",
Environment.GetResourceString("ArgumentNull_Array"));
if (count < 0)
throw new ArgumentOutOfRangeException("count",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
return GetCharCount(bytes, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
[System.Security.SecuritySafeCritical] // overrides public transparent member
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars",
Environment.GetResourceString("ArgumentNull_Array"));
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if ( bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException("bytes",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
if (charIndex < 0 || charIndex > chars.Length)
throw new ArgumentOutOfRangeException("charIndex",
Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
// If no input, return 0 & avoid fixed problem
if (bytes.Length == 0)
return 0;
// Just call pointer version
int charCount = chars.Length - charIndex;
// Fixed doesn't like empty arrays
if (chars.Length == 0)
chars = new char[1];
fixed (byte* pBytes = bytes)
fixed (char* pChars = chars)
// Remember that charCount is # to decode, not size of array
return GetChars(pBytes + byteIndex, byteCount,
pChars + charIndex, charCount, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[System.Security.SecurityCritical] // auto-generated
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars",
Environment.GetResourceString("ArgumentNull_Array"));
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
return GetChars(bytes, byteCount, chars, charCount, null);
}
// Returns a string containing the decoded representation of a range of
// bytes in a byte array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
[System.Security.SecuritySafeCritical] // overrides public transparent member
public override unsafe String GetString(byte[] bytes, int index, int count)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes",
Environment.GetResourceString("ArgumentNull_Array"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException("bytes",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
// Avoid problems with empty input buffer
if (bytes.Length == 0) return String.Empty;
fixed (byte* pBytes = bytes)
return String.CreateStringFromEncoding(
pBytes + index, count, this);
}
public override Decoder GetDecoder()
{
return new DecoderNLS(this);
}
public override Encoder GetEncoder()
{
return new EncoderNLS(this);
}
}
}
#endif // FEATURE_ENCODINGNLS
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using CocosSharp;
namespace CocosSharp
{
/// <summary>
/// Light weight timer
/// </summary>
internal class CCTimer : ICCUpdatable
{
readonly bool runForever;
readonly uint repeat; //0 = once, 1 is 2 x executed
readonly float delay;
readonly ICCUpdatable target;
bool useDelay;
uint timesExecuted;
float elapsed;
#region Properties
public float OriginalInterval { get; internal set; }
public float Interval { get; set; }
public Action<float> Selector { get; set; }
CCScheduler Scheduler { get; set; }
#endregion Properties
#region Constructors
public CCTimer(CCScheduler scheduler, ICCUpdatable target, Action<float> selector)
: this(scheduler, target, selector, 0, 0, 0)
{
}
public CCTimer(CCScheduler scheduler, ICCUpdatable target, Action<float> selector, float seconds)
: this(scheduler, target, selector, seconds, 0, 0)
{
}
public CCTimer(CCScheduler scheduler, ICCUpdatable target, Action<float> selector, float seconds,
uint repeat, float delay)
{
this.Scheduler = scheduler;
this.target = target;
this.Selector = selector;
this.elapsed = -1;
this.OriginalInterval = seconds;
this.Interval = seconds;
this.delay = delay;
this.useDelay = delay > 0f;
this.repeat = repeat;
this.runForever = repeat == uint.MaxValue;
}
#endregion Constructors
#region SelectorProtocol Members
public void Update(float dt)
{
if (elapsed == -1)
{
elapsed = 0;
timesExecuted = 0;
}
else
{
if (runForever && !useDelay)
{
//standard timer usage
elapsed += dt;
if (elapsed >= Interval)
{
if (Selector != null)
{
Selector(elapsed);
}
elapsed = 0;
}
}
else
{
//advanced usage
elapsed += dt;
if (useDelay)
{
if (elapsed >= delay)
{
if (Selector != null)
{
Selector(elapsed);
}
elapsed = elapsed - delay;
timesExecuted += 1;
useDelay = false;
}
}
else
{
if (elapsed >= Interval)
{
if (Selector != null)
{
Selector(elapsed);
}
//Interval = OriginalInterval - (elapsed - Interval);
elapsed = 0;
timesExecuted += 1;
}
}
if (!runForever && timesExecuted > repeat)
{
//unschedule timer
Scheduler.Unschedule(Selector, target);
}
}
}
}
#endregion
}
}
namespace CocosSharp
{
// Defines the predefined Priority Types used by CCScheduler
public static class CCSchedulePriority
{
// We will define this as a static class since we can not define and enum with the way uint.MaxValue is represented.
public const uint RepeatForever = uint.MaxValue - 1;
public const int System = int.MinValue;
public const int User = System + 1;
}
/// <summary>
/// Scheduler is responsible for triggering the scheduled callbacks.
/// You should not use NSTimer. Instead use this class.
///
/// There are 2 different types of callbacks (selectors):
///
/// - update selector: the 'update' selector will be called every frame. You can customize the priority.
/// - custom selector: A custom selector will be called every frame, or with a custom interval of time
///
/// The 'custom selectors' should be avoided when possible. It is faster, and consumes less memory to use the 'update selector'.
/// </summary>
public class CCScheduler
{
static HashTimeEntry[] tmpHashSelectorArray = new HashTimeEntry[128];
static ICCUpdatable[] tmpSelectorArray = new ICCUpdatable[128];
readonly Dictionary<ICCUpdatable, HashTimeEntry> hashForTimers = new Dictionary<ICCUpdatable, HashTimeEntry>();
readonly Dictionary<ICCUpdatable, HashUpdateEntry> hashForUpdates = new Dictionary<ICCUpdatable, HashUpdateEntry>();
// hash used to fetch quickly the list entries for pause,delete,etc
readonly LinkedList<ListEntry> updates0List = new LinkedList<ListEntry>(); // list priority == 0
readonly LinkedList<ListEntry> updatesNegList = new LinkedList<ListEntry>(); // list of priority < 0
readonly LinkedList<ListEntry> updatesPosList = new LinkedList<ListEntry>(); // list priority > 0
HashTimeEntry currentTarget;
bool isCurrentTargetSalvaged;
bool isUpdateHashLocked;
CCActionManager actionManager;
#region Properties
public float TimeScale { get; set; }
// Gets a value indicating whether the ActionManager is active.
// The ActionManager can be stopped from processing actions by calling UnscheduleAll() method.
public bool IsActionManagerActive
{
get {
if (actionManager != null)
{
var target = actionManager;
LinkedListNode<ListEntry> next;
for (LinkedListNode<ListEntry> node = updatesNegList.First; node != null; node = next)
{
next = node.Next;
if (node.Value.Target == target && !node.Value.MarkedForDeletion) {
return true;
}
}
}
return false;
}
}
#endregion Properties
#region Constructors
internal CCScheduler(CCActionManager actionManager = null)
{
TimeScale = 1.0f;
this.actionManager = actionManager;
}
#endregion Constructors
internal void Update (float dt)
{
isUpdateHashLocked = true;
try
{
if (TimeScale != 1.0f)
{
dt *= TimeScale;
}
LinkedListNode<ListEntry> next;
// updates with priority < 0
//foreach (ListEntry entry in _updatesNegList)
for (LinkedListNode<ListEntry> node = updatesNegList.First; node != null; node = next)
{
next = node.Next;
if (!node.Value.Paused && !node.Value.MarkedForDeletion)
{
node.Value.Target.Update(dt);
}
}
// updates with priority == 0
//foreach (ListEntry entry in _updates0List)
for (LinkedListNode<ListEntry> node = updates0List.First; node != null; node = next)
{
next = node.Next;
if (!node.Value.Paused && !node.Value.MarkedForDeletion)
{
node.Value.Target.Update(dt);
}
}
// updates with priority > 0
for (LinkedListNode<ListEntry> node = updatesPosList.First; node != null; node = next)
{
next = node.Next;
if (!node.Value.Paused && !node.Value.MarkedForDeletion)
{
node.Value.Target.Update(dt);
}
}
// Iterate over all the custom selectors
var count = hashForTimers.Count;
if (count > 0)
{
if (tmpSelectorArray.Length < count)
{
tmpSelectorArray = new ICCUpdatable[tmpSelectorArray.Length * 2];
}
hashForTimers.Keys.CopyTo(tmpSelectorArray, 0);
for (int i = 0; i < count; i++)
{
ICCUpdatable key = tmpSelectorArray[i];
if (!hashForTimers.ContainsKey(key))
{
continue;
}
HashTimeEntry elt = hashForTimers[key];
currentTarget = elt;
isCurrentTargetSalvaged = false;
if (!currentTarget.Paused)
{
// The 'timers' array may change while inside this loop
for (elt.TimerIndex = 0; elt.TimerIndex < elt.Timers.Count; ++elt.TimerIndex)
{
elt.CurrentTimer = elt.Timers[elt.TimerIndex];
if(elt.CurrentTimer != null) {
elt.CurrentTimerSalvaged = false;
elt.CurrentTimer.Update(dt);
elt.CurrentTimer = null;
}
}
}
// only delete currentTarget if no actions were scheduled during the cycle (issue #481)
if (isCurrentTargetSalvaged && currentTarget.Timers.Count == 0)
{
RemoveHashElement(currentTarget);
}
}
}
// delete all updates that are marked for deletion
// updates with priority < 0
for (LinkedListNode<ListEntry> node = updatesNegList.First; node != null; node = next)
{
next = node.Next;
if (node.Value.MarkedForDeletion)
{
updatesNegList.Remove(node);
RemoveUpdateFromHash(node.Value);
}
}
// updates with priority == 0
for (LinkedListNode<ListEntry> node = updates0List.First; node != null; node = next)
{
next = node.Next;
if (node.Value.MarkedForDeletion)
{
updates0List.Remove(node);
RemoveUpdateFromHash(node.Value);
}
}
// updates with priority > 0
for (LinkedListNode<ListEntry> node = updatesPosList.First; node != null; node = next)
{
next = node.Next;
if (node.Value.MarkedForDeletion)
{
updatesPosList.Remove(node);
RemoveUpdateFromHash(node.Value);
}
}
}
finally
{
// Always do this just in case there is a problem
isUpdateHashLocked = false;
currentTarget = null;
}
}
/** The scheduled method will be called every 'interval' seconds.
If paused is YES, then it won't be called until it is resumed.
If 'interval' is 0, it will be called every frame, but if so, it's recommended to use 'scheduleUpdateForTarget:' instead.
If the selector is already scheduled, then only the interval parameter will be updated without re-scheduling it again.
repeat let the action be repeated repeat + 1 times, use RepeatForever to let the action run continuously
delay is the amount of time the action will wait before it'll start
@since v0.99.3, repeat and delay added in v1.1
*/
public void Schedule (Action<float> selector, ICCUpdatable target, float interval, uint repeat,
float delay, bool paused)
{
Debug.Assert(selector != null);
Debug.Assert(target != null);
HashTimeEntry element;
lock (hashForTimers)
{
if (!hashForTimers.TryGetValue(target, out element))
{
element = new HashTimeEntry { Target = target };
hashForTimers[target] = element;
// Is this the 1st element ? Then set the pause level to all the selectors of this target
element.Paused = paused;
}
else
{
if (element != null)
{
Debug.Assert(element.Paused == paused, "CCScheduler.Schedule: All are paused");
}
}
if (element != null)
{
if (element.Timers == null)
{
element.Timers = new List<CCTimer>();
}
else
{
CCTimer[] timers = element.Timers.ToArray();
foreach (var timer in timers)
{
if (timer == null)
{
continue;
}
if (selector == timer.Selector)
{
CCLog.Log(
"CCSheduler#scheduleSelector. Selector already scheduled. Updating interval from: {0} to {1}",
timer.Interval, interval);
timer.Interval = interval;
return;
}
}
}
element.Timers.Add(new CCTimer(this, target, selector, interval, repeat, delay));
}
}
}
/** Schedules the 'update' selector for a given target with a given priority.
The 'update' selector will be called every frame.
The lower the priority, the earlier it is called.
@since v0.99.3
*/
public void Schedule (ICCUpdatable targt, int priority, bool paused)
{
HashUpdateEntry element;
if (hashForUpdates.TryGetValue(targt, out element))
{
Debug.Assert(element.Entry.MarkedForDeletion);
// TODO: check if priority has changed!
element.Entry.MarkedForDeletion = false;
return;
}
// most of the updates are going to be 0, that's way there
// is an special list for updates with priority 0
if (priority == 0)
{
AppendIn(updates0List, targt, paused);
}
else if (priority < 0)
{
PriorityIn(updatesNegList, targt, priority, paused);
}
else
{
PriorityIn(updatesPosList, targt, priority, paused);
}
}
/** Unschedule a selector for a given target.
If you want to unschedule the "update", use unscheudleUpdateForTarget.
@since v0.99.3
*/
public void Unschedule (Action<float> selector, ICCUpdatable target)
{
// explicity handle nil arguments when removing an object
if (selector == null || target == null)
{
return;
}
HashTimeEntry element;
if (hashForTimers.TryGetValue(target, out element))
{
for (int i = 0; i < element.Timers.Count; i++)
{
var timer = element.Timers[i];
if (selector == timer.Selector)
{
if (timer == element.CurrentTimer && (!element.CurrentTimerSalvaged))
{
element.CurrentTimerSalvaged = true;
}
element.Timers.RemoveAt(i);
// update timerIndex in case we are in tick:, looping over the actions
if (element.TimerIndex >= i)
{
element.TimerIndex--;
}
if (element.Timers.Count == 0)
{
if (currentTarget == element)
{
isCurrentTargetSalvaged = true;
}
else
{
RemoveHashElement(element);
}
}
return;
}
}
}
}
/** Unschedules all selectors for a given target.
This also includes the "update" selector.
@since v0.99.3
*/
public void UnscheduleAll (ICCUpdatable target)
{
// explicit NULL handling
if (target == null)
{
return;
}
// custom selectors
HashTimeEntry element;
if (hashForTimers.TryGetValue(target, out element))
{
if (element.Timers.Contains(element.CurrentTimer))
{
element.CurrentTimerSalvaged = true;
}
element.Timers.Clear();
if (currentTarget == element)
{
isCurrentTargetSalvaged = true;
}
else
{
RemoveHashElement(element);
}
}
// update selector
Unschedule(target);
}
public void Unschedule (ICCUpdatable target)
{
if (target == null)
{
return;
}
HashUpdateEntry element;
if (hashForUpdates.TryGetValue(target, out element))
{
if (isUpdateHashLocked)
{
element.Entry.MarkedForDeletion = true;
}
else
{
RemoveUpdateFromHash(element.Entry);
}
}
}
/// <summary>
/// Starts the action manager.
/// This would be called after UnscheduleAll() method has been called to restart the ActionManager.
/// </summary>
public void StartActionManager()
{
if (!IsActionManagerActive && actionManager != null)
Schedule(actionManager, CCSchedulePriority.System, false);
}
public void UnscheduleAll ()
{
// This also stops ActionManger from updating which means all actions are stopped as well.
UnscheduleAll (CCSchedulePriority.System);
}
public void UnscheduleAll (int minPriority)
{
var count = hashForTimers.Values.Count;
if (tmpHashSelectorArray.Length < count)
{
tmpHashSelectorArray = new HashTimeEntry[tmpHashSelectorArray.Length * 2];
}
hashForTimers.Values.CopyTo(tmpHashSelectorArray, 0);
for (int i = 0; i < count; i++)
{
// Element may be removed in unscheduleAllSelectorsForTarget
UnscheduleAll(tmpHashSelectorArray[i].Target);
}
// Updates selectors
if (minPriority < 0 && updatesNegList.Count > 0)
{
LinkedList<ListEntry> copy = new LinkedList<ListEntry>(updatesNegList);
foreach (ListEntry entry in copy)
{
if (entry.Priority >= minPriority)
{
UnscheduleAll(entry.Target);
}
}
}
if (minPriority <= 0 && updates0List.Count > 0)
{
LinkedList<ListEntry> copy = new LinkedList<ListEntry>(updates0List);
foreach (ListEntry entry in copy)
{
UnscheduleAll(entry.Target);
}
}
if (updatesPosList.Count > 0)
{
LinkedList<ListEntry> copy = new LinkedList<ListEntry>(updatesPosList);
foreach (ListEntry entry in copy)
{
if (entry.Priority >= minPriority)
{
UnscheduleAll(entry.Target);
}
}
}
}
public List<ICCUpdatable> PauseAllTargets()
{
return PauseAllTargets(int.MinValue);
}
public List<ICCUpdatable> PauseAllTargets(int minPriority)
{
var idsWithSelectors = new List<ICCUpdatable>();
// Custom Selectors
foreach (HashTimeEntry element in hashForTimers.Values)
{
element.Paused = true;
if (!idsWithSelectors.Contains(element.Target))
idsWithSelectors.Add(element.Target);
}
// Updates selectors
if (minPriority < 0)
{
foreach (ListEntry element in updatesNegList)
{
if (element.Priority >= minPriority)
{
element.Paused = true;
if (!idsWithSelectors.Contains(element.Target))
idsWithSelectors.Add(element.Target);
}
}
}
if (minPriority <= 0)
{
foreach (ListEntry element in updates0List)
{
element.Paused = true;
if (!idsWithSelectors.Contains(element.Target))
idsWithSelectors.Add(element.Target);
}
}
if (minPriority < 0)
{
foreach (ListEntry element in updatesPosList)
{
if (element.Priority >= minPriority)
{
element.Paused = true;
if (!idsWithSelectors.Contains(element.Target))
idsWithSelectors.Add(element.Target);
}
}
}
return idsWithSelectors;
}
public void PauseTarget(ICCUpdatable target)
{
Debug.Assert(target != null);
// custom selectors
HashTimeEntry entry;
if (hashForTimers.TryGetValue(target, out entry))
{
entry.Paused = true;
}
// Update selector
HashUpdateEntry updateEntry;
if (hashForUpdates.TryGetValue(target, out updateEntry))
{
updateEntry.Entry.Paused = true;
}
}
public void Resume (List<ICCUpdatable> targetsToResume)
{
foreach (ICCUpdatable target in targetsToResume)
{
Resume(target);
}
}
public void Resume (ICCUpdatable target)
{
Debug.Assert(target != null);
// custom selectors
HashTimeEntry element;
if (hashForTimers.TryGetValue(target, out element))
{
element.Paused = false;
}
// Update selector
HashUpdateEntry elementUpdate;
if (hashForUpdates.TryGetValue(target, out elementUpdate))
{
elementUpdate.Entry.Paused = false;
}
}
public bool IsTargetPaused(ICCUpdatable target)
{
Debug.Assert(target != null, "target must be non nil");
// Custom selectors
HashTimeEntry element;
if (hashForTimers.TryGetValue(target, out element))
{
return element.Paused;
}
// We should check update selectors if target does not have custom selectors
HashUpdateEntry elementUpdate;
if (hashForUpdates.TryGetValue(target, out elementUpdate))
{
return elementUpdate.Entry.Paused;
}
return false; // should never get here
}
void RemoveHashElement(HashTimeEntry element)
{
hashForTimers.Remove(element.Target);
element.Timers.Clear();
element.Target = null;
}
void RemoveUpdateFromHash(ListEntry entry)
{
HashUpdateEntry element;
if (hashForUpdates.TryGetValue(entry.Target, out element))
{
// list entry
element.List.Remove(entry);
element.Entry = null;
// hash entry
hashForUpdates.Remove(entry.Target);
element.Target = null;
}
}
void PriorityIn(LinkedList<ListEntry> list, ICCUpdatable target, int priority, bool paused)
{
var listElement = new ListEntry
{
Target = target,
Priority = priority,
Paused = paused,
MarkedForDeletion = false
};
if (list.First == null)
{
list.AddFirst(listElement);
}
else
{
bool added = false;
for (LinkedListNode<ListEntry> node = list.First; node != null; node = node.Next)
{
if (priority < node.Value.Priority)
{
list.AddBefore(node, listElement);
added = true;
break;
}
}
if (!added)
{
list.AddLast(listElement);
}
}
// update hash entry for quick access
var hashElement = new HashUpdateEntry
{
Target = target,
List = list,
Entry = listElement
};
hashForUpdates.Add(target, hashElement);
}
void AppendIn(LinkedList<ListEntry> list, ICCUpdatable target, bool paused)
{
var listElement = new ListEntry
{
Target = target,
Paused = paused,
MarkedForDeletion = false
};
list.AddLast(listElement);
// update hash entry for quicker access
var hashElement = new HashUpdateEntry
{
Target = target,
List = list,
Entry = listElement
};
hashForUpdates.Add(target, hashElement);
}
#region Nested type: HashSelectorEntry
class HashTimeEntry
{
public CCTimer CurrentTimer;
public bool CurrentTimerSalvaged;
public bool Paused;
public ICCUpdatable Target;
public int TimerIndex;
public List<CCTimer> Timers;
}
#endregion
#region Nested type: HashUpdateEntry
class HashUpdateEntry
{
public ListEntry Entry; // entry in the list
public LinkedList<ListEntry> List; // Which list does it belong to ?
public ICCUpdatable Target; // hash key
}
#endregion
#region Nested type: ListEntry
class ListEntry
{
public bool MarkedForDeletion;
public bool Paused;
public int Priority;
public ICCUpdatable Target;
}
#endregion
}
}
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
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
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using Axiom.Animating;
using Axiom.Collections;
using Axiom.Configuration;
using Axiom.MathLib;
using Axiom.Graphics;
namespace Axiom.Core {
/// <summary>
/// Defines a part of a complete 3D mesh.
/// </summary>
/// <remarks>
/// Models which make up the definition of a discrete 3D object
/// are made up of potentially multiple parts. This is because
/// different parts of the mesh may use different materials or
/// use different vertex formats, such that a rendering state
/// change is required between them.
/// <p/>
/// Like the Mesh class, instatiations of 3D objects in the scene
/// share the SubMesh instances, and have the option of overriding
/// their material differences on a per-object basis if required.
/// See the SubEntity class for more information.
/// </remarks>
public class SubMesh {
#region Member variables
/// <summary>The parent mesh that this subMesh belongs to.</summary>
protected Mesh parent;
/// <summary>Name of the material assigned to this subMesh.</summary>
protected string materialName;
/// <summary>Name of this SubMesh.</summary>
internal string name;
/// <summary></summary>
protected bool isMaterialInitialized;
/// <summary>List of bone assignment for this mesh.</summary>
protected Dictionary<int, List<VertexBoneAssignment>> boneAssignmentList =
new Dictionary<int, List<VertexBoneAssignment>>();
/// <summary>Flag indicating that bone assignments need to be recompiled.</summary>
protected internal bool boneAssignmentsOutOfDate;
/// <summary>Mode used for rendering this submesh.</summary>
protected internal Axiom.Graphics.OperationType operationType;
public VertexData vertexData;
public IndexData indexData = new IndexData();
/// <summary>Indicates if this submesh shares vertex data with other meshes or whether it has it's own vertices.</summary>
public bool useSharedVertices;
/// <summary>
/// Local bounding box of this submesh.
/// </summary>
protected AxisAlignedBox boundingBox = AxisAlignedBox.Null;
/// <summary>
/// Radius of this submesh's bounding sphere.
/// </summary>
protected float boundingSphereRadius;
/// <summary>
/// Dedicated index map for translate blend index to bone index (only valid if useSharedVertices = false).
/// </summary>
/// <remarks>
/// This data is completely owned by this submesh.
///
/// We collect actually used bones of all bone assignments, and build the
/// blend index in 'packed' form, then the range of the blend index in vertex
/// data BlendIndices element is continuous, with no gaps. Thus, by
/// minimising the world matrix array constants passing to GPU, we can support
/// more bones for a mesh when hardware skinning is used. The hardware skinning
/// support limit is applied to each set of vertex data in the mesh, in other words, the
/// hardware skinning support limit is applied only to the actually used bones of each
/// SubMeshes, not all bones across the entire Mesh.
///
/// Because the blend index is different to the bone index, therefore, we use
/// the index map to translate the blend index to bone index.
///
/// The use of shared or non-shared index map is determined when
/// model data is converted to the OGRE .mesh format.
/// </remarks>
protected internal List<ushort> blendIndexToBoneIndexMap = new List<ushort>();
protected internal List<IndexData> lodFaceList = new List<IndexData>();
/// <summary>Type of vertex animation for dedicated vertex data (populated by Mesh)</summary>
protected VertexAnimationType vertexAnimationType = VertexAnimationType.None;
#endregion
#region Constructor
/// <summary>
/// Basic contructor.
/// </summary>
/// <param name="name"></param>
public SubMesh(string name) {
this.name = name;
useSharedVertices = true;
operationType = OperationType.TriangleList;
}
/// <summary>The texture aliases for this submesh.</summary>
protected Dictionary<string, string> textureAliases = new Dictionary<string, string>();
#endregion
#region Methods
/// <summary>
/// Assigns a vertex to a bone with a given weight, for skeletal animation.
/// </summary>
/// <remarks>
/// This method is only valid after setting the SkeletonName property.
/// You should not need to modify bone assignments during rendering (only the positions of bones)
/// and the engine reserves the right to do some internal data reformatting of this information,
/// depending on render system requirements.
/// </remarks>
/// <param name="boneAssignment"></param>
public void AddBoneAssignment(VertexBoneAssignment boneAssignment) {
if (!boneAssignmentList.ContainsKey(boneAssignment.vertexIndex))
boneAssignmentList[boneAssignment.vertexIndex] = new List<VertexBoneAssignment>();
boneAssignmentList[boneAssignment.vertexIndex].Add(boneAssignment);
boneAssignmentsOutOfDate = true;
}
/// <summary>
/// Removes all bone assignments for this mesh.
/// </summary>
/// <remarks>
/// This method is for modifying weights to the shared geometry of the Mesh. To assign
/// weights to the per-SubMesh geometry, see the equivalent methods on SubMesh.
/// </remarks>
public void ClearBoneAssignments() {
boneAssignmentList.Clear();
boneAssignmentsOutOfDate = true;
}
/// <summary>
/// Must be called once to compile bone assignments into geometry buffer.
/// </summary>
protected internal void CompileBoneAssignments() {
int maxBones = parent.RationalizeBoneAssignments(vertexData.vertexCount, boneAssignmentList);
// return if no bone assigments
if(maxBones != 0) {
// FIXME: For now, to support hardware skinning with a single shader,
// we always want to have 4 bones. (robin@multiverse.net)
maxBones = 4;
parent.CompileBoneAssignments(boneAssignmentList, maxBones, blendIndexToBoneIndexMap, vertexData);
}
boneAssignmentsOutOfDate = false;
}
public void RemoveLodLevels() {
lodFaceList.Clear();
}
/// <summary>
/// Adds the alias or replaces an existing one and associates the texture name to it.
/// </summary>
/// <remarks>
/// The submesh uses the texture alias to replace textures used in the material applied
/// to the submesh.
/// </remarks>
/// <param name="aliasName">The name of the alias.</param>
/// <param name="textureName">The name of the texture to be associated with the alias.</param>
public void AddTextureAlias(string aliasName, string textureName) {
textureAliases[aliasName] = textureName;
}
/// <summary>
/// Remove a specific texture alias name from the sub mesh
/// </summary>
/// <param name="aliasName">The name of the alias. If it is not found
/// then it is ignored.
/// </param>
public void RemoveTextureAlias(string aliasName) {
textureAliases.Remove(aliasName);
}
/// <summary>
/// Removes all texture aliases from the sub mesh
/// </summary>
public void RemoveAllTextureAliases() {
textureAliases.Clear();
}
/// <summary>
/// The current material used by the submesh is copied into a new material
/// and the submesh's texture aliases are applied if the current texture alias
/// names match those found in the original material.
/// </summary>
/// <remarks>
/// The submesh's texture aliases must be setup prior to calling this method.
/// If a new material has to be created, the subMesh autogenerates the new name.
/// The new name is the old name + "_" + number.
/// </remarks>
/// <returns>True if texture aliases were applied and a new material was created.</returns>
public bool UpdateMaterialUsingTextureAliases() {
bool newMaterialCreated = false;
// if submesh has texture aliases
// ask the material manager if the current summesh material exists
if (HasTextureAliases && MaterialManager.Instance.HasResource(materialName)) {
// get the current submesh material
Material material = MaterialManager.Instance.GetByName( materialName );
// get test result for if change will occur when the texture aliases are applied
if (material.ApplyTextureAliases(textureAliases, false)) {
// material textures will be changed so copy material,
// new material name is old material name + index
// check with material manager and find a unique name
int index = 0;
string newMaterialName = materialName + "_" + index;
while (MaterialManager.Instance.HasResource(newMaterialName))
// increment index for next name
newMaterialName = materialName + "_" + ++index;
Material newMaterial = (Material)MaterialManager.Instance.Create(newMaterialName, false);
// copy parent material details to new material
material.CopyTo(newMaterial);
// apply texture aliases to new material
newMaterial.ApplyTextureAliases(textureAliases);
// place new material name in submesh
materialName = newMaterialName;
newMaterialCreated = true;
}
}
return newMaterialCreated;
}
#endregion Methods
#region Properties
/// <summary>
/// Gets/Sets the name of this SubMesh.
/// </summary>
public string Name {
get { return name; }
set { name = value; }
}
/// <summary>
/// Gets/Sets the name of the material this SubMesh will be using.
/// </summary>
public string MaterialName {
get { return materialName; }
set { materialName = value; isMaterialInitialized = true; }
}
/// <summary>
/// Gets/Sets the parent mode of this SubMesh.
/// </summary>
public Mesh Parent {
get { return parent; }
set { parent = value; }
}
/// <summary>
/// Overloaded method.
/// </summary>
/// <param name="op"></param>
/// <returns></returns>
public void GetRenderOperation(RenderOperation op) {
// call overloaded method with lod index of 0 by default
GetRenderOperation(op, 0);
}
/// <summary>
/// Fills a RenderOperation structure required to render this mesh.
/// </summary>
/// <param name="op">Reference to a RenderOperation structure to populate.</param>
/// <param name="lodIndex">The index of the LOD to use.</param>
public void GetRenderOperation(RenderOperation op, int lodIndex) {
// SubMeshes always use indices
op.useIndices = true;
// use lod face list if requested, else pass the normal face list
if(lodIndex > 0 && (lodIndex - 1) < lodFaceList.Count) {
// Use the set of indices defined for this LOD level
op.indexData = lodFaceList[lodIndex - 1];
}
else
op.indexData = indexData;
// set the operation type
op.operationType = operationType;
// set the vertex data correctly
op.vertexData = useSharedVertices ? parent.SharedVertexData : vertexData;
}
/// <summary>
/// Gets whether or not a material has been set for this subMesh.
/// </summary>
public bool IsMaterialInitialized {
get { return isMaterialInitialized; }
}
/// <summary>
/// Gets bone assigment list
/// </summary>
public Dictionary<int, List<VertexBoneAssignment>> BoneAssignmentList {
get { return boneAssignmentList; }
}
public List<ushort> BlendIndexToBoneIndexMap {
get {
return blendIndexToBoneIndexMap;
}
}
public int NumFaces {
get {
int numFaces = 0;
if (indexData == null)
return 0;
if (operationType == OperationType.TriangleList)
numFaces = indexData.indexCount / 3;
else
numFaces = indexData.indexCount - 2;
return numFaces;
}
}
public OperationType OperationType {
get {
return operationType;
}
set {
operationType = value;
}
}
public VertexAnimationType VertexAnimationType {
get {
if (parent.AnimationTypesDirty)
parent.DetermineAnimationTypes();
return vertexAnimationType;
}
set { vertexAnimationType = value; }
}
public VertexAnimationType CurrentVertexAnimationType {
get {
return vertexAnimationType;
}
}
public List<IndexData> LodFaceList {
get {
return lodFaceList;
}
}
public VertexData VertexData {
get {
return vertexData;
}
}
public IndexData IndexData {
get {
return indexData;
}
}
/// <summary>
/// Returns true if the sub mesh has texture aliases
/// </summary>
public bool HasTextureAliases {
get { return textureAliases.Count != 0; }
}
/// <summary>
/// Gets the texture aliases assigned to the sub mesh.
/// </summary>
public Dictionary<string, string> TextureAliases
{
get { return textureAliases; }
}
/// <summary>
/// Gets the number of texture aliases assigned to the sub mesh.
/// </summary>
public int TextureAliasCount
{
get { return textureAliases.Count; }
}
/// <summary>
/// Gets/Sets the bounding box for this submesh.
/// </summary>
/// <remarks>
/// Setting this property is required when building manual
/// submeshes now, because Axiom can no longer update the
/// bounds for you, because it cannot necessarily read
/// vertex data back from the vertex buffers which this
/// mesh uses (they very well might be write-only, and
/// even if they are not, reading data from a hardware
/// buffer is a bottleneck).
/// </remarks>
public AxisAlignedBox BoundingBox {
get {
// OPTIMIZE: Cloning to prevent direct modification
return (AxisAlignedBox)boundingBox.Clone();
}
set {
boundingBox = value;
float sqLen1 = boundingBox.Minimum.LengthSquared;
float sqLen2 = boundingBox.Maximum.LengthSquared;
// update the bounding sphere radius as well
boundingSphereRadius = MathUtil.Sqrt(MathUtil.Max(sqLen1, sqLen2));
}
}
/// <summary>
/// Bounding spehere radius from this submesh in local coordinates.
/// </summary>
public float BoundingSphereRadius {
get {
return boundingSphereRadius;
}
set {
boundingSphereRadius = value;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.Sockets;
using System.Text;
namespace System.Net
{
internal enum FtpPrimitive
{
Upload = 0,
Download = 1,
CommandOnly = 2
};
internal enum FtpLoginState : byte
{
NotLoggedIn,
LoggedIn,
LoggedInButNeedsRelogin,
ReloginFailed
};
/// <summary>
/// <para>
/// The FtpControlStream class implements a basic FTP connection,
/// This means basic command sending and parsing.
/// </para>
/// </summary>
internal class FtpControlStream : CommandStream
{
private Socket _dataSocket;
private IPEndPoint _passiveEndPoint;
private TlsStream _tlsStream;
private StringBuilder _bannerMessage;
private StringBuilder _welcomeMessage;
private StringBuilder _exitMessage;
private WeakReference _credentials;
private string _currentTypeSetting = string.Empty;
private long _contentLength = -1;
private DateTime _lastModified;
private bool _dataHandshakeStarted = false;
private string _loginDirectory = null;
private string _establishedServerDirectory = null;
private string _requestedServerDirectory = null;
private Uri _responseUri;
private FtpLoginState _loginState = FtpLoginState.NotLoggedIn;
internal FtpStatusCode StatusCode;
internal string StatusLine;
internal NetworkCredential Credentials
{
get
{
if (_credentials != null && _credentials.IsAlive)
{
return (NetworkCredential)_credentials.Target;
}
else
{
return null;
}
}
set
{
if (_credentials == null)
{
_credentials = new WeakReference(null);
}
_credentials.Target = value;
}
}
private static readonly AsyncCallback s_acceptCallbackDelegate = new AsyncCallback(AcceptCallback);
private static readonly AsyncCallback s_connectCallbackDelegate = new AsyncCallback(ConnectCallback);
private static readonly AsyncCallback s_SSLHandshakeCallback = new AsyncCallback(SSLHandshakeCallback);
internal FtpControlStream(TcpClient client)
: base(client)
{
}
/// <summary>
/// <para>Closes the connecting socket to generate an error.</para>
/// </summary>
internal void AbortConnect()
{
Socket socket = _dataSocket;
if (socket != null)
{
try
{
socket.Close();
}
catch (ObjectDisposedException)
{
}
}
}
/// <summary>
/// <para>Provides a wrapper for the async accept operations
/// </summary>
private static void AcceptCallback(IAsyncResult asyncResult)
{
FtpControlStream connection = (FtpControlStream)asyncResult.AsyncState;
Socket listenSocket = connection._dataSocket;
try
{
connection._dataSocket = listenSocket.EndAccept(asyncResult);
if (!connection.ServerAddress.Equals(((IPEndPoint)connection._dataSocket.RemoteEndPoint).Address))
{
connection._dataSocket.Close();
throw new WebException(SR.net_ftp_active_address_different, WebExceptionStatus.ProtocolError);
}
connection.ContinueCommandPipeline();
}
catch (Exception e)
{
connection.CloseSocket();
connection.InvokeRequestCallback(e);
}
finally
{
listenSocket.Close();
}
}
/// <summary>
/// <para>Provides a wrapper for the async accept operations</para>
/// </summary>
private static void ConnectCallback(IAsyncResult asyncResult)
{
FtpControlStream connection = (FtpControlStream)asyncResult.AsyncState;
try
{
connection._dataSocket.EndConnect(asyncResult);
connection.ContinueCommandPipeline();
}
catch (Exception e)
{
connection.CloseSocket();
connection.InvokeRequestCallback(e);
}
}
private static void SSLHandshakeCallback(IAsyncResult asyncResult)
{
FtpControlStream connection = (FtpControlStream)asyncResult.AsyncState;
try
{
connection._tlsStream.EndAuthenticateAsClient(asyncResult);
connection.ContinueCommandPipeline();
}
catch (Exception e)
{
connection.CloseSocket();
connection.InvokeRequestCallback(e);
}
}
// Creates a FtpDataStream object, constructs a TLS stream if needed.
// In case SSL and ASYNC we delay sigaling the user stream until the handshake is done.
private PipelineInstruction QueueOrCreateFtpDataStream(ref Stream stream)
{
if (_dataSocket == null)
throw new InternalException();
//
// Re-entered pipeline with completed read on the TlsStream
//
if (_tlsStream != null)
{
stream = new FtpDataStream(_tlsStream, (FtpWebRequest)_request, IsFtpDataStreamWriteable());
_tlsStream = null;
return PipelineInstruction.GiveStream;
}
NetworkStream networkStream = new NetworkStream(_dataSocket, true);
if (UsingSecureStream)
{
FtpWebRequest request = (FtpWebRequest)_request;
TlsStream tlsStream = new TlsStream(networkStream, _dataSocket, request.RequestUri.Host, request.ClientCertificates);
networkStream = tlsStream;
if (_isAsync)
{
_tlsStream = tlsStream;
tlsStream.BeginAuthenticateAsClient(s_SSLHandshakeCallback, this);
return PipelineInstruction.Pause;
}
else
{
tlsStream.AuthenticateAsClient();
}
}
stream = new FtpDataStream(networkStream, (FtpWebRequest)_request, IsFtpDataStreamWriteable());
return PipelineInstruction.GiveStream;
}
protected override void ClearState()
{
_contentLength = -1;
_lastModified = DateTime.MinValue;
_responseUri = null;
_dataHandshakeStarted = false;
StatusCode = FtpStatusCode.Undefined;
StatusLine = null;
_dataSocket = null;
_passiveEndPoint = null;
_tlsStream = null;
base.ClearState();
}
// This is called by underlying base class code, each time a new response is received from the wire or a protocol stage is resumed.
// This function controls the setting up of a data socket/connection, and of saving off the server responses.
protected override PipelineInstruction PipelineCallback(PipelineEntry entry, ResponseDescription response, bool timeout, ref Stream stream)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Command:{entry?.Command} Description:{response?.StatusDescription}");
// null response is not expected
if (response == null)
return PipelineInstruction.Abort;
FtpStatusCode status = (FtpStatusCode)response.Status;
//
// Update global "current status" for FtpWebRequest
//
if (status != FtpStatusCode.ClosingControl)
{
// A 221 status won't be reflected on the user FTP response
// Anything else will (by design?)
StatusCode = status;
StatusLine = response.StatusDescription;
}
// If the status code is outside the range defined in RFC (1xx to 5xx) throw
if (response.InvalidStatusCode)
throw new WebException(SR.net_InvalidStatusCode, WebExceptionStatus.ProtocolError);
// Update the banner message if any, this is a little hack because the "entry" param is null
if (_index == -1)
{
if (status == FtpStatusCode.SendUserCommand)
{
_bannerMessage = new StringBuilder();
_bannerMessage.Append(StatusLine);
return PipelineInstruction.Advance;
}
else if (status == FtpStatusCode.ServiceTemporarilyNotAvailable)
{
return PipelineInstruction.Reread;
}
else
throw GenerateException(status, response.StatusDescription, null);
}
//
// Check for the result of our attempt to use UTF8
//
if (entry.Command == "OPTS utf8 on\r\n")
{
if (response.PositiveCompletion)
{
Encoding = Encoding.UTF8;
}
else
{
Encoding = Encoding.Default;
}
return PipelineInstruction.Advance;
}
// If we are already logged in and the server returns 530 then
// the server does not support re-issuing a USER command,
// tear down the connection and start all over again
if (entry.Command.IndexOf("USER") != -1)
{
// The server may not require a password for this user, so bypass the password command
if (status == FtpStatusCode.LoggedInProceed)
{
_loginState = FtpLoginState.LoggedIn;
_index++;
}
}
//
// Throw on an error with possible recovery option
//
if (response.TransientFailure || response.PermanentFailure)
{
if (status == FtpStatusCode.ServiceNotAvailable)
{
MarkAsRecoverableFailure();
}
throw GenerateException(status, response.StatusDescription, null);
}
if (_loginState != FtpLoginState.LoggedIn
&& entry.Command.IndexOf("PASS") != -1)
{
// Note the fact that we logged in
if (status == FtpStatusCode.NeedLoginAccount || status == FtpStatusCode.LoggedInProceed)
_loginState = FtpLoginState.LoggedIn;
else
throw GenerateException(status, response.StatusDescription, null);
}
//
// Parse special cases
//
if (entry.HasFlag(PipelineEntryFlags.CreateDataConnection) && (response.PositiveCompletion || response.PositiveIntermediate))
{
bool isSocketReady;
PipelineInstruction result = QueueOrCreateDataConection(entry, response, timeout, ref stream, out isSocketReady);
if (!isSocketReady)
return result;
// otherwise we have a stream to create
}
//
// This is part of the above case and it's all about giving data stream back
//
if (status == FtpStatusCode.OpeningData || status == FtpStatusCode.DataAlreadyOpen)
{
if (_dataSocket == null)
{
return PipelineInstruction.Abort;
}
if (!entry.HasFlag(PipelineEntryFlags.GiveDataStream))
{
_abortReason = SR.Format(SR.net_ftp_invalid_status_response, status, entry.Command);
return PipelineInstruction.Abort;
}
// Parse out the Content length, if we can
TryUpdateContentLength(response.StatusDescription);
// Parse out the file name, when it is returned and use it for our ResponseUri
FtpWebRequest request = (FtpWebRequest)_request;
if (request.MethodInfo.ShouldParseForResponseUri)
{
TryUpdateResponseUri(response.StatusDescription, request);
}
return QueueOrCreateFtpDataStream(ref stream);
}
//
// Parse responses by status code exclusivelly
//
// Update welcome message
if (status == FtpStatusCode.LoggedInProceed)
{
_welcomeMessage.Append(StatusLine);
}
// OR set the user response ExitMessage
else if (status == FtpStatusCode.ClosingControl)
{
_exitMessage.Append(response.StatusDescription);
// And close the control stream socket on "QUIT"
CloseSocket();
}
// OR set us up for SSL/TLS, after this we'll be writing securely
else if (status == FtpStatusCode.ServerWantsSecureSession)
{
// If NetworkStream is a TlsStream, then this must be in the async callback
// from completing the SSL handshake.
// So just let the pipeline continue.
if (!(NetworkStream is TlsStream))
{
FtpWebRequest request = (FtpWebRequest)_request;
TlsStream tlsStream = new TlsStream(NetworkStream, Socket, request.RequestUri.Host, request.ClientCertificates);
if (_isAsync)
{
tlsStream.BeginAuthenticateAsClient(ar =>
{
try
{
tlsStream.EndAuthenticateAsClient(ar);
NetworkStream = tlsStream;
this.ContinueCommandPipeline();
}
catch (Exception e)
{
this.CloseSocket();
this.InvokeRequestCallback(e);
}
}, null);
return PipelineInstruction.Pause;
}
else
{
tlsStream.AuthenticateAsClient();
NetworkStream = tlsStream;
}
}
}
// OR parse out the file size or file time, usually a result of sending SIZE/MDTM commands
else if (status == FtpStatusCode.FileStatus)
{
FtpWebRequest request = (FtpWebRequest)_request;
if (entry.Command.StartsWith("SIZE "))
{
_contentLength = GetContentLengthFrom213Response(response.StatusDescription);
}
else if (entry.Command.StartsWith("MDTM "))
{
_lastModified = GetLastModifiedFrom213Response(response.StatusDescription);
}
}
// OR parse out our login directory
else if (status == FtpStatusCode.PathnameCreated)
{
if (entry.Command == "PWD\r\n" && !entry.HasFlag(PipelineEntryFlags.UserCommand))
{
_loginDirectory = GetLoginDirectory(response.StatusDescription);
}
}
// Asserting we have some positive response
else
{
// We only use CWD to reset ourselves back to the login directory.
if (entry.Command.IndexOf("CWD") != -1)
{
_establishedServerDirectory = _requestedServerDirectory;
}
}
// Intermediate responses require rereading
if (response.PositiveIntermediate || (!UsingSecureStream && entry.Command == "AUTH TLS\r\n"))
{
return PipelineInstruction.Reread;
}
return PipelineInstruction.Advance;
}
/// <summary>
/// <para>Creates an array of commands, that will be sent to the server</para>
/// </summary>
protected override PipelineEntry[] BuildCommandsList(WebRequest req)
{
bool resetLoggedInState = false;
FtpWebRequest request = (FtpWebRequest)req;
if (NetEventSource.IsEnabled) NetEventSource.Info(this);
_responseUri = request.RequestUri;
ArrayList commandList = new ArrayList();
if (request.EnableSsl && !UsingSecureStream)
{
commandList.Add(new PipelineEntry(FormatFtpCommand("AUTH", "TLS")));
// According to RFC we need to re-authorize with USER/PASS after we re-authenticate.
resetLoggedInState = true;
}
if (resetLoggedInState)
{
_loginDirectory = null;
_establishedServerDirectory = null;
_requestedServerDirectory = null;
_currentTypeSetting = string.Empty;
if (_loginState == FtpLoginState.LoggedIn)
_loginState = FtpLoginState.LoggedInButNeedsRelogin;
}
if (_loginState != FtpLoginState.LoggedIn)
{
Credentials = request.Credentials.GetCredential(request.RequestUri, "basic");
_welcomeMessage = new StringBuilder();
_exitMessage = new StringBuilder();
string domainUserName = string.Empty;
string password = string.Empty;
if (Credentials != null)
{
domainUserName = Credentials.UserName;
string domain = Credentials.Domain;
if (!string.IsNullOrEmpty(domain))
{
domainUserName = domain + "\\" + domainUserName;
}
password = Credentials.Password;
}
if (domainUserName.Length == 0 && password.Length == 0)
{
domainUserName = "anonymous";
password = "anonymous@";
}
commandList.Add(new PipelineEntry(FormatFtpCommand("USER", domainUserName)));
commandList.Add(new PipelineEntry(FormatFtpCommand("PASS", password), PipelineEntryFlags.DontLogParameter));
// If SSL, always configure data channel encryption after authentication to maximum RFC compatibility. The RFC allows for
// PBSZ/PROT commands to come either before or after the USER/PASS, but some servers require USER/PASS immediately after
// the AUTH TLS command.
if (request.EnableSsl && !UsingSecureStream)
{
commandList.Add(new PipelineEntry(FormatFtpCommand("PBSZ", "0")));
commandList.Add(new PipelineEntry(FormatFtpCommand("PROT", "P")));
}
commandList.Add(new PipelineEntry(FormatFtpCommand("OPTS", "utf8 on")));
commandList.Add(new PipelineEntry(FormatFtpCommand("PWD", null)));
}
GetPathOption getPathOption = GetPathOption.Normal;
if (request.MethodInfo.HasFlag(FtpMethodFlags.DoesNotTakeParameter))
{
getPathOption = GetPathOption.AssumeNoFilename;
}
else if (request.MethodInfo.HasFlag(FtpMethodFlags.ParameterIsDirectory))
{
getPathOption = GetPathOption.AssumeFilename;
}
string requestPath;
string requestDirectory;
string requestFilename;
GetPathInfo(getPathOption, request.RequestUri, out requestPath, out requestDirectory, out requestFilename);
if (requestFilename.Length == 0 && request.MethodInfo.HasFlag(FtpMethodFlags.TakesParameter))
throw new WebException(SR.net_ftp_invalid_uri);
// We optimize for having the current working directory staying at the login directory. This ensure that
// our relative paths work right and reduces unnecessary CWD commands.
// Usually, we don't change the working directory except for some FTP commands. If necessary,
// we need to reset our working directory back to the login directory.
if (_establishedServerDirectory != null && _loginDirectory != null && _establishedServerDirectory != _loginDirectory)
{
commandList.Add(new PipelineEntry(FormatFtpCommand("CWD", _loginDirectory), PipelineEntryFlags.UserCommand));
_requestedServerDirectory = _loginDirectory;
}
// For most commands, we don't need to navigate to the directory since we pass in the full
// path as part of the FTP protocol command. However, some commands require it.
if (request.MethodInfo.HasFlag(FtpMethodFlags.MustChangeWorkingDirectoryToPath) && requestDirectory.Length > 0)
{
commandList.Add(new PipelineEntry(FormatFtpCommand("CWD", requestDirectory), PipelineEntryFlags.UserCommand));
_requestedServerDirectory = requestDirectory;
}
if (!request.MethodInfo.IsCommandOnly)
{
string requestedTypeSetting = request.UseBinary ? "I" : "A";
if (_currentTypeSetting != requestedTypeSetting)
{
commandList.Add(new PipelineEntry(FormatFtpCommand("TYPE", requestedTypeSetting)));
_currentTypeSetting = requestedTypeSetting;
}
if (request.UsePassive)
{
string passiveCommand = (ServerAddress.AddressFamily == AddressFamily.InterNetwork) ? "PASV" : "EPSV";
commandList.Add(new PipelineEntry(FormatFtpCommand(passiveCommand, null), PipelineEntryFlags.CreateDataConnection));
}
else
{
string portCommand = (ServerAddress.AddressFamily == AddressFamily.InterNetwork) ? "PORT" : "EPRT";
CreateFtpListenerSocket(request);
commandList.Add(new PipelineEntry(FormatFtpCommand(portCommand, GetPortCommandLine(request))));
}
if (request.ContentOffset > 0)
{
// REST command must always be the last sent before the main file command is sent.
commandList.Add(new PipelineEntry(FormatFtpCommand("REST", request.ContentOffset.ToString(CultureInfo.InvariantCulture))));
}
}
PipelineEntryFlags flags = PipelineEntryFlags.UserCommand;
if (!request.MethodInfo.IsCommandOnly)
{
flags |= PipelineEntryFlags.GiveDataStream;
if (!request.UsePassive)
flags |= PipelineEntryFlags.CreateDataConnection;
}
if (request.MethodInfo.Operation == FtpOperation.Rename)
{
string baseDir = (requestDirectory == string.Empty)
? string.Empty : requestDirectory + "/";
commandList.Add(new PipelineEntry(FormatFtpCommand("RNFR", baseDir + requestFilename), flags));
string renameTo;
if (!string.IsNullOrEmpty(request.RenameTo)
&& request.RenameTo.StartsWith("/", StringComparison.OrdinalIgnoreCase))
{
renameTo = request.RenameTo; // Absolute path
}
else
{
renameTo = baseDir + request.RenameTo; // Relative path
}
commandList.Add(new PipelineEntry(FormatFtpCommand("RNTO", renameTo), flags));
}
else if (request.MethodInfo.HasFlag(FtpMethodFlags.DoesNotTakeParameter))
{
commandList.Add(new PipelineEntry(FormatFtpCommand(request.Method, string.Empty), flags));
}
else if (request.MethodInfo.HasFlag(FtpMethodFlags.MustChangeWorkingDirectoryToPath))
{
commandList.Add(new PipelineEntry(FormatFtpCommand(request.Method, requestFilename), flags));
}
else
{
commandList.Add(new PipelineEntry(FormatFtpCommand(request.Method, requestPath), flags));
}
commandList.Add(new PipelineEntry(FormatFtpCommand("QUIT", null)));
return (PipelineEntry[])commandList.ToArray(typeof(PipelineEntry));
}
private PipelineInstruction QueueOrCreateDataConection(PipelineEntry entry, ResponseDescription response, bool timeout, ref Stream stream, out bool isSocketReady)
{
isSocketReady = false;
if (_dataHandshakeStarted)
{
isSocketReady = true;
return PipelineInstruction.Pause; //if we already started then this is re-entering into the callback where we proceed with the stream
}
_dataHandshakeStarted = true;
// Handle passive responses by parsing the port and later doing a Connect(...)
bool isPassive = false;
int port = -1;
if (entry.Command == "PASV\r\n" || entry.Command == "EPSV\r\n")
{
if (!response.PositiveCompletion)
{
_abortReason = SR.Format(SR.net_ftp_server_failed_passive, response.Status);
return PipelineInstruction.Abort;
}
if (entry.Command == "PASV\r\n")
{
port = GetPortV4(response.StatusDescription);
}
else
{
port = GetPortV6(response.StatusDescription);
}
isPassive = true;
}
if (isPassive)
{
if (port == -1)
{
NetEventSource.Fail(this, "'port' not set.");
}
try
{
_dataSocket = CreateFtpDataSocket((FtpWebRequest)_request, Socket);
}
catch (ObjectDisposedException)
{
throw ExceptionHelper.RequestAbortedException;
}
IPEndPoint localEndPoint = new IPEndPoint(((IPEndPoint)Socket.LocalEndPoint).Address, 0);
_dataSocket.Bind(localEndPoint);
_passiveEndPoint = new IPEndPoint(ServerAddress, port);
}
PipelineInstruction result;
if (_passiveEndPoint != null)
{
IPEndPoint passiveEndPoint = _passiveEndPoint;
_passiveEndPoint = null;
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "starting Connect()");
if (_isAsync)
{
_dataSocket.BeginConnect(passiveEndPoint, s_connectCallbackDelegate, this);
result = PipelineInstruction.Pause;
}
else
{
_dataSocket.Connect(passiveEndPoint);
result = PipelineInstruction.Advance; // for passive mode we end up going to the next command
}
}
else
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "starting Accept()");
if (_isAsync)
{
_dataSocket.BeginAccept(s_acceptCallbackDelegate, this);
result = PipelineInstruction.Pause;
}
else
{
Socket listenSocket = _dataSocket;
try
{
_dataSocket = _dataSocket.Accept();
if (!ServerAddress.Equals(((IPEndPoint)_dataSocket.RemoteEndPoint).Address))
{
_dataSocket.Close();
throw new WebException(SR.net_ftp_active_address_different, WebExceptionStatus.ProtocolError);
}
isSocketReady = true; // for active mode we end up creating a stream before advancing the pipeline
result = PipelineInstruction.Pause;
}
finally
{
listenSocket.Close();
}
}
}
return result;
}
//
// A door into protected CloseSocket() method
//
internal void Quit()
{
CloseSocket();
}
private enum GetPathOption
{
Normal,
AssumeFilename,
AssumeNoFilename
}
/// <summary>
/// <para>Gets the path component of the Uri</para>
/// </summary>
private static void GetPathInfo(GetPathOption pathOption,
Uri uri,
out string path,
out string directory,
out string filename)
{
path = uri.GetComponents(UriComponents.Path, UriFormat.Unescaped);
int index = path.LastIndexOf('/');
if (pathOption == GetPathOption.AssumeFilename &&
index != -1 && index == path.Length - 1)
{
// Remove last '/' and continue normal processing
path = path.Substring(0, path.Length - 1);
index = path.LastIndexOf('/');
}
// split path into directory and filename
if (pathOption == GetPathOption.AssumeNoFilename)
{
directory = path;
filename = string.Empty;
}
else
{
directory = path.Substring(0, index + 1);
filename = path.Substring(index + 1, path.Length - (index + 1));
}
// strip off trailing '/' on directory if present
if (directory.Length > 1 && directory[directory.Length - 1] == '/')
directory = directory.Substring(0, directory.Length - 1);
}
//
/// <summary>
/// <para>Formats an IP address (contained in a UInt32) to a FTP style command string</para>
/// </summary>
private String FormatAddress(IPAddress address, int Port)
{
byte[] localAddressInBytes = address.GetAddressBytes();
// produces a string in FTP IPAddress/Port encoding (a1, a2, a3, a4, p1, p2), for sending as a parameter
// to the port command.
StringBuilder sb = new StringBuilder(32);
foreach (byte element in localAddressInBytes)
{
sb.Append(element);
sb.Append(',');
}
sb.Append(Port / 256);
sb.Append(',');
sb.Append(Port % 256);
return sb.ToString();
}
/// <summary>
/// <para>Formats an IP address (v6) to a FTP style command string
/// Looks something in this form: |2|1080::8:800:200C:417A|5282| <para>
/// |2|4567::0123:5678:0123:5678|0123|
/// </summary>
private string FormatAddressV6(IPAddress address, int port)
{
StringBuilder sb = new StringBuilder(43); // based on max size of IPv6 address + port + seperators
String addressString = address.ToString();
sb.Append("|2|");
sb.Append(addressString);
sb.Append('|');
sb.Append(port.ToString(NumberFormatInfo.InvariantInfo));
sb.Append('|');
return sb.ToString();
}
internal long ContentLength
{
get
{
return _contentLength;
}
}
internal DateTime LastModified
{
get
{
return _lastModified;
}
}
internal Uri ResponseUri
{
get
{
return _responseUri;
}
}
/// <summary>
/// <para>Returns the server message sent before user credentials are sent</para>
/// </summary>
internal string BannerMessage
{
get
{
return (_bannerMessage != null) ? _bannerMessage.ToString() : null;
}
}
/// <summary>
/// <para>Returns the server message sent after user credentials are sent</para>
/// </summary>
internal string WelcomeMessage
{
get
{
return (_welcomeMessage != null) ? _welcomeMessage.ToString() : null;
}
}
/// <summary>
/// <para>Returns the exit sent message on shutdown</para>
/// </summary>
internal string ExitMessage
{
get
{
return (_exitMessage != null) ? _exitMessage.ToString() : null;
}
}
/// <summary>
/// <para>Parses a response string for content length</para>
/// </summary>
private long GetContentLengthFrom213Response(string responseString)
{
string[] parsedList = responseString.Split(new char[] { ' ' });
if (parsedList.Length < 2)
throw new FormatException(SR.Format(SR.net_ftp_response_invalid_format, responseString));
return Convert.ToInt64(parsedList[1], NumberFormatInfo.InvariantInfo);
}
/// <summary>
/// <para>Parses a response string for last modified time</para>
/// </summary>
private DateTime GetLastModifiedFrom213Response(string str)
{
DateTime dateTime = _lastModified;
string[] parsedList = str.Split(new char[] { ' ', '.' });
if (parsedList.Length < 2)
{
return dateTime;
}
string dateTimeLine = parsedList[1];
if (dateTimeLine.Length < 14)
{
return dateTime;
}
int year = Convert.ToInt32(dateTimeLine.Substring(0, 4), NumberFormatInfo.InvariantInfo);
int month = Convert.ToInt16(dateTimeLine.Substring(4, 2), NumberFormatInfo.InvariantInfo);
int day = Convert.ToInt16(dateTimeLine.Substring(6, 2), NumberFormatInfo.InvariantInfo);
int hour = Convert.ToInt16(dateTimeLine.Substring(8, 2), NumberFormatInfo.InvariantInfo);
int minute = Convert.ToInt16(dateTimeLine.Substring(10, 2), NumberFormatInfo.InvariantInfo);
int second = Convert.ToInt16(dateTimeLine.Substring(12, 2), NumberFormatInfo.InvariantInfo);
int millisecond = 0;
if (parsedList.Length > 2)
{
millisecond = Convert.ToInt16(parsedList[2], NumberFormatInfo.InvariantInfo);
}
try
{
dateTime = new DateTime(year, month, day, hour, minute, second, millisecond);
dateTime = dateTime.ToLocalTime(); // must be handled in local time
}
catch (ArgumentOutOfRangeException)
{
}
catch (ArgumentException)
{
}
return dateTime;
}
/// <summary>
/// <para>Attempts to find the response Uri
/// Typical string looks like this, need to get trailing filename
/// "150 Opening BINARY mode data connection for FTP46.tmp."</para>
/// </summary>
private void TryUpdateResponseUri(string str, FtpWebRequest request)
{
Uri baseUri = request.RequestUri;
//
// Not sure what we are doing here but I guess the logic is IIS centric
//
int start = str.IndexOf("for ");
if (start == -1)
return;
start += 4;
int end = str.LastIndexOf('(');
if (end == -1)
end = str.Length;
if (end <= start)
return;
string filename = str.Substring(start, end - start);
filename = filename.TrimEnd(new char[] { ' ', '.', '\r', '\n' });
// Do minimal escaping that we need to get a valid Uri
// when combined with the baseUri
string escapedFilename;
escapedFilename = filename.Replace("%", "%25");
escapedFilename = escapedFilename.Replace("#", "%23");
// help us out if the user forgot to add a slash to the directory name
string orginalPath = baseUri.AbsolutePath;
if (orginalPath.Length > 0 && orginalPath[orginalPath.Length - 1] != '/')
{
UriBuilder uriBuilder = new UriBuilder(baseUri);
uriBuilder.Path = orginalPath + "/";
baseUri = uriBuilder.Uri;
}
Uri newUri;
if (!Uri.TryCreate(baseUri, escapedFilename, out newUri))
{
throw new FormatException(SR.Format(SR.net_ftp_invalid_response_filename, filename));
}
else
{
if (!baseUri.IsBaseOf(newUri) ||
baseUri.Segments.Length != newUri.Segments.Length - 1)
{
throw new FormatException(SR.Format(SR.net_ftp_invalid_response_filename, filename));
}
else
{
_responseUri = newUri;
}
}
}
/// <summary>
/// <para>Parses a response string for content length</para>
/// </summary>
private void TryUpdateContentLength(string str)
{
int pos1 = str.LastIndexOf("(");
if (pos1 != -1)
{
int pos2 = str.IndexOf(" bytes).");
if (pos2 != -1 && pos2 > pos1)
{
pos1++;
long result;
if (Int64.TryParse(str.Substring(pos1, pos2 - pos1),
NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite,
NumberFormatInfo.InvariantInfo, out result))
{
_contentLength = result;
}
}
}
}
/// <summary>
/// <para>Parses a response string for our login dir in " "</para>
/// </summary>
private string GetLoginDirectory(string str)
{
int firstQuote = str.IndexOf('"');
int lastQuote = str.LastIndexOf('"');
if (firstQuote != -1 && lastQuote != -1 && firstQuote != lastQuote)
{
return str.Substring(firstQuote + 1, lastQuote - firstQuote - 1);
}
else
{
return String.Empty;
}
}
/// <summary>
/// <para>Parses a response string for a port number</para>
/// </summary>
private int GetPortV4(string responseString)
{
string[] parsedList = responseString.Split(new char[] { ' ', '(', ',', ')' });
// We need at least the status code and the port
if (parsedList.Length <= 7)
{
throw new FormatException(SR.Format(SR.net_ftp_response_invalid_format, responseString));
}
int index = parsedList.Length - 1;
// skip the last non-number token (e.g. terminating '.')
if (!Char.IsNumber(parsedList[index], 0))
index--;
int port = Convert.ToByte(parsedList[index--], NumberFormatInfo.InvariantInfo);
port = port |
(Convert.ToByte(parsedList[index--], NumberFormatInfo.InvariantInfo) << 8);
return port;
}
/// <summary>
/// <para>Parses a response string for a port number</para>
/// </summary>
private int GetPortV6(string responseString)
{
int pos1 = responseString.LastIndexOf("(");
int pos2 = responseString.LastIndexOf(")");
if (pos1 == -1 || pos2 <= pos1)
throw new FormatException(SR.Format(SR.net_ftp_response_invalid_format, responseString));
// addressInfo will contain a string of format "|||<tcp-port>|"
string addressInfo = responseString.Substring(pos1 + 1, pos2 - pos1 - 1);
string[] parsedList = addressInfo.Split(new char[] { '|' });
if (parsedList.Length < 4)
throw new FormatException(SR.Format(SR.net_ftp_response_invalid_format, responseString));
return Convert.ToInt32(parsedList[3], NumberFormatInfo.InvariantInfo);
}
/// <summary>
/// <para>Creates the Listener socket</para>
/// </summary>
private void CreateFtpListenerSocket(FtpWebRequest request)
{
// Gets an IPEndPoint for the local host for the data socket to bind to.
IPEndPoint epListener = new IPEndPoint(((IPEndPoint)Socket.LocalEndPoint).Address, 0);
try
{
_dataSocket = CreateFtpDataSocket(request, Socket);
}
catch (ObjectDisposedException)
{
throw ExceptionHelper.RequestAbortedException;
}
// Binds the data socket to the local end point.
_dataSocket.Bind(epListener);
_dataSocket.Listen(1); // Put the dataSocket in Listen mode
}
/// <summary>
/// <para>Builds a command line to send to the server with proper port and IP address of client</para>
/// </summary>
private string GetPortCommandLine(FtpWebRequest request)
{
try
{
// retrieves the IP address of the local endpoint
IPEndPoint localEP = (IPEndPoint)_dataSocket.LocalEndPoint;
if (ServerAddress.AddressFamily == AddressFamily.InterNetwork)
{
return FormatAddress(localEP.Address, localEP.Port);
}
else if (ServerAddress.AddressFamily == AddressFamily.InterNetworkV6)
{
return FormatAddressV6(localEP.Address, localEP.Port);
}
else
{
throw new InternalException();
}
}
catch (Exception e)
{
throw GenerateException(SR.net_ftp_protocolerror, WebExceptionStatus.ProtocolError, e); // could not open data connection
}
}
/// <summary>
/// <para>Formats a simple FTP command + parameter in correct pre-wire format</para>
/// </summary>
private string FormatFtpCommand(string command, string parameter)
{
StringBuilder stringBuilder = new StringBuilder(command.Length + ((parameter != null) ? parameter.Length : 0) + 3 /*size of ' ' \r\n*/);
stringBuilder.Append(command);
if (!string.IsNullOrEmpty(parameter))
{
stringBuilder.Append(' ');
stringBuilder.Append(parameter);
}
stringBuilder.Append("\r\n");
return stringBuilder.ToString();
}
/// <summary>
/// <para>
/// This will handle either connecting to a port or listening for one
/// </para>
/// </summary>
protected Socket CreateFtpDataSocket(FtpWebRequest request, Socket templateSocket)
{
// Safe to be called under an Assert.
Socket socket = new Socket(templateSocket.AddressFamily, templateSocket.SocketType, templateSocket.ProtocolType);
return socket;
}
protected override bool CheckValid(ResponseDescription response, ref int validThrough, ref int completeLength)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"CheckValid({response.StatusBuffer})");
// If the response is less than 4 bytes long, it is too short to tell, so return true, valid so far.
if (response.StatusBuffer.Length < 4)
{
return true;
}
string responseString = response.StatusBuffer.ToString();
// Otherwise, if there is no status code for this response yet, get one.
if (response.Status == ResponseDescription.NoStatus)
{
// If the response does not start with three digits, then it is not a valid response from an FTP server.
if (!(Char.IsDigit(responseString[0]) && Char.IsDigit(responseString[1]) && Char.IsDigit(responseString[2]) && (responseString[3] == ' ' || responseString[3] == '-')))
{
return false;
}
else
{
response.StatusCodeString = responseString.Substring(0, 3);
response.Status = Convert.ToInt16(response.StatusCodeString, NumberFormatInfo.InvariantInfo);
}
// IF a hyphen follows the status code on the first line of the response, then we have a multiline response coming.
if (responseString[3] == '-')
{
response.Multiline = true;
}
}
// If a complete line of response has been received from the server, then see if the
// overall response is complete.
// If this was not a multiline response, then the response is complete at the end of the line.
// If this was a multiline response (indicated by three digits followed by a '-' in the first line),
// then we see if the last line received started with the same three digits followed by a space.
// If it did, then this is the sign of a complete multiline response.
// If the line contained three other digits followed by the response, then this is a violation of the
// FTP protocol for multiline responses.
// All other cases indicate that the response is not yet complete.
int index = 0;
while ((index = responseString.IndexOf("\r\n", validThrough)) != -1) // gets the end line.
{
int lineStart = validThrough;
validThrough = index + 2; // validThrough now marks the end of the line being examined.
if (!response.Multiline)
{
completeLength = validThrough;
return true;
}
if (responseString.Length > lineStart + 4)
{
// If the first three characters of the response line currently being examined
// match the status code, then if they are followed by a space, then we
// have reached the end of the reply.
if (responseString.Substring(lineStart, 3) == response.StatusCodeString)
{
if (responseString[lineStart + 3] == ' ')
{
completeLength = validThrough;
return true;
}
}
}
}
return true;
}
/// <summary>
/// <para>Determines whether the stream we return is Writeable or Readable</para>
/// </summary>
private TriState IsFtpDataStreamWriteable()
{
FtpWebRequest request = _request as FtpWebRequest;
if (request != null)
{
if (request.MethodInfo.IsUpload)
{
return TriState.True;
}
else if (request.MethodInfo.IsDownload)
{
return TriState.False;
}
}
return TriState.Unspecified;
}
} // class FtpControlStream
} // namespace System.Net
| |
/* WinUSBNet library
* (C) 2010 Thomas Bleeker (www.madwizard.org)
*
* Licensed under the MIT license, see license.txt or:
* http://www.opensource.org/licenses/mit-license.php
*/
/* NOTE: Parts of the code in this file are based on the work of Jan Axelson
* See http://www.lvr.com/winusb.htm for more information
*/
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace MadWizard.WinUSBNet.API
{
/// <summary>
/// Routines for detecting devices and receiving device notifications.
/// </summary>
internal static partial class DeviceManagement
{
// Get device name from notification message.
// Also checks checkGuid with the GUID from the message to check the notification
// is for a relevant device. Other messages might be received.
public static string GetNotifyMessageDeviceName(Message m, Guid checkGuid)
{
int stringSize;
DEV_BROADCAST_DEVICEINTERFACE_1 devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE_1();
DEV_BROADCAST_HDR devBroadcastHeader = new DEV_BROADCAST_HDR();
// The LParam parameter of Message is a pointer to a DEV_BROADCAST_HDR structure.
Marshal.PtrToStructure(m.LParam, devBroadcastHeader);
if ((devBroadcastHeader.dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE))
{
// The dbch_devicetype parameter indicates that the event applies to a device interface.
// So the structure in LParam is actually a DEV_BROADCAST_INTERFACE structure,
// which begins with a DEV_BROADCAST_HDR.
// Obtain the number of characters in dbch_name by subtracting the 32 bytes
// in the strucutre that are not part of dbch_name and dividing by 2 because there are
// 2 bytes per character.
stringSize = System.Convert.ToInt32((devBroadcastHeader.dbch_size - 32) / 2);
// The dbcc_name parameter of devBroadcastDeviceInterface contains the device name.
// Trim dbcc_name to match the size of the String.
devBroadcastDeviceInterface.dbcc_name = new char[stringSize + 1];
// Marshal data from the unmanaged block pointed to by m.LParam
// to the managed object devBroadcastDeviceInterface.
Marshal.PtrToStructure(m.LParam, devBroadcastDeviceInterface);
// Check if message is for the GUID
if (devBroadcastDeviceInterface.dbcc_classguid != checkGuid)
return null;
// Store the device name in a String.
string deviceNameString = new String(devBroadcastDeviceInterface.dbcc_name, 0, stringSize);
return deviceNameString;
}
return null;
}
private static byte[] GetProperty(IntPtr deviceInfoSet, SP_DEVINFO_DATA deviceInfoData, SPDRP property, out int regType)
{
uint requiredSize;
if (!SetupDiGetDeviceRegistryProperty(deviceInfoSet, ref deviceInfoData, property, IntPtr.Zero, IntPtr.Zero, 0, out requiredSize))
{
if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER)
throw APIException.Win32("Failed to get buffer size for device registry property.");
}
byte[] buffer = new byte[requiredSize];
if (!SetupDiGetDeviceRegistryProperty(deviceInfoSet, ref deviceInfoData, property, out regType, buffer, (uint)buffer.Length, out requiredSize))
throw APIException.Win32("Failed to get device registry property.");
return buffer;
}
// todo: is the queried data always available, or should we check ERROR_INVALID_DATA?
private static string GetStringProperty(IntPtr deviceInfoSet, SP_DEVINFO_DATA deviceInfoData, SPDRP property)
{
int regType;
byte[] buffer = GetProperty(deviceInfoSet, deviceInfoData, property, out regType);
if (regType != (int)RegTypes.REG_SZ)
throw new APIException("Invalid registry type returned for device property.");
// sizof(char), 2 bytes, are removed to leave out the string terminator
return System.Text.Encoding.Unicode.GetString(buffer, 0, buffer.Length - sizeof(char));
}
private static string[] GetMultiStringProperty(IntPtr deviceInfoSet, SP_DEVINFO_DATA deviceInfoData, SPDRP property)
{
int regType;
byte[] buffer = GetProperty(deviceInfoSet, deviceInfoData, property, out regType);
if (regType != (int)RegTypes.REG_MULTI_SZ)
throw new APIException("Invalid registry type returned for device property.");
string fullString = System.Text.Encoding.Unicode.GetString(buffer);
return fullString.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
}
private static DeviceDetails GetDeviceDetails(string devicePath, IntPtr deviceInfoSet, SP_DEVINFO_DATA deviceInfoData)
{
DeviceDetails details = new DeviceDetails();
details.DevicePath = devicePath;
details.DeviceDescription = GetStringProperty(deviceInfoSet, deviceInfoData, SPDRP.SPDRP_DEVICEDESC);
details.Manufacturer = GetStringProperty(deviceInfoSet, deviceInfoData, SPDRP.SPDRP_MFG);
string[] hardwareIDs = GetMultiStringProperty(deviceInfoSet, deviceInfoData, SPDRP.SPDRP_HARDWAREID);
Regex regex = new Regex("^USB\\\\VID_([0-9A-F]{4})&PID_([0-9A-F]{4})", RegexOptions.IgnoreCase);
bool foundVidPid = false;
foreach (string hardwareID in hardwareIDs)
{
Match match = regex.Match(hardwareID);
if (match.Success)
{
details.VID = ushort.Parse(match.Groups[1].Value, System.Globalization.NumberStyles.AllowHexSpecifier);
details.PID = ushort.Parse(match.Groups[2].Value, System.Globalization.NumberStyles.AllowHexSpecifier);
foundVidPid = true;
break;
}
}
if (!foundVidPid)
throw new APIException("Failed to find VID and PID for USB device. No hardware ID could be parsed.");
return details;
}
public static DeviceDetails[] FindDevicesFromGuid(Guid guid)
{
IntPtr deviceInfoSet = IntPtr.Zero;
List<DeviceDetails> deviceList = new List<DeviceDetails>();
try
{
deviceInfoSet = SetupDiGetClassDevs(ref guid, IntPtr.Zero, IntPtr.Zero,
DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (deviceInfoSet == FileIO.INVALID_HANDLE_VALUE)
throw APIException.Win32("Failed to enumerate devices.");
int memberIndex = 0;
while(true)
{
// Begin with 0 and increment through the device information set until
// no more devices are available.
SP_DEVICE_INTERFACE_DATA deviceInterfaceData = new SP_DEVICE_INTERFACE_DATA();
// The cbSize element of the deviceInterfaceData structure must be set to
// the structure's size in bytes.
// The size is 28 bytes for 32-bit code and 32 bytes for 64-bit code.
deviceInterfaceData.cbSize = Marshal.SizeOf(deviceInterfaceData);
bool success;
success = SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref guid, memberIndex, ref deviceInterfaceData);
// Find out if a device information set was retrieved.
if (!success)
{
int lastError = Marshal.GetLastWin32Error();
if (lastError == ERROR_NO_MORE_ITEMS)
break;
throw APIException.Win32("Failed to get device interface.");
}
// A device is present.
int bufferSize = 0;
success = SetupDiGetDeviceInterfaceDetail
(deviceInfoSet,
ref deviceInterfaceData,
IntPtr.Zero,
0,
ref bufferSize,
IntPtr.Zero);
if (!success)
{
if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER)
throw APIException.Win32("Failed to get interface details buffer size.");
}
IntPtr detailDataBuffer = IntPtr.Zero;
try
{
// Allocate memory for the SP_DEVICE_INTERFACE_DETAIL_DATA structure using the returned buffer size.
detailDataBuffer = Marshal.AllocHGlobal(bufferSize);
// Store cbSize in the first bytes of the array. The number of bytes varies with 32- and 64-bit systems.
Marshal.WriteInt32(detailDataBuffer, (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8);
// Call SetupDiGetDeviceInterfaceDetail again.
// This time, pass a pointer to DetailDataBuffer
// and the returned required buffer size.
// build a DevInfo Data structure
SP_DEVINFO_DATA da = new SP_DEVINFO_DATA();
da.cbSize = Marshal.SizeOf(da);
success = SetupDiGetDeviceInterfaceDetail
(deviceInfoSet,
ref deviceInterfaceData,
detailDataBuffer,
bufferSize,
ref bufferSize,
ref da);
if (!success)
throw APIException.Win32("Failed to get device interface details.");
// Skip over cbsize (4 bytes) to get the address of the devicePathName.
IntPtr pDevicePathName = new IntPtr(detailDataBuffer.ToInt64() + 4);
string pathName = Marshal.PtrToStringUni(pDevicePathName);
// Get the String containing the devicePathName.
DeviceDetails details = GetDeviceDetails(pathName, deviceInfoSet, da);
deviceList.Add(details);
}
finally
{
if (detailDataBuffer != IntPtr.Zero)
{
Marshal.FreeHGlobal(detailDataBuffer);
detailDataBuffer = IntPtr.Zero;
}
}
memberIndex++;
}
}
finally
{
if (deviceInfoSet != IntPtr.Zero && deviceInfoSet != FileIO.INVALID_HANDLE_VALUE)
{
SetupDiDestroyDeviceInfoList(deviceInfoSet);
}
}
return deviceList.ToArray();
}
public static void RegisterForDeviceNotifications(IntPtr controlHandle, Guid classGuid, ref IntPtr deviceNotificationHandle)
{
DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE();
IntPtr devBroadcastDeviceInterfaceBuffer = IntPtr.Zero;
try
{
int size = Marshal.SizeOf(devBroadcastDeviceInterface);
devBroadcastDeviceInterface.dbcc_size = size;
devBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
devBroadcastDeviceInterface.dbcc_reserved = 0;
devBroadcastDeviceInterface.dbcc_classguid = classGuid;
devBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(size);
// Copy the DEV_BROADCAST_DEVICEINTERFACE structure to the buffer.
// Set fDeleteOld True to prevent memory leaks.
Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true);
deviceNotificationHandle = RegisterDeviceNotification(controlHandle, devBroadcastDeviceInterfaceBuffer, DEVICE_NOTIFY_WINDOW_HANDLE);
if (deviceNotificationHandle == IntPtr.Zero)
throw APIException.Win32("Failed to register device notification");
// Marshal data from the unmanaged block devBroadcastDeviceInterfaceBuffer to
// the managed object devBroadcastDeviceInterface
Marshal.PtrToStructure(devBroadcastDeviceInterfaceBuffer, devBroadcastDeviceInterface);
}
finally
{
// Free the memory allocated previously by AllocHGlobal.
if (devBroadcastDeviceInterfaceBuffer != IntPtr.Zero)
Marshal.FreeHGlobal(devBroadcastDeviceInterfaceBuffer);
}
}
public static void StopDeviceDeviceNotifications(IntPtr deviceNotificationHandle)
{
if (!DeviceManagement.UnregisterDeviceNotification(deviceNotificationHandle))
throw APIException.Win32("Failed to unregister device notification");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia.Markup.Parsers;
using XamlX;
using XamlX.Ast;
using XamlX.Emit;
using XamlX.IL;
using XamlX.Transform;
using XamlX.Transform.Transformers;
using XamlX.TypeSystem;
namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.Transformers
{
using XamlParseException = XamlX.XamlParseException;
using XamlLoadException = XamlX.XamlLoadException;
class AvaloniaXamlIlSelectorTransformer : IXamlAstTransformer
{
public IXamlAstNode Transform(AstTransformationContext context, IXamlAstNode node)
{
if (!(node is XamlAstObjectNode on && on.Type.GetClrType().FullName == "Avalonia.Styling.Style"))
return node;
var pn = on.Children.OfType<XamlAstXamlPropertyValueNode>()
.FirstOrDefault(p => p.Property.GetClrProperty().Name == "Selector");
if (pn == null)
return node;
if (pn.Values.Count != 1)
throw new XamlParseException("Selector property should should have exactly one value", node);
if (pn.Values[0] is XamlIlSelectorNode)
//Deja vu. I've just been in this place before
return node;
if (!(pn.Values[0] is XamlAstTextNode tn))
throw new XamlParseException("Selector property should be a text node", node);
var selectorType = pn.Property.GetClrProperty().Getter.ReturnType;
var initialNode = new XamlIlSelectorInitialNode(node, selectorType);
XamlIlSelectorNode Create(IEnumerable<SelectorGrammar.ISyntax> syntax,
Func<string, string, XamlAstClrTypeReference> typeResolver)
{
XamlIlSelectorNode result = initialNode;
XamlIlOrSelectorNode results = null;
foreach (var i in syntax)
{
switch (i)
{
case SelectorGrammar.OfTypeSyntax ofType:
result = new XamlIlTypeSelector(result, typeResolver(ofType.Xmlns, ofType.TypeName).Type, true);
break;
case SelectorGrammar.IsSyntax @is:
result = new XamlIlTypeSelector(result, typeResolver(@is.Xmlns, @is.TypeName).Type, false);
break;
case SelectorGrammar.ClassSyntax @class:
result = new XamlIlStringSelector(result, XamlIlStringSelector.SelectorType.Class, @class.Class);
break;
case SelectorGrammar.NameSyntax name:
result = new XamlIlStringSelector(result, XamlIlStringSelector.SelectorType.Name, name.Name);
break;
case SelectorGrammar.PropertySyntax property:
{
var type = result?.TargetType;
if (type == null)
throw new XamlParseException("Property selectors must be applied to a type.", node);
var targetProperty =
type.GetAllProperties().FirstOrDefault(p => p.Name == property.Property);
if (targetProperty == null)
throw new XamlParseException($"Cannot find '{property.Property}' on '{type}", node);
if (!XamlTransformHelpers.TryGetCorrectlyTypedValue(context,
new XamlAstTextNode(node, property.Value, context.Configuration.WellKnownTypes.String),
targetProperty.PropertyType, out var typedValue))
throw new XamlParseException(
$"Cannot convert '{property.Value}' to '{targetProperty.PropertyType.GetFqn()}",
node);
result = new XamlIlPropertyEqualsSelector(result, targetProperty, typedValue);
break;
}
case SelectorGrammar.ChildSyntax child:
result = new XamlIlCombinatorSelector(result, XamlIlCombinatorSelector.SelectorType.Child);
break;
case SelectorGrammar.DescendantSyntax descendant:
result = new XamlIlCombinatorSelector(result, XamlIlCombinatorSelector.SelectorType.Descendant);
break;
case SelectorGrammar.TemplateSyntax template:
result = new XamlIlCombinatorSelector(result, XamlIlCombinatorSelector.SelectorType.Template);
break;
case SelectorGrammar.NotSyntax not:
result = new XamlIlNotSelector(result, Create(not.Argument, typeResolver));
break;
case SelectorGrammar.NthChildSyntax nth:
result = new XamlIlNthChildSelector(result, nth.Step, nth.Offset, XamlIlNthChildSelector.SelectorType.NthChild);
break;
case SelectorGrammar.NthLastChildSyntax nth:
result = new XamlIlNthChildSelector(result, nth.Step, nth.Offset, XamlIlNthChildSelector.SelectorType.NthLastChild);
break;
case SelectorGrammar.CommaSyntax comma:
if (results == null)
results = new XamlIlOrSelectorNode(node, selectorType);
results.Add(result);
result = initialNode;
break;
default:
throw new XamlParseException($"Unsupported selector grammar '{i.GetType()}'.", node);
}
}
if (results != null && result != null)
{
results.Add(result);
}
return results ?? result;
}
IEnumerable<SelectorGrammar.ISyntax> parsed;
try
{
parsed = SelectorGrammar.Parse(tn.Text);
}
catch (Exception e)
{
throw new XamlParseException("Unable to parse selector: " + e.Message, node);
}
var selector = Create(parsed, (p, n)
=> TypeReferenceResolver.ResolveType(context, $"{p}:{n}", true, node, true));
pn.Values[0] = selector;
return new AvaloniaXamlIlTargetTypeMetadataNode(on,
new XamlAstClrTypeReference(selector, selector.TargetType, false),
AvaloniaXamlIlTargetTypeMetadataNode.ScopeTypes.Style);
}
}
abstract class XamlIlSelectorNode : XamlAstNode, IXamlAstValueNode, IXamlAstEmitableNode<IXamlILEmitter, XamlILNodeEmitResult>
{
protected XamlIlSelectorNode Previous { get; }
public abstract IXamlType TargetType { get; }
public XamlIlSelectorNode(XamlIlSelectorNode previous,
IXamlLineInfo info = null,
IXamlType selectorType = null) : base(info ?? previous)
{
Previous = previous;
Type = selectorType == null ? previous.Type : new XamlAstClrTypeReference(this, selectorType, false);
}
public IXamlAstTypeReference Type { get; }
public virtual XamlILNodeEmitResult Emit(XamlEmitContext<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter codeGen)
{
if (Previous != null)
context.Emit(Previous, codeGen, Type.GetClrType());
DoEmit(context, codeGen);
return XamlILNodeEmitResult.Type(0, Type.GetClrType());
}
protected abstract void DoEmit(XamlEmitContext<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter codeGen);
protected void EmitCall(XamlEmitContext<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter codeGen, Func<IXamlMethod, bool> method)
{
var selectors = context.Configuration.TypeSystem.GetType("Avalonia.Styling.Selectors");
var found = selectors.FindMethod(m => m.IsStatic && m.Parameters.Count > 0 && method(m));
codeGen.EmitCall(found);
}
}
class XamlIlSelectorInitialNode : XamlIlSelectorNode
{
public XamlIlSelectorInitialNode(IXamlLineInfo info,
IXamlType selectorType) : base(null, info, selectorType)
{
}
public override IXamlType TargetType => null;
protected override void DoEmit(XamlEmitContext<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter codeGen) => codeGen.Ldnull();
}
class XamlIlTypeSelector : XamlIlSelectorNode
{
public bool Concrete { get; }
public XamlIlTypeSelector(XamlIlSelectorNode previous, IXamlType type, bool concrete) : base(previous)
{
TargetType = type;
Concrete = concrete;
}
public override IXamlType TargetType { get; }
protected override void DoEmit(XamlEmitContext<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter codeGen)
{
var name = Concrete ? "OfType" : "Is";
codeGen.Ldtype(TargetType);
EmitCall(context, codeGen,
m => m.Name == name && m.Parameters.Count == 2 && m.Parameters[1].FullName == "System.Type");
}
}
class XamlIlStringSelector : XamlIlSelectorNode
{
public string String { get; set; }
public enum SelectorType
{
Class,
Name
}
private SelectorType _type;
public XamlIlStringSelector(XamlIlSelectorNode previous, SelectorType type, string s) : base(previous)
{
_type = type;
String = s;
}
public override IXamlType TargetType => Previous?.TargetType;
protected override void DoEmit(XamlEmitContext<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter codeGen)
{
codeGen.Ldstr(String);
var name = _type.ToString();
EmitCall(context, codeGen,
m => m.Name == name && m.Parameters.Count == 2 && m.Parameters[1].FullName == "System.String");
}
}
class XamlIlCombinatorSelector : XamlIlSelectorNode
{
private readonly SelectorType _type;
public enum SelectorType
{
Child,
Descendant,
Template
}
public XamlIlCombinatorSelector(XamlIlSelectorNode previous, SelectorType type) : base(previous)
{
_type = type;
}
public override IXamlType TargetType => null;
protected override void DoEmit(XamlEmitContext<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter codeGen)
{
var name = _type.ToString();
EmitCall(context, codeGen,
m => m.Name == name && m.Parameters.Count == 1);
}
}
class XamlIlNotSelector : XamlIlSelectorNode
{
public XamlIlSelectorNode Argument { get; }
public XamlIlNotSelector(XamlIlSelectorNode previous, XamlIlSelectorNode argument) : base(previous)
{
Argument = argument;
}
public override IXamlType TargetType => Previous?.TargetType;
protected override void DoEmit(XamlEmitContext<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter codeGen)
{
context.Emit(Argument, codeGen, Type.GetClrType());
EmitCall(context, codeGen,
m => m.Name == "Not" && m.Parameters.Count == 2 && m.Parameters[1].Equals(Type.GetClrType()));
}
}
class XamlIlNthChildSelector : XamlIlSelectorNode
{
private readonly int _step;
private readonly int _offset;
private readonly SelectorType _type;
public enum SelectorType
{
NthChild,
NthLastChild
}
public XamlIlNthChildSelector(XamlIlSelectorNode previous, int step, int offset, SelectorType type) : base(previous)
{
_step = step;
_offset = offset;
_type = type;
}
public override IXamlType TargetType => Previous?.TargetType;
protected override void DoEmit(XamlEmitContext<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter codeGen)
{
codeGen.Ldc_I4(_step);
codeGen.Ldc_I4(_offset);
EmitCall(context, codeGen,
m => m.Name == _type.ToString() && m.Parameters.Count == 3);
}
}
class XamlIlPropertyEqualsSelector : XamlIlSelectorNode
{
public XamlIlPropertyEqualsSelector(XamlIlSelectorNode previous,
IXamlProperty property,
IXamlAstValueNode value)
: base(previous)
{
Property = property;
Value = value;
}
public IXamlProperty Property { get; set; }
public IXamlAstValueNode Value { get; set; }
public override IXamlType TargetType => Previous?.TargetType;
protected override void DoEmit(XamlEmitContext<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter codeGen)
{
if (!XamlIlAvaloniaPropertyHelper.Emit(context, codeGen, Property))
throw new XamlLoadException(
$"{Property.Name} of {(Property.Setter ?? Property.Getter).DeclaringType.GetFqn()} doesn't seem to be an AvaloniaProperty",
this);
context.Emit(Value, codeGen, context.Configuration.WellKnownTypes.Object);
EmitCall(context, codeGen,
m => m.Name == "PropertyEquals"
&& m.Parameters.Count == 3
&& m.Parameters[1].FullName == "Avalonia.AvaloniaProperty"
&& m.Parameters[2].Equals(context.Configuration.WellKnownTypes.Object));
}
}
class XamlIlOrSelectorNode : XamlIlSelectorNode
{
List<XamlIlSelectorNode> _selectors = new List<XamlIlSelectorNode>();
public XamlIlOrSelectorNode(IXamlLineInfo info, IXamlType selectorType) : base(null, info, selectorType)
{
}
public void Add(XamlIlSelectorNode node)
{
_selectors.Add(node);
}
public override IXamlType TargetType
{
get
{
IXamlType result = null;
foreach (var selector in _selectors)
{
if (selector.TargetType == null)
{
return null;
}
else if (result == null)
{
result = selector.TargetType;
}
else
{
while (!result.IsAssignableFrom(selector.TargetType))
{
result = result.BaseType;
}
}
}
return result;
}
}
protected override void DoEmit(XamlEmitContext<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter codeGen)
{
if (_selectors.Count == 0)
throw new XamlLoadException("Invalid selector count", this);
if (_selectors.Count == 1)
{
_selectors[0].Emit(context, codeGen);
return;
}
var listType = context.Configuration.TypeSystem.FindType("System.Collections.Generic.List`1")
.MakeGenericType(base.Type.GetClrType());
var add = listType.FindMethod("Add", context.Configuration.WellKnownTypes.Void, false, Type.GetClrType());
codeGen
.Newobj(listType.FindConstructor());
foreach (var s in _selectors)
{
codeGen.Dup();
context.Emit(s, codeGen, Type.GetClrType());
codeGen.EmitCall(add, true);
}
EmitCall(context, codeGen,
m => m.Name == "Or" && m.Parameters.Count == 1 && m.Parameters[0].Name.StartsWith("IReadOnlyList"));
}
}
}
| |
// 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.Reflection.Metadata;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Reflection.Internal
{
/// <summary>
/// Provides helpers to decode strings from unmanaged memory to System.String while avoiding
/// intermediate allocation.
///
/// This has three components:
///
/// (1) Light-up Encoding.GetString(byte*, int) via reflection and resurface it as extension
/// method.
///
/// This is a new API that will provide API convergence across all platforms for
/// this scenario. It is already on .NET 4.6+ and ASP.NET vNext, but not yet available
/// on every platform we support. See below for how we fall back.
///
/// (2) Deal with WinRT prefixes.
///
/// When reading managed winmds with projections enabled, the metadata reader needs to prepend
/// a WinRT prefix in some case . Doing this without allocation poses a problem
/// as we don't have the prefix and input in contiguous data that we can pass to the
/// Encoding.GetString. We handle this case using pooled managed scratch buffers where we copy
/// the prefix and input and decode using Encoding.GetString(byte[], int, int).
///
/// (3) Deal with platforms that don't yet have Encoding.GetString(byte*, int).
///
/// If we're running on a full framework earlier than 4.6, we will bind to the internal
/// String.CreateStringFromEncoding which is equivalent and Encoding.GetString is just a trivial
/// wrapper around it in .NET 4.6. This means that we always have the fast path on every
/// full framework version we support.
///
/// If we can't bind to it via reflection, then we emulate it using what is effectively (2) and
/// with an empty prefix.
///
/// For both (2) and (3), the pooled buffers have a fixed size deemed large enough for the
/// vast majority of metadata strings. In the rare worst case (byteCount > threshold and
/// (lightUpAttemptFailed || prefix != null), we give up and allocate a temporary array,
/// copy to it, decode, and throw it away.
/// </summary>
internal unsafe static class EncodingHelper
{
// Size of pooled buffers. Input larger than that is prefixed or given to us on a
// platform that doesn't have unsafe Encoding.GetString, will cause us to
// allocate and throw away a temporary buffer. The vast majority of metadata strings
// are quite small so we don't need to waste memory with large buffers.
public const int PooledBufferSize = 200;
// The pooled buffers for (2) and (3) above. Use AcquireBuffer(int) and ReleaseBuffer(byte[])
// instead of the pool directly to implement the size check.
private static readonly ObjectPool<byte[]> s_pool = new ObjectPool<byte[]>(() => new byte[PooledBufferSize]);
public static string DecodeUtf8(byte* bytes, int byteCount, byte[] prefix, MetadataStringDecoder utf8Decoder)
{
Debug.Assert(utf8Decoder != null);
if (prefix != null)
{
return DecodeUtf8Prefixed(bytes, byteCount, prefix, utf8Decoder);
}
if (byteCount == 0)
{
return String.Empty;
}
return utf8Decoder.GetString(bytes, byteCount);
}
private static string DecodeUtf8Prefixed(byte* bytes, int byteCount, byte[] prefix, MetadataStringDecoder utf8Decoder)
{
Debug.Assert(utf8Decoder != null);
int prefixedByteCount = byteCount + prefix.Length;
if (prefixedByteCount == 0)
{
return String.Empty;
}
byte[] buffer = AcquireBuffer(prefixedByteCount);
prefix.CopyTo(buffer, 0);
Marshal.Copy((IntPtr)bytes, buffer, prefix.Length, byteCount);
string result;
fixed (byte* prefixedBytes = buffer)
{
result = utf8Decoder.GetString(prefixedBytes, prefixedByteCount);
}
ReleaseBuffer(buffer);
return result;
}
private static byte[] AcquireBuffer(int byteCount)
{
if (byteCount > PooledBufferSize)
{
return new byte[byteCount];
}
return s_pool.Allocate();
}
private static void ReleaseBuffer(byte[] buffer)
{
if (buffer.Length == PooledBufferSize)
{
s_pool.Free(buffer);
}
}
// TODO: Remove everything in this region when we can retarget and use the real
// Encoding.GetString(byte*, int) without reflection.
#region Light-Up
internal delegate string Encoding_GetString(Encoding encoding, byte* bytes, int byteCount); // only internal for test hook
private delegate string String_CreateStringFromEncoding(byte* bytes, int byteCount, Encoding encoding);
private static Encoding_GetString s_getStringPlatform = LoadGetStringPlatform(); // only non-readonly for test hook
public static string GetString(this Encoding encoding, byte* bytes, int byteCount)
{
Debug.Assert(encoding != null);
if (s_getStringPlatform == null)
{
return GetStringPortable(encoding, bytes, byteCount);
}
return s_getStringPlatform(encoding, bytes, byteCount);
}
private static unsafe string GetStringPortable(Encoding encoding, byte* bytes, int byteCount)
{
// This implementation can leak publicly (by design) to MetadataStringDecoder.GetString.
// Therefore we implement the same validation.
Debug.Assert(encoding != null); // validated by MetadataStringDecoder constructor.
if (bytes == null)
{
throw new ArgumentNullException("bytes");
}
if (byteCount < 0)
{
throw new ArgumentOutOfRangeException("byteCount");
}
byte[] buffer = AcquireBuffer(byteCount);
Marshal.Copy((IntPtr)bytes, buffer, 0, byteCount);
string result = encoding.GetString(buffer, 0, byteCount);
ReleaseBuffer(buffer);
return result;
}
private static Encoding_GetString LoadGetStringPlatform()
{
// .NET Framework 4.6+ and recent versions of other .NET platforms.
//
// Try to bind to Encoding.GetString(byte*, int);
MethodInfo getStringInfo = LightUpHelper.GetMethod(typeof(Encoding), "GetString", typeof(byte*), typeof(int));
if (getStringInfo != null && getStringInfo.ReturnType == typeof(String))
{
try
{
return (Encoding_GetString)getStringInfo.CreateDelegate(typeof(Encoding_GetString), null);
}
catch (MemberAccessException)
{
}
catch (InvalidOperationException)
{
// thrown when accessing unapproved API in a Windows Store app
}
}
// .NET Framework < 4.6
//
// Try to bind to String.CreateStringFromEncoding(byte*, int, Encoding)
//
// Note that this one is internal and GetRuntimeMethod only searches public methods, which accounts for the different
// pattern from above.
//
// NOTE: Another seeming equivalent is new string(sbyte*, int, Encoding), but don't be fooled. First of all, we can't get
// a delegate to a constructor. Worst than that, even if we could, it is actually about 4x slower than both of these
// and even the portable version (only ~20% slower than these) crushes it.
//
// It spends an inordinate amount of time transitioning to managed code from the VM and then lands in String.CreateString
// (note no FromEncoding suffix), which defensively copies to a new byte array on every call -- defeating the entire purpose
// of this class!
//
// For this reason, desktop callers should not implement an interner that falls back to the unsafe string ctor but instead
// return null and let us find the best decoding approach for the current platform.
//
// Yet another approach is to use new string('\0', GetCharCount) and use unsafe GetChars to fill it.
// However, on .NET < 4.6, there isn't no-op fast path for zero-initialization case so we'd slow down.
// Plus, mutating a System.String is no better than the reflection here.
IEnumerable<MethodInfo> createStringInfos = typeof(String).GetTypeInfo().GetDeclaredMethods("CreateStringFromEncoding");
foreach (var methodInfo in createStringInfos)
{
var parameters = methodInfo.GetParameters();
if (parameters.Length == 3
&& parameters[0].ParameterType == typeof(byte*)
&& parameters[1].ParameterType == typeof(int)
&& parameters[2].ParameterType == typeof(Encoding)
&& methodInfo.ReturnType == typeof(String))
{
try
{
var createStringFromEncoding = (String_CreateStringFromEncoding)methodInfo.CreateDelegate(typeof(String_CreateStringFromEncoding), null);
return (encoding, bytes, byteCount) => GetStringUsingCreateStringFromEncoding(createStringFromEncoding, bytes, byteCount, encoding);
}
catch (MemberAccessException)
{
}
catch (InvalidOperationException)
{
// thrown when accessing unapproved API in a Windows Store app
}
}
}
// Other platforms: Give up and fall back to GetStringPortable above.
return null;
}
private static unsafe string GetStringUsingCreateStringFromEncoding(
String_CreateStringFromEncoding createStringFromEncoding,
byte* bytes,
int byteCount,
Encoding encoding)
{
// String.CreateStringFromEncoding is an internal method that does not validate
// arguments, but this implementation can leak publicly (by design) via
// MetadataStringDecoder.GetString. Therefore, we implement the same validation
// that Encoding.GetString would do if it were available directly.
Debug.Assert(encoding != null); // validated by MetadataStringDecoder constructor.
if (bytes == null)
{
throw new ArgumentNullException("bytes");
}
if (byteCount < 0)
{
throw new ArgumentOutOfRangeException("byteCount");
}
return createStringFromEncoding(bytes, byteCount, encoding);
}
// Test hook to force portable implementation and ensure light is functioning.
internal static bool TestOnly_LightUpEnabled
{
get { return s_getStringPlatform != null; }
set { s_getStringPlatform = value ? LoadGetStringPlatform() : null; }
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsAzureCompositeModelClient
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// PolymorphicrecursiveOperations operations.
/// </summary>
internal partial class PolymorphicrecursiveOperations : IServiceOperations<AzureCompositeModel>, IPolymorphicrecursiveOperations
{
/// <summary>
/// Initializes a new instance of the PolymorphicrecursiveOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal PolymorphicrecursiveOperations(AzureCompositeModel client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AzureCompositeModel
/// </summary>
public AzureCompositeModel Client { get; private set; }
/// <summary>
/// Get complex types that are polymorphic and have recursive references
/// </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>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<FishInner>> GetValidWithHttpMessagesAsync(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("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphicrecursive/valid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, 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<FishInner>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<FishInner>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types that are polymorphic and have recursive references
/// </summary>
/// <param name='complexBody'>
/// Please put a salmon that looks like this:
/// {
/// "fishtype": "salmon",
/// "species": "king",
/// "length": 1,
/// "age": 1,
/// "location": "alaska",
/// "iswild": true,
/// "siblings": [
/// {
/// "fishtype": "shark",
/// "species": "predator",
/// "length": 20,
/// "age": 6,
/// "siblings": [
/// {
/// "fishtype": "salmon",
/// "species": "coho",
/// "length": 2,
/// "age": 2,
/// "location": "atlantic",
/// "iswild": true,
/// "siblings": [
/// {
/// "fishtype": "shark",
/// "species": "predator",
/// "length": 20,
/// "age": 6
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "length": 10,
/// "age": 105
/// }
/// ]
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "length": 10,
/// "age": 105
/// }
/// ]
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "length": 10,
/// "age": 105
/// }
/// ]
/// }
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutValidWithHttpMessagesAsync(FishInner complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (complexBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "complexBody");
}
if (complexBody != null)
{
complexBody.Validate();
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphicrecursive/valid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, 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;
}
}
}
| |
/*
* GZipStream.cs - Implementation of the
* "System.IO.Compression.GZipStream" class.
*
* Copyright (C) 2004 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.IO.Compression
{
#if CONFIG_COMPRESSION
using System;
using System.IO;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.GZip;
public class GZipStream : Stream
{
// Internal state.
private Stream stream;
private CompressionMode mode;
private bool leaveOpen;
private Inflater inflater;
private Deflater deflater;
private byte[] buf;
private Crc32 crc32;
private bool endOfStream;
private bool headerDone;
// Constructors.
public GZipStream(Stream stream, CompressionMode mode)
: this(stream, mode, false) {}
public GZipStream(Stream stream, CompressionMode mode, bool leaveOpen)
{
if(stream == null)
{
throw new ArgumentNullException("stream");
}
if(mode == CompressionMode.Decompress)
{
if(!stream.CanRead)
{
throw new ArgumentException
(S._("IO_NotReadable"), "stream");
}
}
else if(mode == CompressionMode.Compress)
{
if(!stream.CanWrite)
{
throw new ArgumentException
(S._("IO_NotWritable"), "stream");
}
}
else
{
throw new ArgumentException
(S._("IO_CompressionMode"), "mode");
}
this.stream = stream;
this.mode = mode;
this.leaveOpen = leaveOpen;
this.buf = new byte [4096];
this.crc32 = new Crc32();
this.endOfStream = false;
this.headerDone = false;
if(mode == CompressionMode.Decompress)
{
inflater = new Inflater(true);
}
else
{
deflater = new Deflater(-1, true);
}
}
// Get the base stream that underlies this one.
public Stream BaseStream
{
get
{
return stream;
}
}
// Determine if the stream supports reading, writing, or seeking.
public override bool CanRead
{
get
{
return (stream != null &&
mode == CompressionMode.Decompress);
}
}
public override bool CanWrite
{
get
{
return (stream != null &&
mode == CompressionMode.Compress);
}
}
public override bool CanSeek
{
get
{
return false;
}
}
// Get the length of the stream.
public override long Length
{
get
{
throw new NotSupportedException(S._("IO_NotSupp_Seek"));
}
}
// Get or set the current seek position within this stream.
public override long Position
{
get
{
throw new NotSupportedException(S._("IO_NotSupp_Seek"));
}
set
{
throw new NotSupportedException(S._("IO_NotSupp_Seek"));
}
}
// Begin an asynchronous read operation.
public override IAsyncResult BeginRead
(byte[] buffer, int offset, int count,
AsyncCallback callback, Object state)
{
if(stream == null)
{
throw new ObjectDisposedException
(S._("Exception_Disposed"));
}
if(mode != CompressionMode.Decompress)
{
throw new NotSupportedException(S._("IO_NotSupp_Read"));
}
return base.BeginRead(buffer, offset, count, callback, state);
}
// Wait for an asynchronous read operation to end.
public override int EndRead(IAsyncResult asyncResult)
{
return base.EndRead(asyncResult);
}
// Note: The .NET Framework SDK 2.0 version of this class does
// not have BeginWrite and EndWrite for some inexplicable reason.
// Close this stream.
public override void Close()
{
if(stream != null)
{
if(deflater != null)
{
int temp;
deflater.Finish();
while(!deflater.IsFinished)
{
temp = deflater.Deflate(buf, 0, buf.Length);
if(temp <= 0)
{
if(!deflater.IsFinished)
{
throw new IOException
(S._("IO_Compress_Input"));
}
break;
}
stream.Write(buf, 0, temp);
}
byte[] footer = new byte [8];
temp = (int)(crc32.Value);
footer[0] = (byte)temp;
footer[1] = (byte)(temp << 8);
footer[2] = (byte)(temp << 16);
footer[3] = (byte)(temp << 24);
temp = deflater.TotalIn;
footer[4] = (byte)temp;
footer[5] = (byte)(temp << 8);
footer[6] = (byte)(temp << 16);
footer[7] = (byte)(temp << 24);
stream.Write(footer, 0, 8);
}
if(!leaveOpen)
{
stream.Close();
}
stream = null;
inflater = null;
deflater = null;
buf = null;
}
}
// Flush this stream.
public override void Flush()
{
if(stream == null)
{
throw new ObjectDisposedException
(S._("Exception_Disposed"));
}
}
// Read a byte from the underlying stream and update a crc.
private int ReadByte(Crc32 crc)
{
int value = stream.ReadByte();
if(value >= 0)
{
crc.Update(value);
}
return value;
}
private int ReadByteThrow(Crc32 crc)
{
int value = stream.ReadByte();
if(value >= 0)
{
crc.Update(value);
return value;
}
throw new IOException(S._("IO_Decompress_GzipHeader"));
}
// Read the gzip header from the base stream.
private void ReadHeader()
{
Crc32 headerCrc = new Crc32();
int magic1, magic2, flags, temp;
// Validate the magic number.
magic1 = ReadByte(headerCrc);
if(magic1 < 0)
{
// The stream is empty, so just report EOF and exit.
endOfStream = true;
return;
}
magic2 = ReadByte(headerCrc);
if(magic2 < 0 ||
((magic1 << 8) + magic2) != GZipConstants.GZIP_MAGIC)
{
// The magic number does not match.
throw new IOException(S._("IO_Decompress_GzipHeader"));
}
// Check the compression type, which must be 8.
if(ReadByte(headerCrc) != 0x08)
{
throw new IOException(S._("IO_Decompress_GzipHeader"));
}
// Read the flags.
flags = ReadByte(headerCrc);
if((flags & 0xE0) != 0)
{
throw new IOException(S._("IO_Decompress_GzipHeader"));
}
// Skip the modification time, extra flags, and OS type.
for(temp = 0; temp < 6; ++temp)
{
ReadByteThrow(headerCrc);
}
// Skip the "extra" field.
if((flags & GZipConstants.FEXTRA) != 0)
{
// Get the length of the extra field.
temp = ReadByteThrow(headerCrc);
temp += (ReadByteThrow(headerCrc) << 8);
// Skip the extra field.
while(temp > 0)
{
ReadByteThrow(headerCrc);
--temp;
}
}
// Skip the "filename" field.
if((flags & GZipConstants.FNAME) != 0)
{
do
{
temp = ReadByteThrow(headerCrc);
}
while(temp != 0);
}
// Skip the "comment" field.
if((flags & GZipConstants.FCOMMENT) != 0)
{
do
{
temp = ReadByteThrow(headerCrc);
}
while(temp != 0);
}
// Read the header checksum.
if((flags & GZipConstants.FHCRC) != 0)
{
magic1 = stream.ReadByte();
if(magic1 < 0)
{
throw new IOException(S._("IO_Decompress_GzipHeader"));
}
temp = stream.ReadByte();
if(temp < 0)
{
throw new IOException(S._("IO_Decompress_GzipHeader"));
}
temp = magic1 + (temp << 8);
if(temp != (((int)(headerCrc.Value)) & 0xFFFF))
{
throw new IOException(S._("IO_Decompress_GzipHeader"));
}
}
// The header has been read, and we are ready to go.
headerDone = true;
}
// Read the gzip footer from the base stream.
private void ReadFooter()
{
int temp;
// Fetch 8 bytes from the input stream for the footer.
// We may need to reclaim them from the inflater.
byte[] footer = new byte [8];
int size = inflater.RemainingInput;
if(size > 8)
{
size = 8;
}
while(size < 8)
{
temp = stream.ReadByte();
if(temp < 0)
{
throw new IOException(S._("IO_Decompress_GzipFooter"));
}
footer[size++] = (byte)temp;
}
// Validate the checksum.
temp = footer[0] |
(footer[1] << 8) |
(footer[2] << 16) |
(footer[3] << 24);
if(temp != (int)(crc32.Value))
{
throw new IOException(S._("IO_Decompress_Checksum"));
}
// Validate the total byte counter.
temp = footer[4] |
(footer[5] << 8) |
(footer[6] << 16) |
(footer[7] << 24);
if(temp != inflater.TotalOut)
{
throw new IOException(S._("IO_Decompress_Total"));
}
// We have now reached the end of the stream.
endOfStream = true;
}
// Read data from this stream.
public override int Read(byte[] buffer, int offset, int count)
{
int temp;
if(stream == null)
{
throw new ObjectDisposedException
(S._("Exception_Disposed"));
}
if(mode != CompressionMode.Decompress)
{
throw new NotSupportedException(S._("IO_NotSupp_Read"));
}
DeflateStream.ValidateBuffer(buffer, offset, count);
if(!headerDone)
{
ReadHeader();
}
if(endOfStream)
{
return 0;
}
for(;;)
{
temp = inflater.Inflate(buffer, offset, count);
if(temp > 0)
{
crc32.Update(buffer, offset, temp);
if(inflater.IsFinished)
{
ReadFooter();
}
return temp;
}
if(inflater.IsNeedingDictionary)
{
throw new IOException
(S._("IO_Decompress_NeedDict"));
}
else if(inflater.IsFinished)
{
ReadFooter();
return 0;
}
else if(inflater.IsNeedingInput)
{
temp = stream.Read(buf, 0, buf.Length);
if(temp <= 0)
{
throw new IOException
(S._("IO_Decompress_Truncated"));
}
inflater.SetInput(buf, 0, temp);
}
else
{
throw new IOException
(S._("IO_Decompress_Invalid"));
}
}
}
// Seek to a new position within this stream.
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException(S._("IO_NotSupp_Seek"));
}
// Set the length of this stream.
public override void SetLength(long value)
{
throw new NotSupportedException(S._("IO_NotSupp_SetLength"));
}
// Write data to this stream.
public override void Write(byte[] buffer, int offset, int count)
{
int temp;
if(stream == null)
{
throw new ObjectDisposedException
(S._("Exception_Disposed"));
}
if(mode != CompressionMode.Compress)
{
throw new NotSupportedException(S._("IO_NotSupp_Write"));
}
DeflateStream.ValidateBuffer(buffer, offset, count);
if(!headerDone)
{
// Write the gzip header to the output stream.
stream.WriteByte(0x1F); // Magic number.
stream.WriteByte(0x8B);
stream.WriteByte(0x08); // Compression type.
stream.WriteByte(0x00); // Flags.
int secs = (int)((DateTime.UtcNow.Ticks /
TimeSpan.TicksPerSecond) -
62135596800L);
stream.WriteByte((byte)(secs & 0xFF));
stream.WriteByte((byte)((secs >> 8) & 0xFF));
stream.WriteByte((byte)((secs >> 16) & 0xFF));
stream.WriteByte((byte)((secs >> 24) & 0xFF));
stream.WriteByte(0x00); // Extra flags.
stream.WriteByte(0xFF); // OS type (unknown).
headerDone = true;
}
crc32.Update(buffer, offset, count);
deflater.SetInput(buffer, offset, count);
while(!deflater.IsNeedingInput)
{
temp = deflater.Deflate(buf, 0, buf.Length);
if(temp <= 0)
{
if(!deflater.IsNeedingInput)
{
throw new IOException(S._("IO_Compress_Input"));
}
break;
}
stream.Write(buf, 0, temp);
}
}
}; // class GZipStream
#endif // CONFIG_COMPRESSION
}; // namespace System.IO.Compression
| |
using System.Collections.Generic;
using System.Text;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AttributeSource = Lucene.Net.Util.AttributeSource;
using IBits = Lucene.Net.Util.IBits;
using BytesRef = Lucene.Net.Util.BytesRef;
/// <summary>
/// A <see cref="FilterAtomicReader"/> contains another <see cref="AtomicReader"/>, which it
/// uses as its basic source of data, possibly transforming the data along the
/// way or providing additional functionality. The class
/// <see cref="FilterAtomicReader"/> itself simply implements all abstract methods
/// of <see cref="IndexReader"/> with versions that pass all requests to the
/// contained index reader. Subclasses of <see cref="FilterAtomicReader"/> may
/// further override some of these methods and may also provide additional
/// methods and fields.
/// <para/><b>NOTE</b>: If you override <see cref="LiveDocs"/>, you will likely need
/// to override <see cref="NumDocs"/> as well and vice-versa.
/// <para/><b>NOTE</b>: If this <see cref="FilterAtomicReader"/> does not change the
/// content the contained reader, you could consider overriding
/// <see cref="IndexReader.CoreCacheKey"/> so that <see cref="Search.IFieldCache"/> and
/// <see cref="Search.CachingWrapperFilter"/> share the same entries for this atomic reader
/// and the wrapped one. <see cref="IndexReader.CombinedCoreAndDeletesKey"/> could be
/// overridden as well if the <see cref="LiveDocs"/> are not changed
/// either.
/// </summary>
public class FilterAtomicReader : AtomicReader
{
/// <summary>
/// Get the wrapped instance by <paramref name="reader"/> as long as this reader is
/// an intance of <see cref="FilterAtomicReader"/>.
/// </summary>
public static AtomicReader Unwrap(AtomicReader reader)
{
while (reader is FilterAtomicReader)
{
reader = ((FilterAtomicReader)reader).m_input;
}
return reader;
}
/// <summary>
/// Base class for filtering <see cref="Index.Fields"/>
/// implementations.
/// </summary>
public class FilterFields : Fields
{
/// <summary>
/// The underlying <see cref="Index.Fields"/> instance. </summary>
protected readonly Fields m_input;
/// <summary>
/// Creates a new <see cref="FilterFields"/>. </summary>
/// <param name="input"> the underlying <see cref="Index.Fields"/> instance. </param>
public FilterFields(Fields input)
{
this.m_input = input;
}
public override IEnumerator<string> GetEnumerator()
{
return m_input.GetEnumerator();
}
public override Terms GetTerms(string field)
{
return m_input.GetTerms(field);
}
public override int Count => m_input.Count;
}
/// <summary>
/// Base class for filtering <see cref="Terms"/> implementations.
/// <para/><b>NOTE</b>: If the order of terms and documents is not changed, and if
/// these terms are going to be intersected with automata, you could consider
/// overriding <see cref="Terms.Intersect"/> for better performance.
/// </summary>
public class FilterTerms : Terms
{
/// <summary>
/// The underlying <see cref="Terms"/> instance. </summary>
protected readonly Terms m_input;
/// <summary>
/// Creates a new <see cref="FilterTerms"/> </summary>
/// <param name="input"> the underlying <see cref="Terms"/> instance. </param>
public FilterTerms(Terms input)
{
this.m_input = input;
}
public override TermsEnum GetIterator(TermsEnum reuse)
{
return m_input.GetIterator(reuse);
}
public override IComparer<BytesRef> Comparer => m_input.Comparer;
public override long Count => m_input.Count;
public override long SumTotalTermFreq => m_input.SumTotalTermFreq;
public override long SumDocFreq => m_input.SumDocFreq;
public override int DocCount => m_input.DocCount;
public override bool HasFreqs => m_input.HasFreqs;
public override bool HasOffsets => m_input.HasOffsets;
public override bool HasPositions => m_input.HasPositions;
public override bool HasPayloads => m_input.HasPayloads;
}
/// <summary>
/// Base class for filtering <see cref="TermsEnum"/> implementations. </summary>
public class FilterTermsEnum : TermsEnum
{
/// <summary>
/// The underlying <see cref="TermsEnum"/> instance. </summary>
protected internal readonly TermsEnum m_input;
/// <summary>
/// Creates a new <see cref="FilterTermsEnum"/> </summary>
/// <param name="input"> the underlying <see cref="TermsEnum"/> instance. </param>
public FilterTermsEnum(TermsEnum input)
{
this.m_input = input;
}
public override AttributeSource Attributes => m_input.Attributes;
public override SeekStatus SeekCeil(BytesRef text)
{
return m_input.SeekCeil(text);
}
public override void SeekExact(long ord)
{
m_input.SeekExact(ord);
}
public override BytesRef Next()
{
return m_input.Next();
}
public override BytesRef Term => m_input.Term;
public override long Ord => m_input.Ord;
public override int DocFreq => m_input.DocFreq;
public override long TotalTermFreq => m_input.TotalTermFreq;
public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags)
{
return m_input.Docs(liveDocs, reuse, flags);
}
public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags)
{
return m_input.DocsAndPositions(liveDocs, reuse, flags);
}
public override IComparer<BytesRef> Comparer => m_input.Comparer;
}
/// <summary>
/// Base class for filtering <see cref="DocsEnum"/> implementations. </summary>
public class FilterDocsEnum : DocsEnum
{
/// <summary>
/// The underlying <see cref="DocsEnum"/> instance.
/// </summary>
protected internal DocsEnum m_input;
/// <summary>
/// Create a new <see cref="FilterDocsEnum"/> </summary>
/// <param name="input"> the underlying <see cref="DocsEnum"/> instance. </param>
public FilterDocsEnum(DocsEnum input)
{
this.m_input = input;
}
public override AttributeSource Attributes => m_input.Attributes;
public override int DocID => m_input.DocID;
public override int Freq => m_input.Freq;
public override int NextDoc()
{
return m_input.NextDoc();
}
public override int Advance(int target)
{
return m_input.Advance(target);
}
public override long GetCost()
{
return m_input.GetCost();
}
}
/// <summary>
/// Base class for filtering <see cref="DocsAndPositionsEnum"/> implementations. </summary>
public class FilterDocsAndPositionsEnum : DocsAndPositionsEnum
{
/// <summary>
/// The underlying <see cref="DocsAndPositionsEnum"/> instance. </summary>
protected internal readonly DocsAndPositionsEnum m_input;
/// <summary>
/// Create a new <see cref="FilterDocsAndPositionsEnum"/> </summary>
/// <param name="input"> the underlying <see cref="DocsAndPositionsEnum"/> instance. </param>
public FilterDocsAndPositionsEnum(DocsAndPositionsEnum input)
{
this.m_input = input;
}
public override AttributeSource Attributes => m_input.Attributes;
public override int DocID => m_input.DocID;
public override int Freq => m_input.Freq;
public override int NextDoc()
{
return m_input.NextDoc();
}
public override int Advance(int target)
{
return m_input.Advance(target);
}
public override int NextPosition()
{
return m_input.NextPosition();
}
public override int StartOffset => m_input.StartOffset;
public override int EndOffset => m_input.EndOffset;
public override BytesRef GetPayload()
{
return m_input.GetPayload();
}
public override long GetCost()
{
return m_input.GetCost();
}
}
/// <summary>
/// The underlying <see cref="AtomicReader"/>. </summary>
protected readonly AtomicReader m_input;
/// <summary>
/// Construct a <see cref="FilterAtomicReader"/> based on the specified base reader.
/// <para/>
/// Note that base reader is closed if this <see cref="FilterAtomicReader"/> is closed.
/// </summary>
/// <param name="input"> specified base reader. </param>
public FilterAtomicReader(AtomicReader input)
: base()
{
this.m_input = input;
input.RegisterParentReader(this);
}
public override IBits LiveDocs
{
get
{
EnsureOpen();
return m_input.LiveDocs;
}
}
public override FieldInfos FieldInfos => m_input.FieldInfos;
public override Fields GetTermVectors(int docID)
{
EnsureOpen();
return m_input.GetTermVectors(docID);
}
public override int NumDocs =>
// Don't call ensureOpen() here (it could affect performance)
m_input.NumDocs;
public override int MaxDoc =>
// Don't call ensureOpen() here (it could affect performance)
m_input.MaxDoc;
public override void Document(int docID, StoredFieldVisitor visitor)
{
EnsureOpen();
m_input.Document(docID, visitor);
}
protected internal override void DoClose()
{
m_input.Dispose();
}
public override Fields Fields
{
get
{
EnsureOpen();
return m_input.Fields;
}
}
public override string ToString()
{
StringBuilder buffer = new StringBuilder("FilterAtomicReader(");
buffer.Append(m_input);
buffer.Append(')');
return buffer.ToString();
}
public override NumericDocValues GetNumericDocValues(string field)
{
EnsureOpen();
return m_input.GetNumericDocValues(field);
}
public override BinaryDocValues GetBinaryDocValues(string field)
{
EnsureOpen();
return m_input.GetBinaryDocValues(field);
}
public override SortedDocValues GetSortedDocValues(string field)
{
EnsureOpen();
return m_input.GetSortedDocValues(field);
}
public override SortedSetDocValues GetSortedSetDocValues(string field)
{
EnsureOpen();
return m_input.GetSortedSetDocValues(field);
}
public override NumericDocValues GetNormValues(string field)
{
EnsureOpen();
return m_input.GetNormValues(field);
}
public override IBits GetDocsWithField(string field)
{
EnsureOpen();
return m_input.GetDocsWithField(field);
}
public override void CheckIntegrity()
{
EnsureOpen();
m_input.CheckIntegrity();
}
}
}
| |
// Reference: Newtonsoft.Json
using System.Collections.Generic;
using System;
using System.Reflection;
using System.Data;
using UnityEngine;
using Newtonsoft.Json;
using Oxide.Core;
using Oxide.Core.Libraries;
using Oxide.Core.Plugins;
using Oxide.Game.Rust.Libraries;
namespace Oxide.Plugins
{
[Info("Sky Event", "DannieHansenWeb", 0.1)]
class SkyEvent : RustPlugin
{
public Core.Configuration.DynamicConfigFile eventData;
private Timer EventLobbyTimer;
private Timer EventTimer;
private Timer EventLobbyTimerEnd;
private Timer EventPlayerCheckTimer;
private Timer EventUICounter;
private Timer EventUIBlockCounter;
public Dictionary<Vector3, List<EventBlockWall>> spawnMapping;
public Boolean EventLobby = false;
public Boolean EventStarted = false;
public Boolean EventActive = false;
public Boolean EventWinnerFound = false;
public GameObject wallPrefab;
public GameObject floorPrefab;
public int arenaSize = 20;
public int lobbyNext = 0;
public int lastPlayerCount = 0;
public List<object> eventPlayers = new List<object>();
public List<object> eventBlocks = new List<object>();
public int EventY = 400;
public List<Vector3> spawns;
public string suffix = "[SkyEvent]";
public string suffix_color = "#B000B0";
public string text_color = "#b48bb5";
#region JSON
const string counterJson = @"[
{
""name"": ""SkyEventCounter"",
""fadeOut"": ""0.25"",
""components"":
[
{
""type"":""UnityEngine.UI.Text"",
""text"":""{CounterText}"",
""fontSize"":32,
""align"": ""MiddleCenter"",
},
{
""type"":""RectTransform"",
""anchormin"": ""0 0.5"",
""anchormax"": ""1 0.9""
}
]
}
]";
const string countDownJson = @"[
{
""name"": ""SkyEventCountDown"",
""components"":
[
{
""type"":""UnityEngine.UI.Text"",
""text"":""Players left: {PlayerCount}"",
""fontSize"":16,
""align"": ""MiddleCenter"",
},
{
""type"":""RectTransform"",
""anchormin"": ""0 0.2"",
""anchormax"": ""1 1""
}
]
}
]";
const string winnerJson = @"[
{
""name"": ""SkyEventWinner"",
""fadeOut"": ""0.25"",
""components"":
[
{
""type"":""UnityEngine.UI.Text"",
""text"":""You won the event! Check chat for more info on how to claim your reward"",
""fontSize"":18,
""align"": ""MiddleCenter"",
},
{
""type"":""RectTransform"",
""anchormin"": ""0 0.5"",
""anchormax"": ""1 0.9""
}
]
}
]";
#endregion
#region Mono extensions
public class EventPlayerTeleporting : MonoBehaviour
{
}
public class EventFloor : MonoBehaviour
{
public int position = 1; // 1: up & 2: down
public int state = 0; // 0: default, 1: down & 2: damaged
private Vector3 nativePosition;
public EventFloor()
{
Vector3 currPoS = GetComponent<BuildingBlock>().gameObject.transform.position;
nativePosition = new Vector3(currPoS.x, currPoS.y, currPoS.z);
}
public void sendToOriginal()
{
GetComponent<BuildingBlock>().gameObject.transform.position = nativePosition;
}
}
public class EventWinner : MonoBehaviour
{
public int amount = -1;
public EventWinner()
{
List<int> amounts = new List<int>();
amounts.Add(1);
amounts.Add(2);
amounts.Add(3);
amounts.Add(4);
this.amount = amounts.GetRandom<int>();
amounts = null;
}
}
public class EventBlock : MonoBehaviour
{
}
public class EventBlockWall : MonoBehaviour
{
public int position = 1; // 1: up & 2: down
}
class EventPlayer : MonoBehaviour
{
public Vector3 home;
public BasePlayer player;
public Boolean teleportingOut = false;
public EventPlayer()
{
this.player = GetComponent<BasePlayer>();
}
}
#endregion
#region Player Methods
public void PrintChat(BasePlayer player, string message)
{
PrintToChat(player, string.Format("<color={0}>{1}</color> <color={2}>{3}</color>", this.suffix_color, this.suffix, this.text_color, message));
}
public void PrintChat(string message)
{
PrintToChat(string.Format("<color={0}>{1}</color> <color={2}>{3}</color>", this.suffix_color, this.suffix, this.text_color, message));
}
public void Awake(BasePlayer player)
{
if (player.IsSleeping())
{
player.EndSleeping();
}
}
void TeleportPlayerPosition(BasePlayer player, Vector3 destination)
{
player.gameObject.AddComponent<EventPlayerTeleporting>();
player.SetPlayerFlag(BasePlayer.PlayerFlags.Sleeping, true);
if (!BasePlayer.sleepingPlayerList.Contains(player)) BasePlayer.sleepingPlayerList.Add(player);
player.CancelInvoke("InventoryUpdate");
player.inventory.crafting.CancelAll(true);
player.MovePosition(destination);
player.ClientRPCPlayer(null, player, "ForcePositionTo", destination, null, null, null, null);
player.TransformChanged();
player.SetPlayerFlag(BasePlayer.PlayerFlags.ReceivingSnapshot, true);
player.UpdateNetworkGroup();
player.SendNetworkUpdateImmediate(false);
player.ClientRPCPlayer(null, player, "StartLoading", null, null, null, null, null);
player.SendFullSnapshot();
timer.Once(3, () =>
{
UnityEngine.GameObject.Destroy(player.gameObject.GetComponent<EventPlayerTeleporting>());
});
}
#endregion
#region Hooks
private object OnAttackShared(BasePlayer attacker, BasePlayer victim, ref HitInfo hit)
{
if (victim.GetComponent<EventPlayerTeleporting>() != null)
{
hit.damageTypes = new Rust.DamageTypeList();
hit.HitMaterial = 0;
hit.PointStart = Vector3.zero;
victim.metabolism.bleeding.Reset();
return false;
}
if (!EventLobby && eventPlayers.Count > 0 && victim.GetComponent<EventPlayer>() == null)
{
hit.damageTypes = new Rust.DamageTypeList();
hit.HitMaterial = 0;
hit.PointStart = Vector3.zero;
victim.metabolism.bleeding.Reset();
return false;
}
return true;
}
[HookMethod("OnPlayerAttack")]
void OnPlayerAttack(BasePlayer attacker, HitInfo hit)
{
if (attacker.GetComponent<EventPlayerTeleporting>() != null)
{
hit.damageTypes = new Rust.DamageTypeList();
hit.HitMaterial = 0;
hit.PointStart = Vector3.zero;
attacker.metabolism.bleeding.Reset();
return;
}
if (!EventLobby && eventPlayers.Count > 0)
{
if (hit.HitEntity is BasePlayer)
{
OnAttackShared(attacker, hit.HitEntity as BasePlayer, ref hit);
}
}
}
[HookMethod("OnEntityTakeDamage")]
void OnEntityTakeDamage(BaseCombatEntity entity, ref HitInfo hit)
{
if (entity is BuildingBlock)
{
// Building being attacked? Which one?
EventBlock event_block = entity.GetComponent<EventBlock>();
if (event_block != null)
{
hit.damageTypes = new Rust.DamageTypeList();
hit.HitMaterial = 0;
hit.PointStart = Vector3.zero;
}
}
if (entity.GetComponent<EventPlayerTeleporting>() != null)
{
hit.damageTypes = new Rust.DamageTypeList();
hit.HitMaterial = 0;
hit.PointStart = Vector3.zero;
entity.GetComponent<BasePlayer>().metabolism.bleeding.Reset();
}
if (!EventLobby && eventPlayers.Count > 0 && entity is BasePlayer)
{
if (entity is BasePlayer && hit.Initiator is BasePlayer && hit.Initiator.GetComponent<EventPlayer>() != null)
{
OnAttackShared(hit.Initiator as BasePlayer, entity as BasePlayer, ref hit);
}
else if (entity is BasePlayer && !(hit.Initiator is BasePlayer) && entity.GetComponent<EventPlayer>() != null)
{
hit.damageTypes = new Rust.DamageTypeList();
hit.HitMaterial = 0;
hit.PointStart = Vector3.zero;
entity.GetComponent<BasePlayer>().metabolism.bleeding.Reset();
}
}
}
[HookMethod("CanBeWounded")]
bool CanBeWounded(BasePlayer player, HitInfo hit)
{
if (player.GetComponent<EventPlayerTeleporting>() != null)
{
hit.damageTypes = new Rust.DamageTypeList();
hit.HitMaterial = 0;
hit.PointStart = Vector3.zero;
player.metabolism.bleeding.Reset();
return false;
}
if (player.GetComponent<EventPlayer>() != null && !EventLobby && eventPlayers.Count > 0)
{
hit.damageTypes = new Rust.DamageTypeList();
hit.HitMaterial = 0;
hit.PointStart = Vector3.zero;
player.metabolism.bleeding.Reset();
return false;
}
return true;
}
[HookMethod("CanLootPlayer")]
bool CanLootPlayer(BasePlayer player, BasePlayer target)
{
if ((player.GetComponent<EventPlayer>() != null || player.GetComponent<EventPlayerTeleporting>() != null) && !EventLobby && eventPlayers.Count > 0)
{
return false;
}
return true;
}
#endregion
#region Plugin register
void Loaded()
{
fetchConfigs();
}
void Unload()
{
clearGUI();
if (EventStarted)
{
eventTransferPlayersFrom();
}
clearEventPlayers();
clearEventBlocks();
clearTimers();
}
void OnServerInitialized()
{
wallPrefab = GameManager.server.FindPrefab("assets/prefabs/building core/wall/wall.prefab");
floorPrefab = GameManager.server.FindPrefab("assets/prefabs/building core/floor/floor.prefab");
spawnSkyEvent();
loadEventLobbyTimer();
}
#endregion
#region Cleanup
void clearGUI()
{
foreach (EventPlayer gameObj in eventPlayers)
{
if (gameObj != null)
{
CommunityEntity.ServerInstance.ClientRPCEx(
new Network.SendInfo(gameObj.player.net.connection),
null,
"DestroyUI",
new Facepunch.ObjectList("SkyEventCounter", null, null, null, null)
);
CommunityEntity.ServerInstance.ClientRPCEx(
new Network.SendInfo(gameObj.player.net.connection),
null,
"DestroyUI",
new Facepunch.ObjectList("SkyEventCountDown", null, null, null, null)
);
CommunityEntity.ServerInstance.ClientRPCEx(
new Network.SendInfo(gameObj.player.net.connection),
null,
"DestroyUI",
new Facepunch.ObjectList("SkyEventWinner", null, null, null, null)
);
}
}
}
void clearGUI(BasePlayer player)
{
CommunityEntity.ServerInstance.ClientRPCEx(
new Network.SendInfo(player.net.connection),
null,
"DestroyUI",
new Facepunch.ObjectList("SkyEventCounter", null, null, null, null)
);
CommunityEntity.ServerInstance.ClientRPCEx(
new Network.SendInfo(player.net.connection),
null,
"DestroyUI",
new Facepunch.ObjectList("SkyEventCountDown", null, null, null, null)
);
}
void clearEventPlayers()
{
foreach (EventPlayer gameObj in eventPlayers)
{
if (gameObj != null)
{
UnityEngine.GameObject.Destroy(gameObj);
}
}
eventPlayers.Clear();
}
void clearEventBlocks()
{
foreach (EventBlock gameObj in eventBlocks)
{
if (gameObj != null)
{
BuildingBlock block = gameObj.GetComponent<BuildingBlock>();
if (block != null)
{
//block.Kill(BaseNetworkable.DestroyMode.Gib);
block.Kill();
}
else
{
BaseEntity entity = gameObj.GetComponent<BaseEntity>();
if (entity != null)
{
//entity.Kill(BaseNetworkable.DestroyMode.Gib);
entity.Kill();
}
}
}
}
eventBlocks.Clear();
}
void clearEventPlayersForced()
{
if (BasePlayer.activePlayerList.Count > 0)
{
foreach (BasePlayer player in BasePlayer.activePlayerList)
{
if (player != null) {
EventPlayer event_player = player.GetComponent<EventPlayer>();
if (event_player != null)
{
UnityEngine.GameObject.Destroy(event_player);
}
}
}
}
eventPlayers.Clear();
}
void clearEventWalls()
{
foreach (EventBlock block in eventBlocks)
{
if (block != null)
{
EventBlockWall block_wall = block.GetComponent<EventBlockWall>();
if (block_wall != null && block_wall.position == 2)
{
block_wall.position = 1;
BuildingBlock buildingBlock = block.GetComponent<BuildingBlock>();
if (buildingBlock != null)
{
buildingBlock.gameObject.transform.position = new Vector3(block.gameObject.transform.position.x, block.gameObject.transform.position.y + 500, block.gameObject.transform.position.z);
buildingBlock.SendNetworkUpdate(BasePlayer.NetworkQueue.Update);
//block.GetComponent<BuildingBlock>().Kill(BaseNetworkable.DestroyMode.Gib);
}
}
}
}
EventPlayerCheckTimer = timer.Repeat(1, 0, () => checkPlayerFall());
EventTimer = timer.Repeat(float.Parse(eventData["timer", "tick-timer"].ToString()), 0, () => eventTick());
}
void eventCleanupForced()
{
clearEventPlayersForced();
//clearEventBlocks();
EventActive = false;
EventLobby = false;
EventStarted = false;
loadEventLobbyTimer();
}
#endregion
void fetchConfigs()
{
eventData = Interface.GetMod().DataFileSystem.GetDatafile("SkyEvent");
eventData["timer", "lobby"] = 30f;
eventData["timer", "lobby-end"] = 2f;
eventData["timer", "tick-timer"] = 1f;
eventData["timer", "tick-count"] = 8;
if (eventData["players", "min"] == null)
{
eventData["players", "min"] = 5;
}
}
void loadEventLobbyTimer()
{
clearTimers();
if (EventLobbyTimer != null)
{
EventLobbyTimer.Destroy();
}
TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
this.lobbyNext = (int)t.TotalSeconds + (Convert.ToInt16(eventData["timer", "lobby"].ToString()) * 60);
EventLobbyTimer = timer.Repeat((float.Parse(eventData["timer", "lobby"].ToString()) * 60), 0, () => eventOpenLobby(false));
}
void eventOpenLobby(bool ignoreMinPlayers)
{
lastPlayerCount = -1;
EventWinnerFound = false;
loadEventLobbyTimer();
clearEventPlayersForced();
moveSkyEventDown();
EventLobby = true;
EventStarted = false;
EventActive = false;
PrintChat("The lobby is now open - type <color=color=DC143C>'/sky join'</color> in order to join the event.");
PrintChat("Lobby will be open for 2 minutes.");
timer.Once((1 * 60), () =>
{
int minPlayers = Convert.ToInt16(eventData["players", "min"].ToString());
if (ignoreMinPlayers)
{
minPlayers = 1;
}
if (minPlayers <= eventPlayers.Count)
{
PrintChat(string.Format("Lobby will be open for 1 more minute. If you wish to join in, write <color=DC143C>'/sky join'</color>"));
}
else
{
PrintChat(string.Format("Lobby will be open for 1 more minute. Hurry up! We need {0} more player(s)!", (minPlayers - eventPlayers.Count)));
}
});
if (EventLobbyTimerEnd != null)
{
EventLobbyTimerEnd.Destroy();
}
EventLobbyTimerEnd = timer.Once((float.Parse(eventData["timer", "lobby-end"].ToString()) * 60), () => eventBegin(ignoreMinPlayers));
}
List<EventFloor> getEventFloors()
{
List<EventFloor> list = new List<EventFloor>();
foreach (EventBlock block in eventBlocks)
{
if (block != null)
{
EventFloor floor = block.GetComponent<EventFloor>();
if (floor != null)
{
list.Add(floor);
}
}
}
return list;
}
List<EventFloor> fetchUniqueFloor(int count, List<EventFloor> items)
{
List<EventFloor> list = new List<EventFloor>();
for (int i = 0; i < count; i++ )
{
EventFloor floor = null;
int ran = 0;
while (floor == null && ran < 50) {
EventFloor thisFloor = items.GetRandom<EventFloor>();
if (thisFloor != null && (thisFloor.state == 1 || thisFloor.state == 2) && list.IndexOf(thisFloor) == -1)
{
floor = thisFloor;
}
else
{
thisFloor = null;
}
ran++;
}
if (floor != null)
{
list.Add(floor);
}
}
return list;
}
void eventTick()
{
if (!EventWinnerFound)
{
int tickCount = Convert.ToInt16(eventData["timer", "tick-count"].ToString());
if (eventBlocks.Count > 0)
{
List<EventFloor> floorList = getEventFloors();
List<EventFloor> floors = fetchUniqueFloor(tickCount, floorList);
if (floors.Count == 0)
{
if (EventTimer != null)
{
EventTimer.Destroy();
return;
}
}
foreach (EventFloor floor in floors)
{
if (floor == null)
{
continue;
}
BuildingBlock buildBlock = floor.GetComponent<BuildingBlock>();
//buildBlock.health -= 250f;
//if (buildBlock.health <= 0)
//{
// buildBlock.Die();
//}
//floor.position = 2;
if (floor.state == 1)
{
floor.state = 2;
buildBlock.gameObject.transform.position = new Vector3(
buildBlock.gameObject.transform.position.x,
buildBlock.gameObject.transform.position.y - 0.5f,
buildBlock.gameObject.transform.position.z
);
}
else
{
floor.state = 0;
floor.sendToOriginal();
}
buildBlock.SendNetworkUpdateImmediate(false);
}
}
}
}
void eventTransferPlayersTo()
{
List<Vector3> spawnsCopy = new List<Vector3>(spawns);
foreach (EventPlayer gameObj in eventPlayers)
{
if (gameObj != null)
{
gameObj.home = gameObj.player.transform.position;
Vector3 spawn = spawnsCopy.GetRandom<Vector3>();
spawnsCopy.Remove(spawn);
sendWallsDown(spawn);
Vector3 teleportLocation = new Vector3(
spawn.x,
spawn.y + 3,
spawn.z
);
TeleportPlayerPosition(gameObj.player, teleportLocation);
}
}
}
void eventTransferPlayersFrom()
{
foreach (EventPlayer gameObj in eventPlayers)
{
if (gameObj != null)
{
if (!gameObj.teleportingOut && gameObj.home != null)
{
gameObj.teleportingOut = true;
TeleportPlayerPosition(gameObj.player, gameObj.home);
}
}
}
}
void clearTimers()
{
if (EventTimer != null)
{
EventTimer.Destroy();
}
if (EventLobbyTimerEnd != null)
{
EventLobbyTimerEnd.Destroy();
}
if (EventPlayerCheckTimer != null)
{
EventPlayerCheckTimer.Destroy();
}
if (EventUICounter != null)
{
EventUICounter.Destroy();
}
if (EventUIBlockCounter != null)
{
EventUIBlockCounter.Destroy();
}
}
void eventBegin(bool ignoreMinPlayers)
{
int minPlayers = Convert.ToInt16(eventData["players", "min"].ToString());
if (ignoreMinPlayers)
{
minPlayers = 1;
}
if (eventPlayers.Count >= minPlayers)
{
PrintChat("Lobby ended. The event is starting!");
EventLobby = false;
EventStarted = true;
EventActive = false;
clearTimers();
foreach (EventPlayer gameObj in eventPlayers.ToArray())
{
if (gameObj != null)
{
if (gameObj.player.IsSleeping() || gameObj.player.IsWounded() || gameObj.player.IsDead())
{
EventLeave(gameObj.player);
}
}
}
timer.Once(1, () =>
{
eventTransferPlayersTo();
int count = 30;
if (EventUICounter != null)
{
EventUICounter.Destroy();
}
if (EventUIBlockCounter != null)
{
EventUIBlockCounter.Destroy();
}
EventUICounter = timer.Repeat(1, 30, () =>
{
count--;
foreach (EventPlayer gameObj in eventPlayers.ToArray())
{
if (gameObj != null)
{
CommunityEntity.ServerInstance.ClientRPCEx(
new Network.SendInfo(gameObj.player.net.connection),
null,
"DestroyUI",
new Facepunch.ObjectList("SkyEventCounter", null, null, null, null)
);
CommunityEntity.ServerInstance.ClientRPCEx(
new Network.SendInfo(gameObj.player.net.connection),
null,
"AddUI",
new Facepunch.ObjectList(counterJson.Replace("{CounterText}", (count == 0 ? "GO!" : count.ToString())), null, null, null, null)
);
}
}
if (count == 0)
{
clearEventWalls();
EventActive = true;
foreach (EventPlayer gameObj in eventPlayers.ToArray())
{
if (gameObj != null)
{
if (gameObj.player.IsSleeping() || gameObj.player.IsWounded())
{
EventLeave(gameObj.player);
}
}
}
timer.Once(1, () =>
{
foreach (EventPlayer gameObj in eventPlayers.ToArray())
{
if (gameObj != null)
{
CommunityEntity.ServerInstance.ClientRPCEx(
new Network.SendInfo(gameObj.player.net.connection),
null,
"DestroyUI",
new Facepunch.ObjectList("SkyEventCounter", null, null, null, null)
);
}
}
EventUIBlockCounter = timer.Repeat(1, 0, () =>
{
int lastSeenPlayerCount = 0;
foreach (EventPlayer gameObj in eventPlayers.ToArray())
{
if (gameObj != null)
{
if (EventActive && !gameObj.teleportingOut && !gameObj.player.IsSleeping() && gameObj.player.transform.position.y > (EventY - 10))
{
lastSeenPlayerCount++;
}
else
{
if (eventPlayers.Count == 1)
{
lastSeenPlayerCount = 1;
}
}
}
}
if (lastSeenPlayerCount != lastPlayerCount)
{
lastPlayerCount = lastSeenPlayerCount;
foreach (EventPlayer gameObj in eventPlayers.ToArray())
{
if (gameObj != null)
{
CommunityEntity.ServerInstance.ClientRPCEx(
new Network.SendInfo(gameObj.player.net.connection),
null,
"DestroyUI",
new Facepunch.ObjectList("SkyEventCountDown", null, null, null, null)
);
CommunityEntity.ServerInstance.ClientRPCEx(
new Network.SendInfo(gameObj.player.net.connection),
null,
"AddUI",
new Facepunch.ObjectList(countDownJson.Replace("{PlayerCount}", lastSeenPlayerCount.ToString()), null, null, null, null)
);
}
}
}
});
});
}
});
});
}
else
{
clearEventPlayersForced();
timer.Once(1, () =>
{
eventEnd();
});
PrintChat("Lobby ended. There wasn't enough players for the event to start.");
}
}
int getEventFloorsCount()
{
int EventFloors = 0;
foreach (EventBlock block in eventBlocks)
{
if (block != null)
{
if (block.GetComponent<EventFloor>() != null)
{
EventFloors++;
}
}
}
return EventFloors;
}
void checkPlayerFall()
{
if (!EventWinnerFound)
{
List<EventPlayer> players = new List<EventPlayer>();
foreach (EventPlayer gameObj in eventPlayers)
{
if (gameObj != null)
{
if (EventActive && !gameObj.teleportingOut && !gameObj.player.IsSleeping() && gameObj.player.transform.position.y <= (EventY - 10))
{
players.Add(gameObj);
}
}
}
if (players.Count > 0)
{
foreach (EventPlayer player in players)
{
EventLeave(player.player);
}
}
}
}
void eventEnd()
{
moveSkyEventUp();
//clearEventBlocks();
EventLobby = false;
EventStarted = false;
clearTimers();
}
void OnPlayerDisconnected(BasePlayer player)
{
if (player.GetComponent<EventPlayer>() != null)
{
EventLeave(player);
}
}
void EventLeave(BasePlayer player)
{
EventPlayer event_player = player.GetComponent<EventPlayer>();
if (event_player != null && !event_player.teleportingOut)
{
TeleportPlayerPosition(event_player.player, event_player.home);
event_player.teleportingOut = true;
clearGUI(player);
timer.Once(1, () =>
{
clearGUI(player);
});
eventPlayers.Remove(event_player);
timer.Once(4, () =>
{
UnityEngine.GameObject.Destroy(event_player);
clearGUI(player);
});
}
eventWinnerCheck(player);
}
void weGotaWinner(BasePlayer pPlayer)
{
EventWinnerFound = true;
EventPlayer event_player = pPlayer.GetComponent<EventPlayer>();
if (event_player != null && !event_player.teleportingOut)
{
TeleportPlayerPosition(event_player.player, event_player.home);
timer.Once(4, () =>
{
UnityEngine.GameObject.Destroy(event_player);
clearGUI(pPlayer);
});
}
EventWinner event_winner = pPlayer.gameObject.AddComponent<EventWinner>();
clearGUI(pPlayer);
eventEnd();
eventData["winner", "name"] = pPlayer.displayName;
eventData["winner", "amount"] = event_winner.amount.ToString();
PrintChat("We got a winner!");
PrintChat(string.Format("'{0}' won {1} supply signal(s)", pPlayer.displayName, event_winner.amount));
PrintChat(pPlayer, "To claim your reward, type /sky reward");
CommunityEntity.ServerInstance.ClientRPCEx(
new Network.SendInfo(pPlayer.net.connection),
null,
"DestroyUI",
new Facepunch.ObjectList("SkyEventWinner", null, null, null, null)
);
CommunityEntity.ServerInstance.ClientRPCEx(
new Network.SendInfo(pPlayer.net.connection),
null,
"AddUI",
new Facepunch.ObjectList(winnerJson, null, null, null, null)
);
timer.Once(15, () =>
{
CommunityEntity.ServerInstance.ClientRPCEx(
new Network.SendInfo(pPlayer.net.connection),
null,
"DestroyUI",
new Facepunch.ObjectList("SkyEventWinner", null, null, null, null)
);
});
}
void eventWinnerCheck(BasePlayer player)
{
if (!EventWinnerFound)
{
if (eventPlayers.Count == 1)
{
weGotaWinner(((EventPlayer)eventPlayers[0]).player);
}
else if (eventPlayers.Count == 0)
{
weGotaWinner(player);
}
}
}
EventPlayer GetEventPlayerByBasePlayer(BasePlayer player)
{
foreach (EventPlayer obj in eventPlayers)
{
if (obj != null && player.Equals(obj.player))
{
return obj;
}
}
return null;
}
void EventCommandLeave(BasePlayer pPlayer)
{
EventPlayer event_player = pPlayer.GetComponent<EventPlayer>();
if (event_player && event_player != null)
{
if (EventStarted)
{
EventLeave(event_player.player);
}
else
{
UnityEngine.GameObject.Destroy(event_player);
eventPlayers.Remove(event_player);
}
PrintChat(pPlayer, "You left the event");
}
else
{
PrintChat(pPlayer, "You're not currently in the event");
}
}
void EventJoin(BasePlayer pPlayer)
{
if (pPlayer.gameObject != null)
{
if (!EventLobby && !EventStarted)
{
PrintChat(pPlayer, "There is no active event");
return;
}
if (!EventLobby && EventStarted)
{
PrintChat(pPlayer, "Lobby has been closed. Please wait for event to re-open");
return;
}
if (EventLobby && !EventStarted)
{
if (pPlayer.GetComponent<EventPlayer>() != null)
{
PrintChat(pPlayer, "Already in lobby");
return;
}
if (pPlayer.GetComponent<EventPlayer>() == null)
{
EventPlayer event_player = pPlayer.gameObject.AddComponent<EventPlayer>();
eventPlayers.Add(event_player);
}
else
{
eventPlayers.Add(pPlayer.GetComponent<EventPlayer>());
}
PrintChat(pPlayer, "You joined the event queue");
}
}
}
void EventReward(BasePlayer player)
{
EventWinner winner = player.GetComponent<EventWinner>();
if (winner != null)
{
clearGUI(player);
player.GiveItem(ItemManager.CreateByPartialName("supply.signal", winner.amount));
UnityEngine.GameObject.Destroy(winner);
PrintChat(player, "Your reward has been added to your inventory.");
}
else
{
PrintChat(player, "You haven't won the event.");
}
}
[ChatCommand("sky")]
void cmdChatSky(BasePlayer player, string command, string[] args)
{
if (args.Length > 0)
{
if (args[0] == "join")
{
EventJoin(player);
}
else if (args[0] == "leave")
{
EventCommandLeave(player);
}
else if (args[0] == "info")
{
skyInfo(player);
}
else if (args[0] == "reward")
{
EventReward(player);
}
else if (args[0] == "help")
{
if (player.IsAdmin())
{
PrintChat(player, "/sky settings set position");
PrintChat(player, "/sky settings get position");
PrintChat(player, "/sky admin lobby");
PrintChat(player, "/sky admin start");
PrintChat(player, "/sky admin end");
PrintChat(player, "/sky admin cleanup");
PrintChat(player, "/sky admin spawn");
PrintChat(player, "/sky admin winner-test");
}
PrintChat(player, "/sky join");
PrintChat(player, "/sky leave");
PrintChat(player, "/sky info");
}
else if (args[0] == "admin")
{
if (player.IsAdmin())
{
if (args.Length > 1)
{
switch (args[1])
{
case "goto-position":
TeleportPlayerPosition(player, getEventPosition());
break;
case "winner-test":
weGotaWinner(player);
break;
case "lobby":
eventOpenLobby(false);
break;
case "cleanup":
clearGUI();
eventCleanupForced();
var objects = UnityEngine.GameObject.FindObjectsOfType<EventWinner>();
if (objects != null)
{
foreach (EventWinner gameObj in objects)
{
if (gameObj != null)
{
UnityEngine.GameObject.Destroy(gameObj);
}
}
}
break;
case "movedown":
//spawnSkyEvent();
moveSkyEventDown();
PrintChat(player, "Moved SkyEvent platform down");
break;
case "moveup":
//spawnSkyEvent();
moveSkyEventUp();
PrintChat(player, "Moved SkyEvent platform up");
break;
case "test":
timer.Once(1, () =>
{
var winners = GameObject.FindObjectsOfType<EventWinner>();
if (winners != null)
{
foreach (EventWinner gameObj in winners)
{
if (gameObj != null)
{
UnityEngine.GameObject.Destroy(gameObj);
}
}
}
});
timer.Once(2, () =>
{
eventOpenLobby(true);
});
timer.Once(10, () =>
{
foreach (BasePlayer pPlayer in Resources.FindObjectsOfTypeAll<BasePlayer>())
{
if (pPlayer.isConnected)
{
EventJoin(pPlayer);
}
}
});
timer.Once(11, () =>
{
eventBegin(true);
});
break;
default:
PrintChat(player, "Cannot find that command");
break;
}
}
}
else
{
PrintChat(player, "Access denied");
}
}
else if (args[0] == "settings")
{
if (player.IsAdmin())
{
if (args.Length > 1)
{
switch (args[1])
{
case "set":
if (args.Length > 2)
{
switch (args[2])
{
case "position":
int x = Convert.ToInt32(player.transform.position.x);
int z = Convert.ToInt32(player.transform.position.z);
eventData["placement", "position_x"] = x;
eventData["placement", "position_z"] = z;
Interface.GetMod().DataFileSystem.SaveDatafile("SkyEvent");
PrintChat(player, "Saved position");
break;
default:
PrintChat(player, "Cannot find that command");
break;
}
}
break;
case "get":
if (args.Length > 2)
{
switch (args[2])
{
case "position":
PrintChat(player, string.Format("PoSx: {0}", eventData["placement", "position_x"]));
PrintChat(player, string.Format("PoSz: {0}", eventData["placement", "position_z"]));
break;
default:
PrintChat(player, "Cannot find that command");
break;
}
}
break;
default:
PrintChat(player, "Cannot find that command");
break;
}
}
}
else
{
PrintChat(player, "Access denied");
}
}
else
{
PrintChat(player, "Cannot find that command");
}
}
}
void skyInfo(BasePlayer player)
{
TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
int diffSeconds = (this.lobbyNext - (int)t.TotalSeconds);
int minutes = (int)Math.Floor((float)(diffSeconds / 60));
int seconds = (int)Math.Floor((float)(diffSeconds % 60));
string message = "";
if (seconds > 0 && minutes > 0)
{
message = string.Format("The next SkyEvent will start in: {0} minute(s) and {1} second(s)", minutes, seconds);
}
else if (seconds > 0)
{
message = string.Format("The next SkyEvent will start in: {0} second(s)", seconds);
}
else if (minutes > 0)
{
message = string.Format("The next SkyEvent will start in: {0} minute(s)", minutes);
}
if (message != "")
{
SendReply(player, string.Format("[SkyEvent] {0}", message));
}
if (eventData["winner", "name"] != null)
{
SendReply(player, string.Format("[SkyEvent] Last winner was '{0}' who won {1} supply signal(s)", eventData["winner", "name"], eventData["winner", "amount"]));
}
}
Vector3 getEventPosition()
{
float x = float.Parse(eventData["placement", "position_x"].ToString());
float y = (float)EventY;
float z = float.Parse(eventData["placement", "position_z"].ToString());
return new Vector3(x, y, z);
}
void spawnSkyEvent()
{
//clearEventBlocks();
Vector3 position = getEventPosition();
position.y += 500;
spawns = new List<Vector3>();
#region Spawn timers
spawnPlane(position, arenaSize);
timer.Once(5, () =>
{
int cupBoard = arenaSize / 5;
for (int cupX = 0; cupX < cupBoard; cupX++)
{
for (int cupZ = 0; cupZ < cupBoard; cupZ++)
{
Vector3 blockPosition = new Vector3(position.x + ((cupX * 5) * 3), (position.y - 12f) - 500f, position.z + ((cupZ * 5) * 3));
BaseEntity ent = GameManager.server.CreateEntity(
"assets/prefabs/deployable/tool cupboard/cupboard.tool.deployed.prefab",
blockPosition,
new UnityEngine.Quaternion(0, 0, 0, 0)
);
ent.gameObject.AddComponent<EventBlock>();
ent.SpawnAsMapEntity();
}
}
});
#endregion
}
[HookMethod("BuildServerTags")]
void BuildServerTags(IList<string> tags)
{
if (tags.IndexOf("skyevent") == -1) {
tags.Add("skyevent");
}
}
void spawnPlanePart1(Vector3 position, int size)
{
UnityEngine.Quaternion euler = UnityEngine.Quaternion.Euler(0, 90, 0);
UnityEngine.Quaternion quat = new UnityEngine.Quaternion(0, 0, 0, 0);
for (int blockX = 0; blockX < size / 2; blockX++)
{
for (int blockZ = 0; blockZ < size / 2; blockZ++)
{
spawnPlaneBlock(position, blockX, blockZ, euler, quat);
}
}
}
void spawnPlanePart2(Vector3 position, int size)
{
UnityEngine.Quaternion euler = UnityEngine.Quaternion.Euler(0, 90, 0);
UnityEngine.Quaternion quat = new UnityEngine.Quaternion(0, 0, 0, 0);
for (int blockX = 0; blockX < size / 2; blockX++)
{
for (int blockZ = size / 2; blockZ < size; blockZ++)
{
spawnPlaneBlock(position, blockX, blockZ, euler, quat);
}
}
}
void spawnPlanePart3(Vector3 position, int size)
{
UnityEngine.Quaternion euler = UnityEngine.Quaternion.Euler(0, 90, 0);
UnityEngine.Quaternion quat = new UnityEngine.Quaternion(0, 0, 0, 0);
for (int blockX = size / 2; blockX < size; blockX++)
{
for (int blockZ = 0; blockZ < size / 2; blockZ++)
{
spawnPlaneBlock(position, blockX, blockZ, euler, quat);
}
}
}
void spawnPlanePart4(Vector3 position, int size)
{
UnityEngine.Quaternion euler = UnityEngine.Quaternion.Euler(0, 90, 0);
UnityEngine.Quaternion quat = new UnityEngine.Quaternion(0, 0, 0, 0);
for (int blockX = size / 2; blockX < size; blockX++)
{
for (int blockZ = size / 2; blockZ < size; blockZ++)
{
spawnPlaneBlock(position, blockX, blockZ, euler, quat);
}
}
}
void spawnPlaneBlock(Vector3 position, int blockX, int blockZ, Quaternion euler, Quaternion quat)
{
Vector3 blockPosition = new Vector3(position.x + (blockX * 3), position.y, position.z + (blockZ * 3));
BuildingBlock block = SpawnStructureBlock(
floorPrefab,
blockPosition,
quat,
BuildingGrade.Enum.Stone
);
block.gameObject.AddComponent<EventFloor>();
Vector3 spawn = new Vector3(blockPosition.x, ((blockPosition.y + 0.25f) - 500f), blockPosition.z);
Vector3 wallPlacement = new Vector3(blockPosition.x, (blockPosition.y + 0.25f), blockPosition.z);
spawns.Add(
spawn
);
Vector3 blockPositionLeft = new Vector3(wallPlacement.x + 1.5f, wallPlacement.y - 0.25f, wallPlacement.z);
Vector3 blockPositionTop = new Vector3(wallPlacement.x, wallPlacement.y - 0.25f, wallPlacement.z + 1.5f);
Vector3 blockPositionRight = new Vector3(wallPlacement.x - 1.5f, wallPlacement.y - 0.25f, wallPlacement.z);
Vector3 blockPositionBottom = new Vector3(wallPlacement.x, wallPlacement.y - 0.25f, wallPlacement.z - 1.5f);
List<EventBlockWall> wallList = new List<EventBlockWall>();
wallList.Add(SpawnStructureBlock(
wallPrefab,
blockPositionLeft,
quat,
BuildingGrade.Enum.Stone
).gameObject.AddComponent<EventBlockWall>());
wallList.Add(SpawnStructureBlock(
wallPrefab,
blockPositionTop,
euler,
BuildingGrade.Enum.Stone
).gameObject.AddComponent<EventBlockWall>());
wallList.Add(SpawnStructureBlock(
wallPrefab,
blockPositionRight,
quat,
BuildingGrade.Enum.Stone
).gameObject.AddComponent<EventBlockWall>());
wallList.Add(SpawnStructureBlock(
wallPrefab,
blockPositionBottom,
euler,
BuildingGrade.Enum.Stone
).gameObject.AddComponent<EventBlockWall>());
spawnMapping.Add(spawn, wallList);
}
// 1: EventFloor
void spawnPlane(Vector3 position, int size)
{
spawnMapping = new Dictionary<Vector3, List<EventBlockWall>>();
timer.Once(1, () => spawnPlanePart1(position, size));
timer.Once(5, () => spawnPlanePart2(position, size));
timer.Once(10, () => spawnPlanePart3(position, size));
timer.Once(15, () => spawnPlanePart4(position, size));
}
void moveSkyEventDown()
{
List<EventFloor> floorList = getEventFloors();
if (floorList.Count > 0)
{
foreach (EventFloor event_block in floorList)
{
if (event_block != null) {
event_block.state = 1;
event_block.gameObject.transform.position = new Vector3(
event_block.gameObject.transform.position.x,
event_block.gameObject.transform.position.y - 500,
event_block.gameObject.transform.position.z
);
BuildingBlock block = event_block.GetComponent<BuildingBlock>();
block.SendNetworkUpdate(BasePlayer.NetworkQueue.Update);
}
}
}
}
void moveSkyEventUp()
{
List<EventFloor> floorList = getEventFloors();
if (floorList.Count > 0)
{
foreach (EventFloor event_block in floorList)
{
if (event_block != null && (event_block.state == 1 || event_block.state == 2))
{
event_block.sendToOriginal();
BuildingBlock block = event_block.GetComponent<BuildingBlock>();
block.SendNetworkUpdate(BasePlayer.NetworkQueue.Update);
}
}
}
}
void sendWallsDown(Vector3 position)
{
List<EventBlockWall> wallList = spawnMapping[position];
if (wallList != null)
{
foreach (EventBlockWall wall in wallList) {
if (wall != null) {
BuildingBlock block = wall.GetComponent<BuildingBlock>();
if (block != null) {
wall.position = 2;
block.gameObject.transform.position = new Vector3(
block.gameObject.transform.position.x,
block.gameObject.transform.position.y - 500f,
block.gameObject.transform.position.z
);
block.SendNetworkUpdate(BasePlayer.NetworkQueue.Update);
}
}
}
}
}
BuildingBlock SpawnStructureBlock(GameObject prefab, Vector3 pos, Quaternion angles, BuildingGrade.Enum grade)
{
GameObject build = UnityEngine.GameObject.Instantiate(prefab);
if (build == null)
{
return null;
}
BuildingBlock block = build.GetComponent<BuildingBlock>();
if (block == null)
{
return null;
}
block.enableStability = false;
block.transform.position = pos;
block.transform.rotation = angles;
block.gameObject.SetActive(true);
eventBlocks.Add(block.gameObject.AddComponent<EventBlock>());
block.blockDefinition = PrefabAttribute.server.Find<Construction>(block.prefabID);
block.grade = grade;
block.Spawn(true);
block.health = 500;
//block.SendNetworkUpdate(BasePlayer.NetworkQueue.Update);
return block;
}
}
}
| |
#if !BESTHTTP_DISABLE_WEBSOCKET && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using System.Text;
using BestHTTP.Extensions;
using BestHTTP.WebSocket.Frames;
namespace BestHTTP.WebSocket
{
public sealed class WebSocketResponse : HTTPResponse, IHeartbeat, IProtocol
{
#region Public Interface
/// <summary>
/// A reference to the original WebSocket instance. Used for accessing extensions.
/// </summary>
public WebSocket WebSocket { get; internal set; }
/// <summary>
/// Called when a Text message received
/// </summary>
public Action<WebSocketResponse, string> OnText;
/// <summary>
/// Called when a Binary message received
/// </summary>
public Action<WebSocketResponse, byte[]> OnBinary;
/// <summary>
/// Called when an incomplete frame received. No attemp will be made to reassemble these fragments.
/// </summary>
public Action<WebSocketResponse, WebSocketFrameReader> OnIncompleteFrame;
/// <summary>
/// Called when the connection closed.
/// </summary>
public Action<WebSocketResponse, UInt16, string> OnClosed;
/// <summary>
/// Indicates whether the connection to the server is closed or not.
/// </summary>
public bool IsClosed { get { return closed; } }
/// <summary>
/// On what frequency we have to send a ping to the server.
/// </summary>
public TimeSpan PingFrequnecy { get; private set; }
/// <summary>
/// Maximum size of a fragment's payload data. Its default value is 32767.
/// </summary>
public UInt16 MaxFragmentSize { get; private set; }
#endregion
#region Private Fields
private List<WebSocketFrameReader> IncompleteFrames = new List<WebSocketFrameReader>();
private List<WebSocketFrameReader> CompletedFrames = new List<WebSocketFrameReader>();
private WebSocketFrameReader CloseFrame;
private object FrameLock = new object();
private object SendLock = new object();
/// <summary>
/// True if we sent out a Close message to the server
/// </summary>
private bool closeSent;
/// <summary>
/// True if this WebSocket connection is closed
/// </summary>
private bool closed;
private DateTime lastPing = DateTime.MinValue;
#endregion
internal WebSocketResponse(HTTPRequest request, Stream stream, bool isStreamed, bool isFromCache)
: base(request, stream, isStreamed, isFromCache)
{
base.IsClosedManually = true;
closed = false;
MaxFragmentSize = UInt16.MaxValue / 2;
}
internal void StartReceive()
{
if (IsUpgraded)
{
#if NETFX_CORE
#pragma warning disable 4014
Windows.System.Threading.ThreadPool.RunAsync(ReceiveThreadFunc);
#pragma warning restore 4014
#else
new Thread(ReceiveThreadFunc)
.Start();
#endif
}
}
#region Public interface for interacting with the server
/// <summary>
/// It will send the given message to the server in one frame.
/// </summary>
public void Send(string message)
{
if (message == null)
throw new ArgumentNullException("message must not be null!");
byte[] data = System.Text.Encoding.UTF8.GetBytes(message);
Send(new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.Text, data));
}
/// <summary>
/// It will send the given data to the server in one frame.
/// </summary>
public void Send(byte[] data)
{
if (data == null)
throw new ArgumentNullException("data must not be null!");
WebSocketFrame frame = new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.Binary, data);
if (frame.Data != null && frame.Data.Length > this.MaxFragmentSize)
{
WebSocketFrame[] additionalFrames = frame.Fragment(this.MaxFragmentSize);
lock(SendLock)
{
Send(frame);
if (additionalFrames != null)
for (int i = 0; i < additionalFrames.Length; ++i)
Send(additionalFrames[i]);
}
}
else
Send(frame);
}
/// <summary>
/// Will send count bytes from a byte array, starting from offset.
/// </summary>
public void Send(byte[] data, ulong offset, ulong count)
{
if (data == null)
throw new ArgumentNullException("data must not be null!");
if (offset + count > (ulong)data.Length)
throw new ArgumentOutOfRangeException("offset + count >= data.Length");
WebSocketFrame frame = new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.Binary, data, offset, count, true, true);
if (frame.Data != null && frame.Data.Length > this.MaxFragmentSize)
{
WebSocketFrame[] additionalFrames = frame.Fragment(this.MaxFragmentSize);
lock (SendLock)
{
Send(frame);
if (additionalFrames != null)
for (int i = 0; i < additionalFrames.Length; ++i)
Send(additionalFrames[i]);
}
}
else
Send(frame);
}
/// <summary>
/// It will send the given frame to the server.
/// </summary>
public void Send(WebSocketFrame frame)
{
if (frame == null)
throw new ArgumentNullException("frame is null!");
if (closed)
return;
byte[] rawData = frame.Get();
lock (SendLock)
{
Stream.Write(rawData, 0, rawData.Length);
Stream.Flush();
if (frame.Type == WebSocketFrameTypes.ConnectionClose)
closeSent = true;
}
}
/// <summary>
/// It will initiate the closing of the connection to the server.
/// </summary>
public void Close()
{
Close(1000, "Bye!");
}
/// <summary>
/// It will initiate the closing of the connection to the server.
/// </summary>
public void Close(UInt16 code, string msg)
{
if (closed)
return;
Send(new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.ConnectionClose, WebSocket.EncodeCloseData(code, msg)));
}
public void StartPinging(int frequency)
{
if (frequency < 100)
throw new ArgumentException("frequency must be at least 100 millisec!");
PingFrequnecy = TimeSpan.FromMilliseconds(frequency);
HTTPManager.Heartbeats.Subscribe(this);
}
#endregion
#region Private Threading Functions
private void ReceiveThreadFunc(object param)
{
try
{
while (!closed)
{
try
{
// TODO: reuse WebSocketFrameReader instances
WebSocketFrameReader frame = new WebSocketFrameReader();
frame.Read(Stream);
// A server MUST NOT mask any frames that it sends to the client. A client MUST close a connection if it detects a masked frame.
// In this case, it MAY use the status code 1002 (protocol error)
// (These rules might be relaxed in a future specification.)
if (frame.HasMask)
{
Close(1002, "Protocol Error: masked frame received from server!");
continue;
}
if (!frame.IsFinal)
{
if (OnIncompleteFrame == null)
IncompleteFrames.Add(frame);
else
lock (FrameLock) CompletedFrames.Add(frame);
continue;
}
switch (frame.Type)
{
// For a complete documentation and rules on fragmentation see http://tools.ietf.org/html/rfc6455#section-5.4
// A fragmented Frame's last fragment's opcode is 0 (Continuation) and the FIN bit is set to 1.
case WebSocketFrameTypes.Continuation:
// Do an assemble pass only if OnFragment is not set. Otherwise put it in the CompletedFrames, we will handle it in the HandleEvent phase.
if (OnIncompleteFrame == null)
{
frame.Assemble(IncompleteFrames);
frame.DecodeWithExtensions(WebSocket);
// Remove all imcomplete frames
IncompleteFrames.Clear();
// Control frames themselves MUST NOT be fragmented. So, its a normal text or binary frame. Go, handle it as usual.
goto case WebSocketFrameTypes.Binary;
}
else
lock (FrameLock) CompletedFrames.Add(frame);
break;
case WebSocketFrameTypes.Text:
case WebSocketFrameTypes.Binary:
frame.DecodeWithExtensions(WebSocket);
lock (FrameLock) CompletedFrames.Add(frame);
break;
// Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in response, unless it already received a Close frame.
case WebSocketFrameTypes.Ping:
if (!closeSent && !closed)
Send(new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.Pong, frame.Data));
break;
// If an endpoint receives a Close frame and did not previously send a Close frame, the endpoint MUST send a Close frame in response.
case WebSocketFrameTypes.ConnectionClose:
CloseFrame = frame;
if (!closeSent)
Send(new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.ConnectionClose, null));
closed = closeSent;
break;
}
}
#if !NETFX_CORE
catch (ThreadAbortException)
{
IncompleteFrames.Clear();
this.baseRequest.State = HTTPRequestStates.Aborted;
closed = true;
}
#endif
catch (Exception e)
{
if (HTTPUpdateDelegator.IsCreated)
{
this.baseRequest.Exception = e;
this.baseRequest.State = HTTPRequestStates.Error;
}
else
this.baseRequest.State = HTTPRequestStates.Aborted;
closed = true;
}
}
}
finally
{
HTTPManager.Heartbeats.Unsubscribe(this);
}
}
#endregion
#region Sending Out Events
/// <summary>
/// Internal function to send out received messages.
/// </summary>
void IProtocol.HandleEvents()
{
lock (FrameLock)
{
for (int i = 0; i < CompletedFrames.Count; ++i)
{
WebSocketFrameReader frame = CompletedFrames[i];
// Bugs in the clients shouldn't interrupt the code, so we need to try-catch and ignore any exception occuring here
try
{
switch (frame.Type)
{
case WebSocketFrameTypes.Continuation:
if (OnIncompleteFrame != null)
OnIncompleteFrame(this, frame);
break;
case WebSocketFrameTypes.Text:
// Any not Final frame is handled as a fragment
if (!frame.IsFinal)
goto case WebSocketFrameTypes.Continuation;
if (OnText != null)
OnText(this, Encoding.UTF8.GetString(frame.Data, 0, frame.Data.Length));
break;
case WebSocketFrameTypes.Binary:
// Any not Final frame is handled as a fragment
if (!frame.IsFinal)
goto case WebSocketFrameTypes.Continuation;
if (OnBinary != null)
OnBinary(this, frame.Data);
break;
}
}
catch (Exception ex)
{
HTTPManager.Logger.Exception("WebSocketResponse", "HandleEvents", ex);
}
}
CompletedFrames.Clear();
}//lock (ReadLock)
// 2015.05.09
// State checking added becouse if there is an error the OnClose called first, and then the OnError.
// Now, when there is an error only the OnError event will be called!
if (IsClosed && OnClosed != null && baseRequest.State == HTTPRequestStates.Processing)
{
try
{
UInt16 statusCode = 0;
string msg = string.Empty;
// If we received any data, we will get the status code and the message from it
if (CloseFrame != null && CloseFrame.Data != null && CloseFrame.Data.Length >= 2)
{
if (BitConverter.IsLittleEndian)
Array.Reverse(CloseFrame.Data, 0, 2);
statusCode = BitConverter.ToUInt16(CloseFrame.Data, 0);
if (CloseFrame.Data.Length > 2)
msg = Encoding.UTF8.GetString(CloseFrame.Data, 2, CloseFrame.Data.Length - 2);
}
OnClosed(this, statusCode, msg);
}
catch (Exception ex)
{
HTTPManager.Logger.Exception("WebSocketResponse", "HandleEvents - OnClosed", ex);
}
}
}
#endregion
#region IHeartbeat Implementation
void IHeartbeat.OnHeartbeatUpdate(TimeSpan dif)
{
if (lastPing == DateTime.MinValue)
{
lastPing = DateTime.UtcNow;
return;
}
if (DateTime.UtcNow - lastPing >= PingFrequnecy)
{
Send(new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.Ping, Encoding.UTF8.GetBytes(string.Empty)));
lastPing = DateTime.UtcNow;
}
}
#endregion
}
}
#endif
| |
// Copyright (c) 2012-2014 Sharpex2D - Kevin Scholz (ThuCommix)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the 'Software'), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
using Sharpex2D.Debug.Logging;
using Sharpex2D.Network.Logic;
using Sharpex2D.Network.Packages;
using Sharpex2D.Network.Packages.System;
namespace Sharpex2D.Network.Protocols.Udp
{
[Developer("ThuCommix", "developer@sharpex2d.de")]
[TestState(TestState.Untested)]
public class UdpServer : IServer, IDisposable
{
private const int IdleMax = 30;
private readonly UdpConnectionManager _connectionManager;
private readonly List<IConnection> _connections;
private readonly System.Net.Sockets.UdpClient _listener;
private readonly Logger _logger;
private readonly List<IPackageListener> _packageListeners;
private int _currentIdle;
private int _idleTimeout;
/// <summary>
/// Initializes a new UdpServer class.
/// </summary>
public UdpServer()
{
_packageListeners = new List<IPackageListener>();
_connections = new List<IConnection>();
_logger = LogManager.GetClassLogger();
_connectionManager = new UdpConnectionManager();
_connectionManager.PingTimedOut += _connectionManager_PingTimedOut;
_connectionManager.Start();
TimeOutLatency = 500f;
_listener = new System.Net.Sockets.UdpClient(2563);
IsActive = true;
var beginHandle = new Thread(BeginAcceptConnections) {IsBackground = true};
var pingHandle = new Thread(PingRequestLoop) {IsBackground = true};
beginHandle.Start();
pingHandle.Start();
}
/// <summary>
/// Sets or gets the TimeOutLatency, if a client latency is higher than this value, the client is going to be
/// disconnected.
/// </summary>
public float TimeOutLatency { set; get; }
/// <summary>
/// Called if a PingRequest timed out.
/// </summary>
private void _connectionManager_PingTimedOut(object sender, IPAddress ipAddress)
{
for (int i = 0; i <= _connections.Count - 1; i++)
{
if (Equals(_connections[i].IPAddress, ipAddress))
{
//remove the connection
_connections.RemoveAt(i);
//notify clients
SendNotificationPackage(NotificationMode.TimeOut,
new IConnection[] {SerializableConnection.FromIConnection(_connections[i])});
break;
}
}
}
/// <summary>
/// Accepts clients if available.
/// </summary>
private void BeginAcceptConnections()
{
var incommingConnection = new IPEndPoint(IPAddress.Any, 2565);
while (IsActive)
{
try
{
if (_listener.Available > 0)
{
byte[] receivedData = _listener.Receive(ref incommingConnection);
using (var mStream = new MemoryStream(receivedData))
{
IBasePackage package = PackageSerializer.Deserialize(mStream);
var udpPackage = package as UdpPackage;
if (udpPackage != null)
{
if (udpPackage.NotifyMode == UdpNotify.Hi)
{
//notify
SendNotificationPackage(NotificationMode.ClientJoined, _connections.ToArray());
//add connection
var udpConnection = new UdpConnection(incommingConnection.Address);
_connections.Add(udpConnection);
// publish the new server list, after a new connection.
SendNotificationPackage(NotificationMode.ClientList, _connections.ToArray());
}
else //(UdpNotify.Bye)
{
//notify
SendNotificationPackage(NotificationMode.ClientExited, _connections.ToArray());
//remove connection
UdpConnection udpConnection = GetConnection(incommingConnection.Address);
if (udpConnection != null)
{
_connections.Remove(udpConnection);
// publish the new server list, after a lost connection.
SendNotificationPackage(NotificationMode.ClientList, _connections.ToArray());
}
}
}
else
{
//any other package handle in new void
HandlePackage(package);
}
}
}
else
{
//no data available
Idle();
}
}
catch (Exception ex)
{
_logger.Error(ex.Message);
}
}
}
/// <summary>
/// Handles the given package.
/// </summary>
/// <param name="package">The Package.</param>
private void HandlePackage(IBasePackage package)
{
var binaryPackage = package as BinaryPackage;
if (binaryPackage != null)
{
//notify package listeners
foreach (IPackageListener subscriber in GetPackageSubscriber(binaryPackage.OriginType))
{
subscriber.OnPackageReceived(binaryPackage);
}
//send the package to its destination
if (binaryPackage.Receiver == null)
{
Send(binaryPackage);
}
else
{
Send(binaryPackage, binaryPackage.Receiver);
}
return;
}
//system package pingpackage
var pingPackage = package as PingPackage;
if (pingPackage != null)
{
SetLatency(pingPackage);
}
}
/// <summary>
/// Sets the latency of a connection.
/// </summary>
/// <param name="pingPackage">The PingPackage.</param>
private void SetLatency(PingPackage pingPackage)
{
DateTime timeNow = DateTime.Now;
TimeSpan dif = timeNow - pingPackage.TimeStamp;
UdpConnection connection = GetConnection(pingPackage.Receiver);
connection.Latency = (float) dif.TotalMilliseconds;
//alert the connectionmanager
_connectionManager.RemoveByIP(pingPackage.Receiver);
//Kick the client if the latency is to high
if (!(connection.Latency > TimeOutLatency)) return;
SendNotificationPackage(NotificationMode.TimeOut,
new IConnection[] {SerializableConnection.FromIConnection(connection)});
_connections.Remove(connection);
}
/// <summary>
/// Gets the UpdConnection by the specified IPAddress.
/// </summary>
/// <param name="ipAddress">The IPAddress.</param>
/// <returns>UpdConnection</returns>
private UdpConnection GetConnection(IPAddress ipAddress)
{
for (int i = 0; i <= _connections.Count - 1; i++)
{
if (Equals(_connections[i].IPAddress, ipAddress))
{
return (UdpConnection) _connections[i];
}
}
return null;
}
/// <summary>
/// Sending a ping request every 30 seconds to all clients.
/// </summary>
private void PingRequestLoop()
{
while (IsActive)
{
IConnection[] connectionList = SerializableConnection.FromIConnection(_connections.ToArray());
//Send a ping request to all clients
for (int i = 0; i <= _connections.Count - 1; i++)
{
var pingPackage = new PingPackage {Receiver = _connections[i].IPAddress};
Send(pingPackage, _connections[i].IPAddress);
//add the ping request to the connection manager.
_connectionManager.AddPingRequest(new UdpPingRequest(_connections[i].IPAddress,
pingPackage.TimeStamp));
//Also update the client list.
SendNotificationPackage(NotificationMode.ClientList, connectionList);
}
//Idle for 15 seconds
Thread.Sleep(15000);
}
}
/// <summary>
/// Sends a NotificationPackage to all clients.
/// </summary>
/// <param name="mode">The Mode.</param>
/// <param name="connections">The ConnectionParams.</param>
private void SendNotificationPackage(NotificationMode mode, IConnection[] connections)
{
var notificationPackage = new NotificationPackage(connections, mode);
Send(notificationPackage);
}
/// <summary>
/// Idles the thread.
/// </summary>
private void Idle()
{
//Idle to save cpu power.
_currentIdle++;
if (_idleTimeout > 0)
{
Thread.Sleep(_idleTimeout);
}
if (_currentIdle < IdleMax) return;
_currentIdle = 0;
if (_idleTimeout < 15)
{
_idleTimeout++;
}
}
/// <summary>
/// Gets a list of all matching package listeners.
/// </summary>
/// <param name="type">The Type.</param>
/// <returns>List of package listeners</returns>
private IEnumerable<IPackageListener> GetPackageSubscriber(Type type)
{
var listenerContext = new List<IPackageListener>();
for (int i = 0; i <= _packageListeners.Count - 1; i++)
{
//if listener type is null go to next
if (_packageListeners[i].ListenerType == null)
{
continue;
}
if (_packageListeners[i].ListenerType == type)
{
listenerContext.Add(_packageListeners[i]);
}
}
return listenerContext;
}
/// <summary>
/// Closes the server.
/// </summary>
public void Close()
{
SendNotificationPackage(NotificationMode.ServerShutdown, null);
_listener.Close();
_connectionManager.Stop();
IsActive = false;
}
#region IServer Implementation
/// <summary>
/// Sends a package to the given receivers.
/// </summary>
/// <param name="package">The Package.</param>
public void Send(IBasePackage package)
{
byte[] result;
using (var mStream = new MemoryStream())
{
PackageSerializer.Serialize(package, mStream);
result = mStream.ToArray();
}
for (int i = 0; i <= _connections.Count - 1; i++)
{
_listener.Client.SendTo(result, new IPEndPoint(_connections[i].IPAddress, 2565));
}
}
/// <summary>
/// Sends a package to the given receivers.
/// </summary>
/// <param name="package">The Package.</param>
/// <param name="receiver">The Receiver.</param>
public void Send(IBasePackage package, IPAddress receiver)
{
byte[] result;
using (var mStream = new MemoryStream())
{
PackageSerializer.Serialize(package, mStream);
result = mStream.ToArray();
}
_listener.Client.SendTo(result, new IPEndPoint(receiver, 2565));
}
/// <summary>
/// A value indicating whether the server is active.
/// </summary>
public bool IsActive { get; private set; }
/// <summary>
/// Subscribes to a Client.
/// </summary>
/// <param name="subscriber">The Subscriber.</param>
public void Subscribe(IPackageListener subscriber)
{
_packageListeners.Add(subscriber);
}
/// <summary>
/// Unsubscribes from a Client.
/// </summary>
/// <param name="unsubscriber">The Unsubscriber.</param>
public void Unsubscribe(IPackageListener unsubscriber)
{
_packageListeners.Remove(unsubscriber);
}
#endregion
#region IDisposable Implementation
private bool _isDisposed;
/// <summary>
/// Disposes the object.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes the object.
/// </summary>
/// <param name="disposing">Indicates whether managed resources should be disposed.</param>
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
_isDisposed = true;
if (disposing)
{
_listener.Close();
}
}
}
#endregion
}
}
| |
/*
* Copyright (c) 2009 Jim Radford http://www.jimradford.com
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using Microsoft.Win32;
using WeifenLuo.WinFormsUI.Docking;
using log4net;
using System.Xml.Serialization;
using System.IO;
using System.Collections;
using System.Reflection;
namespace SuperPutty.Data
{
public enum ConnectionProtocol
{
SSH,
SSH2,
Telnet,
Rlogin,
Raw,
Serial,
Cygterm,
Mintty
}
/// <summary>The main class containing configuration settings for a session</summary>
public class SessionData : IComparable, ICloneable
{
private static readonly ILog Log = LogManager.GetLogger(typeof(SessionData));
/// <summary>Full session id (includes path for session tree)e.g. FolderName/SessionName</summary>
private string _SessionId;
[XmlAttribute]
public string SessionId
{
get { return this._SessionId; }
set
{
this.OldSessionId = SessionId;
this._SessionId = value;
}
}
internal string OldSessionId { get; set; }
private string _OldName;
[XmlIgnore]
public string OldName
{
get { return _OldName; }
set { _OldName = value; }
}
private string _SessionName;
[XmlAttribute]
public string SessionName
{
get { return _SessionName; }
set { OldName = _SessionName;
_SessionName = value;
if (SessionId == null)
{
SessionId = value;
}
}
}
private string _ImageKey;
/// <summary>A string containing the key of the image associated with this session</summary>
[XmlAttribute]
public string ImageKey
{
get { return _ImageKey; }
set { _ImageKey = value; }
}
private string _Host;
[XmlAttribute]
public string Host
{
get { return _Host; }
set { _Host = value; }
}
private int _Port;
[XmlAttribute]
public int Port
{
get { return _Port; }
set { _Port = value; }
}
private ConnectionProtocol _Proto;
[XmlAttribute]
public ConnectionProtocol Proto
{
get { return _Proto; }
set { _Proto = value; }
}
private string _PuttySession;
[XmlAttribute]
public string PuttySession
{
get { return _PuttySession; }
set { _PuttySession = value; }
}
private string _Username;
[XmlAttribute]
public string Username
{
get { return _Username; }
set { _Username = value; }
}
private string _Password;
[XmlIgnore]
public string Password
{
get { return _Password; }
set { _Password = value; }
}
private string _ExtraArgs;
[XmlAttribute]
public string ExtraArgs
{
get { return _ExtraArgs; }
set { _ExtraArgs = value; }
}
private DockState m_LastDockstate = DockState.Document;
[XmlIgnore]
public DockState LastDockstate
{
get { return m_LastDockstate; }
set { m_LastDockstate = value; }
}
private bool m_AutoStartSession = false;
[XmlIgnore]
public bool AutoStartSession
{
get { return m_AutoStartSession; }
set { m_AutoStartSession = value; }
}
/// <summary>Construct a new session data object</summary>
/// <param name="sessionName">A string representing the name of the session</param>
/// <param name="hostName">The hostname or ip address of the remote host</param>
/// <param name="port">The port on the remote host</param>
/// <param name="protocol">The protocol to use when connecting to the remote host</param>
/// <param name="sessionConfig">the name of the saved configuration settings from putty to use</param>
public SessionData(string sessionName, string hostName, int port, ConnectionProtocol protocol, string sessionConfig)
{
SessionName = sessionName;
Host = hostName;
Port = port;
Proto = protocol;
PuttySession = sessionConfig;
}
/// <summary>Default constructor, instantiate a new <seealso cref="SessionData"/> object</summary>
public SessionData()
{
}
/// <summary>Read any existing saved sessions from the registry, decode and populate a list containing the data</summary>
/// <returns>A list containing the configuration entries retrieved from the registry</returns>
public static List<SessionData> LoadSessionsFromRegistry()
{
Log.Info("LoadSessionsFromRegistry...");
List<SessionData> sessionList = new List<SessionData>();
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Jim Radford\SuperPuTTY\Sessions");
if (key != null)
{
string[] sessionKeys = key.GetSubKeyNames();
foreach (string session in sessionKeys)
{
SessionData sessionData = new SessionData();
RegistryKey itemKey = key.OpenSubKey(session);
if (itemKey != null)
{
sessionData.Host = (string)itemKey.GetValue("Host", "");
sessionData.Port = (int)itemKey.GetValue("Port", 22);
sessionData.Proto = (ConnectionProtocol)Enum.Parse(typeof(ConnectionProtocol), (string)itemKey.GetValue("Proto", "SSH"));
sessionData.PuttySession = (string)itemKey.GetValue("PuttySession", "Default Session");
sessionData.SessionName = session;
sessionData.SessionId = (string)itemKey.GetValue("SessionId", session);
sessionData.Username = (string)itemKey.GetValue("Login", "");
sessionData.LastDockstate = (DockState)itemKey.GetValue("Last Dock", DockState.Document);
sessionData.AutoStartSession = bool.Parse((string)itemKey.GetValue("Auto Start", "False"));
sessionList.Add(sessionData);
}
}
}
return sessionList;
}
/// <summary>Load session configuration data from the specified XML file</summary>
/// <param name="fileName">The filename containing the settings</param>
/// <returns>A <seealso cref="List"/> containing the session configuration data</returns>
public static List<SessionData> LoadSessionsFromFile(string fileName)
{
List<SessionData> sessions = new List<SessionData>();
if (File.Exists(fileName))
{
WorkaroundCygwinBug();
XmlSerializer s = new XmlSerializer(sessions.GetType());
using (TextReader r = new StreamReader(fileName))
{
sessions = (List<SessionData>)s.Deserialize(r);
}
Log.InfoFormat("Loaded {0} sessions from {1}", sessions.Count, fileName);
}
else
{
Log.WarnFormat("Could not load sessions, file doesn't exist. file={0}", fileName);
}
return sessions;
}
static void WorkaroundCygwinBug()
{
try
{
// work around known bug with cygwin
Dictionary<string, string> envVars = new Dictionary<string, string>();
foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
{
string envVar = (string) de.Key;
if (envVars.ContainsKey(envVar.ToUpper()))
{
// duplicate found... (e.g. TMP and tmp)
Log.DebugFormat("Clearing duplicate envVariable, {0}", envVar);
Environment.SetEnvironmentVariable(envVar, null);
continue;
}
envVars.Add(envVar.ToUpper(), envVar);
}
}
catch (Exception ex)
{
Log.WarnFormat("Error working around cygwin issue: {0}", ex.Message);
}
}
/// <summary>Save session configuration to the specified XML file</summary>
/// <param name="sessions">A <seealso cref="List"/> containing the session configuration data</param>
/// <param name="fileName">A path to a filename to save the data in</param>
public static void SaveSessionsToFile(List<SessionData> sessions, string fileName)
{
Log.InfoFormat("Saving {0} sessions to {1}", sessions.Count, fileName);
BackUpFiles(fileName, 20);
// sort and save file
sessions.Sort();
XmlSerializer s = new XmlSerializer(sessions.GetType());
using (TextWriter w = new StreamWriter(fileName))
{
s.Serialize(w, sessions);
}
}
private static void BackUpFiles(string fileName, int count)
{
if (File.Exists(fileName) && count > 0)
{
try
{
// backup
string fileBaseName = Path.GetFileNameWithoutExtension(fileName);
string dirName = Path.Combine( Path.GetDirectoryName(fileName), "backup" );
Directory.CreateDirectory(dirName); //checks and creates only if not exist
string backupName = Path.Combine(dirName, string.Format("{0}.{1:yyyyMMdd_hhmmss}.XML", fileBaseName, DateTime.Now));
File.Copy(fileName, backupName, true);
// limit last count saves
List<string> oldFiles = new List<string>(Directory.GetFiles(dirName, fileBaseName + ".*.XML"));
oldFiles.Sort();
oldFiles.Reverse();
if (oldFiles.Count > count)
{
for (int i = count; i < oldFiles.Count; i++)
{
Log.InfoFormat("Cleaning up old file, {0}", oldFiles[i]);
File.Delete(oldFiles[i]);
}
}
}
catch (Exception ex)
{
Log.Error("Error backing up files", ex);
}
}
}
public int CompareTo(object obj)
{
SessionData s = obj as SessionData;
return s == null ? 1 : this.SessionId.CompareTo(s.SessionId);
}
public static string CombineSessionIds(string parent, string child)
{
if (parent == null && child == null)
{
return null;
}
else if (child == null)
{
return parent;
}
else if (parent == null)
{
return child;
}
else
{
return parent + "/" + child;
}
}
public static string GetSessionNameFromId(string sessionId)
{
string[] parts = GetSessionNameParts(sessionId);
return parts.Length > 0 ? parts[parts.Length - 1] : sessionId;
}
/// <summary>Split the SessionID into its parent/child parts</summary>
/// <param name="sessionId">The SessionID</param>
/// <returns>A string array containing the individual path components</returns>
public static string[] GetSessionNameParts(string sessionId)
{
return sessionId.Split('/');
}
/// <summary>Get the parent ID of the specified session</summary>
/// <param name="sessionId">the ID of the session</param>
/// <returns>A string containing the parent sessions ID</returns>
public static string GetSessionParentId(string sessionId)
{
string parentPath = null;
if (sessionId != null)
{
int idx = sessionId.LastIndexOf('/');
if (idx != -1)
{
parentPath = sessionId.Substring(0, idx);
}
}
return parentPath;
}
/// <summary>Create a deep copy of the SessionData object</summary>
/// <returns>A clone of the <seealso cref="SessionData"/> object</returns>
public object Clone()
{
SessionData session = new SessionData();
foreach (PropertyInfo pi in this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (pi.CanWrite)
{
pi.SetValue(session, pi.GetValue(this, null), null);
}
}
return session;
}
/// <summary>Return a string containing a uri to the protocol://host:port of this sesssions defined host</summary>
/// <returns>A string in uri format containing connection information to this sessions host</returns>
public override string ToString()
{
if (this.Proto == ConnectionProtocol.Cygterm || this.Proto == ConnectionProtocol.Mintty)
{
return string.Format("{0}://{1}", this.Proto.ToString().ToLower(), this.Host);
}
else
{
return string.Format("{0}://{1}:{2}", this.Proto.ToString().ToLower(), this.Host, this.Port);
}
}
}
}
| |
// 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.
/*============================================================
**
**
**
**
**
** CustomAttributeBuilder is a helper class to help building custom attribute.
**
**
===========================================================*/
namespace System.Reflection.Emit {
using System;
using System.Reflection;
using System.IO;
using System.Text;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Diagnostics.Contracts;
[HostProtection(MayLeakOnAbort = true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_CustomAttributeBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
public class CustomAttributeBuilder : _CustomAttributeBuilder
{
// public constructor to form the custom attribute with constructor and constructor
// parameters.
public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs)
{
InitCustomAttributeBuilder(con, constructorArgs,
new PropertyInfo[]{}, new Object[]{},
new FieldInfo[]{}, new Object[]{});
}
// public constructor to form the custom attribute with constructor, constructor
// parameters and named properties.
public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs,
PropertyInfo[] namedProperties, Object[] propertyValues)
{
InitCustomAttributeBuilder(con, constructorArgs, namedProperties,
propertyValues, new FieldInfo[]{}, new Object[]{});
}
// public constructor to form the custom attribute with constructor and constructor
// parameters.
public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs,
FieldInfo[] namedFields, Object[] fieldValues)
{
InitCustomAttributeBuilder(con, constructorArgs, new PropertyInfo[]{},
new Object[]{}, namedFields, fieldValues);
}
// public constructor to form the custom attribute with constructor and constructor
// parameters.
public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs,
PropertyInfo[] namedProperties, Object[] propertyValues,
FieldInfo[] namedFields, Object[] fieldValues)
{
InitCustomAttributeBuilder(con, constructorArgs, namedProperties,
propertyValues, namedFields, fieldValues);
}
// Check that a type is suitable for use in a custom attribute.
private bool ValidateType(Type t)
{
if (t.IsPrimitive)
{
return t != typeof(IntPtr) && t != typeof(UIntPtr);
}
if (t == typeof(String) || t == typeof(Type))
{
return true;
}
if (t.IsEnum)
{
switch (Type.GetTypeCode(Enum.GetUnderlyingType(t)))
{
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
return true;
default:
return false;
}
}
if (t.IsArray)
{
if (t.GetArrayRank() != 1)
return false;
return ValidateType(t.GetElementType());
}
return t == typeof(Object);
}
internal void InitCustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs,
PropertyInfo[] namedProperties, Object[] propertyValues,
FieldInfo[] namedFields, Object[] fieldValues)
{
if (con == null)
throw new ArgumentNullException("con");
if (constructorArgs == null)
throw new ArgumentNullException("constructorArgs");
if (namedProperties == null)
throw new ArgumentNullException("namedProperties");
if (propertyValues == null)
throw new ArgumentNullException("propertyValues");
if (namedFields == null)
throw new ArgumentNullException("namedFields");
if (fieldValues == null)
throw new ArgumentNullException("fieldValues");
if (namedProperties.Length != propertyValues.Length)
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayLengthsDiffer"), "namedProperties, propertyValues");
if (namedFields.Length != fieldValues.Length)
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayLengthsDiffer"), "namedFields, fieldValues");
Contract.EndContractBlock();
if ((con.Attributes & MethodAttributes.Static) == MethodAttributes.Static ||
(con.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private)
throw new ArgumentException(Environment.GetResourceString("Argument_BadConstructor"));
if ((con.CallingConvention & CallingConventions.Standard) != CallingConventions.Standard)
throw new ArgumentException(Environment.GetResourceString("Argument_BadConstructorCallConv"));
// Cache information used elsewhere.
m_con = con;
m_constructorArgs = new Object[constructorArgs.Length];
Array.Copy(constructorArgs, 0, m_constructorArgs, 0, constructorArgs.Length);
Type[] paramTypes;
int i;
// Get the types of the constructor's formal parameters.
paramTypes = con.GetParameterTypes();
// Since we're guaranteed a non-var calling convention, the number of arguments must equal the number of parameters.
if (paramTypes.Length != constructorArgs.Length)
throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterCountsForConstructor"));
// Verify that the constructor has a valid signature (custom attributes only support a subset of our type system).
for (i = 0; i < paramTypes.Length; i++)
if (!ValidateType(paramTypes[i]))
throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeInCustomAttribute"));
// Now verify that the types of the actual parameters are compatible with the types of the formal parameters.
for (i = 0; i < paramTypes.Length; i++)
{
object constructorArg = constructorArgs[i];
if (constructorArg == null)
{
if (paramTypes[i].IsValueType)
{
throw new ArgumentNullException($"{nameof(constructorArgs)}[{i}]");
}
continue;
}
VerifyTypeAndPassedObjectType(paramTypes[i], constructorArg.GetType(), $"{nameof(constructorArgs)}[{i}]");
}
// Allocate a memory stream to represent the CA blob in the metadata and a binary writer to help format it.
MemoryStream stream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(stream);
// Write the blob protocol version (currently 1).
writer.Write((ushort)1);
// Now emit the constructor argument values (no need for types, they're inferred from the constructor signature).
for (i = 0; i < constructorArgs.Length; i++)
EmitValue(writer, paramTypes[i], constructorArgs[i]);
// Next a short with the count of properties and fields.
writer.Write((ushort)(namedProperties.Length + namedFields.Length));
// Emit all the property sets.
for (i = 0; i < namedProperties.Length; i++)
{
// Validate the property.
PropertyInfo property = namedProperties[i];
if (property == null)
throw new ArgumentNullException("namedProperties[" + i + "]");
// Allow null for non-primitive types only.
Type propType = property.PropertyType;
object propertyValue = propertyValues[i];
if (propertyValue == null && propType.IsValueType)
throw new ArgumentNullException("propertyValues[" + i + "]");
// Validate property type.
if (!ValidateType(propType))
throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeInCustomAttribute"));
// Property has to be writable.
if (!property.CanWrite)
throw new ArgumentException(Environment.GetResourceString("Argument_NotAWritableProperty"));
// Property has to be from the same class or base class as ConstructorInfo.
if (property.DeclaringType != con.DeclaringType
&& (!(con.DeclaringType is TypeBuilderInstantiation))
&& !con.DeclaringType.IsSubclassOf(property.DeclaringType))
{
// Might have failed check because one type is a XXXBuilder
// and the other is not. Deal with these special cases
// separately.
if (!TypeBuilder.IsTypeEqual(property.DeclaringType, con.DeclaringType))
{
// IsSubclassOf is overloaded to do the right thing if
// the constructor is a TypeBuilder, but we still need
// to deal with the case where the property's declaring
// type is one.
if (!(property.DeclaringType is TypeBuilder) ||
!con.DeclaringType.IsSubclassOf(((TypeBuilder)property.DeclaringType).BakedRuntimeType))
throw new ArgumentException(Environment.GetResourceString("Argument_BadPropertyForConstructorBuilder"));
}
}
// Make sure the property's type can take the given value.
// Note that there will be no coersion.
if (propertyValue != null)
{
VerifyTypeAndPassedObjectType(propType, propertyValue.GetType(), $"{nameof(propertyValues)}[{i}]");
}
// First a byte indicating that this is a property.
writer.Write((byte)CustomAttributeEncoding.Property);
// Emit the property type, name and value.
EmitType(writer, propType);
EmitString(writer, namedProperties[i].Name);
EmitValue(writer, propType, propertyValue);
}
// Emit all the field sets.
for (i = 0; i < namedFields.Length; i++)
{
// Validate the field.
FieldInfo namedField = namedFields[i];
if (namedField == null)
throw new ArgumentNullException("namedFields[" + i + "]");
// Allow null for non-primitive types only.
Type fldType = namedField.FieldType;
object fieldValue = fieldValues[i];
if (fieldValue == null && fldType.IsValueType)
throw new ArgumentNullException("fieldValues[" + i + "]");
// Validate field type.
if (!ValidateType(fldType))
throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeInCustomAttribute"));
// Field has to be from the same class or base class as ConstructorInfo.
if (namedField.DeclaringType != con.DeclaringType
&& (!(con.DeclaringType is TypeBuilderInstantiation))
&& !con.DeclaringType.IsSubclassOf(namedField.DeclaringType))
{
// Might have failed check because one type is a XXXBuilder
// and the other is not. Deal with these special cases
// separately.
if (!TypeBuilder.IsTypeEqual(namedField.DeclaringType, con.DeclaringType))
{
// IsSubclassOf is overloaded to do the right thing if
// the constructor is a TypeBuilder, but we still need
// to deal with the case where the field's declaring
// type is one.
if (!(namedField.DeclaringType is TypeBuilder) ||
!con.DeclaringType.IsSubclassOf(((TypeBuilder)namedFields[i].DeclaringType).BakedRuntimeType))
throw new ArgumentException(Environment.GetResourceString("Argument_BadFieldForConstructorBuilder"));
}
}
// Make sure the field's type can take the given value.
// Note that there will be no coersion.
if (fieldValue != null)
{
VerifyTypeAndPassedObjectType(fldType, fieldValue.GetType(), $"{nameof(fieldValues)}[{i}]");
}
// First a byte indicating that this is a field.
writer.Write((byte)CustomAttributeEncoding.Field);
// Emit the field type, name and value.
EmitType(writer, fldType);
EmitString(writer, namedField.Name);
EmitValue(writer, fldType, fieldValue);
}
// Create the blob array.
m_blob = ((MemoryStream)writer.BaseStream).ToArray();
}
private static void VerifyTypeAndPassedObjectType(Type type, Type passedType, string paramName)
{
if (type != typeof(object) && Type.GetTypeCode(passedType) != Type.GetTypeCode(type))
{
throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
}
if (passedType == typeof(IntPtr) || passedType == typeof(UIntPtr))
{
throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForCAB"), paramName);
}
}
private void EmitType(BinaryWriter writer, Type type)
{
if (type.IsPrimitive)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.SByte:
writer.Write((byte)CustomAttributeEncoding.SByte);
break;
case TypeCode.Byte:
writer.Write((byte)CustomAttributeEncoding.Byte);
break;
case TypeCode.Char:
writer.Write((byte)CustomAttributeEncoding.Char);
break;
case TypeCode.Boolean:
writer.Write((byte)CustomAttributeEncoding.Boolean);
break;
case TypeCode.Int16:
writer.Write((byte)CustomAttributeEncoding.Int16);
break;
case TypeCode.UInt16:
writer.Write((byte)CustomAttributeEncoding.UInt16);
break;
case TypeCode.Int32:
writer.Write((byte)CustomAttributeEncoding.Int32);
break;
case TypeCode.UInt32:
writer.Write((byte)CustomAttributeEncoding.UInt32);
break;
case TypeCode.Int64:
writer.Write((byte)CustomAttributeEncoding.Int64);
break;
case TypeCode.UInt64:
writer.Write((byte)CustomAttributeEncoding.UInt64);
break;
case TypeCode.Single:
writer.Write((byte)CustomAttributeEncoding.Float);
break;
case TypeCode.Double:
writer.Write((byte)CustomAttributeEncoding.Double);
break;
default:
Contract.Assert(false, "Invalid primitive type");
break;
}
}
else if (type.IsEnum)
{
writer.Write((byte)CustomAttributeEncoding.Enum);
EmitString(writer, type.AssemblyQualifiedName);
}
else if (type == typeof(String))
{
writer.Write((byte)CustomAttributeEncoding.String);
}
else if (type == typeof(Type))
{
writer.Write((byte)CustomAttributeEncoding.Type);
}
else if (type.IsArray)
{
writer.Write((byte)CustomAttributeEncoding.Array);
EmitType(writer, type.GetElementType());
}
else
{
// Tagged object case.
writer.Write((byte)CustomAttributeEncoding.Object);
}
}
private void EmitString(BinaryWriter writer, String str)
{
// Strings are emitted with a length prefix in a compressed format (1, 2 or 4 bytes) as used internally by metadata.
byte[] utf8Str = Encoding.UTF8.GetBytes(str);
uint length = (uint)utf8Str.Length;
if (length <= 0x7f)
{
writer.Write((byte)length);
}
else if (length <= 0x3fff)
{
writer.Write((byte)((length >> 8) | 0x80));
writer.Write((byte)(length & 0xff));
}
else
{
writer.Write((byte)((length >> 24) | 0xc0));
writer.Write((byte)((length >> 16) & 0xff));
writer.Write((byte)((length >> 8) & 0xff));
writer.Write((byte)(length & 0xff));
}
writer.Write(utf8Str);
}
private void EmitValue(BinaryWriter writer, Type type, Object value)
{
if (type.IsEnum)
{
switch (Type.GetTypeCode(Enum.GetUnderlyingType(type)))
{
case TypeCode.SByte:
writer.Write((sbyte)value);
break;
case TypeCode.Byte:
writer.Write((byte)value);
break;
case TypeCode.Int16:
writer.Write((short)value);
break;
case TypeCode.UInt16:
writer.Write((ushort)value);
break;
case TypeCode.Int32:
writer.Write((int)value);
break;
case TypeCode.UInt32:
writer.Write((uint)value);
break;
case TypeCode.Int64:
writer.Write((long)value);
break;
case TypeCode.UInt64:
writer.Write((ulong)value);
break;
default:
Contract.Assert(false, "Invalid enum base type");
break;
}
}
else if (type == typeof(String))
{
if (value == null)
writer.Write((byte)0xff);
else
EmitString(writer, (String)value);
}
else if (type == typeof(Type))
{
if (value == null)
writer.Write((byte)0xff);
else
{
String typeName = TypeNameBuilder.ToString((Type)value, TypeNameBuilder.Format.AssemblyQualifiedName);
if (typeName == null)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeForCA",
value.GetType()));
EmitString(writer, typeName);
}
}
else if (type.IsArray)
{
if (value == null)
writer.Write((uint)0xffffffff);
else
{
Array a = (Array)value;
Type et = type.GetElementType();
writer.Write(a.Length);
for (int i = 0; i < a.Length; i++)
EmitValue(writer, et, a.GetValue(i));
}
}
else if (type.IsPrimitive)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.SByte:
writer.Write((sbyte)value);
break;
case TypeCode.Byte:
writer.Write((byte)value);
break;
case TypeCode.Char:
writer.Write(Convert.ToUInt16((char)value));
break;
case TypeCode.Boolean:
writer.Write((byte)((bool)value ? 1 : 0));
break;
case TypeCode.Int16:
writer.Write((short)value);
break;
case TypeCode.UInt16:
writer.Write((ushort)value);
break;
case TypeCode.Int32:
writer.Write((int)value);
break;
case TypeCode.UInt32:
writer.Write((uint)value);
break;
case TypeCode.Int64:
writer.Write((long)value);
break;
case TypeCode.UInt64:
writer.Write((ulong)value);
break;
case TypeCode.Single:
writer.Write((float)value);
break;
case TypeCode.Double:
writer.Write((double)value);
break;
default:
Contract.Assert(false, "Invalid primitive type");
break;
}
}
else if (type == typeof(object))
{
// Tagged object case. Type instances aren't actually Type, they're some subclass (such as RuntimeType or
// TypeBuilder), so we need to canonicalize this case back to Type. If we have a null value we follow the convention
// used by C# and emit a null typed as a string (it doesn't really matter what type we pick as long as it's a
// reference type).
Type ot = value == null ? typeof(String) : value is Type ? typeof(Type) : value.GetType();
// value cannot be a "System.Object" object.
// If we allow this we will get into an infinite recursion
if (ot == typeof(object))
throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForCAB", ot.ToString()));
EmitType(writer, ot);
EmitValue(writer, ot, value);
}
else
{
string typename = "null";
if (value != null)
typename = value.GetType().ToString();
throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForCAB", typename));
}
}
// return the byte interpretation of the custom attribute
[System.Security.SecurityCritical] // auto-generated
internal void CreateCustomAttribute(ModuleBuilder mod, int tkOwner)
{
CreateCustomAttribute(mod, tkOwner, mod.GetConstructorToken(m_con).Token, false);
}
//*************************************************
// Upon saving to disk, we need to create the memberRef token for the custom attribute's type
// first of all. So when we snap the in-memory module for on disk, this token will be there.
// We also need to enforce the use of MemberRef. Because MemberDef token might move.
// This function has to be called before we snap the in-memory module for on disk (i.e. Presave on
// ModuleBuilder.
//*************************************************
[System.Security.SecurityCritical] // auto-generated
internal int PrepareCreateCustomAttributeToDisk(ModuleBuilder mod)
{
return mod.InternalGetConstructorToken(m_con, true).Token;
}
//*************************************************
// Call this function with toDisk=1, after on disk module has been snapped.
//*************************************************
[System.Security.SecurityCritical] // auto-generated
internal void CreateCustomAttribute(ModuleBuilder mod, int tkOwner, int tkAttrib, bool toDisk)
{
TypeBuilder.DefineCustomAttribute(mod, tkOwner, tkAttrib, m_blob, toDisk,
typeof(System.Diagnostics.DebuggableAttribute) == m_con.DeclaringType);
}
#if !FEATURE_CORECLR
void _CustomAttributeBuilder.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _CustomAttributeBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _CustomAttributeBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
void _CustomAttributeBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
#endif
internal ConstructorInfo m_con;
internal Object[] m_constructorArgs;
internal byte[] m_blob;
}
}
| |
// 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.Web.Security.Membership.cs
// Automatically generated contract file.
using System.Collections.Generic;
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.Web.Security
{
static public partial class Membership
{
#region Methods and constructors
public static MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, Object providerUserKey, out MembershipCreateStatus status)
{
status = default(MembershipCreateStatus);
return default(MembershipUser);
}
public static MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, out MembershipCreateStatus status)
{
status = default(MembershipCreateStatus);
return default(MembershipUser);
}
public static MembershipUser CreateUser(string username, string password)
{
return default(MembershipUser);
}
public static MembershipUser CreateUser(string username, string password, string email)
{
return default(MembershipUser);
}
public static bool DeleteUser(string username)
{
return default(bool);
}
public static bool DeleteUser(string username, bool deleteAllRelatedData)
{
return default(bool);
}
public static MembershipUserCollection FindUsersByEmail(string emailToMatch)
{
return default(MembershipUserCollection);
}
public static MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
{
totalRecords = default(int);
return default(MembershipUserCollection);
}
public static MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
totalRecords = default(int);
return default(MembershipUserCollection);
}
public static MembershipUserCollection FindUsersByName(string usernameToMatch)
{
return default(MembershipUserCollection);
}
public static string GeneratePassword(int length, int numberOfNonAlphanumericCharacters)
{
return default(string);
}
public static MembershipUserCollection GetAllUsers()
{
return default(MembershipUserCollection);
}
public static MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
{
totalRecords = default(int);
return default(MembershipUserCollection);
}
public static int GetNumberOfUsersOnline()
{
return default(int);
}
public static MembershipUser GetUser(string username, bool userIsOnline)
{
return default(MembershipUser);
}
public static MembershipUser GetUser(string username)
{
return default(MembershipUser);
}
public static MembershipUser GetUser()
{
return default(MembershipUser);
}
public static MembershipUser GetUser(Object providerUserKey)
{
return default(MembershipUser);
}
public static MembershipUser GetUser(bool userIsOnline)
{
return default(MembershipUser);
}
public static MembershipUser GetUser(Object providerUserKey, bool userIsOnline)
{
return default(MembershipUser);
}
public static string GetUserNameByEmail(string emailToMatch)
{
return default(string);
}
public static void UpdateUser(MembershipUser user)
{
}
public static bool ValidateUser(string username, string password)
{
return default(bool);
}
#endregion
#region Properties and indexers
public static string ApplicationName
{
get
{
return default(string);
}
set
{
}
}
public static bool EnablePasswordReset
{
get
{
return default(bool);
}
}
public static bool EnablePasswordRetrieval
{
get
{
return default(bool);
}
}
public static string HashAlgorithmType
{
get
{
return default(string);
}
}
public static int MaxInvalidPasswordAttempts
{
get
{
return default(int);
}
}
public static int MinRequiredNonAlphanumericCharacters
{
get
{
return default(int);
}
}
public static int MinRequiredPasswordLength
{
get
{
return default(int);
}
}
public static int PasswordAttemptWindow
{
get
{
return default(int);
}
}
public static string PasswordStrengthRegularExpression
{
get
{
return default(string);
}
}
public static MembershipProvider Provider
{
get
{
return default(MembershipProvider);
}
}
public static MembershipProviderCollection Providers
{
get
{
return default(MembershipProviderCollection);
}
}
public static bool RequiresQuestionAndAnswer
{
get
{
return default(bool);
}
}
public static int UserIsOnlineTimeWindow
{
get
{
return default(int);
}
}
#endregion
#region Events
public static event MembershipValidatePasswordEventHandler ValidatingPassword
{
add
{
}
remove
{
}
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Models.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml.Serialization {
using System;
using System.Reflection;
using System.Collections;
using System.Diagnostics;
// These classes define the abstract serialization model, e.g. the rules for WHAT is serialized.
// The answer of HOW the values are serialized is answered by a particular reflection importer
// by looking for a particular set of custom attributes specific to the serialization format
// and building an appropriate set of accessors/mappings.
internal class ModelScope {
TypeScope typeScope;
Hashtable models = new Hashtable();
Hashtable arrayModels = new Hashtable();
internal ModelScope(TypeScope typeScope) {
this.typeScope = typeScope;
}
internal TypeScope TypeScope {
get { return typeScope; }
}
internal TypeModel GetTypeModel(Type type) {
return GetTypeModel(type, true);
}
internal TypeModel GetTypeModel(Type type, bool directReference) {
TypeModel model = (TypeModel)models[type];
if (model != null) return model;
TypeDesc typeDesc = typeScope.GetTypeDesc(type, null, directReference);
switch (typeDesc.Kind) {
case TypeKind.Enum:
model = new EnumModel(type, typeDesc, this);
break;
case TypeKind.Primitive:
model = new PrimitiveModel(type, typeDesc, this);
break;
case TypeKind.Array:
case TypeKind.Collection:
case TypeKind.Enumerable:
model = new ArrayModel(type, typeDesc, this);
break;
case TypeKind.Root:
case TypeKind.Class:
case TypeKind.Struct:
model = new StructModel(type, typeDesc, this);
break;
default:
if (!typeDesc.IsSpecial) throw new NotSupportedException(Res.GetString(Res.XmlUnsupportedTypeKind, type.FullName));
model = new SpecialModel(type, typeDesc, this);
break;
}
models.Add(type, model);
return model;
}
internal ArrayModel GetArrayModel(Type type) {
TypeModel model = (TypeModel)arrayModels[type];
if (model == null) {
model = GetTypeModel(type);
if (!(model is ArrayModel)) {
TypeDesc typeDesc = typeScope.GetArrayTypeDesc(type);
model = new ArrayModel(type, typeDesc, this);
}
arrayModels.Add(type, model);
}
return (ArrayModel)model;
}
}
internal abstract class TypeModel {
TypeDesc typeDesc;
Type type;
ModelScope scope;
protected TypeModel(Type type, TypeDesc typeDesc, ModelScope scope) {
this.scope = scope;
this.type = type;
this.typeDesc = typeDesc;
}
internal Type Type {
get { return type; }
}
internal ModelScope ModelScope {
get { return scope; }
}
internal TypeDesc TypeDesc {
get { return typeDesc; }
}
}
internal class ArrayModel : TypeModel {
internal ArrayModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, typeDesc, scope) { }
internal TypeModel Element {
get { return ModelScope.GetTypeModel(TypeScope.GetArrayElementType(Type, null)); }
}
}
internal class PrimitiveModel : TypeModel {
internal PrimitiveModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, typeDesc, scope) { }
}
internal class SpecialModel : TypeModel {
internal SpecialModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, typeDesc, scope) { }
}
internal class StructModel : TypeModel {
internal StructModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, typeDesc, scope) { }
internal MemberInfo[] GetMemberInfos() {
// we use to return Type.GetMembers() here, the members were returned in a different order: fields first, properties last
// Current System.Reflection code returns members in oposite order: properties first, then fields.
// This code make sure that returns members in the Everett order.
MemberInfo[] members = Type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
MemberInfo[] fieldsAndProps = new MemberInfo[members.Length];
int cMember = 0;
// first copy all non-property members over
for (int i = 0; i < members.Length; i++) {
if ((members[i].MemberType & MemberTypes.Property) == 0) {
fieldsAndProps[cMember++] = members[i];
}
}
// now copy all property members over
for (int i = 0; i < members.Length; i++) {
if ((members[i].MemberType & MemberTypes.Property) != 0) {
fieldsAndProps[cMember++] = members[i];
}
}
return fieldsAndProps;
}
internal FieldModel GetFieldModel(MemberInfo memberInfo) {
FieldModel model = null;
if (memberInfo is FieldInfo)
model = GetFieldModel((FieldInfo)memberInfo);
else if (memberInfo is PropertyInfo)
model = GetPropertyModel((PropertyInfo)memberInfo);
if (model != null) {
if (model.ReadOnly && model.FieldTypeDesc.Kind != TypeKind.Collection && model.FieldTypeDesc.Kind != TypeKind.Enumerable)
return null;
}
return model;
}
void CheckSupportedMember(TypeDesc typeDesc, MemberInfo member, Type type) {
if (typeDesc == null)
return;
if (typeDesc.IsUnsupported) {
if (typeDesc.Exception == null) {
typeDesc.Exception = new NotSupportedException(Res.GetString(Res.XmlSerializerUnsupportedType, typeDesc.FullName));
}
throw new InvalidOperationException(Res.GetString(Res.XmlSerializerUnsupportedMember, member.DeclaringType.FullName + "." + member.Name, type.FullName), typeDesc.Exception);
}
CheckSupportedMember(typeDesc.BaseTypeDesc, member, type);
CheckSupportedMember(typeDesc.ArrayElementTypeDesc, member, type);
}
FieldModel GetFieldModel(FieldInfo fieldInfo) {
if (fieldInfo.IsStatic) return null;
if (fieldInfo.DeclaringType != Type) return null;
TypeDesc typeDesc = ModelScope.TypeScope.GetTypeDesc(fieldInfo.FieldType, fieldInfo, true, false);
if (fieldInfo.IsInitOnly && typeDesc.Kind != TypeKind.Collection && typeDesc.Kind != TypeKind.Enumerable)
return null;
CheckSupportedMember(typeDesc, fieldInfo, fieldInfo.FieldType);
return new FieldModel(fieldInfo, fieldInfo.FieldType, typeDesc);
}
FieldModel GetPropertyModel(PropertyInfo propertyInfo) {
if (propertyInfo.DeclaringType != Type) return null;
if (CheckPropertyRead(propertyInfo)) {
TypeDesc typeDesc = ModelScope.TypeScope.GetTypeDesc(propertyInfo.PropertyType, propertyInfo, true, false);
// Fix for CSDMain 100492, please contact arssrvlt if you need to change this line
if (!propertyInfo.CanWrite && typeDesc.Kind != TypeKind.Collection && typeDesc.Kind != TypeKind.Enumerable)
return null;
CheckSupportedMember(typeDesc, propertyInfo, propertyInfo.PropertyType);
return new FieldModel(propertyInfo, propertyInfo.PropertyType, typeDesc);
}
return null;
}
//CheckProperty
internal static bool CheckPropertyRead(PropertyInfo propertyInfo) {
if (!propertyInfo.CanRead) return false;
MethodInfo getMethod = propertyInfo.GetGetMethod();
if (getMethod.IsStatic) return false;
ParameterInfo[] parameters = getMethod.GetParameters();
if (parameters.Length > 0) return false;
return true;
}
}
internal enum SpecifiedAccessor {
None,
ReadOnly,
ReadWrite,
}
internal class FieldModel {
SpecifiedAccessor checkSpecified = SpecifiedAccessor.None;
MemberInfo memberInfo;
MemberInfo checkSpecifiedMemberInfo;
MethodInfo checkShouldPersistMethodInfo;
bool checkShouldPersist;
bool readOnly = false;
bool isProperty = false;
Type fieldType;
string name;
TypeDesc fieldTypeDesc;
internal FieldModel(string name, Type fieldType, TypeDesc fieldTypeDesc, bool checkSpecified, bool checkShouldPersist) :
this(name, fieldType, fieldTypeDesc, checkSpecified, checkShouldPersist, false) {
}
internal FieldModel(string name, Type fieldType, TypeDesc fieldTypeDesc, bool checkSpecified, bool checkShouldPersist, bool readOnly) {
this.fieldTypeDesc = fieldTypeDesc;
this.name = name;
this.fieldType = fieldType;
this.checkSpecified = checkSpecified ? SpecifiedAccessor.ReadWrite : SpecifiedAccessor.None;
this.checkShouldPersist = checkShouldPersist;
this.readOnly = readOnly;
}
internal FieldModel(MemberInfo memberInfo, Type fieldType, TypeDesc fieldTypeDesc) {
this.name = memberInfo.Name;
this.fieldType = fieldType;
this.fieldTypeDesc = fieldTypeDesc;
this.memberInfo = memberInfo;
this.checkShouldPersistMethodInfo = memberInfo.DeclaringType.GetMethod("ShouldSerialize" + memberInfo.Name, new Type[0]);
this.checkShouldPersist = this.checkShouldPersistMethodInfo != null;
FieldInfo specifiedField = memberInfo.DeclaringType.GetField(memberInfo.Name + "Specified");
if (specifiedField != null) {
if (specifiedField.FieldType != typeof(bool)) {
throw new InvalidOperationException(Res.GetString(Res.XmlInvalidSpecifiedType, specifiedField.Name, specifiedField.FieldType.FullName, typeof(bool).FullName));
}
this.checkSpecified = specifiedField.IsInitOnly ? SpecifiedAccessor.ReadOnly : SpecifiedAccessor.ReadWrite;
this.checkSpecifiedMemberInfo = specifiedField;
}
else {
PropertyInfo specifiedProperty = memberInfo.DeclaringType.GetProperty(memberInfo.Name + "Specified");
if (specifiedProperty != null) {
if (StructModel.CheckPropertyRead(specifiedProperty)) {
this.checkSpecified = specifiedProperty.CanWrite ? SpecifiedAccessor.ReadWrite : SpecifiedAccessor.ReadOnly;
this.checkSpecifiedMemberInfo = specifiedProperty;
}
if (this.checkSpecified != SpecifiedAccessor.None && specifiedProperty.PropertyType != typeof(bool)) {
throw new InvalidOperationException(Res.GetString(Res.XmlInvalidSpecifiedType, specifiedProperty.Name, specifiedProperty.PropertyType.FullName, typeof(bool).FullName));
}
}
}
if (memberInfo is PropertyInfo) {
readOnly = !((PropertyInfo)memberInfo).CanWrite;
isProperty = true;
}
else if (memberInfo is FieldInfo) {
readOnly = ((FieldInfo)memberInfo).IsInitOnly;
}
}
internal string Name {
get { return name; }
}
internal Type FieldType {
get { return fieldType; }
}
internal TypeDesc FieldTypeDesc {
get { return fieldTypeDesc; }
}
internal bool CheckShouldPersist {
get { return checkShouldPersist; }
}
internal SpecifiedAccessor CheckSpecified {
get { return checkSpecified; }
}
internal MemberInfo MemberInfo {
get { return memberInfo; }
}
internal MemberInfo CheckSpecifiedMemberInfo {
get { return checkSpecifiedMemberInfo; }
}
internal MethodInfo CheckShouldPersistMethodInfo {
get { return checkShouldPersistMethodInfo; }
}
internal bool ReadOnly {
get { return readOnly; }
}
internal bool IsProperty {
get { return isProperty; }
}
}
internal class ConstantModel {
FieldInfo fieldInfo;
long value;
internal ConstantModel(FieldInfo fieldInfo, long value) {
this.fieldInfo = fieldInfo;
this.value = value;
}
internal string Name {
get { return fieldInfo.Name; }
}
internal long Value {
get { return value; }
}
internal FieldInfo FieldInfo {
get { return fieldInfo; }
}
}
internal class EnumModel : TypeModel {
ConstantModel[] constants;
internal EnumModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, typeDesc, scope) { }
internal ConstantModel[] Constants {
get {
if (constants == null) {
ArrayList list = new ArrayList();
FieldInfo[] fields = Type.GetFields();
for (int i = 0; i < fields.Length; i++) {
FieldInfo field = fields[i];
ConstantModel constant = GetConstantModel(field);
if (constant != null) list.Add(constant);
}
constants = (ConstantModel[])list.ToArray(typeof(ConstantModel));
}
return constants;
}
}
ConstantModel GetConstantModel(FieldInfo fieldInfo) {
if (fieldInfo.IsSpecialName) return null;
return new ConstantModel(fieldInfo, ((IConvertible)fieldInfo.GetValue(null)).ToInt64(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.Diagnostics;
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", Scope = "member", Target = "System.ComponentModel.PropertyDescriptorCollection.System.Collections.IDictionary.Add(System.Object,System.Object):System.Void")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", Scope = "member", Target = "System.ComponentModel.PropertyDescriptorCollection.System.Collections.IList.set_Item(System.Int32,System.Object):System.Void")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", Scope = "member", Target = "System.ComponentModel.PropertyDescriptorCollection.System.Collections.IDictionary.set_Item(System.Object,System.Object):System.Void")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2112:SecuredTypesShouldNotExposeFields", Scope = "type", Target = "System.ComponentModel.PropertyDescriptorCollection")]
namespace System.ComponentModel
{
/// <summary>
/// <para>
/// Represents a collection of properties.
/// </para>
/// </summary>
public class PropertyDescriptorCollection : ICollection, IList, IDictionary
{
/// <summary>
/// An empty PropertyDescriptorCollection that can used instead of creating a new one with no items.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2112:SecuredTypesShouldNotExposeFields")]
public static readonly PropertyDescriptorCollection Empty = new PropertyDescriptorCollection(null, true);
private IDictionary _cachedFoundProperties;
private bool _cachedIgnoreCase;
private PropertyDescriptor[] _properties;
private int _propCount = 0;
private readonly string[] _namedSort;
private readonly IComparer _comparer;
private bool _propsOwned;
private bool _needSort = false;
private bool _readOnly = false;
private readonly object _internalSyncObject = new object();
/// <summary>
/// <para>
/// Initializes a new instance of the <see cref='System.ComponentModel.PropertyDescriptorCollection'/>
/// class.
/// </para>
/// </summary>
public PropertyDescriptorCollection(PropertyDescriptor[] properties)
{
if (properties == null)
{
_properties = Array.Empty<PropertyDescriptor>();
_propCount = 0;
}
else
{
_properties = properties;
_propCount = properties.Length;
}
_propsOwned = true;
}
/// <summary>
/// Initializes a new instance of a property descriptor collection, and allows you to mark the
/// collection as read-only so it cannot be modified.
/// </summary>
public PropertyDescriptorCollection(PropertyDescriptor[] properties, bool readOnly)
: this(properties)
{
_readOnly = readOnly;
}
private PropertyDescriptorCollection(PropertyDescriptor[] properties, int propCount, string[] namedSort, IComparer comparer)
{
_propsOwned = false;
if (namedSort != null)
{
_namedSort = (string[])namedSort.Clone();
}
_comparer = comparer;
_properties = properties;
_propCount = propCount;
_needSort = true;
}
/// <summary>
/// <para>
/// Gets the number
/// of property descriptors in the
/// collection.
/// </para>
/// </summary>
public int Count
{
get
{
return _propCount;
}
}
/// <summary>
/// <para>Gets the property with the specified index
/// number.</para>
/// </summary>
public virtual PropertyDescriptor this[int index]
{
get
{
if (index >= _propCount)
{
throw new IndexOutOfRangeException();
}
EnsurePropsOwned();
return _properties[index];
}
}
/// <summary>
/// <para>Gets the property with the specified name.</para>
/// </summary>
public virtual PropertyDescriptor this[string name]
{
get
{
return Find(name, false);
}
}
/// <summary>
/// <para>[To be supplied.]</para>
/// </summary>
public int Add(PropertyDescriptor value)
{
if (_readOnly)
{
throw new NotSupportedException();
}
EnsureSize(_propCount + 1);
_properties[_propCount++] = value;
return _propCount - 1;
}
/// <summary>
/// <para>[To be supplied.]</para>
/// </summary>
public void Clear()
{
if (_readOnly)
{
throw new NotSupportedException();
}
_propCount = 0;
_cachedFoundProperties = null;
}
/// <summary>
/// <para>[To be supplied.]</para>
/// </summary>
public bool Contains(PropertyDescriptor value)
{
return IndexOf(value) >= 0;
}
/// <summary>
/// <para>[To be supplied.]</para>
/// </summary>
public void CopyTo(Array array, int index)
{
EnsurePropsOwned();
Array.Copy(_properties, 0, array, index, Count);
}
private void EnsurePropsOwned()
{
if (!_propsOwned)
{
_propsOwned = true;
if (_properties != null)
{
PropertyDescriptor[] newProps = new PropertyDescriptor[Count];
Array.Copy(_properties, 0, newProps, 0, Count);
_properties = newProps;
}
}
if (_needSort)
{
_needSort = false;
InternalSort(_namedSort);
}
}
private void EnsureSize(int sizeNeeded)
{
if (sizeNeeded <= _properties.Length)
{
return;
}
if (_properties.Length == 0)
{
_propCount = 0;
_properties = new PropertyDescriptor[sizeNeeded];
return;
}
EnsurePropsOwned();
int newSize = Math.Max(sizeNeeded, _properties.Length * 2);
PropertyDescriptor[] newProps = new PropertyDescriptor[newSize];
Array.Copy(_properties, 0, newProps, 0, _propCount);
_properties = newProps;
}
/// <summary>
/// <para>Gets the description of the property with the specified name.</para>
/// </summary>
public virtual PropertyDescriptor Find(string name, bool ignoreCase)
{
lock (_internalSyncObject)
{
PropertyDescriptor p = null;
if (_cachedFoundProperties == null || _cachedIgnoreCase != ignoreCase)
{
_cachedIgnoreCase = ignoreCase;
if (ignoreCase)
{
_cachedFoundProperties = new Hashtable(StringComparer.OrdinalIgnoreCase);
}
else
{
_cachedFoundProperties = new Hashtable();
}
}
// first try to find it in the cache
//
object cached = _cachedFoundProperties[name];
if (cached != null)
{
return (PropertyDescriptor)cached;
}
// Now start walking from where we last left off, filling
// the cache as we go.
//
for (int i = 0; i < _propCount; i++)
{
if (ignoreCase)
{
if (string.Equals(_properties[i].Name, name, StringComparison.OrdinalIgnoreCase))
{
_cachedFoundProperties[name] = _properties[i];
p = _properties[i];
break;
}
}
else
{
if (_properties[i].Name.Equals(name))
{
_cachedFoundProperties[name] = _properties[i];
p = _properties[i];
break;
}
}
}
return p;
}
}
/// <summary>
/// <para>[To be supplied.]</para>
/// </summary>
public int IndexOf(PropertyDescriptor value)
{
return Array.IndexOf(_properties, value, 0, _propCount);
}
/// <summary>
/// <para>[To be supplied.]</para>
/// </summary>
public void Insert(int index, PropertyDescriptor value)
{
if (_readOnly)
{
throw new NotSupportedException();
}
EnsureSize(_propCount + 1);
if (index < _propCount)
{
Array.Copy(_properties, index, _properties, index + 1, _propCount - index);
}
_properties[index] = value;
_propCount++;
}
/// <summary>
/// <para>[To be supplied.]</para>
/// </summary>
public void Remove(PropertyDescriptor value)
{
if (_readOnly)
{
throw new NotSupportedException();
}
int index = IndexOf(value);
if (index != -1)
{
RemoveAt(index);
}
}
/// <summary>
/// <para>[To be supplied.]</para>
/// </summary>
public void RemoveAt(int index)
{
if (_readOnly)
{
throw new NotSupportedException();
}
if (index < _propCount - 1)
{
Array.Copy(_properties, index + 1, _properties, index, _propCount - index - 1);
}
_properties[_propCount - 1] = null;
_propCount--;
}
/// <summary>
/// <para>
/// Sorts the members of this PropertyDescriptorCollection, using the default sort for this collection,
/// which is usually alphabetical.
/// </para>
/// </summary>
public virtual PropertyDescriptorCollection Sort()
{
return new PropertyDescriptorCollection(_properties, _propCount, _namedSort, _comparer);
}
/// <summary>
/// <para>
/// Sorts the members of this PropertyDescriptorCollection. Any specified NamedSort arguments will
/// be applied first, followed by sort using the specified IComparer.
/// </para>
/// </summary>
public virtual PropertyDescriptorCollection Sort(string[] names)
{
return new PropertyDescriptorCollection(_properties, _propCount, names, _comparer);
}
/// <summary>
/// <para>
/// Sorts the members of this PropertyDescriptorCollection. Any specified NamedSort arguments will
/// be applied first, followed by sort using the specified IComparer.
/// </para>
/// </summary>
public virtual PropertyDescriptorCollection Sort(string[] names, IComparer comparer)
{
return new PropertyDescriptorCollection(_properties, _propCount, names, comparer);
}
/// <summary>
/// <para>
/// Sorts the members of this PropertyDescriptorCollection, using the specified IComparer to compare,
/// the PropertyDescriptors contained in the collection.
/// </para>
/// </summary>
public virtual PropertyDescriptorCollection Sort(IComparer comparer)
{
return new PropertyDescriptorCollection(_properties, _propCount, _namedSort, comparer);
}
/// <summary>
/// <para>
/// Sorts the members of this PropertyDescriptorCollection. Any specified NamedSort arguments will
/// be applied first, followed by sort using the specified IComparer.
/// </para>
/// </summary>
protected void InternalSort(string[] names)
{
if (_properties.Length == 0)
{
return;
}
this.InternalSort(_comparer);
if (names != null && names.Length > 0)
{
ArrayList propArrayList = new ArrayList(_properties);
int foundCount = 0;
int propCount = _properties.Length;
for (int i = 0; i < names.Length; i++)
{
for (int j = 0; j < propCount; j++)
{
PropertyDescriptor currentProp = (PropertyDescriptor)propArrayList[j];
// Found a matching property. Here, we add it to our array. We also
// mark it as null in our array list so we don't add it twice later.
//
if (currentProp != null && currentProp.Name.Equals(names[i]))
{
_properties[foundCount++] = currentProp;
propArrayList[j] = null;
break;
}
}
}
// At this point we have filled in the first "foundCount" number of propeties, one for each
// name in our name array. If a name didn't match, then it is ignored. Next, we must fill
// in the rest of the properties. We now have a sparse array containing the remainder, so
// it's easy.
//
for (int i = 0; i < propCount; i++)
{
if (propArrayList[i] != null)
{
_properties[foundCount++] = (PropertyDescriptor)propArrayList[i];
}
}
Debug.Assert(foundCount == propCount, "We did not completely fill our property array");
}
}
/// <summary>
/// <para>
/// Sorts the members of this PropertyDescriptorCollection using the specified IComparer.
/// </para>
/// </summary>
protected void InternalSort(IComparer sorter)
{
if (sorter == null)
{
TypeDescriptor.SortDescriptorArray(this);
}
else
{
Array.Sort(_properties, sorter);
}
}
/// <summary>
/// <para>
/// Gets an enumerator for this <see cref='System.ComponentModel.PropertyDescriptorCollection'/>.
/// </para>
/// </summary>
public virtual IEnumerator GetEnumerator()
{
EnsurePropsOwned();
// we can only return an enumerator on the props we actually have...
if (_properties.Length != _propCount)
{
PropertyDescriptor[] enumProps = new PropertyDescriptor[_propCount];
Array.Copy(_properties, 0, enumProps, 0, _propCount);
return enumProps.GetEnumerator();
}
return _properties.GetEnumerator();
}
/// <internalonly/>
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
/// <internalonly/>
object ICollection.SyncRoot
{
get
{
return null;
}
}
/// <internalonly/>
void IDictionary.Add(object key, object value)
{
PropertyDescriptor newProp = value as PropertyDescriptor;
if (newProp == null)
{
throw new ArgumentException(nameof(value));
}
Add(newProp);
}
/// <internalonly/>
bool IDictionary.Contains(object key)
{
if (key is string)
{
return this[(string)key] != null;
}
return false;
}
/// <internalonly/>
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new PropertyDescriptorEnumerator(this);
}
/// <internalonly/>
bool IDictionary.IsFixedSize
{
get
{
return _readOnly;
}
}
/// <internalonly/>
bool IDictionary.IsReadOnly
{
get
{
return _readOnly;
}
}
/// <internalonly/>
object IDictionary.this[object key]
{
get
{
if (key is string)
{
return this[(string)key];
}
return null;
}
set
{
if (_readOnly)
{
throw new NotSupportedException();
}
if (value != null && !(value is PropertyDescriptor))
{
throw new ArgumentException(nameof(value));
}
int index = -1;
if (key is int)
{
index = (int)key;
if (index < 0 || index >= _propCount)
{
throw new IndexOutOfRangeException();
}
}
else if (key is string)
{
for (int i = 0; i < _propCount; i++)
{
if (_properties[i].Name.Equals((string)key))
{
index = i;
break;
}
}
}
else
{
throw new ArgumentException(nameof(key));
}
if (index == -1)
{
Add((PropertyDescriptor)value);
}
else
{
EnsurePropsOwned();
_properties[index] = (PropertyDescriptor)value;
if (_cachedFoundProperties != null && key is string)
{
_cachedFoundProperties[key] = value;
}
}
}
}
/// <internalonly/>
ICollection IDictionary.Keys
{
get
{
string[] keys = new string[_propCount];
for (int i = 0; i < _propCount; i++)
{
keys[i] = _properties[i].Name;
}
return keys;
}
}
/// <internalonly/>
ICollection IDictionary.Values
{
get
{
// we can only return an enumerator on the props we actually have...
//
if (_properties.Length != _propCount)
{
PropertyDescriptor[] newProps = new PropertyDescriptor[_propCount];
Array.Copy(_properties, 0, newProps, 0, _propCount);
return newProps;
}
else
{
return (ICollection)_properties.Clone();
}
}
}
/// <internalonly/>
void IDictionary.Remove(object key)
{
if (key is string)
{
PropertyDescriptor pd = this[(string)key];
if (pd != null)
{
((IList)this).Remove(pd);
}
}
}
/// <internalonly/>
int IList.Add(object value)
{
return Add((PropertyDescriptor)value);
}
/// <internalonly/>
bool IList.Contains(object value)
{
return Contains((PropertyDescriptor)value);
}
/// <internalonly/>
int IList.IndexOf(object value)
{
return IndexOf((PropertyDescriptor)value);
}
/// <internalonly/>
void IList.Insert(int index, object value)
{
Insert(index, (PropertyDescriptor)value);
}
/// <internalonly/>
bool IList.IsReadOnly
{
get
{
return _readOnly;
}
}
/// <internalonly/>
bool IList.IsFixedSize
{
get
{
return _readOnly;
}
}
/// <internalonly/>
void IList.Remove(object value)
{
Remove((PropertyDescriptor)value);
}
/// <internalonly/>
object IList.this[int index]
{
get
{
return this[index];
}
set
{
if (_readOnly)
{
throw new NotSupportedException();
}
if (index >= _propCount)
{
throw new IndexOutOfRangeException();
}
if (value != null && !(value is PropertyDescriptor))
{
throw new ArgumentException(nameof(value));
}
EnsurePropsOwned();
_properties[index] = (PropertyDescriptor)value;
}
}
private class PropertyDescriptorEnumerator : IDictionaryEnumerator
{
private PropertyDescriptorCollection _owner;
private int _index = -1;
public PropertyDescriptorEnumerator(PropertyDescriptorCollection owner)
{
_owner = owner;
}
public object Current
{
get
{
return Entry;
}
}
public DictionaryEntry Entry
{
get
{
PropertyDescriptor curProp = _owner[_index];
return new DictionaryEntry(curProp.Name, curProp);
}
}
public object Key
{
get
{
return _owner[_index].Name;
}
}
public object Value
{
get
{
return _owner[_index].Name;
}
}
public bool MoveNext()
{
if (_index < (_owner.Count - 1))
{
_index++;
return true;
}
return false;
}
public void Reset()
{
_index = -1;
}
}
}
}
| |
using System;
using System.Linq;
using System.Runtime.InteropServices;
using Torque6.Engine.SimObjects;
using Torque6.Engine.SimObjects.Scene;
using Torque6.Engine.Namespaces;
using Torque6.Utility;
namespace Torque6.Engine.SimObjects.GuiControls
{
public unsafe class GuiTabBookCtrl : GuiControl
{
public GuiTabBookCtrl()
{
ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.GuiTabBookCtrlCreateInstance());
}
public GuiTabBookCtrl(uint pId) : base(pId)
{
}
public GuiTabBookCtrl(string pName) : base(pName)
{
}
public GuiTabBookCtrl(IntPtr pObjPtr) : base(pObjPtr)
{
}
public GuiTabBookCtrl(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr)
{
}
public GuiTabBookCtrl(SimObject pObj) : base(pObj)
{
}
#region UnsafeNativeMethods
new internal struct InternalUnsafeMethods
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int _GuiTabBookCtrlGetTabPosition(IntPtr ctrl);
private static _GuiTabBookCtrlGetTabPosition _GuiTabBookCtrlGetTabPositionFunc;
internal static int GuiTabBookCtrlGetTabPosition(IntPtr ctrl)
{
if (_GuiTabBookCtrlGetTabPositionFunc == null)
{
_GuiTabBookCtrlGetTabPositionFunc =
(_GuiTabBookCtrlGetTabPosition)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiTabBookCtrlGetTabPosition"), typeof(_GuiTabBookCtrlGetTabPosition));
}
return _GuiTabBookCtrlGetTabPositionFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiTabBookCtrlSetTabPosition(IntPtr ctrl, int tabPosition);
private static _GuiTabBookCtrlSetTabPosition _GuiTabBookCtrlSetTabPositionFunc;
internal static void GuiTabBookCtrlSetTabPosition(IntPtr ctrl, int tabPosition)
{
if (_GuiTabBookCtrlSetTabPositionFunc == null)
{
_GuiTabBookCtrlSetTabPositionFunc =
(_GuiTabBookCtrlSetTabPosition)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiTabBookCtrlSetTabPosition"), typeof(_GuiTabBookCtrlSetTabPosition));
}
_GuiTabBookCtrlSetTabPositionFunc(ctrl, tabPosition);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int _GuiTabBookCtrlGetTabHeight(IntPtr ctrl);
private static _GuiTabBookCtrlGetTabHeight _GuiTabBookCtrlGetTabHeightFunc;
internal static int GuiTabBookCtrlGetTabHeight(IntPtr ctrl)
{
if (_GuiTabBookCtrlGetTabHeightFunc == null)
{
_GuiTabBookCtrlGetTabHeightFunc =
(_GuiTabBookCtrlGetTabHeight)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiTabBookCtrlGetTabHeight"), typeof(_GuiTabBookCtrlGetTabHeight));
}
return _GuiTabBookCtrlGetTabHeightFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiTabBookCtrlSetTabHeight(IntPtr ctrl, int height);
private static _GuiTabBookCtrlSetTabHeight _GuiTabBookCtrlSetTabHeightFunc;
internal static void GuiTabBookCtrlSetTabHeight(IntPtr ctrl, int height)
{
if (_GuiTabBookCtrlSetTabHeightFunc == null)
{
_GuiTabBookCtrlSetTabHeightFunc =
(_GuiTabBookCtrlSetTabHeight)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiTabBookCtrlSetTabHeight"), typeof(_GuiTabBookCtrlSetTabHeight));
}
_GuiTabBookCtrlSetTabHeightFunc(ctrl, height);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int _GuiTabBookCtrlGetTabMargin(IntPtr ctrl);
private static _GuiTabBookCtrlGetTabMargin _GuiTabBookCtrlGetTabMarginFunc;
internal static int GuiTabBookCtrlGetTabMargin(IntPtr ctrl)
{
if (_GuiTabBookCtrlGetTabMarginFunc == null)
{
_GuiTabBookCtrlGetTabMarginFunc =
(_GuiTabBookCtrlGetTabMargin)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiTabBookCtrlGetTabMargin"), typeof(_GuiTabBookCtrlGetTabMargin));
}
return _GuiTabBookCtrlGetTabMarginFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiTabBookCtrlSetTabMargin(IntPtr ctrl, int margin);
private static _GuiTabBookCtrlSetTabMargin _GuiTabBookCtrlSetTabMarginFunc;
internal static void GuiTabBookCtrlSetTabMargin(IntPtr ctrl, int margin)
{
if (_GuiTabBookCtrlSetTabMarginFunc == null)
{
_GuiTabBookCtrlSetTabMarginFunc =
(_GuiTabBookCtrlSetTabMargin)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiTabBookCtrlSetTabMargin"), typeof(_GuiTabBookCtrlSetTabMargin));
}
_GuiTabBookCtrlSetTabMarginFunc(ctrl, margin);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int _GuiTabBookCtrlGetMinTabWidth(IntPtr ctrl);
private static _GuiTabBookCtrlGetMinTabWidth _GuiTabBookCtrlGetMinTabWidthFunc;
internal static int GuiTabBookCtrlGetMinTabWidth(IntPtr ctrl)
{
if (_GuiTabBookCtrlGetMinTabWidthFunc == null)
{
_GuiTabBookCtrlGetMinTabWidthFunc =
(_GuiTabBookCtrlGetMinTabWidth)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiTabBookCtrlGetMinTabWidth"), typeof(_GuiTabBookCtrlGetMinTabWidth));
}
return _GuiTabBookCtrlGetMinTabWidthFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiTabBookCtrlSetMinTabWidth(IntPtr ctrl, int width);
private static _GuiTabBookCtrlSetMinTabWidth _GuiTabBookCtrlSetMinTabWidthFunc;
internal static void GuiTabBookCtrlSetMinTabWidth(IntPtr ctrl, int width)
{
if (_GuiTabBookCtrlSetMinTabWidthFunc == null)
{
_GuiTabBookCtrlSetMinTabWidthFunc =
(_GuiTabBookCtrlSetMinTabWidth)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiTabBookCtrlSetMinTabWidth"), typeof(_GuiTabBookCtrlSetMinTabWidth));
}
_GuiTabBookCtrlSetMinTabWidthFunc(ctrl, width);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _GuiTabBookCtrlCreateInstance();
private static _GuiTabBookCtrlCreateInstance _GuiTabBookCtrlCreateInstanceFunc;
internal static IntPtr GuiTabBookCtrlCreateInstance()
{
if (_GuiTabBookCtrlCreateInstanceFunc == null)
{
_GuiTabBookCtrlCreateInstanceFunc =
(_GuiTabBookCtrlCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiTabBookCtrlCreateInstance"), typeof(_GuiTabBookCtrlCreateInstance));
}
return _GuiTabBookCtrlCreateInstanceFunc();
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiTabBookCtrlAddPage(IntPtr ctrl);
private static _GuiTabBookCtrlAddPage _GuiTabBookCtrlAddPageFunc;
internal static void GuiTabBookCtrlAddPage(IntPtr ctrl)
{
if (_GuiTabBookCtrlAddPageFunc == null)
{
_GuiTabBookCtrlAddPageFunc =
(_GuiTabBookCtrlAddPage)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiTabBookCtrlAddPage"), typeof(_GuiTabBookCtrlAddPage));
}
_GuiTabBookCtrlAddPageFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiTabBookCtrlSelectPage(IntPtr ctrl, int pageIndex);
private static _GuiTabBookCtrlSelectPage _GuiTabBookCtrlSelectPageFunc;
internal static void GuiTabBookCtrlSelectPage(IntPtr ctrl, int pageIndex)
{
if (_GuiTabBookCtrlSelectPageFunc == null)
{
_GuiTabBookCtrlSelectPageFunc =
(_GuiTabBookCtrlSelectPage)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiTabBookCtrlSelectPage"), typeof(_GuiTabBookCtrlSelectPage));
}
_GuiTabBookCtrlSelectPageFunc(ctrl, pageIndex);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiTabBookCtrlSelectPageName(IntPtr ctrl, string pageName);
private static _GuiTabBookCtrlSelectPageName _GuiTabBookCtrlSelectPageNameFunc;
internal static void GuiTabBookCtrlSelectPageName(IntPtr ctrl, string pageName)
{
if (_GuiTabBookCtrlSelectPageNameFunc == null)
{
_GuiTabBookCtrlSelectPageNameFunc =
(_GuiTabBookCtrlSelectPageName)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiTabBookCtrlSelectPageName"), typeof(_GuiTabBookCtrlSelectPageName));
}
_GuiTabBookCtrlSelectPageNameFunc(ctrl, pageName);
}
}
#endregion
#region Properties
public int TabPosition
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.GuiTabBookCtrlGetTabPosition(ObjectPtr->ObjPtr);
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiTabBookCtrlSetTabPosition(ObjectPtr->ObjPtr, value);
}
}
public int TabHeight
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.GuiTabBookCtrlGetTabHeight(ObjectPtr->ObjPtr);
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiTabBookCtrlSetTabHeight(ObjectPtr->ObjPtr, value);
}
}
public int TabMargin
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.GuiTabBookCtrlGetTabMargin(ObjectPtr->ObjPtr);
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiTabBookCtrlSetTabMargin(ObjectPtr->ObjPtr, value);
}
}
public int MinTabWidth
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.GuiTabBookCtrlGetMinTabWidth(ObjectPtr->ObjPtr);
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiTabBookCtrlSetMinTabWidth(ObjectPtr->ObjPtr, value);
}
}
#endregion
#region Methods
public void AddPage()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiTabBookCtrlAddPage(ObjectPtr->ObjPtr);
}
public void SelectPage(int pageIndex)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiTabBookCtrlSelectPage(ObjectPtr->ObjPtr, pageIndex);
}
public void SelectPageName(string pageName)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiTabBookCtrlSelectPageName(ObjectPtr->ObjPtr, pageName);
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="PrologCodeParser.cs" company="Axiom">
//
// Copyright (c) 2006 Ali Hodroj. All rights reserved.
//
// The use and distribution terms for this source code are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.IO;
using Axiom.Compiler.CodeObjectModel;
namespace Axiom.Compiler.Framework
{
/// <summary>
/// Summary description for PrologCodeParser.
/// </summary>
public class PrologCodeParser : IPrologParser
{
private PrologScanner _scanner = null;
private PrologOperatorTable _operators = new PrologOperatorTable();
private PrologCodeUnit _codeUnit = new PrologCodeUnit();
private ArrayList _errors = new ArrayList();
private int _randomVariableID = 100;
public PrologCodeParser()
{
_operators.Initialize();
}
public PrologCodeUnit Parse(TextReader input)
{
_scanner = new PrologScanner(input);
_errors.Clear();
PrologCodeTerm term = null;
while(true)
{
term = ReadTerm(1200);
if (_scanner.Next().Kind != PrologToken.DOT)
{
_errors.Add(new PrologCompilerError("P0001", "Unexpected end of term", "", false, _scanner.Current.Line, _scanner.Current.Column));
break;
}
if (term is PrologCodeHeadlessClause)
{
ProcessHeadlessClause(term);
}
else
{
_codeUnit.Terms.Add(term);
}
if (_scanner.Lookahead.Kind == PrologToken.EOF)
break;
}
return _codeUnit;
}
private void ProcessHeadlessClause(PrologCodeTerm term)
{
PrologCodeHeadlessClause clause = (PrologCodeHeadlessClause)term;
foreach (PrologCodeTerm t in clause.Goals)
{
if (t is PrologCodePredicate)
{
PrologCodePredicate pred = (PrologCodePredicate)t;
switch (pred.Name)
{
case "op":
ProcessOperator(pred);
break;
case "class":
PrologCodeTerm arg = (PrologCodeTerm)pred.Arguments[0];
if (arg is PrologCodeConstantAtom)
{
PrologCodeConstantAtom atom = (PrologCodeConstantAtom)arg;
_codeUnit.Class = atom.Value;
}
else if (arg is PrologCodeStringAtom)
{
PrologCodeStringAtom atom = (PrologCodeStringAtom)arg;
_codeUnit.Class = atom.Value.Replace("'", "");
}
else
{
_errors.Add(new PrologCompilerError("P0002", "Illegal class name.", "", false, _scanner.Current.Line, _scanner.Current.Column));
}
break;
case "foreign":
ProcessForeignMethod(pred);
break;
case "load_assembly":
ProcessAssemblyDirective(pred);
break;
case "using":
ProcessUsingDirective(pred);
break;
}
}
else if (t is PrologCodeList)
{
}
}
}
private void ProcessUsingDirective(PrologCodePredicate pred)
{
string ns = ((PrologCodeStringAtom)pred.Arguments[0]).Value;
ns = ns.Replace("'", "");
_codeUnit.Namespaces.Add(ns);
}
private void ProcessAssemblyDirective(PrologCodePredicate pred)
{
string asm = ((PrologCodeStringAtom)pred.Arguments[0]).Value;
asm = asm.Replace("'", "");
_codeUnit.AssemblyFiles.Add(asm);
}
private void ProcessOperator(PrologCodePredicate p)
{
if (!(p.Arguments[0] is PrologCodeIntegerAtom))
{
_errors.Add(new PrologCompilerError("P0009", "Invalid operator priority.", "", false, _scanner.Current.Line, _scanner.Current.Column));
}
int priority = ((PrologCodeIntegerAtom)p.Arguments[0]).Value;
if (!(p.Arguments[1] is PrologCodeConstantAtom))
{
_errors.Add(new PrologCompilerError("P0010", "Invalid operator associativity specifier.", "", false, _scanner.Current.Line, _scanner.Current.Column));
}
string associativity = ((PrologCodeConstantAtom)p.Arguments[1]).Value;
if (p.Arguments[2] is PrologCodeNonEmptyList)
{
ArrayList operators = GetListOperators((PrologCodeNonEmptyList)p.Arguments[2]);
foreach (PrologCodeTerm op in operators)
{
DefineNewOperator(priority, associativity, op);
}
}
else if(p.Arguments[2] is PrologCodeConstantAtom)
{
DefineNewOperator(priority, associativity, (PrologCodeTerm)p.Arguments[2]);
}
else if (p.Arguments[2] is PrologCodeStringAtom)
{
DefineNewOperator(priority, associativity, (PrologCodeTerm)p.Arguments[2]);
}
else
{
_errors.Add(new PrologCompilerError("P0011", "Invalid operator definition.", "", false, _scanner.Current.Line, _scanner.Current.Column));
}
}
private ArrayList GetListOperators(PrologCodeNonEmptyList list)
{
ArrayList listMembers = new ArrayList();
for (PrologCodeTerm l = list.Head; !(l is PrologCodeEmptyList); l = list.Tail)
{
if (l is PrologCodeAtom)
{
listMembers.Add(l);
}
else
{
_errors.Add(new PrologCompilerError("P0011", "Invalid operator definition.", "", false, _scanner.Current.Line, _scanner.Current.Column));
}
}
return listMembers;
}
private void DefineNewOperator(int pri, string assoc, PrologCodeTerm op)
{
// Check operator name
string opValue = "";
if (op is PrologCodeConstantAtom)
{
opValue = ((PrologCodeConstantAtom)op).Value;
}
else if (op is PrologCodeStringAtom)
{
opValue = ((PrologCodeStringAtom)op).Value;
}
else
{
_errors.Add(new PrologCompilerError("P0011", "Invalid operator definition.", "", false, _scanner.Current.Line, _scanner.Current.Column));
return;
}
if (opValue == "," || opValue == "','")
{
_errors.Add(new PrologCompilerError("P0011", "Invalid operator definition.", "", false, _scanner.Current.Line, _scanner.Current.Column));
return;
}
// Check operator priority
if (pri > 0 && pri < 1200)
{
UpdateOperatorTable(pri, assoc, opValue);
}
else if (pri == 0)
{
// Remove an operator
_operators.RemoveOperator(opValue);
}
else
{
// Error
}
}
private void UpdateOperatorTable(int priority, string associativity, string name)
{
switch (associativity)
{
case "xfx":
/* xfx */
_operators.AddInfixOperator(name, false, false, priority);
break;
case "xfy":
_operators.AddInfixOperator(name, false, true, priority);
break;
case "yfx":
_operators.AddInfixOperator(name, true, false, priority);
break;
case "fx":
_operators.AddPrefixOperator(name, false, priority);
break;
case "fy":
_operators.AddPrefixOperator(name, true, priority);
break;
case "xf":
_operators.AddPostfixOperator(name, false, priority);
break;
default:
_errors.Add(new PrologCompilerError("P0010", "Invalid operator associativity specifier.", "", false, _scanner.Current.Line, _scanner.Current.Column));
break;
}
}
private void ProcessForeignMethod(PrologCodePredicate p)
{
// :- foreign(functor(+term,...),'Assembly','Class','MethodName').
PrologCodeMethod foreignMethod = new PrologCodeMethod();
PrologCodePredicate predicateFunctor = (PrologCodePredicate)p.Arguments[0];
// Add argument types
foreignMethod.Arguments = GetForeignMethodArguments(predicateFunctor);
foreignMethod.AssemblyName = GetAtomOrStringValue((PrologCodeTerm)p.Arguments[1]);
foreignMethod.Class = GetAtomOrStringValue((PrologCodeTerm)p.Arguments[2]);
foreignMethod.PredicateName = predicateFunctor.Name;
foreignMethod.MethodName = predicateFunctor.Name.Replace("'", "");
if (p.Arguments.Count == 4)
{
foreignMethod.MethodName = GetAtomOrStringValue((PrologCodeTerm)p.Arguments[3]);
}
// Add the method
_codeUnit.Methods.Add(foreignMethod);
}
private string GetAtomOrStringValue(PrologCodeTerm term)
{
if (term is PrologCodeConstantAtom)
{
return ((PrologCodeConstantAtom)term).Value;
}
else if (term is PrologCodeStringAtom)
{
return ((PrologCodeStringAtom)term).Value.Replace("'", "");
}
return null;
}
private ArrayList GetForeignMethodArguments(PrologCodePredicate f)
{
ArrayList args = new ArrayList();
if (f.Arguments[0] is PrologCodeConstantAtom)
{
PrologCodeConstantAtom fc = (PrologCodeConstantAtom)f.Arguments[0];
if (fc.Value == "none")
{
return args;
}
else
{
_errors.Add(new PrologCompilerError("P0012", "Invalid predicate-method definition", "", false, _scanner.Current.Line, _scanner.Current.Column));
return args;
}
}
PrologCodePredicate functor = (PrologCodePredicate)f;
foreach (PrologCodePredicate a in functor.Arguments)
{
int passing = 0;
int datatype = 0;
switch (a.Name)
{
case "+":
passing = PrologCodeMethodArgument.PASS_IN;
break;
case "-":
passing = PrologCodeMethodArgument.PASS_OUT;
break;
case "?":
passing = PrologCodeMethodArgument.PASS_INOUT;
break;
default:
break;
}
switch (((PrologCodeConstantAtom)a.Arguments[0]).Value)
{
case "string":
datatype = PrologCodeMethodArgument.STRING;
break;
case "char":
datatype = PrologCodeMethodArgument.CHAR;
break;
case "int":
datatype = PrologCodeMethodArgument.INT;
break;
case "float":
datatype = PrologCodeMethodArgument.FLOAT;
break;
case "term":
datatype = PrologCodeMethodArgument.TERM;
break;
case "bool":
datatype = PrologCodeMethodArgument.BOOL;
break;
default:
break;
}
args.Add(new PrologCodeMethodArgument(datatype, passing));
}
return args;
}
public PrologCodeTerm ReadTerm(int priority)
{
/* Read a term as binary tree */
BinaryTree ast = Term(1200);
/* Convert binary tree into PrologCodeTerm and return it*/
return ConvertBinaryTreeToCodeDOM(ast);
}
public BinaryTree Term(int n)
{
int m = 0;
BinaryTree ast = null;
_scanner.Next();
switch (_scanner.Current.Kind)
{
case PrologToken.LPAREN:
ast = Term(1200);
_scanner.Next();
if (_scanner.Current.Kind != PrologToken.RPAREN)
{
_errors.Add(new PrologCompilerError("P0003", "Expected ) after term", "", false, _scanner.Current.Line, _scanner.Current.Column));
}
break;
// Handle list terms here...
case PrologToken.LBRACKET:
ArrayList listArguments = new ArrayList();
// Peek after [ token
if (_scanner.Lookahead.Kind == PrologToken.RBRACKET)
{
_scanner.Next();
// return a nil atom: []
ast = new BinaryList(); // empty list
break;
}
listArguments.Add(Term(999));
_scanner.Next();
// if , is encountered
while (_scanner.Current.Kind == PrologToken.COMMA)
{
listArguments.Add(Term(999));
_scanner.Next();
}
if (_scanner.Current.Kind == PrologToken.LIST_SEP)
{
listArguments.Add(Term(999));
_scanner.Next();
}
else
{
listArguments.Add(new BinaryList());
}
if (_scanner.Current.Kind != PrologToken.RBRACKET)
{
_errors.Add(new PrologCompilerError("P0004", "Unterminated list, expected ]", "", false, _scanner.Current.Line, _scanner.Current.Column));
}
int i = listArguments.Count - 1;
BinaryList list = new BinaryList((BinaryTree)listArguments[i - 1], (BinaryTree)listArguments[i]);
i -= 2;
while (i > -1)
{
list = new BinaryList((BinaryTree)listArguments[i--], list);
}
ast = list;
break;
case PrologToken.RPAREN:
case PrologToken.RBRACKET:
case PrologToken.COMMA:
case PrologToken.DOT:
_errors.Add(new PrologCompilerError("P0005", "Unexpected closure of term", "", false, _scanner.Current.Line, _scanner.Current.Column));
return null;
case PrologToken.ATOM:
case PrologToken.VARIABLE:
string atomName = _scanner.Current.StringValue;
if (_scanner.Lookahead.Kind == PrologToken.LPAREN)
{
ArrayList arguments = new ArrayList();
_scanner.Next();
arguments.Add(Term(1200));
_scanner.Next();
while (_scanner.Current.Kind == PrologToken.COMMA)
{
arguments.Add(Term(1200));
_scanner.Next();
}
if (_scanner.Current.Kind != PrologToken.RPAREN)
{
_errors.Add(new PrologCompilerError("P0005", "Unexpected closure of term", "", false, _scanner.Current.Line, _scanner.Current.Column));
return null;
}
ast = new BinaryTree(atomName, arguments);
break;
}
if (_operators.IsOperator(_scanner.Current.StringValue))
{
PrologOperator op = _operators.GetOperator(_scanner.Current.StringValue);
if (op.IsPrefix)
{
// prefix operator
if (n < op.PrefixPrecedence)
{
ParserError("prefix precedence error", _scanner.Current.Line, _scanner.Current.Column);
return null;
}
switch (_scanner.Lookahead.Kind)
{
case PrologToken.LPAREN:
case PrologToken.LBRACKET:
ast = new BinaryTree(op.Name, Term(op.PrefixRightPrecedence));
m = op.PrefixPrecedence;
Right(n, m, ref ast);
break;
case PrologToken.RPAREN:
case PrologToken.RBRACKET:
case PrologToken.DOT:
case PrologToken.LIST_SEP:
if (n < m)
{
_errors.Add(new PrologCompilerError("P0006", "Unexpected atom '" + _scanner.Lookahead.StringValue + "'", "", false, _scanner.Current.Line, _scanner.Current.Column));
return null;
}
ast = new BinaryTree(_scanner.Current.StringValue);
Right(n, m, ref ast);
break;
case PrologToken.ATOM:
if (_operators.IsOperator(_scanner.Lookahead.StringValue))
{
PrologOperator atomOp = _operators.GetOperator(_scanner.Lookahead.StringValue);
if (atomOp.IsInfix && m <= atomOp.InfixLeftPrecedence)
{
if (n < m)
{
ParserError("n < m", _scanner.Lookahead.Line, _scanner.Current.Column);
return null;
}
ast = new BinaryTree(_scanner.Lookahead.StringValue);
Right(n, m, ref ast);
break;
}
else if (atomOp.IsPostfix && m <= atomOp.PostfixLeftPrecedence)
{
if (n < m)
{
ParserError("n < m", _scanner.Current.Line, _scanner.Current.Column);
return null;
}
ast = new BinaryTree(_scanner.Current.StringValue);
Right(n, m, ref ast);
break;
}
// Just added on 6/23/2006. Might not fix anything.
else
{
ast = new BinaryTree(_scanner.Current.StringValue, null, Term(op.InfixRightPrecedence));
m = op.PrefixPrecedence;
Right(n, m, ref ast);
break;
}
}
else
{
ast = new BinaryTree(_scanner.Current.StringValue, null, Term(op.InfixRightPrecedence));
m = op.PrefixPrecedence;
Right(n, m, ref ast);
}
break;
default:
ParserError("Unknown internal error", _scanner.Current.Line, _scanner.Current.Column);
return null;
}
}
}
else
{
ast = new BinaryTree(_scanner.Current.StringValue);
}
break;
default:
ParserError("Unknown internal error", _scanner.Current.Line, _scanner.Current.Column);
return null;
}
Right(n, m, ref ast);
return ast;
}
private BinaryTree Right(int n, int m, ref BinaryTree result)
{
switch (_scanner.Lookahead.Kind)
{
case PrologToken.DOT:
case PrologToken.RPAREN:
case PrologToken.RBRACKET:
return result;
case PrologToken.LPAREN:
case PrologToken.LBRACKET:
_errors.Add(new PrologCompilerError("P0007", "Unexpected open brackets or parenthsis", "", false, _scanner.Current.Line, _scanner.Current.Column));
return result;
case PrologToken.COMMA:
if (n >= 1000 && m <= 1000)
{
m = 1000;
_scanner.Next();
result = new BinaryTree(",", result, Term(m));
if (n > m)
{
Right(n, m, ref result);
}
}
return result;
case PrologToken.ATOM:
PrologOperator laOp = _operators.GetOperator(_scanner.Lookahead.StringValue);
if (laOp != null)
{
if (laOp.IsPostfix &&
n >= laOp.PostfixPrecedence &&
m <= laOp.PostfixLeftPrecedence)
{
_scanner.Next();
if (_operators.IsOperator(_scanner.Current.StringValue))
{
PrologOperator o = _operators.GetOperator(_scanner.Current.StringValue);
if (o.IsInfix &&
n >= o.InfixPrecedence &&
m <= o.InfixLeftPrecedence)
{
switch (_scanner.Lookahead.Kind)
{
case PrologToken.LPAREN:
case PrologToken.LBRACKET:
result = new BinaryTree(o.Name, result, Term(o.InfixRightPrecedence));
m = o.InfixPrecedence;
Right(n, m, ref result);
break;
case PrologToken.COMMA:
case PrologToken.RPAREN:
case PrologToken.RBRACKET:
result = new BinaryTree(_scanner.Current.StringValue, result);
m = o.InfixPrecedence;
Right(n, m, ref result);
break;
case PrologToken.ATOM:
if (_operators.IsOperator(_scanner.Lookahead.StringValue))
{
if (_operators.ExclusivelyPrefix(_scanner.Lookahead.StringValue))
{
result = new BinaryTree(_scanner.Lookahead.StringValue, result, Term(_operators.GetOperator(_scanner.Lookahead.StringValue).PrefixRightPrecedence));
m = o.InfixPrecedence;
Right(n, m, ref result);
break;
}
}
else
{
result = new BinaryTree(_scanner.Lookahead.StringValue, result, null);
m = _operators.GetOperator(_scanner.Lookahead.StringValue).InfixPrecedence;
Right(n, m, ref result);
break;
}
break;
}
}
else
{
result = new BinaryTree(_scanner.Current.StringValue, result);
m = _operators.GetOperator(_scanner.Current.StringValue).InfixPrecedence;
Right(n, m, ref result);
}
}
break;
}
else if (laOp.IsInfix && n >= laOp.InfixPrecedence && m <= laOp.InfixLeftPrecedence)
{
_scanner.Next();
int p = _operators.GetOperator(_scanner.Current.StringValue).InfixPrecedence;
int t = _operators.GetOperator(_scanner.Current.StringValue).InfixRightPrecedence;
result = new BinaryTree(_scanner.Current.StringValue, result, Term(t));
m = p;
Right(n, m, ref result);
break;
}
}
else
{
return result;
}
break;
}
return result;
}
private void ParserError(string error, int line, int column)
{
Console.WriteLine("Parser Internal Error: " + error + ". Line: " + line + ", Column: " + column);
}
private PrologCodeTerm ConvertGoalVariableBinaryTreeToCodeDOM(BinaryTree var)
{
if (Char.IsUpper(var.Name[0]) || var.Name[0] == '_' || var.Name == "_")
{
if (var.Name == "_")
{
_randomVariableID++;
return new PrologCodeVariable(var.Name + "%" + _randomVariableID.ToString());
}
return new PrologCodeVariable(var.Name);
}
else
{
// Not a functor, => atom | number | string
if (var.Arguments == null || var.Arguments.Count == 0)
{
if (var.Name == ".")
{
// TODO: can place return PrologCodeEmptyList() here.
return ConvertBinaryListToCodeDOM(var);
}
if (var.Left == null && var.Right == null)
{
// 'Atom string'
if (var.Name[0] == '\'')
{
return new PrologCodeStringAtom(var.Name);
}
else if (Char.IsDigit(var.Name[0]))
{
// 1.234
if (var.Name.IndexOf('.') != -1)
{
return new PrologCodeFloatAtom(float.Parse(var.Name));
}
// 213
else
{
return new PrologCodeIntegerAtom(Int32.Parse(var.Name));
}
}
else if (var.Name == "_")
{
return new PrologCodeNilAtom();
}
// atom
else
{
return new PrologCodeConstantAtom(var.Name);
}
}
else if (var.Left != null && var.Right != null)
{
PrologCodePredicate infixPredicate = new PrologCodePredicate(var.Name);
infixPredicate.Arguments.Add(ConvertGoalVariableBinaryTreeToCodeDOM(var.Left));
infixPredicate.Arguments.Add(ConvertGoalVariableBinaryTreeToCodeDOM(var.Right));
return infixPredicate;
}
else if (var.Left == null && var.Right != null)
{
PrologCodePredicate prefixPredicate = new PrologCodePredicate(var.Name);
prefixPredicate.Arguments.Add(ConvertGoalVariableBinaryTreeToCodeDOM(var.Right));
return prefixPredicate;
}
else if (var.Left != null && var.Right == null)
{
PrologCodePredicate postfixPredicate = new PrologCodePredicate(var.Name);
postfixPredicate.Arguments.Add(ConvertGoalVariableBinaryTreeToCodeDOM(var.Left));
return postfixPredicate;
}
}
// atom(a,X,atom(X)).
else
{
PrologCodePredicate functor = new PrologCodePredicate(var.Name);
ArrayList arguments = new ArrayList();
var.Flatten((BinaryTree)var.Arguments[0], ref arguments);
foreach (BinaryTree a in arguments)
{
functor.Arguments.Add(ConvertGoalVariableBinaryTreeToCodeDOM(a));
}
return functor;
}
}
return null;
}
private PrologCodeTerm ConvertGoalBinaryTreeToCodeDOM(BinaryTree goal)
{
if (goal.Name == ".")
{
return ConvertBinaryListToCodeDOM(goal);
}
else if (Char.IsUpper(goal.Name[0])) // Goal is a variable
{
return new PrologCodeVariable(goal.Name);
}
else
{
PrologCodePredicate goalPredicate = new PrologCodePredicate(goal.Name);
ArrayList gargs = new ArrayList();
goal.Flatten(goal, ref gargs);
goalPredicate.IsMethod = IsMethod(goal.Name, gargs.Count);
goalPredicate.MethodInfo = GetMethodInfo(goal.Name);
if (goal.Arguments != null && goal.Arguments.Count != 0)
{
// Example:
// goal(X,a).
ArrayList arguments = new ArrayList();
goal.Flatten((BinaryTree)goal.Arguments[0], ref arguments);
foreach (BinaryTree a in arguments)
{
goalPredicate.Arguments.Add(ConvertGoalVariableBinaryTreeToCodeDOM(a));
}
return goalPredicate;
}
else
{
// X = a (goal is '=')
if (goal.Left != null && goal.Right != null)
{
goalPredicate.Arguments.Add(ConvertGoalVariableBinaryTreeToCodeDOM(goal.Left));
goalPredicate.Arguments.Add(ConvertGoalVariableBinaryTreeToCodeDOM(goal.Right));
return goalPredicate;
}
// [] + foo.
if (goal.Left == null && goal.Right != null)
{
goalPredicate.Arguments.Add(ConvertGoalVariableBinaryTreeToCodeDOM(goal.Right));
return goalPredicate;
}
// X + []
if (goal.Left != null && goal.Right == null)
{
goalPredicate.Arguments.Add(ConvertGoalVariableBinaryTreeToCodeDOM(goal.Left));
return goalPredicate;
}
if (goal.Left == null && goal.Right == null)
{
return goalPredicate;
}
}
}
return null;
}
private PrologCodeTerm ConvertBinaryListToCodeDOM(BinaryTree l)
{
BinaryList list = (BinaryList)l;
if (list.Head == null && list.Tail == null)
{
return new PrologCodeEmptyList();
}
PrologCodeNonEmptyList NEList = null;
if (list.Head.Name == ".")
{
NEList = new PrologCodeNonEmptyList(ConvertBinaryListToCodeDOM(list.Head));
}
else
{
NEList = new PrologCodeNonEmptyList(ConvertGoalVariableBinaryTreeToCodeDOM(list.Head));
}
// Check the tail
if (list.Tail.Name == ".")
{
NEList.Tail = ConvertBinaryListToCodeDOM(list.Tail);
}
else
{
NEList.Tail = ConvertGoalVariableBinaryTreeToCodeDOM(list.Tail);
}
return NEList;
}
public PrologCodeTerm ConvertBinaryTreeToCodeDOM(BinaryTree tree)
{
// Clause
if (tree.Name == ":-")
{
PrologCodeClause term = new PrologCodeClause();
if (tree.Left != null)
{
ArrayList goals = new ArrayList();
tree.Flatten(tree.Right, ref goals);
foreach (BinaryTree goal in goals)
{
term.Goals.Add(ConvertGoalBinaryTreeToCodeDOM(goal));
}
term.Head = (PrologCodePredicate)ConvertBinaryTreeToCodeDOM(tree.Left);
return term;
}
// Headless clause
else
{
// process headless clause here
PrologCodeHeadlessClause hClause = new PrologCodeHeadlessClause();
ArrayList goals = new ArrayList();
tree.Flatten(tree.Right, ref goals);
foreach (BinaryTree goal in goals)
{
hClause.Goals.Add(ConvertGoalBinaryTreeToCodeDOM(goal));
}
return hClause;
}
}
else if (tree.Name == ".")
{
return ConvertBinaryListToCodeDOM(tree);
}
// Variable
else if (Char.IsUpper(tree.Name[0]))
{
if (tree.Left != null || tree.Right != null)
{
ParserError("Something was not parsed right. Variable has arity > 0", 0, 0);
}
PrologCodeVariable var = new PrologCodeVariable(tree.Name);
return var;
}
else
{
return ConvertGoalBinaryTreeToCodeDOM(tree);
}
//return null;
}
public PrologScanner Scanner
{
get { return _scanner; }
set { _scanner = value; }
}
public ArrayList Errors
{
get { return _errors; }
set { _errors = value; }
}
// determines whether its a method or not
private bool IsMethod(string name, int arity)
{
foreach (PrologCodeMethod method in _codeUnit.Methods)
{
if (name == method.PredicateName && method.Arguments.Count == arity)
{
return true;
}
}
return false;
}
private PrologCodeMethod GetMethodInfo(string name)
{
foreach (PrologCodeMethod method in _codeUnit.Methods)
{
if (method.PredicateName == name)
{
return method;
}
}
return null;
}
}
#region BinaryTree internal class
public class BinaryTree
{
public BinaryTree _left;
public BinaryTree _right;
public string _name;
public ArrayList _arguments = null;
public BinaryTree(string name)
{
_name = name;
_left = null;
_right = null;
}
public BinaryTree(string name, BinaryTree left, BinaryTree right)
{
_name = name;
_left = left;
_right = right;
_arguments = new ArrayList();
}
public BinaryTree(string name, ArrayList arguments)
{
_left = null;
_right = null;
_arguments = arguments;
_name = name;
}
public BinaryTree(string name, BinaryTree left)
{
_name = name;
_left = left;
_arguments = null;
}
/* converts a Tree to an array list */
public void Flatten(BinaryTree t, ref ArrayList args)
{
if (t.Name == ",")
{
args.Add(t.Left);
if (t.Right.Name == ",")
{
Flatten(t.Right, ref args);
}
else
{
args.Add(t.Right);
}
}
else
{
args.Add(t);
}
}
public BinaryTree Left
{
get { return _left; }
set { _left = value; }
}
public BinaryTree Right
{
get { return _right; }
set { _right = value; }
}
public ArrayList Arguments
{
get { return _arguments; }
set { _arguments = value; }
}
public string Name
{
get { return _name; }
set { _name = value; }
}
}
#endregion
#region BinaryList internal class
public class BinaryList : BinaryTree
{
private BinaryTree _head = null;
private BinaryTree _tail = null;
private bool _empty = true;
public BinaryList() : base(".", null, null)
{
}
public BinaryList(BinaryTree head, BinaryTree tail) : base(".", null, null)
{
_head = head;
_tail = tail;
_empty = false;
}
public BinaryTree Head
{
get { return _head; }
set { _head = value; }
}
public BinaryTree Tail
{
get { return _tail; }
set { _tail = value; }
}
public bool IsEmpty
{
get { return _empty; }
}
}
#endregion
}
| |
// Graph Engine
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using Trinity;
using Trinity.Diagnostics;
namespace Trinity.Utilities
{
internal class ASMFactory
{
static ASMFactory()
{
Log.WriteLine(LogLevel.Verbose, "ASMFactory", "ASM factory initializing.");
AppDomain.CurrentDomain.AssemblyLoad += OnAssemblyLoad;
AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve;
//Initialize the Assembly Cache, fill in existing assemblies
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
{
AssemblyCache[asm.FullName] = asm;
}
//Initialize the Core Assembly Dependency List
Assembly[] coreAssemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (var asm in coreAssemblies)
{
try//When attached to debugger, there'storage some exceptions
{
_coreAssemblyDependencyList.AddRange(GetAssemblyDependencyList(asm));
}
catch (Exception)
{
//Console.WriteLine(e.Message);
}
}
_coreAssemblyDependencyList = _coreAssemblyDependencyList.Distinct().ToList();
}
/// <summary>
/// Recursively retrive all dependencies ( including itself ) of an assembly.
/// </summary>
/// <param name="asm">The given assembly</param>
/// <param name="searchPath">The path to search.</param>
/// <returns>A list of assembly full names.</returns>
internal static List<string> GetAssemblyDependencyList(Assembly asm, string searchPath = "")
{
AppDomain newDomain = AppDomain.CreateDomain("Sandbox");
newDomain.Load(Assembly.GetExecutingAssembly().GetName());
_asm_factory_ factory = newDomain.CreateInstanceAndUnwrap(
Assembly.GetExecutingAssembly().GetName().FullName,
"Trinity.Utilities._asm_factory_") as _asm_factory_;
var ret = factory.__get_assembly_dependency_list__(asm, searchPath);
AppDomain.Unload(newDomain);
return (List<string>)ret;
}
public static List<string> GetAssemblyDependencyList(byte[] asmBytes, string searchPath = "")
{
AppDomain newDomain = AppDomain.CreateDomain("Sandbox");
newDomain.Load(Assembly.GetExecutingAssembly().GetName());
_asm_factory_ factory = newDomain.CreateInstanceAndUnwrap(
Assembly.GetExecutingAssembly().GetName().FullName,
"Trinity.Utilities._asm_factory_") as _asm_factory_;
var ret = factory.__get_assembly_dependency_list__(asmBytes, searchPath);
AppDomain.Unload(newDomain);
return (List<string>)ret;
}
public static List<string> GetAssemblyDependencyList(string filename, string searchPath = "")
{
AppDomain newDomain = AppDomain.CreateDomain("Sandbox");
newDomain.Load(Assembly.GetExecutingAssembly().GetName());
_asm_factory_ factory = newDomain.CreateInstanceAndUnwrap(
Assembly.GetExecutingAssembly().GetName().FullName,
"Trinity.Utilities._asm_factory_") as _asm_factory_;
var ret = factory.__get_assembly_dependency_list_with_filename__(filename, searchPath);
AppDomain.Unload(newDomain);
return (List<string>)ret;
}
static void OnAssemblyLoad(object sender, AssemblyLoadEventArgs args)
{
//register the loaded assembly into the assembly cache
AssemblyCache[args.LoadedAssembly.FullName] = args.LoadedAssembly;
Log.WriteLine(LogLevel.Verbose, "ASMFactory", "New assembly loaded: {0}", args.LoadedAssembly.FullName);
}
static Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
{
Assembly asm = null;
AssemblyCache.TryGetValue(args.Name, out asm);
Log.WriteLine(LogLevel.Verbose, "ASMFactory", "Resolving assembly: {0}", args.Name);
return asm;
}
static Dictionary<string, Assembly> AssemblyCache = new Dictionary<string, Assembly>();
static List<string> _coreAssemblyDependencyList = new List<string>();
/// <summary>
/// The dependency list generated on application startup, without any plug-ins.
/// </summary>
public static List<string> CoreAssemblyDependencyList
{
get { return _coreAssemblyDependencyList.ToList(); }
}
public static object CreateInstance(Assembly asm, Type t)
{
return asm.CreateInstance(t.FullName, true, BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, null, null, null);
}
public static T CreateInstance<T>(Assembly asm, List<string> RequiredMethodList)
{
foreach (Type t in asm.GetTypes())
{
//Abstract class, Interface, Generic types cannot be instantiated
//in our situation.
if (t.IsAbstract || t.IsInterface || t.IsGenericType)
continue;
//Sometimes an instance cannot be created from certain classes.
//Wrap it with try-catch for stability.
try
{
bool hasAllRequiredMethods = true;
foreach (string requiredMethod in RequiredMethodList)
{
bool hasMethod = false;
foreach (MethodInfo m in t.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance))
{
if (m.Name == requiredMethod)
{
hasMethod = true;
break;
}
}
if (!hasMethod)
{
hasAllRequiredMethods = false;
break;
}
}
if (!hasAllRequiredMethods)
continue;
object o = CreateInstance(asm, t);
if (o != null && o is T)
return (T)o;
}
catch (Exception)
{
}
}
return default(T);
}
public static T CreateInstance<T>(Assembly asm)
{
Type typeOfT = typeof(T);
List<string> requiredMethodList = new List<string>();
foreach (MethodInfo m in typeOfT.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance))
{
requiredMethodList.Add(m.Name);
}
return CreateInstance<T>(asm, requiredMethodList);
}
public static Assembly LoadFrom(string filename, Action<Assembly> lockedAction = null)
{
if (!File.Exists(filename))
{
return null;
}
byte[] asmBytes = File.ReadAllBytes(filename);
return Load(asmBytes, lockedAction);
}
/// <summary>
/// This method load an assembly into the nameless context.
/// Note that unlike Assembly.Load, this method will prevent
/// auto-resolving on disk. When a dependency is not already
/// loaded into AssemblyCache, it will not load the new assembly.
/// </summary>
/// <param name="asmBytes">Target assembly binary</param>
/// <param name="lockedAction">Action to execute while auto-resolving is disabled</param>
/// <returns>An Assembly if loaded successful, otherwise null</returns>
internal static Assembly Load(byte[] asmBytes, Action<Assembly> lockedAction = null)
{
return Load(asmBytes, lockedAction, false);
}
/// <summary>
/// This method load an assembly into the nameless context.
/// Note that unlike Assembly.Load, this method will prevent
/// auto-resolving on disk. When a dependency is not already
/// loaded into AssemblyCache, it will not load the new assembly.
/// </summary>
/// <param name="asmBytes">Target assembly binary</param>
/// <param name="lockedAction">Action to execute while auto-resolving is disabled</param>
/// <param name="ResolveToLoadedAssembly">If the assembly is already loaded, don't load again</param>
/// <returns>An Assembly if loaded successful, otherwise null</returns>
public static Assembly Load(byte[] asmBytes, Action<Assembly> lockedAction, bool ResolveToLoadedAssembly)
{
if (lockedAction != null)
{
AppDomain newDomain = AppDomain.CreateDomain("Sandbox");
newDomain.Load(Assembly.GetExecutingAssembly().GetName());
_asm_factory_ factory = newDomain.CreateInstanceAndUnwrap(
Assembly.GetExecutingAssembly().GetName().FullName,
"Trinity.Utilities._asm_factory_") as _asm_factory_;
List<string> depList = factory.__get_assembly_dependency_list__(asmBytes);
//Unload the domain, release the assemblies
AppDomain.Unload(newDomain);
List<FileStream> locked_files = LockDependencyFiles(depList);
Assembly ret = null;
if (!ResolveToLoadedAssembly)
ret = Assembly.Load(asmBytes);
else
{
newDomain = AppDomain.CreateDomain("Sandbox");
newDomain.Load(Assembly.GetExecutingAssembly().GetName());
factory = newDomain.CreateInstanceAndUnwrap(
Assembly.GetExecutingAssembly().GetName().FullName,
"Trinity.Utilities._asm_factory_") as _asm_factory_;
string fullName = factory.__get_assembly_fullname__(asmBytes);
AppDomain.Unload(newDomain);
if (AssemblyCache.ContainsKey(fullName))
{
ret = AssemblyCache[fullName];
}
else
ret = Assembly.Load(asmBytes);
}
lockedAction(ret);
UnlockDependencyFiles(locked_files);
return ret;
}
else
return Assembly.Load(asmBytes);
}
/// <summary>
/// Scan through all dll/exe files in current working directory,
/// load them up and check whether they match the given full asm name.
/// If one matches the given full name, return an reflection-only assembly of that file.
/// These interfaces might be slow since it creates a sandbox for the assembly loading.
/// </summary>
/// <param name="fullname">The full name of the desired assembly</param>
/// <param name="searchPath">The path to search</param>
/// <param name="fullPath">The full path of the located assembly.</param>
/// <returns>Null if file not found. An assembly if found.</returns>
internal static Assembly LoadReflectionOnly(string fullname, string searchPath, out string fullPath)
{
AppDomain newDomain = AppDomain.CreateDomain("Sandbox");
newDomain.Load(Assembly.GetExecutingAssembly().GetName());
fullPath = "";
_asm_factory_ factory = newDomain.CreateInstanceAndUnwrap(
Assembly.GetExecutingAssembly().GetName().FullName,
"Trinity.Utilities._asm_factory_") as _asm_factory_;
var ret = factory.__load_reflection_only__(fullname, searchPath, out fullPath);
AppDomain.Unload(newDomain);
return (Assembly)ret;
}
public static Assembly LoadReflectionOnly(string fullname, out string fullPath)
{
return LoadReflectionOnly(fullname, Directory.GetCurrentDirectory(), out fullPath);
}
public static Assembly LoadReflectionOnly(string fullname)
{
string notUsed;
return LoadReflectionOnly(fullname, out notUsed);
}
static internal List<FileStream> LockDependencyFiles(List<string> depList)
{
List<FileStream> lockList = new List<FileStream>();
try
{
foreach (string fullName in depList)
{
string fullPath = LookupAssemblyLocation(fullName, Global.MyAssemblyPath);
try
{
File.Move(fullPath, fullPath + "__LOCKED__");
FileStream lockStream = new FileStream(
fullPath + "__LOCKED__",
FileMode.Open,
FileAccess.ReadWrite,
FileShare.None);
lockList.Add(lockStream);
}
catch (Exception)
{
//Log.WriteLine(LogLevel.L5, "[ERROR] ASMFactory : LockDependencyFiles : {0}", e.Message);
}
}
}
catch (Exception e)
{
Log.WriteLine(LogLevel.Debug, "ASMFactory", "{0}", e.Message);
}
return lockList;
}
static internal void UnlockDependencyFiles(List<FileStream> locked_files)
{
foreach (FileStream fs in locked_files)
{
string path = fs.Name;
fs.Close();
File.Move(path, path.Substring(0, path.Length - "__LOCKED__".Length));
}
}
internal static string LookupAssemblyLocation(string fullName, string path)
{
AppDomain newDomain = AppDomain.CreateDomain("Sandbox");
newDomain.Load(Assembly.GetExecutingAssembly().GetName());
string fullPath = "";
_asm_factory_ factory = newDomain.CreateInstanceAndUnwrap(
Assembly.GetExecutingAssembly().GetName().FullName,
"Trinity.Utilities._asm_factory_") as _asm_factory_;
fullPath = factory.__lookup_assembly_location__(fullName, path);
AppDomain.Unload(newDomain);
return fullPath;
}
}
class _asm_factory_ : MarshalByRefObject
{
// this interface do not contain the origin assembly in the dependency list
public List<string> __get_assembly_dependency_list_with_filename__(string filename, string searchPath = "")
{
//Console.WriteLine("Executing in domain {0}", AppDomain.CurrentDomain.FriendlyName);
try
{
Assembly asm = Assembly.ReflectionOnlyLoadFrom(filename);
List<string> list = __get_assembly_dependency_list__(asm, searchPath);
list.Remove(asm.FullName);
return list;
}
catch (Exception)
{
return new List<string>();
}
}
public List<string> __get_assembly_dependency_list__(byte[] asmBytes, string searchPath = "")
{
Assembly asm = Assembly.ReflectionOnlyLoad(asmBytes);
return __get_assembly_dependency_list__(asm, searchPath);
}
public List<string> __get_assembly_dependency_list__(Assembly asm, string searchPath = "")
{
//Console.WriteLine("Executing in domain {0}", AppDomain.CurrentDomain.FriendlyName);
string asmLocation;
if (asm.Location != "")
asmLocation = Path.GetDirectoryName(asm.Location.ToLowerInvariant());
else
asmLocation = "";
if (
(
asmLocation != ""//the assembly is not on disk
&&
asmLocation != Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location).ToLowerInvariant()
)
&&
(searchPath == "" || (asmLocation != searchPath.ToLowerInvariant()))
)
{
return new List<string>();
}
if (asm.FullName.Contains("vshost"))
return new List<string>();
List<string> ret = new List<string>();
ret.Add(asm.FullName);
foreach (var refAsm in asm.GetReferencedAssemblies())
{
//filter assembly Trinity.Shell.exe and Trinity.Core.dll to reduce network traffic
if (refAsm.Name == "Trinity.Shell" || refAsm.Name == "Trinity.Core" || refAsm.Name.StartsWith("Microsoft.SqlServer", StringComparison.Ordinal))
continue;
//filter all "mscorlib" related items
if (refAsm.FullName.Contains("mscorlib"))
continue;
string fullPath;
Assembly refAsmReflectOnly = null;
try
{
refAsmReflectOnly = __load_reflection_only__(refAsm.FullName, asmLocation, out fullPath);
}
catch (Exception)
{
//Cannot load the referenced assembly into current domain.
//So don't add this assembly to dependency list
continue;
}
ret.AddRange(__get_assembly_dependency_list__(refAsmReflectOnly));
}
ret = ret.Distinct().ToList();
return ret;
}
public string __lookup_assembly_location__(string fullname, string searchPath)
{
string fullPath = "";
if (searchPath == "")// search the assembly path
{
searchPath = Global.MyAssemblyPath;
}
foreach (string s in Directory.GetFileSystemEntries(searchPath))
{
string fname = s.ToLowerInvariant();
if (s.EndsWith(".exe", StringComparison.Ordinal) || s.EndsWith(".dll", StringComparison.Ordinal))
{
try
{
Assembly asm = Assembly.ReflectionOnlyLoadFrom(s);
if (asm.FullName == fullname)
{
fullPath = s;
return fullPath;
}
}
catch (Exception)
{
}
}
}
return "";
}
public Assembly __load_reflection_only__(string fullname, string searchPath, out string fullPath)
{
fullPath = "";
if (searchPath == "")// search the assembly path
{
searchPath = Global.MyAssemblyPath;
}
foreach (string s in Directory.GetFileSystemEntries(searchPath))
{
string fname = s.ToLowerInvariant();
if (s.EndsWith(".exe", StringComparison.Ordinal) || s.EndsWith(".dll", StringComparison.Ordinal))
{
Assembly asm = Assembly.ReflectionOnlyLoadFrom(s);
if (asm.FullName == fullname)
{
fullPath = s;
return asm;
}
}
}
return null;
}
public string __get_assembly_fullname__(byte[] asmBytes)
{
Assembly asm = Assembly.ReflectionOnlyLoad(asmBytes);
return asm.FullName;
}
}
}
| |
// 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.
//
// Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused.
//
using System;
using System.Diagnostics.Contracts;
using System.Globalization;
namespace System.Text
{
// Encodes text into and out of UTF-32. UTF-32 is a way of writing
// Unicode characters with a single storage unit (32 bits) per character,
//
// The UTF-32 byte order mark is simply the Unicode byte order mark
// (0x00FEFF) written in UTF-32 (0x0000FEFF or 0xFFFE0000). The byte order
// mark is used mostly to distinguish UTF-32 text from other encodings, and doesn't
// switch the byte orderings.
public sealed class UTF32Encoding : Encoding
{
/*
words bits UTF-32 representation
----- ---- -----------------------------------
1 16 00000000 00000000 xxxxxxxx xxxxxxxx
2 21 00000000 000xxxxx hhhhhhll llllllll
----- ---- -----------------------------------
Surrogate:
Real Unicode value = (HighSurrogate - 0xD800) * 0x400 + (LowSurrogate - 0xDC00) + 0x10000
*/
// Used by Encoding.UTF32/BigEndianUTF32 for lazy initialization
// The initialization code will not be run until a static member of the class is referenced
internal static readonly UTF32Encoding s_default = new UTF32Encoding(bigEndian: false, byteOrderMark: true);
internal static readonly UTF32Encoding s_bigEndianDefault = new UTF32Encoding(bigEndian: true, byteOrderMark: true);
private bool _emitUTF32ByteOrderMark = false;
private bool _isThrowException = false;
private bool _bigEndian = false;
public UTF32Encoding() : this(false, true, false)
{
}
public UTF32Encoding(bool bigEndian, bool byteOrderMark) :
this(bigEndian, byteOrderMark, false)
{
}
public UTF32Encoding(bool bigEndian, bool byteOrderMark, bool throwOnInvalidCharacters) :
base(bigEndian ? 12001 : 12000)
{
_bigEndian = bigEndian;
_emitUTF32ByteOrderMark = byteOrderMark;
_isThrowException = throwOnInvalidCharacters;
// Encoding's constructor already did this, but it'll be wrong if we're throwing exceptions
if (_isThrowException)
SetDefaultFallbacks();
}
internal override void SetDefaultFallbacks()
{
// For UTF-X encodings, we use a replacement fallback with an empty string
if (_isThrowException)
{
this.encoderFallback = EncoderFallback.ExceptionFallback;
this.decoderFallback = DecoderFallback.ExceptionFallback;
}
else
{
this.encoderFallback = new EncoderReplacementFallback("\xFFFD");
this.decoderFallback = new DecoderReplacementFallback("\xFFFD");
}
}
// NOTE: Many methods in this class forward to EncodingForwarder for
// validating arguments/wrapping the unsafe methods in this class
// which do the actual work. That class contains
// shared logic for doing this which is used by
// ASCIIEncoding, EncodingNLS, UnicodeEncoding, UTF32Encoding,
// UTF7Encoding, and UTF8Encoding.
// The reason the code is separated out into a static class, rather
// than a base class which overrides all of these methods for us
// (which is what EncodingNLS is for internal Encodings) is because
// that's really more of an implementation detail so it's internal.
// At the same time, C# doesn't allow a public class subclassing an
// internal/private one, so we end up having to re-override these
// methods in all of the public Encodings + EncodingNLS.
// Returns the number of bytes required to encode a range of characters in
// a character array.
public override int GetByteCount(char[] chars, int index, int count)
{
return EncodingForwarder.GetByteCount(this, chars, index, count);
}
public override int GetByteCount(String s)
{
return EncodingForwarder.GetByteCount(this, s);
}
[CLSCompliant(false)]
public override unsafe int GetByteCount(char* chars, int count)
{
return EncodingForwarder.GetByteCount(this, chars, count);
}
public override int GetBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
return EncodingForwarder.GetBytes(this, s, charIndex, charCount, bytes, byteIndex);
}
// Encodes a range of characters in a character array into a range of bytes
// in a byte array. An exception occurs if the byte array is not large
// enough to hold the complete encoding of the characters. The
// GetByteCount method can be used to determine the exact number of
// bytes that will be produced for a given range of characters.
// Alternatively, the GetMaxByteCount method can be used to
// determine the maximum number of bytes that will be produced for a given
// number of characters, regardless of the actual character values.
public override int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
}
[CLSCompliant(false)]
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
return EncodingForwarder.GetBytes(this, chars, charCount, bytes, byteCount);
}
// Returns the number of characters produced by decoding a range of bytes
// in a byte array.
public override int GetCharCount(byte[] bytes, int index, int count)
{
return EncodingForwarder.GetCharCount(this, bytes, index, count);
}
[CLSCompliant(false)]
public override unsafe int GetCharCount(byte* bytes, int count)
{
return EncodingForwarder.GetCharCount(this, bytes, count);
}
public override int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex);
}
[CLSCompliant(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
return EncodingForwarder.GetChars(this, bytes, byteCount, chars, charCount);
}
// Returns a string containing the decoded representation of a range of
// bytes in a byte array.
public override String GetString(byte[] bytes, int index, int count)
{
return EncodingForwarder.GetString(this, bytes, index, count);
}
// End of overridden methods which use EncodingForwarder
internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
{
Contract.Assert(chars != null, "[UTF32Encoding.GetByteCount]chars!=null");
Contract.Assert(count >= 0, "[UTF32Encoding.GetByteCount]count >=0");
char* end = chars + count;
char* charStart = chars;
int byteCount = 0;
char highSurrogate = '\0';
// For fallback we may need a fallback buffer
EncoderFallbackBuffer fallbackBuffer = null;
if (encoder != null)
{
highSurrogate = encoder.charLeftOver;
fallbackBuffer = encoder.FallbackBuffer;
// We mustn't have left over fallback data when counting
if (fallbackBuffer.Remaining > 0)
throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty,
this.EncodingName, encoder.Fallback.GetType()));
}
else
{
fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, end, encoder, false);
char ch;
TryAgain:
while (((ch = fallbackBuffer.InternalGetNextChar()) != 0) || chars < end)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// Do we need a low surrogate?
if (highSurrogate != '\0')
{
//
// In previous char, we encounter a high surrogate, so we are expecting a low surrogate here.
//
if (Char.IsLowSurrogate(ch))
{
// They're all legal
highSurrogate = '\0';
//
// One surrogate pair will be translated into 4 bytes UTF32.
//
byteCount += 4;
continue;
}
// We are missing our low surrogate, decrement chars and fallback the high surrogate
// The high surrogate may have come from the encoder, but nothing else did.
Contract.Assert(chars > charStart,
"[UTF32Encoding.GetByteCount]Expected chars to have advanced if no low surrogate");
chars--;
// Do the fallback
fallbackBuffer.InternalFallback(highSurrogate, ref chars);
// We're going to fallback the old high surrogate.
highSurrogate = '\0';
continue;
}
// Do we have another high surrogate?
if (Char.IsHighSurrogate(ch))
{
//
// We'll have a high surrogate to check next time.
//
highSurrogate = ch;
continue;
}
// Check for illegal characters
if (Char.IsLowSurrogate(ch))
{
// We have a leading low surrogate, do the fallback
fallbackBuffer.InternalFallback(ch, ref chars);
// Try again with fallback buffer
continue;
}
// We get to add the character (4 bytes UTF32)
byteCount += 4;
}
// May have to do our last surrogate
if ((encoder == null || encoder.MustFlush) && highSurrogate > 0)
{
// We have to do the fallback for the lonely high surrogate
fallbackBuffer.InternalFallback(highSurrogate, ref chars);
highSurrogate = (char)0;
goto TryAgain;
}
// Check for overflows.
if (byteCount < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_GetByteCountOverflow);
// Shouldn't have anything in fallback buffer for GetByteCount
// (don't have to check m_throwOnOverflow for count)
Contract.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetByteCount]Expected empty fallback buffer at end");
// Return our count
return byteCount;
}
internal override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS encoder)
{
Contract.Assert(chars != null, "[UTF32Encoding.GetBytes]chars!=null");
Contract.Assert(bytes != null, "[UTF32Encoding.GetBytes]bytes!=null");
Contract.Assert(byteCount >= 0, "[UTF32Encoding.GetBytes]byteCount >=0");
Contract.Assert(charCount >= 0, "[UTF32Encoding.GetBytes]charCount >=0");
char* charStart = chars;
char* charEnd = chars + charCount;
byte* byteStart = bytes;
byte* byteEnd = bytes + byteCount;
char highSurrogate = '\0';
// For fallback we may need a fallback buffer
EncoderFallbackBuffer fallbackBuffer = null;
if (encoder != null)
{
highSurrogate = encoder.charLeftOver;
fallbackBuffer = encoder.FallbackBuffer;
// We mustn't have left over fallback data when not converting
if (encoder.m_throwOnOverflow && fallbackBuffer.Remaining > 0)
throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty,
this.EncodingName, encoder.Fallback.GetType()));
}
else
{
fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true);
char ch;
TryAgain:
while (((ch = fallbackBuffer.InternalGetNextChar()) != 0) || chars < charEnd)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// Do we need a low surrogate?
if (highSurrogate != '\0')
{
//
// In previous char, we encountered a high surrogate, so we are expecting a low surrogate here.
//
if (Char.IsLowSurrogate(ch))
{
// Is it a legal one?
uint iTemp = GetSurrogate(highSurrogate, ch);
highSurrogate = '\0';
//
// One surrogate pair will be translated into 4 bytes UTF32.
//
if (bytes + 3 >= byteEnd)
{
// Don't have 4 bytes
if (fallbackBuffer.bFallingBack)
{
fallbackBuffer.MovePrevious(); // Aren't using these 2 fallback chars
fallbackBuffer.MovePrevious();
}
else
{
// If we don't have enough room, then either we should've advanced a while
// or we should have bytes==byteStart and throw below
Contract.Assert(chars > charStart + 1 || bytes == byteStart,
"[UnicodeEncoding.GetBytes]Expected chars to have when no room to add surrogate pair");
chars -= 2; // Aren't using those 2 chars
}
ThrowBytesOverflow(encoder, bytes == byteStart); // Throw maybe (if no bytes written)
highSurrogate = (char)0; // Nothing left over (we backed up to start of pair if supplimentary)
break;
}
if (_bigEndian)
{
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)(iTemp >> 16); // Implies & 0xFF, which isn't needed cause high are all 0
*(bytes++) = (byte)(iTemp >> 8); // Implies & 0xFF
*(bytes++) = (byte)(iTemp); // Implies & 0xFF
}
else
{
*(bytes++) = (byte)(iTemp); // Implies & 0xFF
*(bytes++) = (byte)(iTemp >> 8); // Implies & 0xFF
*(bytes++) = (byte)(iTemp >> 16); // Implies & 0xFF, which isn't needed cause high are all 0
*(bytes++) = (byte)(0x00);
}
continue;
}
// We are missing our low surrogate, decrement chars and fallback the high surrogate
// The high surrogate may have come from the encoder, but nothing else did.
Contract.Assert(chars > charStart,
"[UTF32Encoding.GetBytes]Expected chars to have advanced if no low surrogate");
chars--;
// Do the fallback
fallbackBuffer.InternalFallback(highSurrogate, ref chars);
// We're going to fallback the old high surrogate.
highSurrogate = '\0';
continue;
}
// Do we have another high surrogate?, if so remember it
if (Char.IsHighSurrogate(ch))
{
//
// We'll have a high surrogate to check next time.
//
highSurrogate = ch;
continue;
}
// Check for illegal characters (low surrogate)
if (Char.IsLowSurrogate(ch))
{
// We have a leading low surrogate, do the fallback
fallbackBuffer.InternalFallback(ch, ref chars);
// Try again with fallback buffer
continue;
}
// We get to add the character, yippee.
if (bytes + 3 >= byteEnd)
{
// Don't have 4 bytes
if (fallbackBuffer.bFallingBack)
fallbackBuffer.MovePrevious(); // Aren't using this fallback char
else
{
// Must've advanced already
Contract.Assert(chars > charStart,
"[UTF32Encoding.GetBytes]Expected chars to have advanced if normal character");
chars--; // Aren't using this char
}
ThrowBytesOverflow(encoder, bytes == byteStart); // Throw maybe (if no bytes written)
break; // Didn't throw, stop
}
if (_bigEndian)
{
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)((uint)ch >> 8); // Implies & 0xFF
*(bytes++) = (byte)(ch); // Implies & 0xFF
}
else
{
*(bytes++) = (byte)(ch); // Implies & 0xFF
*(bytes++) = (byte)((uint)ch >> 8); // Implies & 0xFF
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)(0x00);
}
}
// May have to do our last surrogate
if ((encoder == null || encoder.MustFlush) && highSurrogate > 0)
{
// We have to do the fallback for the lonely high surrogate
fallbackBuffer.InternalFallback(highSurrogate, ref chars);
highSurrogate = (char)0;
goto TryAgain;
}
// Fix our encoder if we have one
Contract.Assert(highSurrogate == 0 || (encoder != null && !encoder.MustFlush),
"[UTF32Encoding.GetBytes]Expected encoder to be flushed.");
if (encoder != null)
{
// Remember our left over surrogate (or 0 if flushing)
encoder.charLeftOver = highSurrogate;
// Need # chars used
encoder.m_charsUsed = (int)(chars - charStart);
}
// return the new length
return (int)(bytes - byteStart);
}
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
Contract.Assert(bytes != null, "[UTF32Encoding.GetCharCount]bytes!=null");
Contract.Assert(count >= 0, "[UTF32Encoding.GetCharCount]count >=0");
UTF32Decoder decoder = (UTF32Decoder)baseDecoder;
// None so far!
int charCount = 0;
byte* end = bytes + count;
byte* byteStart = bytes;
// Set up decoder
int readCount = 0;
uint iChar = 0;
// For fallback we may need a fallback buffer
DecoderFallbackBuffer fallbackBuffer = null;
// See if there's anything in our decoder
if (decoder != null)
{
readCount = decoder.readByteCount;
iChar = (uint)decoder.iChar;
fallbackBuffer = decoder.FallbackBuffer;
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check m_throwOnOverflow for chars or count)
Contract.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetCharCount]Expected empty fallback buffer at start");
}
else
{
fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(byteStart, null);
// Loop through our input, 4 characters at a time!
while (bytes < end && charCount >= 0)
{
// Get our next character
if (_bigEndian)
{
// Scoot left and add it to the bottom
iChar <<= 8;
iChar += *(bytes++);
}
else
{
// Scoot right and add it to the top
iChar >>= 8;
iChar += (uint)(*(bytes++)) << 24;
}
readCount++;
// See if we have all the bytes yet
if (readCount < 4)
continue;
// Have the bytes
readCount = 0;
// See if its valid to encode
if (iChar > 0x10FFFF || (iChar >= 0xD800 && iChar <= 0xDFFF))
{
// Need to fall back these 4 bytes
byte[] fallbackBytes;
if (_bigEndian)
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar>>24)), unchecked((byte)(iChar>>16)),
unchecked((byte)(iChar>>8)), unchecked((byte)(iChar)) };
}
else
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar)), unchecked((byte)(iChar>>8)),
unchecked((byte)(iChar>>16)), unchecked((byte)(iChar>>24)) };
}
charCount += fallbackBuffer.InternalFallback(fallbackBytes, bytes);
// Ignore the illegal character
iChar = 0;
continue;
}
// Ok, we have something we can add to our output
if (iChar >= 0x10000)
{
// Surrogates take 2
charCount++;
}
// Add the rest of the surrogate or our normal character
charCount++;
// iChar is back to 0
iChar = 0;
}
// See if we have something left over that has to be decoded
if (readCount > 0 && (decoder == null || decoder.MustFlush))
{
// Oops, there's something left over with no place to go.
byte[] fallbackBytes = new byte[readCount];
if (_bigEndian)
{
while (readCount > 0)
{
fallbackBytes[--readCount] = unchecked((byte)iChar);
iChar >>= 8;
}
}
else
{
while (readCount > 0)
{
fallbackBytes[--readCount] = unchecked((byte)(iChar >> 24));
iChar <<= 8;
}
}
charCount += fallbackBuffer.InternalFallback(fallbackBytes, bytes);
}
// Check for overflows.
if (charCount < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_GetByteCountOverflow);
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check m_throwOnOverflow for chars or count)
Contract.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetCharCount]Expected empty fallback buffer at end");
// Return our count
return charCount;
}
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS baseDecoder)
{
Contract.Assert(chars != null, "[UTF32Encoding.GetChars]chars!=null");
Contract.Assert(bytes != null, "[UTF32Encoding.GetChars]bytes!=null");
Contract.Assert(byteCount >= 0, "[UTF32Encoding.GetChars]byteCount >=0");
Contract.Assert(charCount >= 0, "[UTF32Encoding.GetChars]charCount >=0");
UTF32Decoder decoder = (UTF32Decoder)baseDecoder;
// None so far!
char* charStart = chars;
char* charEnd = chars + charCount;
byte* byteStart = bytes;
byte* byteEnd = bytes + byteCount;
// See if there's anything in our decoder (but don't clear it yet)
int readCount = 0;
uint iChar = 0;
// For fallback we may need a fallback buffer
DecoderFallbackBuffer fallbackBuffer = null;
// See if there's anything in our decoder
if (decoder != null)
{
readCount = decoder.readByteCount;
iChar = (uint)decoder.iChar;
fallbackBuffer = baseDecoder.FallbackBuffer;
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check m_throwOnOverflow for chars)
Contract.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetChars]Expected empty fallback buffer at start");
}
else
{
fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(bytes, chars + charCount);
// Loop through our input, 4 characters at a time!
while (bytes < byteEnd)
{
// Get our next character
if (_bigEndian)
{
// Scoot left and add it to the bottom
iChar <<= 8;
iChar += *(bytes++);
}
else
{
// Scoot right and add it to the top
iChar >>= 8;
iChar += (uint)(*(bytes++)) << 24;
}
readCount++;
// See if we have all the bytes yet
if (readCount < 4)
continue;
// Have the bytes
readCount = 0;
// See if its valid to encode
if (iChar > 0x10FFFF || (iChar >= 0xD800 && iChar <= 0xDFFF))
{
// Need to fall back these 4 bytes
byte[] fallbackBytes;
if (_bigEndian)
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar>>24)), unchecked((byte)(iChar>>16)),
unchecked((byte)(iChar>>8)), unchecked((byte)(iChar)) };
}
else
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar)), unchecked((byte)(iChar>>8)),
unchecked((byte)(iChar>>16)), unchecked((byte)(iChar>>24)) };
}
// Chars won't be updated unless this works.
if (!fallbackBuffer.InternalFallback(fallbackBytes, bytes, ref chars))
{
// Couldn't fallback, throw or wait til next time
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
Contract.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (bad surrogate)");
bytes -= 4; // get back to where we were
iChar = 0; // Remembering nothing
fallbackBuffer.InternalReset();
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
break; // Stop here, didn't throw
}
// Ignore the illegal character
iChar = 0;
continue;
}
// Ok, we have something we can add to our output
if (iChar >= 0x10000)
{
// Surrogates take 2
if (chars >= charEnd - 1)
{
// Throwing or stopping
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
Contract.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (surrogate)");
bytes -= 4; // get back to where we were
iChar = 0; // Remembering nothing
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
break; // Stop here, didn't throw
}
*(chars++) = GetHighSurrogate(iChar);
iChar = GetLowSurrogate(iChar);
}
// Bounds check for normal character
else if (chars >= charEnd)
{
// Throwing or stopping
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
Contract.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (normal char)");
bytes -= 4; // get back to where we were
iChar = 0; // Remembering nothing
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
break; // Stop here, didn't throw
}
// Add the rest of the surrogate or our normal character
*(chars++) = (char)iChar;
// iChar is back to 0
iChar = 0;
}
// See if we have something left over that has to be decoded
if (readCount > 0 && (decoder == null || decoder.MustFlush))
{
// Oops, there's something left over with no place to go.
byte[] fallbackBytes = new byte[readCount];
int tempCount = readCount;
if (_bigEndian)
{
while (tempCount > 0)
{
fallbackBytes[--tempCount] = unchecked((byte)iChar);
iChar >>= 8;
}
}
else
{
while (tempCount > 0)
{
fallbackBytes[--tempCount] = unchecked((byte)(iChar >> 24));
iChar <<= 8;
}
}
if (!fallbackBuffer.InternalFallback(fallbackBytes, bytes, ref chars))
{
// Couldn't fallback.
fallbackBuffer.InternalReset();
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
// Stop here, didn't throw, backed up, so still nothing in buffer
}
else
{
// Don't clear our decoder unless we could fall it back.
// If we caught the if above, then we're a convert() and will catch this next time.
readCount = 0;
iChar = 0;
}
}
// Remember any left over stuff, clearing buffer as well for MustFlush
if (decoder != null)
{
decoder.iChar = (int)iChar;
decoder.readByteCount = readCount;
decoder.m_bytesUsed = (int)(bytes - byteStart);
}
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check m_throwOnOverflow for chars)
Contract.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetChars]Expected empty fallback buffer at end");
// Return our count
return (int)(chars - charStart);
}
private uint GetSurrogate(char cHigh, char cLow)
{
return (((uint)cHigh - 0xD800) * 0x400) + ((uint)cLow - 0xDC00) + 0x10000;
}
private char GetHighSurrogate(uint iChar)
{
return (char)((iChar - 0x10000) / 0x400 + 0xD800);
}
private char GetLowSurrogate(uint iChar)
{
return (char)((iChar - 0x10000) % 0x400 + 0xDC00);
}
public override Decoder GetDecoder()
{
return new UTF32Decoder(this);
}
public override Encoder GetEncoder()
{
return new EncoderNLS(this);
}
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
throw new ArgumentOutOfRangeException("charCount",
SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Characters would be # of characters + 1 in case left over high surrogate is ? * max fallback
long byteCount = (long)charCount + 1;
if (EncoderFallback.MaxCharCount > 1)
byteCount *= EncoderFallback.MaxCharCount;
// 4 bytes per char
byteCount *= 4;
if (byteCount > 0x7fffffff)
throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_GetByteCountOverflow);
return (int)byteCount;
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
throw new ArgumentOutOfRangeException("byteCount",
SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// A supplementary character becomes 2 surrogate characters, so 4 input bytes becomes 2 chars,
// plus we may have 1 surrogate char left over if the decoder has 3 bytes in it already for a non-bmp char.
// Have to add another one because 1/2 == 0, but 3 bytes left over could be 2 char surrogate pair
int charCount = (byteCount / 2) + 2;
// Also consider fallback because our input bytes could be out of range of unicode.
// Since fallback would fallback 4 bytes at a time, we'll only fall back 1/2 of MaxCharCount.
if (DecoderFallback.MaxCharCount > 2)
{
// Multiply time fallback size
charCount *= DecoderFallback.MaxCharCount;
// We were already figuring 2 chars per 4 bytes, but fallback will be different #
charCount /= 2;
}
if (charCount > 0x7fffffff)
throw new ArgumentOutOfRangeException("byteCount", SR.ArgumentOutOfRange_GetCharCountOverflow);
return (int)charCount;
}
public override byte[] GetPreamble()
{
if (_emitUTF32ByteOrderMark)
{
// Allocate new array to prevent users from modifying it.
if (_bigEndian)
{
return new byte[4] { 0x00, 0x00, 0xFE, 0xFF };
}
else
{
return new byte[4] { 0xFF, 0xFE, 0x00, 0x00 }; // 00 00 FE FF
}
}
else
return Array.Empty<byte>();
}
public override bool Equals(Object value)
{
UTF32Encoding that = value as UTF32Encoding;
if (that != null)
{
return (_emitUTF32ByteOrderMark == that._emitUTF32ByteOrderMark) &&
(_bigEndian == that._bigEndian) &&
// (isThrowException == that.isThrowException) && // same as encoder/decoderfallback being exceptions
(EncoderFallback.Equals(that.EncoderFallback)) &&
(DecoderFallback.Equals(that.DecoderFallback));
}
return (false);
}
public override int GetHashCode()
{
//Not great distribution, but this is relatively unlikely to be used as the key in a hashtable.
return this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode() +
CodePage + (_emitUTF32ByteOrderMark ? 4 : 0) + (_bigEndian ? 8 : 0);
}
internal class UTF32Decoder : DecoderNLS
{
// Need a place to store any extra bytes we may have picked up
internal int iChar = 0;
internal int readByteCount = 0;
public UTF32Decoder(UTF32Encoding encoding) : base(encoding)
{
// base calls reset
}
public override void Reset()
{
this.iChar = 0;
this.readByteCount = 0;
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
// Anything left in our decoder?
internal override bool HasState
{
get
{
// ReadByteCount is our flag. (iChar==0 doesn't mean much).
return (this.readByteCount != 0);
}
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="RoslynV1SarifFixerTests.cs" company="SonarSource SA and Microsoft Corporation">
// Copyright (c) SonarSource SA and Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// </copyright>
//-----------------------------------------------------------------------
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SonarRunner.Shim;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using TestUtilities;
namespace SonarQube.Shim.Tests
{
[TestClass]
public class RoslynV1SarifFixerTests
{
public TestContext TestContext { get; set; }
#region Tests
/// <summary>
/// There should be no change to input if it is already valid, as attempting to fix valid SARIF may cause over-escaping.
/// This should be the case even if the output came from VS 2015 RTM.
/// </summary>
[TestMethod]
public void SarifFixer_ShouldNotChange_Valid()
{
// Arrange
TestLogger logger = new TestLogger();
string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext);
string testSarifString = @"{
""version"": ""0.1"",
""toolInfo"": {
""toolName"": ""Microsoft (R) Visual C# Compiler"",
""productVersion"": ""1.0.0"",
""fileVersion"": ""1.0.0""
},
""issues"": [
{
""ruleId"": ""DD001"",
""locations"": [
{
""analysisTarget"": [
{
""uri"": ""C:\\agent\\_work\\2\\s\\MyTestProj\\Program.cs"",
}
]
}
],
""shortMessage"": ""Test shortMessage. It features \""quoted text\""."",
""properties"": {
""severity"": ""Info"",
""helpLink"": ""https://github.com/SonarSource/sonar-msbuild-runner"",
}
}
]
}";
string testSarifPath = Path.Combine(testDir, "testSarif.json");
File.WriteAllText(testSarifPath, testSarifString);
DateTime originalWriteTime = new FileInfo(testSarifPath).LastWriteTime;
// Act
string returnedSarifPath = new RoslynV1SarifFixer().LoadAndFixFile(testSarifPath, logger);
// Assert
// already valid -> no change to file, same file path returned
AssertFileUnchanged(testSarifPath, originalWriteTime);
Assert.AreEqual(testSarifPath, returnedSarifPath);
}
[TestMethod]
public void SarifFixer_ShouldNotChange_Unfixable()
{
// Arrange
TestLogger logger = new TestLogger();
string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext);
string testSarifString = @"{
""version"": ""0.1"",
""toolInfo"": {
""toolName"": ""Microsoft (R) Visual C# Compiler"",
""productVersion"": ""1.0.0"",
""fileVersion"": ""1.0.0""
},
""issues"": [
{
}}}}}}}}}}}}}}}}}}}}}}}}}
""ruleId"": ""DD001"",
""locations"": [
{
""analysisTarget"": [
{
""uri"": ""C:\\agent\\_work\\2\\s\\MyTestProj\\Program.cs"",
}
]
}
],
""shortMessage"": ""Test shortMessage. It features \""quoted text\""."",
""properties"": {
""severity"": ""Info"",
""helpLink"": ""https://github.com/SonarSource/sonar-msbuild-runner"",
}
}
]
}";
string testSarifPath = Path.Combine(testDir, "testSarif.json");
File.WriteAllText(testSarifPath, testSarifString);
DateTime originalWriteTime = new FileInfo(testSarifPath).LastWriteTime;
// Act
string returnedSarifPath = new RoslynV1SarifFixer().LoadAndFixFile(testSarifPath, logger);
// Assert
// unfixable -> no change to file, null return
AssertFileUnchanged(testSarifPath, originalWriteTime);
Assert.IsNull(returnedSarifPath);
}
/// <summary>
/// The current solution cannot fix values spanning multiple fields. As such it should not attempt to.
///
/// Example invalid:
/// "fullMessage": "message
/// \test\ ["_"]",
/// </summary>
[TestMethod]
public void SarifFixer_ShouldNotChange_MultipleLineValues()
{
// Arrange
TestLogger logger = new TestLogger();
string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext);
string testSarifString = @"{
""version"": ""0.1"",
""toolInfo"": {
""toolName"": ""Microsoft (R) Visual C# Compiler"",
""productVersion"": ""1.0.0"",
""fileVersion"": ""1.0.0""
},
""issues"": [
{
""ruleId"": ""DD001"",
""shortMessage"": ""Test shortMessage.
It features ""quoted text""."",
""properties"": {
""severity"": ""Info"",
""helpLink"": ""https://github.com/SonarSource/sonar-msbuild-runner"",
}
}
]
}";
string testSarifPath = Path.Combine(testDir, "testSarif.json");
File.WriteAllText(testSarifPath, testSarifString);
DateTime originalWriteTime = new FileInfo(testSarifPath).LastWriteTime;
// Act
string returnedSarifPath = new RoslynV1SarifFixer().LoadAndFixFile(testSarifPath, logger);
// Assert
// unfixable -> no change to file, null return
AssertFileUnchanged(testSarifPath, originalWriteTime);
Assert.IsNull(returnedSarifPath);
}
[TestMethod]
public void SarifFixer_ShouldChange_EscapeBackslashes()
{
// Arrange
TestLogger logger = new TestLogger();
string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext);
string testSarifString = @"{
""version"": ""0.1"",
""toolInfo"": {
""toolName"": ""Microsoft (R) Visual C# Compiler"",
""productVersion"": ""1.0.0"",
""fileVersion"": ""1.0.0""
},
""issues"": [
{
""ruleId"": ""DD001"",
""locations"": [
{
""analysisTarget"": [
{
""uri"": ""C:\agent\_work\2\s\MyTestProj\Program.cs"",
}
]
}
],
}
]
}";
string testSarifPath = Path.Combine(testDir, "testSarif.json");
File.WriteAllText(testSarifPath, testSarifString);
DateTime originalWriteTime = new FileInfo(testSarifPath).LastWriteTime;
// Act
string returnedSarifPath = new RoslynV1SarifFixer().LoadAndFixFile(testSarifPath, logger);
// Assert
// fixable -> no change to file, file path in return value, file contents as expected
AssertFileUnchanged(testSarifPath, originalWriteTime);
Assert.IsNotNull(returnedSarifPath);
string returnedSarifString = File.ReadAllText(returnedSarifPath);
Assert.AreEqual(@"{
""version"": ""0.1"",
""toolInfo"": {
""toolName"": ""Microsoft (R) Visual C# Compiler"",
""productVersion"": ""1.0.0"",
""fileVersion"": ""1.0.0""
},
""issues"": [
{
""ruleId"": ""DD001"",
""locations"": [
{
""analysisTarget"": [
{
""uri"": ""C:\\agent\\_work\\2\\s\\MyTestProj\\Program.cs"",
}
]
}
],
}
]
}", returnedSarifString);
}
[TestMethod]
public void SarifFixer_ShouldChange_EscapeQuotes()
{
// Arrange
TestLogger logger = new TestLogger();
string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext);
string testSarifString = @"{
""version"": ""0.1"",
""toolInfo"": {
""toolName"": ""Microsoft (R) Visual C# Compiler"",
""productVersion"": ""1.0.0"",
""fileVersion"": ""1.0.0""
},
""issues"": [
{
""ruleId"": ""DD001"",
""shortMessage"": ""Test shortMessage. It features ""quoted text""."",
""properties"": {
""severity"": ""Info"",
""helpLink"": ""https://github.com/SonarSource/sonar-msbuild-runner"",
}
}
]
}";
string testSarifPath = Path.Combine(testDir, "testSarif.json");
File.WriteAllText(testSarifPath, testSarifString);
DateTime originalWriteTime = new FileInfo(testSarifPath).LastWriteTime;
// Act
string returnedSarifPath = new RoslynV1SarifFixer().LoadAndFixFile(testSarifPath, logger);
// Assert
// fixable -> no change to file, file path in return value, file contents as expected
AssertFileUnchanged(testSarifPath, originalWriteTime);
Assert.IsNotNull(returnedSarifPath);
string returnedSarifString = File.ReadAllText(returnedSarifPath);
Assert.AreEqual(@"{
""version"": ""0.1"",
""toolInfo"": {
""toolName"": ""Microsoft (R) Visual C# Compiler"",
""productVersion"": ""1.0.0"",
""fileVersion"": ""1.0.0""
},
""issues"": [
{
""ruleId"": ""DD001"",
""shortMessage"": ""Test shortMessage. It features \""quoted text\""."",
""properties"": {
""severity"": ""Info"",
""helpLink"": ""https://github.com/SonarSource/sonar-msbuild-runner"",
}
}
]
}", returnedSarifString);
}
[TestMethod]
public void SarifFixer_ShouldChange_EscapeCharsInAllAffectedFields()
{
// Arrange
TestLogger logger = new TestLogger();
string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext);
string testSarifString = @"{
""version"": ""0.1"",
""toolInfo"": {
""toolName"": ""Microsoft (R) Visual C# Compiler"",
""productVersion"": ""1.0.0"",
""fileVersion"": ""1.0.0""
},
""issues"": [
{
""ruleId"": ""DD001"",
""locations"": [
{
""analysisTarget"": [
{
""uri"": ""C:\agent\_work\2\s\MyTestProj\Program.cs"",
}
]
}
],
""shortMessage"": ""Test shortMessage. It features ""quoted text"" and has \slashes."",
""fullMessage"": ""Test fullMessage. It features ""quoted text"" and has \slashes."",
""properties"": {
""severity"": ""Info"",
""title"": ""Test title. It features ""quoted text"" and has \slashes."",
""helpLink"": ""https://github.com/SonarSource/sonar-msbuild-runner"",
}
}
]
}";
string testSarifPath = Path.Combine(testDir, "testSarif.json");
File.WriteAllText(testSarifPath, testSarifString);
DateTime originalWriteTime = new FileInfo(testSarifPath).LastWriteTime;
// Act
string returnedSarifPath = new RoslynV1SarifFixer().LoadAndFixFile(testSarifPath, logger);
// Assert
// fixable -> no change to file, file path in return value, file contents as expected
AssertFileUnchanged(testSarifPath, originalWriteTime);
Assert.IsNotNull(returnedSarifPath);
string returnedSarifString = File.ReadAllText(returnedSarifPath);
Assert.AreEqual(@"{
""version"": ""0.1"",
""toolInfo"": {
""toolName"": ""Microsoft (R) Visual C# Compiler"",
""productVersion"": ""1.0.0"",
""fileVersion"": ""1.0.0""
},
""issues"": [
{
""ruleId"": ""DD001"",
""locations"": [
{
""analysisTarget"": [
{
""uri"": ""C:\\agent\\_work\\2\\s\\MyTestProj\\Program.cs"",
}
]
}
],
""shortMessage"": ""Test shortMessage. It features \""quoted text\"" and has \\slashes."",
""fullMessage"": ""Test fullMessage. It features \""quoted text\"" and has \\slashes."",
""properties"": {
""severity"": ""Info"",
""title"": ""Test title. It features \""quoted text\"" and has \\slashes."",
""helpLink"": ""https://github.com/SonarSource/sonar-msbuild-runner"",
}
}
]
}", returnedSarifString);
}
#endregion
#region Private Methods
private void AssertFileUnchanged(string filePath, DateTime originalWriteTime)
{
Assert.AreEqual(originalWriteTime, new FileInfo(filePath).LastWriteTime);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using Validation;
namespace System.Collections.Immutable
{
/// <summary>
/// Extension methods for immutable types.
/// </summary>
internal static class ImmutableExtensions
{
/// <summary>
/// Tries to divine the number of elements in a sequence without actually enumerating each element.
/// </summary>
/// <typeparam name="T">The type of elements in the sequence.</typeparam>
/// <param name="sequence">The enumerable source.</param>
/// <param name="count">Receives the number of elements in the enumeration, if it could be determined.</param>
/// <returns><c>true</c> if the count could be determined; <c>false</c> otherwise.</returns>
internal static bool TryGetCount<T>(this IEnumerable<T> sequence, out int count)
{
return TryGetCount<T>((IEnumerable)sequence, out count);
}
/// <summary>
/// Tries to divine the number of elements in a sequence without actually enumerating each element.
/// </summary>
/// <typeparam name="T">The type of elements in the sequence.</typeparam>
/// <param name="sequence">The enumerable source.</param>
/// <param name="count">Receives the number of elements in the enumeration, if it could be determined.</param>
/// <returns><c>true</c> if the count could be determined; <c>false</c> otherwise.</returns>
internal static bool TryGetCount<T>(this IEnumerable sequence, out int count)
{
var collection = sequence as ICollection;
if (collection != null)
{
count = collection.Count;
return true;
}
var collectionOfT = sequence as ICollection<T>;
if (collectionOfT != null)
{
count = collectionOfT.Count;
return true;
}
var readOnlyCollection = sequence as IReadOnlyCollection<T>;
if (readOnlyCollection != null)
{
count = readOnlyCollection.Count;
return true;
}
count = 0;
return false;
}
/// <summary>
/// Gets the number of elements in the specified sequence,
/// while guaranteeing that the sequence is only enumerated once
/// in total by this method and the caller.
/// </summary>
/// <typeparam name="T">The type of element in the collection.</typeparam>
/// <param name="sequence">The sequence.</param>
/// <returns>The number of elements in the sequence.</returns>
internal static int GetCount<T>(ref IEnumerable<T> sequence)
{
int count;
if (!sequence.TryGetCount(out count))
{
// We cannot predict the length of the sequence. We must walk the entire sequence
// to find the count. But avoid our caller also having to enumerate by capturing
// the enumeration in a snapshot and passing that back to the caller.
var list = sequence.ToList();
count = list.Count;
sequence = list;
}
return count;
}
/// <summary>
/// Gets a copy of a sequence as an array.
/// </summary>
/// <typeparam name="T">The type of element.</typeparam>
/// <param name="sequence">The sequence to be copied.</param>
/// <param name="count">The number of elements in the sequence.</param>
/// <returns>The array.</returns>
/// <remarks>
/// This is more efficient than the Enumerable.ToArray{T} extension method
/// because that only tries to cast the sequence to ICollection{T} to determine
/// the count before it falls back to reallocating arrays as it enumerates.
/// </remarks>
internal static T[] ToArray<T>(this IEnumerable<T> sequence, int count)
{
Requires.NotNull(sequence, "sequence");
Requires.Range(count >= 0, "count");
T[] array = new T[count];
int i = 0;
foreach (var item in sequence)
{
Requires.Argument(i < count);
array[i++] = item;
}
Requires.Argument(i == count);
return array;
}
#if EqualsStructurally
/// <summary>
/// An optimized version of <see cref="Enumerable.SequenceEqual{T}(IEnumerable{T}, IEnumerable{T}, IEqualityComparer{T})"/>
/// that allows nulls, considers reference equality and count before beginning the enumeration.
/// </summary>
/// <typeparam name="T">The type of elements in the sequence.</typeparam>
/// <param name="sequence1">The first sequence.</param>
/// <param name="sequence2">The second sequence.</param>
/// <param name="equalityComparer">The equality comparer to use for the elements.</param>
/// <returns><c>true</c> if the sequences are equal (same elements in the same order); <c>false</c> otherwise.</returns>
internal static bool CollectionEquals<T>(this IEnumerable<T> sequence1, IEnumerable<T> sequence2, IEqualityComparer<T> equalityComparer = null)
{
if (sequence1 == sequence2)
{
return true;
}
if ((sequence1 == null) ^ (sequence2 == null))
{
return false;
}
int count1, count2;
if (sequence1.TryGetCount(out count1) && sequence2.TryGetCount(out count2))
{
if (count1 != count2)
{
return false;
}
if (count1 == 0 && count2 == 0)
{
return true;
}
}
return sequence1.SequenceEqual(sequence2, equalityComparer);
}
/// <summary>
/// An optimized version of <see cref="Enumerable.SequenceEqual{T}(IEnumerable{T}, IEnumerable{T}, IEqualityComparer{T})"/>
/// that allows nulls, considers reference equality and count before beginning the enumeration.
/// </summary>
/// <typeparam name="T">The type of elements in the sequence.</typeparam>
/// <param name="sequence1">The first sequence.</param>
/// <param name="sequence2">The second sequence.</param>
/// <param name="equalityComparer">The equality comparer to use for the elements.</param>
/// <returns><c>true</c> if the sequences are equal (same elements in the same order); <c>false</c> otherwise.</returns>
internal static bool CollectionEquals<T>(this IEnumerable<T> sequence1, IEnumerable sequence2, IEqualityComparer equalityComparer = null)
{
if (sequence1 == sequence2)
{
return true;
}
if ((sequence1 == null) ^ (sequence2 == null))
{
return false;
}
int count1, count2;
if (sequence1.TryGetCount(out count1) && sequence2.TryGetCount<T>(out count2))
{
if (count1 != count2)
{
return false;
}
if (count1 == 0 && count2 == 0)
{
return true;
}
}
if (equalityComparer == null)
{
equalityComparer = EqualityComparer<T>.Default;
}
// If we have generic types we can use, use them to avoid boxing.
var sequence2OfT = sequence2 as IEnumerable<T>;
var equalityComparerOfT = equalityComparer as IEqualityComparer<T>;
if (sequence2OfT != null && equalityComparerOfT != null)
{
return sequence1.SequenceEqual(sequence2OfT, equalityComparerOfT);
}
else
{
// We have to fallback to doing it manually since the underlying collection
// being compared isn't a (matching) generic type.
using (var enumerator = sequence1.GetEnumerator())
{
var enumerator2 = sequence2.GetEnumerator();
try
{
while (enumerator.MoveNext())
{
if (!enumerator2.MoveNext() || !equalityComparer.Equals(enumerator.Current, enumerator2.Current))
{
return false;
}
}
if (enumerator2.MoveNext())
{
return false;
}
return true;
}
finally
{
var enum2Disposable = enumerator2 as IDisposable;
if (enum2Disposable != null)
{
enum2Disposable.Dispose();
}
}
}
}
}
#endif
/// <summary>
/// Provides a known wrapper around a sequence of elements that provides the number of elements
/// and an indexer into its contents.
/// </summary>
/// <typeparam name="T">The type of elements in the collection.</typeparam>
/// <param name="sequence">The collection.</param>
/// <returns>An ordered collection. May not be thread-safe. Never null.</returns>
internal static IOrderedCollection<T> AsOrderedCollection<T>(this IEnumerable<T> sequence)
{
Requires.NotNull(sequence, "sequence");
Contract.Ensures(Contract.Result<IOrderedCollection<T>>() != null);
var orderedCollection = sequence as IOrderedCollection<T>;
if (orderedCollection != null)
{
return orderedCollection;
}
var listOfT = sequence as IList<T>;
if (listOfT != null)
{
return new ListOfTWrapper<T>(listOfT);
}
// It would be great if SortedSet<T> and SortedDictionary<T> provided indexers into their collections,
// but since they don't we have to clone them to an array.
return new FallbackWrapper<T>(sequence);
}
/// <summary>
/// Clears the specified stack. For empty stacks, it avoids the call to Clear, which
/// avoids a call into the runtime's implementation of Array.Clear, helping performance,
/// in particular around inlining. Stack.Count typically gets inlined by today's JIT, while
/// stack.Clear and Array.Clear typically don't.
/// </summary>
/// <typeparam name="T">Specifies the type of data in the stack to be cleared.</typeparam>
/// <param name="stack">The stack to clear.</param>
internal static void ClearFastWhenEmpty<T>(this Stack<T> stack)
{
if (stack.Count > 0)
{
stack.Clear();
}
}
/// <summary>
/// Gets a non-disposable enumerable that can be used as the source for a C# foreach loop
/// that will not box the enumerator if it is of a particular type.
/// </summary>
/// <typeparam name="T">The type of value to be enumerated.</typeparam>
/// <typeparam name="TEnumerator">
/// The type of the Enumerator struct. This must NOT implement <see cref="IDisposable"/> (or <see cref="IEnumerator{T}"/>).
/// If it does, call <see cref="GetEnumerableDisposable{T, TEnumerator}"/> instead.
/// </typeparam>
/// <param name="enumerable">The collection to be enumerated.</param>
/// <returns>A struct that enumerates the collection.</returns>
internal static EnumeratorAdapter<T, TEnumerator> GetEnumerable<T, TEnumerator>(this IEnumerable<T> enumerable)
where TEnumerator : struct, IStrongEnumerator<T>
{
Requires.NotNull(enumerable, "enumerable");
// This debug-only check is sufficient to cause test failures to flag errors so they never get checked in.
Debug.Assert(!typeof(IDisposable).GetTypeInfo().IsAssignableFrom(typeof(TEnumerator).GetTypeInfo()), "The enumerator struct implements IDisposable. Call GetEnumerableDisposable instead.");
var strongEnumerable = enumerable as IStrongEnumerable<T, TEnumerator>;
if (strongEnumerable != null)
{
return new EnumeratorAdapter<T, TEnumerator>(strongEnumerable.GetEnumerator());
}
else
{
// Consider for future: we could add more special cases for common
// mutable collection types like List<T>+Enumerator and such.
return new EnumeratorAdapter<T, TEnumerator>(enumerable.GetEnumerator());
}
}
/// <summary>
/// Gets a disposable enumerable that can be used as the source for a C# foreach loop
/// that will not box the enumerator if it is of a particular type.
/// </summary>
/// <typeparam name="T">The type of value to be enumerated.</typeparam>
/// <typeparam name="TEnumerator">The type of the Enumerator struct.</typeparam>
/// <param name="enumerable">The collection to be enumerated.</param>
/// <returns>A struct that enumerates the collection.</returns>
internal static DisposableEnumeratorAdapter<T, TEnumerator> GetEnumerableDisposable<T, TEnumerator>(this IEnumerable<T> enumerable)
where TEnumerator : struct, IStrongEnumerator<T>, IEnumerator<T>
{
Requires.NotNull(enumerable, "enumerable");
var strongEnumerable = enumerable as IStrongEnumerable<T, TEnumerator>;
if (strongEnumerable != null)
{
return new DisposableEnumeratorAdapter<T, TEnumerator>(strongEnumerable.GetEnumerator());
}
else
{
// Consider for future: we could add more special cases for common
// mutable collection types like List<T>+Enumerator and such.
return new DisposableEnumeratorAdapter<T, TEnumerator>(enumerable.GetEnumerator());
}
}
/// <summary>
/// Wraps a List{T} as an ordered collection.
/// </summary>
/// <typeparam name="T">The type of element in the collection.</typeparam>
private class ListOfTWrapper<T> : IOrderedCollection<T>
{
/// <summary>
/// The list being exposed.
/// </summary>
private readonly IList<T> collection;
/// <summary>
/// Initializes a new instance of the <see cref="ListOfTWrapper<T>"/> class.
/// </summary>
/// <param name="collection">The collection.</param>
internal ListOfTWrapper(IList<T> collection)
{
Requires.NotNull(collection, "collection");
this.collection = collection;
}
/// <summary>
/// Gets the count.
/// </summary>
public int Count
{
get { return this.collection.Count; }
}
/// <summary>
/// Gets the <typeparamref name="T"/> at the specified index.
/// </summary>
public T this[int index]
{
get { return this.collection[index]; }
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<T> GetEnumerator()
{
return this.collection.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 this.GetEnumerator();
}
}
/// <summary>
/// Wraps any IEnumerable as an ordered, indexable list.
/// </summary>
/// <typeparam name="T">The type of element in the collection.</typeparam>
private class FallbackWrapper<T> : IOrderedCollection<T>
{
/// <summary>
/// The original sequence.
/// </summary>
private readonly IEnumerable<T> sequence;
/// <summary>
/// The list-ified sequence.
/// </summary>
private IList<T> collection;
/// <summary>
/// Initializes a new instance of the <see cref="FallbackWrapper<T>"/> class.
/// </summary>
/// <param name="sequence">The sequence.</param>
internal FallbackWrapper(IEnumerable<T> sequence)
{
Requires.NotNull(sequence, "sequence");
this.sequence = sequence;
}
/// <summary>
/// Gets the count.
/// </summary>
public int Count
{
get
{
if (this.collection == null)
{
int count;
if (this.sequence.TryGetCount(out count))
{
return count;
}
this.collection = this.sequence.ToArray();
}
return this.collection.Count;
}
}
/// <summary>
/// Gets the <typeparamref name="T"/> at the specified index.
/// </summary>
public T this[int index]
{
get
{
if (this.collection == null)
{
this.collection = this.sequence.ToArray();
}
return this.collection[index];
}
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<T> GetEnumerator()
{
return this.sequence.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>
[ExcludeFromCodeCoverage]
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace Sandbox.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ActionDescriptor.ReturnType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Newtonsoft.Json.Linq;
using ReactNative.Bridge;
using ReactNative.Common;
using ReactNative.Modules.Core;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.System;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
namespace ReactNative
{
/// <summary>
/// Base page for React Native applications.
/// </summary>
[Obsolete("Please use ReactNativeHost instead of ReactPage.")]
public abstract class ReactPage : Page, IAsyncDisposable
{
private readonly ReactInstanceManager _reactInstanceManager;
private bool _isShiftKeyDown;
private bool _isControlKeyDown;
/// <summary>
/// Instantiates the <see cref="ReactPage"/>.
/// </summary>
protected ReactPage()
{
_reactInstanceManager = CreateReactInstanceManager();
RootView = CreateRootView();
Content = RootView;
}
/// <summary>
/// The custom path of the bundle file.
/// </summary>
/// <remarks>
/// This is used in cases where the bundle should be loaded from a
/// custom path.
/// </remarks>
public virtual string JavaScriptBundleFile
{
get
{
return null;
}
}
/// <summary>
/// The name of the main module.
/// </summary>
/// <remarks>
/// This is used to determine the URL used to fetch the JavaScript
/// bundle from the packager server. It is only used when dev support
/// is enabled.
/// </remarks>
public virtual string JavaScriptMainModuleName
{
get
{
return "index.windows";
}
}
/// <summary>
/// Instantiates the JavaScript executor.
/// </summary>
public virtual Func<IJavaScriptExecutor> JavaScriptExecutorFactory
{
get
{
return null;
}
}
/// <summary>
/// The name of the main component registered from JavaScript.
/// </summary>
public abstract string MainComponentName { get; }
/// <summary>
/// Signals whether developer mode should be enabled.
/// </summary>
public abstract bool UseDeveloperSupport { get; }
/// <summary>
/// The list of <see cref="IReactPackage"/>s used by the application.
/// </summary>
public abstract List<IReactPackage> Packages { get; }
/// <summary>
/// The root view managed by the page.
/// </summary>
public ReactRootView RootView { get; }
/// <summary>
/// Called when the application is first initialized.
/// </summary>
/// <param name="arguments">The launch arguments.</param>
public void OnCreate(string arguments)
{
OnCreate(arguments, default(JObject));
}
/// <summary>
/// Called when the application is first initialized.
/// </summary>
/// <param name="arguments">The launch arguments.</param>
/// <param name="initialProps">The initialProps.</param>
public void OnCreate(string arguments, JObject initialProps)
{
RootView.Background = (Brush)Application.Current.Resources["ApplicationPageBackgroundThemeBrush"];
ApplyArguments(arguments);
RootView.StartReactApplication(_reactInstanceManager, MainComponentName, initialProps);
SystemNavigationManager.GetForCurrentView().BackRequested += (sender, args) =>
{
_reactInstanceManager.OnBackPressed();
args.Handled = true;
};
Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated += OnAcceleratorKeyActivated;
}
/// <summary>
/// Called before the application is suspended.
/// </summary>
public void OnSuspend()
{
_reactInstanceManager.OnSuspend();
}
/// <summary>
/// Called when the application is resumed.
/// </summary>
/// <param name="onBackPressed">
/// Default action to take when back pressed.
/// </param>
public void OnResume(Action onBackPressed)
{
_reactInstanceManager.OnResume(onBackPressed);
}
/// <summary>
/// Called before the application shuts down.
/// </summary>
public async Task DisposeAsync()
{
Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated -= OnAcceleratorKeyActivated;
await RootView.StopReactApplicationAsync();
await _reactInstanceManager.DisposeAsync();
}
/// <summary>
/// Creates the React root view.
/// </summary>
/// <returns>The root view.</returns>
/// <remarks>
/// Subclasses may override this method if it needs to use a custom
/// root view.
/// </remarks>
protected virtual ReactRootView CreateRootView()
{
return new ReactRootView();
}
/// <summary>
/// Captures the all key downs and Ups.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnAcceleratorKeyActivated(CoreDispatcher sender, AcceleratorKeyEventArgs e)
{
if (_reactInstanceManager.DevSupportManager.IsEnabled)
{
if (e.VirtualKey == VirtualKey.Shift)
{
_isShiftKeyDown = e.EventType == CoreAcceleratorKeyEventType.KeyDown;
}
else if (e.VirtualKey == VirtualKey.Control)
{
_isControlKeyDown = e.EventType == CoreAcceleratorKeyEventType.KeyDown;
}
else if ( (_isShiftKeyDown && e.VirtualKey == VirtualKey.F10) ||
(e.EventType == CoreAcceleratorKeyEventType.KeyDown && e.VirtualKey == VirtualKey.Menu))
{
_reactInstanceManager.DevSupportManager.ShowDevOptionsDialog();
}
else if (e.EventType == CoreAcceleratorKeyEventType.KeyUp && _isControlKeyDown && e.VirtualKey == VirtualKey.R)
{
_reactInstanceManager.DevSupportManager.HandleReloadJavaScript();
}
}
}
private ReactInstanceManager CreateReactInstanceManager()
{
var builder = new ReactInstanceManagerBuilder
{
UseDeveloperSupport = UseDeveloperSupport,
InitialLifecycleState = LifecycleState.BeforeCreate,
JavaScriptBundleFile = JavaScriptBundleFile,
JavaScriptMainModuleName = JavaScriptMainModuleName,
JavaScriptExecutorFactory = JavaScriptExecutorFactory,
};
builder.Packages.AddRange(Packages);
return builder.Build();
}
private void ApplyArguments(string arguments)
{
if (!string.IsNullOrEmpty(arguments))
{
var args = arguments.Split(',');
var index = Array.IndexOf(args, "remoteDebugging");
if (index < 0)
{
return;
}
if (args.Length <= index + 1)
{
throw new ArgumentException("Expected value for remoteDebugging argument.", nameof(arguments));
}
if (bool.TryParse(args[index + 1], out var isRemoteDebuggingEnabled))
{
_reactInstanceManager.DevSupportManager.IsRemoteDebuggingEnabled = isRemoteDebuggingEnabled;
}
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Windows;
using System.Collections.Generic;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PushSDK;
using WPCordovaClassLib.Cordova;
using WPCordovaClassLib.Cordova.JSON;
using System.Runtime.Serialization;
using System.Threading;
using Newtonsoft.Json.Linq;
using PushSDK.Classes;
using Newtonsoft.Json;
namespace WPCordovaClassLib.Cordova.Commands
{
public class PushNotification : BaseCommand
{
private String appid;
private String authenticatedServiceName = null;
private NotificationService service = null;
volatile private bool deviceReady = false;
private string registerCallbackId = null;
// returns null value if it fails.
private string getCallbackId(string options)
{
string[] optStings = null;
try
{
optStings = JSON.JsonHelper.Deserialize<string[]>(options);
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), CurrentCommandCallbackId);
}
if (optStings == null)
return CurrentCommandCallbackId;
//callback id is the last item
return optStings[optStings.Length - 1];
}
//Phonegap runs all plugins methods on a separate threads, make sure onDeviceReady goes first
void waitDeviceReady()
{
while (!deviceReady)
Thread.Sleep(10);
}
public void onDeviceReady(string options)
{
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
PushOptions pushOptions = JSON.JsonHelper.Deserialize<PushOptions>(args[0]);
this.appid = pushOptions.AppID;
authenticatedServiceName = pushOptions.ServiceName;
service = NotificationService.GetCurrent(appid, authenticatedServiceName, null);
service.OnPushTokenReceived += OnPushTokenReceived;
service.OnPushTokenFailed += OnPushTokenFailed;
service.OnPushAccepted += ExecutePushNotificationCallback;
deviceReady = true;
}
private void OnPushTokenReceived(object sender, string token)
{
if(registerCallbackId != null)
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, token), registerCallbackId);
}
private void OnPushTokenFailed(object sender, string error)
{
if (registerCallbackId != null)
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, error), registerCallbackId);
}
public void registerDevice(string options)
{
string callbackId = getCallbackId(options);
waitDeviceReady();
service.SubscribeToPushService(authenticatedServiceName);
if (string.IsNullOrEmpty(service.PushToken))
{
registerCallbackId = callbackId;
PluginResult plugResult = new PluginResult(PluginResult.Status.NO_RESULT);
plugResult.KeepCallback = true;
DispatchCommandResult(plugResult, callbackId);
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, service.PushToken), callbackId);
}
}
public void unregisterDevice(string options)
{
string callbackId = getCallbackId(options);
PluginResult plugResult = new PluginResult(PluginResult.Status.NO_RESULT);
plugResult.KeepCallback = true;
DispatchCommandResult(plugResult);
waitDeviceReady();
service.UnsubscribeFromPushes(
(obj, args) =>
{
string result = JsonConvert.SerializeObject(args);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, result));
},
(obj, args) =>
{
string result = JsonConvert.SerializeObject(args);
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, result));
});
}
public void getTags(string options)
{
string callbackId = getCallbackId(options);
PluginResult plugResult = new PluginResult(PluginResult.Status.NO_RESULT);
plugResult.KeepCallback = true;
DispatchCommandResult(plugResult);
waitDeviceReady();
service.GetTags(
(obj, args) =>
{
string result = JsonConvert.SerializeObject(args);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, result), callbackId);
},
(obj, args) =>
{
string result = JsonConvert.SerializeObject(args);
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, result), callbackId);
});
}
public void getPushwooshHWID(string options)
{
waitDeviceReady();
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, service.DeviceUniqueID));
}
public void getPushToken(string options)
{
waitDeviceReady();
if (service != null && !string.IsNullOrEmpty(service.PushToken))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, service.PushToken));
}
}
public void setTags(string options)
{
string callbackId = getCallbackId(options);
PluginResult plugResult = new PluginResult(PluginResult.Status.NO_RESULT);
plugResult.KeepCallback = true;
DispatchCommandResult(plugResult);
waitDeviceReady();
string[] opts = JSON.JsonHelper.Deserialize<string[]>(options);
JObject jsonObject = JObject.Parse(opts[0]);
List<KeyValuePair<string, object>> tags = new List<KeyValuePair<string, object>>();
foreach (var element in jsonObject)
{
tags.Add(new KeyValuePair<string,object>(element.Key, element.Value));
}
service.SendTag(tags,
(obj, args) =>
{
string result = JsonConvert.SerializeObject(args);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, result), callbackId);
},
(obj, args) =>
{
string result = JsonConvert.SerializeObject(args);
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, result), callbackId);
}
);
}
public void startLocationTracking(string options)
{
waitDeviceReady();
service.StartGeoLocation();
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "GeoZone service is started"));
}
public void stopLocationTracking(string options)
{
waitDeviceReady();
service.StopGeoLocation();
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "GeoZone service is stopped"));
}
void ExecutePushNotificationCallback(object sender, ToastPush push)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
PhoneApplicationFrame frame;
PhoneApplicationPage page;
CordovaView cView;
if (TryCast(Application.Current.RootVisual, out frame) &&
TryCast(frame.Content, out page) &&
TryCast(page.FindName("CordovaView"), out cView))
{
cView.Browser.Dispatcher.BeginInvoke(() =>
{
try
{
string pushPayload = JsonConvert.SerializeObject(push);
cView.Browser.InvokeScript("eval", "cordova.require(\"pushwoosh-cordova-plugin.PushNotification\").notificationCallback(" + pushPayload + ")");
}
catch (Exception ex)
{
Debug.WriteLine("ERROR: Exception in InvokeScriptCallback :: " + ex.Message);
}
});
}
});
}
static bool TryCast<T>(object obj, out T result) where T : class
{
result = obj as T;
return result != null;
}
[DataContract]
public class PushOptions
{
[DataMember(Name = "appid", IsRequired = true)]
public string AppID { get; set; }
[DataMember(Name = "serviceName", IsRequired = false)]
public string ServiceName { get; set; }
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) 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.
*
* 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;
using System.Collections.Generic;
using CookComputing.XmlRpc;
namespace XenAPI
{
/// <summary>
/// A user of the system
/// First published in XenServer 4.0.
/// </summary>
public partial class User : XenObject<User>
{
public User()
{
}
public User(string uuid,
string short_name,
string fullname,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.short_name = short_name;
this.fullname = fullname;
this.other_config = other_config;
}
/// <summary>
/// Creates a new User from a Proxy_User.
/// </summary>
/// <param name="proxy"></param>
public User(Proxy_User proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(User update)
{
uuid = update.uuid;
short_name = update.short_name;
fullname = update.fullname;
other_config = update.other_config;
}
internal void UpdateFromProxy(Proxy_User proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
short_name = proxy.short_name == null ? null : (string)proxy.short_name;
fullname = proxy.fullname == null ? null : (string)proxy.fullname;
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public Proxy_User ToProxy()
{
Proxy_User result_ = new Proxy_User();
result_.uuid = (uuid != null) ? uuid : "";
result_.short_name = (short_name != null) ? short_name : "";
result_.fullname = (fullname != null) ? fullname : "";
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
/// <summary>
/// Creates a new User from a Hashtable.
/// </summary>
/// <param name="table"></param>
public User(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
short_name = Marshalling.ParseString(table, "short_name");
fullname = Marshalling.ParseString(table, "fullname");
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public bool DeepEquals(User other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._short_name, other._short_name) &&
Helper.AreEqual2(this._fullname, other._fullname) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
public override string SaveChanges(Session session, string opaqueRef, User server)
{
if (opaqueRef == null)
{
Proxy_User p = this.ToProxy();
return session.proxy.user_create(session.uuid, p).parse();
}
else
{
if (!Helper.AreEqual2(_fullname, server._fullname))
{
User.set_fullname(session, opaqueRef, _fullname);
}
if (!Helper.AreEqual2(_other_config, server._other_config))
{
User.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static User get_record(Session session, string _user)
{
return new User((Proxy_User)session.proxy.user_get_record(session.uuid, (_user != null) ? _user : "").parse());
}
/// <summary>
/// Get a reference to the user instance with the specified UUID.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<User> get_by_uuid(Session session, string _uuid)
{
return XenRef<User>.Create(session.proxy.user_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
}
/// <summary>
/// Create a new user instance, and return its handle.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<User> create(Session session, User _record)
{
return XenRef<User>.Create(session.proxy.user_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new user instance, and return its handle.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Task> async_create(Session session, User _record)
{
return XenRef<Task>.Create(session.proxy.async_user_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified user instance.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static void destroy(Session session, string _user)
{
session.proxy.user_destroy(session.uuid, (_user != null) ? _user : "").parse();
}
/// <summary>
/// Destroy the specified user instance.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static XenRef<Task> async_destroy(Session session, string _user)
{
return XenRef<Task>.Create(session.proxy.async_user_destroy(session.uuid, (_user != null) ? _user : "").parse());
}
/// <summary>
/// Get the uuid field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static string get_uuid(Session session, string _user)
{
return (string)session.proxy.user_get_uuid(session.uuid, (_user != null) ? _user : "").parse();
}
/// <summary>
/// Get the short_name field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static string get_short_name(Session session, string _user)
{
return (string)session.proxy.user_get_short_name(session.uuid, (_user != null) ? _user : "").parse();
}
/// <summary>
/// Get the fullname field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static string get_fullname(Session session, string _user)
{
return (string)session.proxy.user_get_fullname(session.uuid, (_user != null) ? _user : "").parse();
}
/// <summary>
/// Get the other_config field of the given user.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static Dictionary<string, string> get_other_config(Session session, string _user)
{
return Maps.convert_from_proxy_string_string(session.proxy.user_get_other_config(session.uuid, (_user != null) ? _user : "").parse());
}
/// <summary>
/// Set the fullname field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_fullname">New value to set</param>
public static void set_fullname(Session session, string _user, string _fullname)
{
session.proxy.user_set_fullname(session.uuid, (_user != null) ? _user : "", (_fullname != null) ? _fullname : "").parse();
}
/// <summary>
/// Set the other_config field of the given user.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _user, Dictionary<string, string> _other_config)
{
session.proxy.user_set_other_config(session.uuid, (_user != null) ? _user : "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given user.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _user, string _key, string _value)
{
session.proxy.user_add_to_other_config(session.uuid, (_user != null) ? _user : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given user. If the key is not in that Map, then do nothing.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _user, string _key)
{
session.proxy.user_remove_from_other_config(session.uuid, (_user != null) ? _user : "", (_key != null) ? _key : "").parse();
}
/// <summary>
/// Get all the user Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<User>, User> get_all_records(Session session)
{
return XenRef<User>.Create<Proxy_User>(session.proxy.user_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// short name (e.g. userid)
/// </summary>
public virtual string short_name
{
get { return _short_name; }
set
{
if (!Helper.AreEqual(value, _short_name))
{
_short_name = value;
Changed = true;
NotifyPropertyChanged("short_name");
}
}
}
private string _short_name;
/// <summary>
/// full name
/// </summary>
public virtual string fullname
{
get { return _fullname; }
set
{
if (!Helper.AreEqual(value, _fullname))
{
_fullname = value;
Changed = true;
NotifyPropertyChanged("fullname");
}
}
}
private string _fullname;
/// <summary>
/// additional configuration
/// First published in XenServer 5.0.
/// </summary>
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config;
}
}
| |
// 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 Microsoft.Xunit.Performance;
using Xunit;
namespace System.Collections.Tests
{
public class Perf_List
{
/// <summary>
/// Creates a list containing a number of elements equal to the specified size
/// </summary>
public static List<object> CreateList(int size)
{
Random rand = new Random(24565653);
List<object> list = new List<object>();
for (int i = 0; i < size; i++)
list.Add(rand.Next());
return list;
}
[Benchmark]
[InlineData(1000)]
[InlineData(10000)]
[InlineData(100000)]
public void Add(int size)
{
List<object> list = CreateList(size);
foreach (var iteration in Benchmark.Iterations)
{
List<object> copyList = new List<object>(list);
using (iteration.StartMeasurement())
{
for (int i = 0; i < 10000; i++)
{
copyList.Add(123555); copyList.Add(123555); copyList.Add(123555); copyList.Add(123555);
copyList.Add(123555); copyList.Add(123555); copyList.Add(123555); copyList.Add(123555);
}
}
}
}
[Benchmark]
[InlineData(1000)]
[InlineData(10000)]
[InlineData(100000)]
public void AddRange(int size)
{
List<object> list = CreateList(size);
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
for (int i = 0; i < 5000; i++)
{
List<object> emptyList = new List<object>();
emptyList.AddRange(list);
}
}
[Benchmark]
[InlineData(1000)]
[InlineData(10000)]
public void Clear(int size)
{
List<object> list = CreateList(size);
foreach (var iteration in Benchmark.Iterations)
{
// Setup lists to clear
List<object>[] listlist = new List<object>[5000];
for (int i = 0; i < 5000; i++)
listlist[i] = new List<object>(list);
// Clear the lists
using (iteration.StartMeasurement())
for (int i = 0; i < 5000; i++)
listlist[i].Clear();
}
}
[Benchmark]
[InlineData(1000)]
[InlineData(10000)]
[InlineData(100000)]
public void Contains(int size)
{
List<object> list = CreateList(size);
object contained = list[list.Count / 2];
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
{
for (int i = 0; i < 500; i++)
{
list.Contains(contained); list.Contains(contained); list.Contains(contained); list.Contains(contained);
list.Contains(contained); list.Contains(contained); list.Contains(contained); list.Contains(contained);
list.Contains(contained); list.Contains(contained); list.Contains(contained); list.Contains(contained);
}
}
}
[Benchmark]
public void ctor()
{
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
{
for (int i = 0; i < 20000; i++)
{
new List<object>(); new List<object>(); new List<object>(); new List<object>(); new List<object>();
new List<object>(); new List<object>(); new List<object>(); new List<object>(); new List<object>();
new List<object>(); new List<object>(); new List<object>(); new List<object>(); new List<object>();
}
}
}
[Benchmark]
[InlineData(1000)]
[InlineData(10000)]
[InlineData(100000)]
public void ctor_IEnumerable(int size)
{
List<object> list = CreateList(size);
var array = list.ToArray();
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
for (int i = 0; i < 10000; i++)
new List<object>(array);
}
[Benchmark]
[InlineData(1000)]
[InlineData(10000)]
[InlineData(100000)]
public void GetCount(int size)
{
List<object> list = CreateList(size);
int temp;
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
{
for (int i = 0; i < 10000; i++)
{
temp = list.Count; temp = list.Count; temp = list.Count; temp = list.Count; temp = list.Count;
temp = list.Count; temp = list.Count; temp = list.Count; temp = list.Count; temp = list.Count;
temp = list.Count; temp = list.Count; temp = list.Count; temp = list.Count; temp = list.Count;
}
}
}
[Benchmark]
[InlineData(1000)]
[InlineData(10000)]
[InlineData(100000)]
public void GetItem(int size)
{
List<object> list = CreateList(size);
object temp;
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
{
for (int i = 0; i < 10000; i++)
{
temp = list[50]; temp = list[50]; temp = list[50]; temp = list[50]; temp = list[50];
temp = list[50]; temp = list[50]; temp = list[50]; temp = list[50]; temp = list[50];
temp = list[50]; temp = list[50]; temp = list[50]; temp = list[50]; temp = list[50];
temp = list[50]; temp = list[50]; temp = list[50]; temp = list[50]; temp = list[50];
}
}
}
[Benchmark]
[InlineData(1000)]
[InlineData(10000)]
[InlineData(100000)]
public void Enumerator(int size)
{
List<object> list = CreateList(size);
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
for (int i = 0; i < 10000; i++)
foreach (var element in list) { }
}
[Benchmark]
[InlineData(1000)]
[InlineData(10000)]
[InlineData(100000)]
public void SetCapacity(int size)
{
List<object> list = CreateList(size);
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
for (int i = 0; i < 100; i++)
{
// Capacity set back and forth between size+1 and size+2
list.Capacity = size + (i % 2) + 1;
}
}
[Benchmark]
[InlineData(1000)]
[InlineData(10000)]
[InlineData(100000)]
public void ToArray(int size)
{
List<object> list = CreateList(size);
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
for (int i = 0; i < 10000; i++)
list.ToArray();
}
[Benchmark]
public static void IndexOf_ValueType()
{
List<int> collection = new List<int>();
int nonexistentItem, firstItem, middleItem, lastItem;
for (int i = 0; i < 8192; ++i)
{
collection.Add(i);
}
nonexistentItem = -1;
firstItem = 0;
middleItem = collection.Count / 2;
lastItem = collection.Count - 1;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
collection.IndexOf(nonexistentItem);
collection.IndexOf(firstItem);
collection.IndexOf(middleItem);
collection.IndexOf(lastItem);
}
}
}
[Benchmark]
public static void IndexOf_ReferenceType()
{
List<string> collection = new List<string>();
string nonexistentItem, firstItem, middleItem, lastItem;
for (int i = 0; i < 8192; ++i)
{
collection.Add(i.ToString());
}
nonexistentItem = "foo";
firstItem = 0.ToString();
middleItem = (collection.Count / 2).ToString();
lastItem = (collection.Count - 1).ToString();
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
collection.IndexOf(nonexistentItem);
collection.IndexOf(firstItem);
collection.IndexOf(middleItem);
collection.IndexOf(lastItem);
}
}
}
private static int getSampleLength(bool largeSets)
{
if (largeSets)
return LARGE_SAMPLE_LENGTH;
else
return smallSampleLength;
}
[Benchmark]
[InlineData(true)]
[InlineData(false)]
public static void GenericList_AddRange_Int_NoCapacityIncrease(bool largeSets)
{
int sampleLength = getSampleLength(largeSets);
int[] sampleSet = new int[sampleLength];
for (int i = 0; i < sampleLength; i++)
{
sampleSet[i] = i;
}
int addLoops = LARGE_SAMPLE_LENGTH / sampleLength;
//Create an ArrayList big enough to hold 17 copies of the sample set
int startingCapacity = 17 * sampleLength * addLoops;
List<int> list = new List<int>(startingCapacity);
//Add the data to the array list.
for (int j = 0; j < addLoops; j++)
{
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
}
foreach (var iteration in Benchmark.Iterations)
{
//Clear the ArrayList without changing its capacity, so that when more data is added to the list its
//capacity will not need to increase.
list.RemoveRange(0, startingCapacity);
using (iteration.StartMeasurement())
{
for (int j = 0; j < addLoops; j++)
{
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
}
}
}
}
[Benchmark]
[InlineData(true)]
[InlineData(false)]
public static void GenericList_AddRange_Int_CapacityIncrease(bool largeSets)
{
int sampleLength = getSampleLength(largeSets);
int[] sampleSet = new int[sampleLength];
for (int i = 0; i < sampleLength; i++)
{
sampleSet[i] = i;
}
int addLoops = LARGE_SAMPLE_LENGTH / sampleLength;
foreach (var iteration in Benchmark.Iterations)
{
List<int> list = new List<int>();
using (iteration.StartMeasurement())
{
for (int j = 0; j < addLoops; j++)
{
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
}
}
}
}
[Benchmark]
[InlineData(true)]
[InlineData(false)]
public static void GenericList_AddRange_String_NoCapacityIncrease(bool largeSets)
{
int sampleLength = getSampleLength(largeSets);
string[] sampleSet = new string[sampleLength];
for (int i = 0; i < sampleLength; i++)
{
sampleSet[i] = i.ToString();
}
int addLoops = LARGE_SAMPLE_LENGTH / sampleLength;
//Create an ArrayList big enough to hold 17 copies of the sample set
int startingCapacity = 17 * sampleLength * addLoops;
List<string> list = new List<string>(startingCapacity);
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int j = 0; j < addLoops; j++)
{
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
}
}
list.RemoveRange(0, startingCapacity);
}
}
[Benchmark]
[InlineData(true)]
[InlineData(false)]
public static void GenericList_AddRange_String_CapacityIncrease(bool largeSets)
{
int sampleLength = getSampleLength(largeSets);
string[] sampleSet = new string[sampleLength];
for (int i = 0; i < sampleLength; i++)
{
sampleSet[i] = i.ToString();
}
int addLoops = LARGE_SAMPLE_LENGTH / sampleLength;
foreach (var iteration in Benchmark.Iterations)
{
List<string> list = new List<string>();
using (iteration.StartMeasurement())
{
for (int j = 0; j < addLoops; j++)
{
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
}
}
}
}
[Benchmark]
public static void Add_ValueType()
{
foreach (var iteration in Benchmark.Iterations)
{
List<int> collection = new List<int>();
using (iteration.StartMeasurement())
{
for (int j = 0; j < 256; ++j)
{
collection.Add(j);
collection.Add(j);
collection.Add(j);
collection.Add(j);
collection.Add(j);
collection.Add(j);
collection.Add(j);
collection.Add(j);
collection.Add(j);
collection.Add(j);
}
}
}
}
[Benchmark]
public static void Add_ReferenceType()
{
string itemToAdd = "foo";
foreach (var iteration in Benchmark.Iterations)
{
List<string> collection = new List<string>();
using (iteration.StartMeasurement())
{
for (int j = 0; j < 256; ++j)
{
collection.Add(itemToAdd);
collection.Add(itemToAdd);
collection.Add(itemToAdd);
collection.Add(itemToAdd);
collection.Add(itemToAdd);
collection.Add(itemToAdd);
collection.Add(itemToAdd);
collection.Add(itemToAdd);
collection.Add(itemToAdd);
collection.Add(itemToAdd);
}
}
}
}
[Benchmark]
public static void GenericList_BinarySearch_Int()
{
int sampleLength = 10000;
int[] sampleSet = new int[sampleLength];
for (int i = 0; i < sampleLength; i++)
{
sampleSet[i] = i;
}
List<int> list = new List<int>(sampleSet);
IComparer<int> comparer = Comparer<int>.Default;
int result = 0;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int j = 0; j < sampleLength; j++)
result = list.BinarySearch(sampleSet[j], comparer);
}
}
}
[Benchmark]
public static void GenericList_BinarySearch_String()
{
int sampleLength = 1000;
string[] sampleSet = new string[sampleLength];
for (int i = 0; i < sampleLength; i++)
{
sampleSet[i] = i.ToString();
}
List<string> list = new List<string>(sampleSet);
IComparer<string> comparer = Comparer<string>.Default;
int result = 0;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int j = 0; j < sampleLength; j++)
result = list.BinarySearch(sampleSet[j], comparer);
}
}
}
[Benchmark]
public static void Contains_ValueType()
{
List<int> collection = new List<int>();
int nonexistentItem, firstItem, middleItem, lastItem;
//[] Initialize
for (int i = 0; i < 8192; ++i)
{
collection.Add(i);
}
nonexistentItem = -1;
firstItem = 0;
middleItem = collection.Count / 2;
lastItem = collection.Count - 1;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
collection.Contains(nonexistentItem);
collection.Contains(firstItem);
collection.Contains(middleItem);
collection.Contains(lastItem);
}
}
}
[Benchmark]
public static void Contains_ReferenceType()
{
List<string> collection = new List<string>();
string nonexistentItem, firstItem, middleItem, lastItem;
//[] Initialize
for (int i = 0; i < 8192; ++i)
{
collection.Add(i.ToString());
}
nonexistentItem = "foo";
firstItem = 0.ToString();
middleItem = (collection.Count / 2).ToString();
lastItem = (collection.Count - 1).ToString();
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
collection.Contains(nonexistentItem);
collection.Contains(firstItem);
collection.Contains(middleItem);
collection.Contains(lastItem);
}
}
}
[Benchmark]
public static void ctor_ICollection_ValueType()
{
List<int> originalCollection = new List<int>();
List<int> newCollection;
//[] Initialize
for (int i = 0; i < 1024; ++i)
{
originalCollection.Add(i);
}
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
newCollection = new List<int>(originalCollection);
}
}
}
[Benchmark]
public static void ctor_ICollection_ReferenceType()
{
List<string> originalCollection = new List<string>();
List<string> newCollection;
//[] Initialize
for (int i = 0; i < 1024; ++i)
{
originalCollection.Add(i.ToString());
}
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
newCollection = new List<string>(originalCollection);
}
}
}
[Benchmark]
public static void Indexer_ValueType()
{
List<int> collection = new List<int>();
int item = 0;
//[] Initialize
for (int i = 0; i < 8192; ++i)
{
collection.Add(i);
}
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int j = 0; j < 8192; ++j)
{
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
}
}
}
}
[Benchmark]
public static void Indexer_ReferenceType()
{
List<string> collection = new List<string>();
string item = null;
//[] Initialize
for (int i = 0; i < 8192; ++i)
{
collection.Add(i.ToString());
}
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int j = 0; j < 8192; ++j)
{
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
}
}
}
}
[Benchmark]
public static void Sort_ValueType()
{
Random random = new Random(32829);
int size = 3000;
int[] items;
List<int> collection;
//[] Initialize
items = new int[size];
for (int i = 0; i < size; ++i)
items[i] = random.Next();
foreach (var iteration in Benchmark.Iterations)
{
collection = new List<int>(size);
for (int j = 0; j < size; ++j)
collection.Add(items[j]);
using (iteration.StartMeasurement())
collection.Sort();
}
}
[Benchmark]
public static void Sort_ReferenceType()
{
Random random = new Random(32829);
int size = 3000;
string[] items;
List<string> collection;
//[] Initialize
items = new string[size];
for (int i = 0; i < size; ++i)
{
items[i] = random.Next().ToString();
}
foreach (var iteration in Benchmark.Iterations)
{
collection = new List<string>(size);
for (int j = 0; j < size; ++j)
{
collection.Add(items[j]);
}
using (iteration.StartMeasurement())
collection.Sort();
}
}
[Benchmark]
public static void GenericList_Reverse_Int()
{
int sampleLength = 100000;
int[] sampleSet = new int[sampleLength];
for (int i = 0; i < sampleLength; i++)
{
sampleSet[i] = i;
}
List<int> list = new List<int>(sampleSet);
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
list.Reverse();
}
[Benchmark]
public static void GenericList_Reverse_String()
{
int sampleLength = 100000;
string[] sampleSet = new string[sampleLength];
for (int i = 0; i < sampleLength; i++)
{
sampleSet[i] = i.ToString();
}
List<string> list = new List<string>(sampleSet);
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
list.Reverse();
}
[Benchmark]
public static void Remove_ValueType()
{
int size = 3000;
int[] items;
List<int> collection;
int start, middle, end;
//[] Initialize
items = new int[size];
for (int i = 0; i < size; ++i)
{
items[i] = i;
}
foreach (var iteration in Benchmark.Iterations)
{
collection = new List<int>();
for (int j = 0; j < size; ++j)
{
collection.Add(items[j]);
}
start = 0;
middle = size / 3;
end = size - 1;
using (iteration.StartMeasurement())
{
for (int j = 0; j < size / 3; j++)
{
collection.Remove(-1);
collection.Remove(items[start]);
collection.Remove(items[middle]);
collection.Remove(items[end]);
++start;
++middle;
--end;
}
}
}
}
[Benchmark]
public static void Remove_ReferenceType()
{
int size = 3000;
string[] items;
List<string> collection;
int start, middle, end;
//[] Initialize
items = new string[size];
for (int i = 0; i < size; ++i)
{
items[i] = i.ToString();
}
foreach (var iteration in Benchmark.Iterations)
{
collection = new List<string>();
for (int j = 0; j < size; ++j)
{
collection.Add(items[j]);
}
start = 0;
middle = size / 3;
end = size - 1;
using (iteration.StartMeasurement())
{
for (int j = 0; j < size / 3; j++)
{
collection.Remove("-1");
collection.Remove(items[start]);
collection.Remove(items[middle]);
collection.Remove(items[end]);
++start;
++middle;
--end;
}
}
}
}
[Benchmark]
public static void Insert_ValueType()
{
List<int> collection;
collection = new List<int>();
for (int j = 0; j < 1024; ++j)
{
collection.Insert(0, j);//Insert at the begining of the list
collection.Insert(j / 2, j);//Insert in the middle of the list
collection.Insert(collection.Count, j);//Insert at the end of the list
}
foreach (var iteration in Benchmark.Iterations)
{
collection = new List<int>();
using (iteration.StartMeasurement())
{
for (int j = 0; j < 1024; ++j)
{
collection.Insert(0, j);//Insert at the begining of the list
collection.Insert(j / 2, j);//Insert in the middle of the list
collection.Insert(collection.Count, j);//Insert at the end of the list
}
}
}
}
[Benchmark]
public static void Insert_ReferenceType()
{
List<string> collection;
string itemToAdd = "foo";
foreach (var iteration in Benchmark.Iterations)
{
collection = new List<string>();
using (iteration.StartMeasurement())
{
for (int j = 0; j < 1024; ++j)
{
collection.Insert(0, itemToAdd);//Insert at the begining of the list
collection.Insert(j / 2, itemToAdd);//Insert in the middle of the list
collection.Insert(collection.Count, itemToAdd);//Insert at the end of the list
}
}
}
}
[Benchmark]
public static void Enumeration_ValueType()
{
List<int> collection = new List<int>();
int item;
//[] Initialize
for (int i = 0; i < 8192; ++i)
{
collection.Add(i);
}
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
foreach (int tempItem in collection)
{
item = tempItem;
}
}
}
}
[Benchmark]
public static void Enumeration_ReferenceType()
{
List<string> collection = new List<string>();
string item;
//[] Initialize
for (int i = 0; i < 8192; ++i)
{
collection.Add(i.ToString());
}
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
foreach (string tempItem in collection)
{
item = tempItem;
}
}
}
}
private const int LARGE_SAMPLE_LENGTH = 10000;
private const int SMALL_LOOPS = 1000;
private const int smallSampleLength = LARGE_SAMPLE_LENGTH / SMALL_LOOPS;
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="Management.TrafficGroupBinding", Namespace="urn:iControl")]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(ManagementTrafficGroupHAOrder))]
public partial class ManagementTrafficGroup : iControlInterface {
public ManagementTrafficGroup() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// add_ha_order
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
public void add_ha_order(
string [] traffic_groups,
ManagementTrafficGroupHAOrder [] [] orders
) {
this.Invoke("add_ha_order", new object [] {
traffic_groups,
orders});
}
public System.IAsyncResult Beginadd_ha_order(string [] traffic_groups,ManagementTrafficGroupHAOrder [] [] orders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_ha_order", new object[] {
traffic_groups,
orders}, callback, asyncState);
}
public void Endadd_ha_order(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
public void create(
string [] traffic_groups
) {
this.Invoke("create", new object [] {
traffic_groups});
}
public System.IAsyncResult Begincreate(string [] traffic_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
traffic_groups}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_traffic_group
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
public void delete_traffic_group(
string [] traffic_groups
) {
this.Invoke("delete_traffic_group", new object [] {
traffic_groups});
}
public System.IAsyncResult Begindelete_traffic_group(string [] traffic_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_traffic_group", new object[] {
traffic_groups}, callback, asyncState);
}
public void Enddelete_traffic_group(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_auto_failback_enabled_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_auto_failback_enabled_state(
string [] traffic_groups
) {
object [] results = this.Invoke("get_auto_failback_enabled_state", new object [] {
traffic_groups});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_auto_failback_enabled_state(string [] traffic_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_auto_failback_enabled_state", new object[] {
traffic_groups}, callback, asyncState);
}
public CommonEnabledState [] Endget_auto_failback_enabled_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_auto_failback_time
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_auto_failback_time(
string [] traffic_groups
) {
object [] results = this.Invoke("get_auto_failback_time", new object [] {
traffic_groups});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_auto_failback_time(string [] traffic_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_auto_failback_time", new object[] {
traffic_groups}, callback, asyncState);
}
public long [] Endget_auto_failback_time(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_default_device
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_default_device(
string [] traffic_groups
) {
object [] results = this.Invoke("get_default_device", new object [] {
traffic_groups});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_default_device(string [] traffic_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_default_device", new object[] {
traffic_groups}, callback, asyncState);
}
public string [] Endget_default_device(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] traffic_groups
) {
object [] results = this.Invoke("get_description", new object [] {
traffic_groups});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] traffic_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
traffic_groups}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_failover_method
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public ManagementTrafficGroupFailoverMethod [] get_failover_method(
string [] traffic_groups
) {
object [] results = this.Invoke("get_failover_method", new object [] {
traffic_groups});
return ((ManagementTrafficGroupFailoverMethod [])(results[0]));
}
public System.IAsyncResult Beginget_failover_method(string [] traffic_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_failover_method", new object[] {
traffic_groups}, callback, asyncState);
}
public ManagementTrafficGroupFailoverMethod [] Endget_failover_method(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((ManagementTrafficGroupFailoverMethod [])(results[0]));
}
//-----------------------------------------------------------------------
// get_ha_group
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_ha_group(
string [] traffic_groups
) {
object [] results = this.Invoke("get_ha_group", new object [] {
traffic_groups});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_ha_group(string [] traffic_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ha_group", new object[] {
traffic_groups}, callback, asyncState);
}
public string [] Endget_ha_group(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_ha_load_factor
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_ha_load_factor(
string [] traffic_groups
) {
object [] results = this.Invoke("get_ha_load_factor", new object [] {
traffic_groups});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_ha_load_factor(string [] traffic_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ha_load_factor", new object[] {
traffic_groups}, callback, asyncState);
}
public long [] Endget_ha_load_factor(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_ha_order
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public ManagementTrafficGroupHAOrder [] [] get_ha_order(
string [] traffic_groups
) {
object [] results = this.Invoke("get_ha_order", new object [] {
traffic_groups});
return ((ManagementTrafficGroupHAOrder [] [])(results[0]));
}
public System.IAsyncResult Beginget_ha_order(string [] traffic_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ha_order", new object[] {
traffic_groups}, callback, asyncState);
}
public ManagementTrafficGroupHAOrder [] [] Endget_ha_order(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((ManagementTrafficGroupHAOrder [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_is_floating
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public bool [] get_is_floating(
string [] traffic_groups
) {
object [] results = this.Invoke("get_is_floating", new object [] {
traffic_groups});
return ((bool [])(results[0]));
}
public System.IAsyncResult Beginget_is_floating(string [] traffic_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_is_floating", new object[] {
traffic_groups}, callback, asyncState);
}
public bool [] Endget_is_floating(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((bool [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_mac_masquerade_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_mac_masquerade_address(
string [] traffic_groups
) {
object [] results = this.Invoke("get_mac_masquerade_address", new object [] {
traffic_groups});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_mac_masquerade_address(string [] traffic_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_mac_masquerade_address", new object[] {
traffic_groups}, callback, asyncState);
}
public string [] Endget_mac_masquerade_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_monitor_ha_group
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_monitor_ha_group(
string [] traffic_groups
) {
object [] results = this.Invoke("get_monitor_ha_group", new object [] {
traffic_groups});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_monitor_ha_group(string [] traffic_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_monitor_ha_group", new object[] {
traffic_groups}, callback, asyncState);
}
public string [] Endget_monitor_ha_group(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_unit_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_unit_id(
string [] traffic_groups
) {
object [] results = this.Invoke("get_unit_id", new object [] {
traffic_groups});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_unit_id(string [] traffic_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_unit_id", new object[] {
traffic_groups}, callback, asyncState);
}
public long [] Endget_unit_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// remove_all_ha_orders
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
public void remove_all_ha_orders(
string [] traffic_groups
) {
this.Invoke("remove_all_ha_orders", new object [] {
traffic_groups});
}
public System.IAsyncResult Beginremove_all_ha_orders(string [] traffic_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_ha_orders", new object[] {
traffic_groups}, callback, asyncState);
}
public void Endremove_all_ha_orders(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_ha_order
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
public void remove_ha_order(
string [] traffic_groups,
ManagementTrafficGroupHAOrder [] [] orders
) {
this.Invoke("remove_ha_order", new object [] {
traffic_groups,
orders});
}
public System.IAsyncResult Beginremove_ha_order(string [] traffic_groups,ManagementTrafficGroupHAOrder [] [] orders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_ha_order", new object[] {
traffic_groups,
orders}, callback, asyncState);
}
public void Endremove_ha_order(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_auto_failback_enabled_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
public void set_auto_failback_enabled_state(
string [] traffic_groups,
CommonEnabledState [] states
) {
this.Invoke("set_auto_failback_enabled_state", new object [] {
traffic_groups,
states});
}
public System.IAsyncResult Beginset_auto_failback_enabled_state(string [] traffic_groups,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_auto_failback_enabled_state", new object[] {
traffic_groups,
states}, callback, asyncState);
}
public void Endset_auto_failback_enabled_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_auto_failback_time
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
public void set_auto_failback_time(
string [] traffic_groups,
long [] times
) {
this.Invoke("set_auto_failback_time", new object [] {
traffic_groups,
times});
}
public System.IAsyncResult Beginset_auto_failback_time(string [] traffic_groups,long [] times, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_auto_failback_time", new object[] {
traffic_groups,
times}, callback, asyncState);
}
public void Endset_auto_failback_time(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_default_device
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
public void set_default_device(
string [] traffic_groups,
string [] devices
) {
this.Invoke("set_default_device", new object [] {
traffic_groups,
devices});
}
public System.IAsyncResult Beginset_default_device(string [] traffic_groups,string [] devices, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_default_device", new object[] {
traffic_groups,
devices}, callback, asyncState);
}
public void Endset_default_device(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
public void set_description(
string [] traffic_groups,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
traffic_groups,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] traffic_groups,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
traffic_groups,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_failover_method
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
public void set_failover_method(
string [] traffic_groups,
ManagementTrafficGroupFailoverMethod [] failover_methods
) {
this.Invoke("set_failover_method", new object [] {
traffic_groups,
failover_methods});
}
public System.IAsyncResult Beginset_failover_method(string [] traffic_groups,ManagementTrafficGroupFailoverMethod [] failover_methods, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_failover_method", new object[] {
traffic_groups,
failover_methods}, callback, asyncState);
}
public void Endset_failover_method(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_ha_group
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
public void set_ha_group(
string [] traffic_groups,
string [] ha_groups
) {
this.Invoke("set_ha_group", new object [] {
traffic_groups,
ha_groups});
}
public System.IAsyncResult Beginset_ha_group(string [] traffic_groups,string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_ha_group", new object[] {
traffic_groups,
ha_groups}, callback, asyncState);
}
public void Endset_ha_group(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_ha_load_factor
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
public void set_ha_load_factor(
string [] traffic_groups,
long [] loads
) {
this.Invoke("set_ha_load_factor", new object [] {
traffic_groups,
loads});
}
public System.IAsyncResult Beginset_ha_load_factor(string [] traffic_groups,long [] loads, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_ha_load_factor", new object[] {
traffic_groups,
loads}, callback, asyncState);
}
public void Endset_ha_load_factor(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_mac_masquerade_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
public void set_mac_masquerade_address(
string [] traffic_groups,
string [] addresses
) {
this.Invoke("set_mac_masquerade_address", new object [] {
traffic_groups,
addresses});
}
public System.IAsyncResult Beginset_mac_masquerade_address(string [] traffic_groups,string [] addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_mac_masquerade_address", new object[] {
traffic_groups,
addresses}, callback, asyncState);
}
public void Endset_mac_masquerade_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_monitor_ha_group
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TrafficGroup",
RequestNamespace="urn:iControl:Management/TrafficGroup", ResponseNamespace="urn:iControl:Management/TrafficGroup")]
public void set_monitor_ha_group(
string [] traffic_groups,
string [] ha_groups
) {
this.Invoke("set_monitor_ha_group", new object [] {
traffic_groups,
ha_groups});
}
public System.IAsyncResult Beginset_monitor_ha_group(string [] traffic_groups,string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_monitor_ha_group", new object[] {
traffic_groups,
ha_groups}, callback, asyncState);
}
public void Endset_monitor_ha_group(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.TrafficGroup.FailoverMethod", Namespace = "urn:iControl")]
public enum ManagementTrafficGroupFailoverMethod
{
TRAFFIC_GROUP_FAILOVER_METHOD_UNKNOWN,
TRAFFIC_GROUP_FAILOVER_METHOD_HA_SCORE,
TRAFFIC_GROUP_FAILOVER_METHOD_HA_ORDER,
}
//=======================================================================
// Structs
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.TrafficGroup.HAOrder", Namespace = "urn:iControl")]
public partial class ManagementTrafficGroupHAOrder
{
private string deviceField;
public string device
{
get { return this.deviceField; }
set { this.deviceField = value; }
}
private long orderField;
public long order
{
get { return this.orderField; }
set { this.orderField = value; }
}
};
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.OpenGL.Textures;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Textures;
using osu.Framework.IO.Stores;
using osu.Framework.Platform;
using osu.Game.Beatmaps;
using osu.Game.Graphics.Sprites;
using osu.Game.IO;
using osu.Game.Rulesets;
using osu.Game.Skinning;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual
{
public abstract class SkinnableTestScene : OsuGridTestScene, IStorageResourceProvider
{
private Skin metricsSkin;
private Skin defaultSkin;
private Skin specialSkin;
private Skin oldSkin;
[Resolved]
private GameHost host { get; set; }
protected SkinnableTestScene()
: base(2, 3)
{
}
[BackgroundDependencyLoader]
private void load(AudioManager audio, SkinManager skinManager)
{
var dllStore = new DllResourceStore(DynamicCompilationOriginal.GetType().Assembly);
metricsSkin = new TestLegacySkin(new SkinInfo { Name = "metrics-skin" }, new NamespacedResourceStore<byte[]>(dllStore, "Resources/metrics_skin"), this, true);
defaultSkin = new DefaultLegacySkin(this);
specialSkin = new TestLegacySkin(new SkinInfo { Name = "special-skin" }, new NamespacedResourceStore<byte[]>(dllStore, "Resources/special_skin"), this, true);
oldSkin = new TestLegacySkin(new SkinInfo { Name = "old-skin" }, new NamespacedResourceStore<byte[]>(dllStore, "Resources/old_skin"), this, true);
}
private readonly List<Drawable> createdDrawables = new List<Drawable>();
protected void SetContents(Func<ISkin, Drawable> creationFunction)
{
createdDrawables.Clear();
var beatmap = CreateBeatmapForSkinProvider();
Cell(0).Child = createProvider(null, creationFunction, beatmap);
Cell(1).Child = createProvider(metricsSkin, creationFunction, beatmap);
Cell(2).Child = createProvider(defaultSkin, creationFunction, beatmap);
Cell(3).Child = createProvider(specialSkin, creationFunction, beatmap);
Cell(4).Child = createProvider(oldSkin, creationFunction, beatmap);
}
protected IEnumerable<Drawable> CreatedDrawables => createdDrawables;
private Drawable createProvider(Skin skin, Func<ISkin, Drawable> creationFunction, IBeatmap beatmap)
{
var created = creationFunction(skin);
createdDrawables.Add(created);
SkinProvidingContainer mainProvider;
Container childContainer;
OutlineBox outlineBox;
SkinProvidingContainer skinProvider;
var children = new Container
{
RelativeSizeAxes = Axes.Both,
BorderColour = Color4.White,
BorderThickness = 5,
Masking = true,
Children = new Drawable[]
{
new Box
{
AlwaysPresent = true,
Alpha = 0,
RelativeSizeAxes = Axes.Both,
},
new OsuSpriteText
{
Text = skin?.SkinInfo?.Name ?? "none",
Scale = new Vector2(1.5f),
Padding = new MarginPadding(5),
},
childContainer = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Children = new Drawable[]
{
outlineBox = new OutlineBox(),
(mainProvider = new SkinProvidingContainer(skin)).WithChild(
skinProvider = new SkinProvidingContainer(Ruleset.Value.CreateInstance().CreateLegacySkinProvider(mainProvider, beatmap))
{
Child = created,
}
)
}
},
}
};
// run this once initially to bring things into a sane state as early as possible.
updateSizing();
// run this once after construction to handle the case the changes are made in a BDL/LoadComplete call.
Schedule(updateSizing);
return children;
void updateSizing()
{
var autoSize = created.RelativeSizeAxes == Axes.None;
foreach (var c in new[] { mainProvider, childContainer, skinProvider })
{
c.RelativeSizeAxes = Axes.None;
c.AutoSizeAxes = Axes.None;
c.RelativeSizeAxes = !autoSize ? Axes.Both : Axes.None;
c.AutoSizeAxes = autoSize ? Axes.Both : Axes.None;
}
outlineBox.Alpha = autoSize ? 1 : 0;
}
}
/// <summary>
/// Creates the ruleset for adding the corresponding skin transforming component.
/// </summary>
[NotNull]
protected abstract Ruleset CreateRulesetForSkinProvider();
protected sealed override Ruleset CreateRuleset() => CreateRulesetForSkinProvider();
protected virtual IBeatmap CreateBeatmapForSkinProvider() => CreateWorkingBeatmap(Ruleset.Value).GetPlayableBeatmap(Ruleset.Value);
#region IResourceStorageProvider
public AudioManager AudioManager => Audio;
public IResourceStore<byte[]> Files => null;
public new IResourceStore<byte[]> Resources => base.Resources;
public IResourceStore<TextureUpload> CreateTextureLoaderStore(IResourceStore<byte[]> underlyingStore) => host.CreateTextureLoaderStore(underlyingStore);
#endregion
private class OutlineBox : CompositeDrawable
{
public OutlineBox()
{
BorderColour = Color4.IndianRed;
BorderThickness = 5;
Masking = true;
RelativeSizeAxes = Axes.Both;
InternalChild = new Box
{
RelativeSizeAxes = Axes.Both,
Alpha = 0,
Colour = Color4.Brown,
AlwaysPresent = true
};
}
}
private class TestLegacySkin : LegacySkin
{
private readonly bool extrapolateAnimations;
public TestLegacySkin(SkinInfo skin, IResourceStore<byte[]> storage, IStorageResourceProvider resources, bool extrapolateAnimations)
: base(skin, storage, resources, "skin.ini")
{
this.extrapolateAnimations = extrapolateAnimations;
}
public override Texture GetTexture(string componentName, WrapMode wrapModeS, WrapMode wrapModeT)
{
var lookup = base.GetTexture(componentName, wrapModeS, wrapModeT);
if (lookup != null)
return lookup;
// extrapolate frames to test longer animations
if (extrapolateAnimations)
{
var match = Regex.Match(componentName, "-([0-9]*)");
if (match.Length > 0 && int.TryParse(match.Groups[1].Value, out var number) && number < 60)
return base.GetTexture(componentName.Replace($"-{number}", $"-{number % 2}"), wrapModeS, wrapModeT);
}
return null;
}
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Android.Telephony.Gsm.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Android.Telephony.Gsm
{
/// <java-name>
/// android/telephony/gsm/SmsMessage
/// </java-name>
[Dot42.DexImport("android/telephony/gsm/SmsMessage", AccessFlags = 33)]
public partial class SmsMessage
/* scope: __dot42__ */
{
/// <java-name>
/// ENCODING_UNKNOWN
/// </java-name>
[Dot42.DexImport("ENCODING_UNKNOWN", "I", AccessFlags = 25)]
public const int ENCODING_UNKNOWN = 0;
/// <java-name>
/// ENCODING_7BIT
/// </java-name>
[Dot42.DexImport("ENCODING_7BIT", "I", AccessFlags = 25)]
public const int ENCODING_7BIT = 1;
/// <java-name>
/// ENCODING_8BIT
/// </java-name>
[Dot42.DexImport("ENCODING_8BIT", "I", AccessFlags = 25)]
public const int ENCODING_8BIT = 2;
/// <java-name>
/// ENCODING_16BIT
/// </java-name>
[Dot42.DexImport("ENCODING_16BIT", "I", AccessFlags = 25)]
public const int ENCODING_16BIT = 3;
/// <java-name>
/// MAX_USER_DATA_BYTES
/// </java-name>
[Dot42.DexImport("MAX_USER_DATA_BYTES", "I", AccessFlags = 25)]
public const int MAX_USER_DATA_BYTES = 140;
/// <java-name>
/// MAX_USER_DATA_SEPTETS
/// </java-name>
[Dot42.DexImport("MAX_USER_DATA_SEPTETS", "I", AccessFlags = 25)]
public const int MAX_USER_DATA_SEPTETS = 160;
/// <java-name>
/// MAX_USER_DATA_SEPTETS_WITH_HEADER
/// </java-name>
[Dot42.DexImport("MAX_USER_DATA_SEPTETS_WITH_HEADER", "I", AccessFlags = 25)]
public const int MAX_USER_DATA_SEPTETS_WITH_HEADER = 153;
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public SmsMessage() /* MethodBuilder.Create */
{
}
/// <java-name>
/// createFromPdu
/// </java-name>
[Dot42.DexImport("createFromPdu", "([B)Landroid/telephony/gsm/SmsMessage;", AccessFlags = 9)]
public static global::Android.Telephony.Gsm.SmsMessage CreateFromPdu(sbyte[] sByte) /* MethodBuilder.Create */
{
return default(global::Android.Telephony.Gsm.SmsMessage);
}
/// <java-name>
/// createFromPdu
/// </java-name>
[Dot42.DexImport("createFromPdu", "([B)Landroid/telephony/gsm/SmsMessage;", AccessFlags = 9, IgnoreFromJava = true)]
public static global::Android.Telephony.Gsm.SmsMessage CreateFromPdu(byte[] @byte) /* MethodBuilder.Create */
{
return default(global::Android.Telephony.Gsm.SmsMessage);
}
/// <java-name>
/// getTPLayerLengthForPDU
/// </java-name>
[Dot42.DexImport("getTPLayerLengthForPDU", "(Ljava/lang/String;)I", AccessFlags = 9)]
public static int GetTPLayerLengthForPDU(string @string) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// calculateLength
/// </java-name>
[Dot42.DexImport("calculateLength", "(Ljava/lang/CharSequence;Z)[I", AccessFlags = 9)]
public static int[] CalculateLength(global::Java.Lang.ICharSequence charSequence, bool boolean) /* MethodBuilder.Create */
{
return default(int[]);
}
/// <java-name>
/// calculateLength
/// </java-name>
[Dot42.DexImport("calculateLength", "(Ljava/lang/String;Z)[I", AccessFlags = 9)]
public static int[] CalculateLength(string @string, bool boolean) /* MethodBuilder.Create */
{
return default(int[]);
}
/// <java-name>
/// getSubmitPdu
/// </java-name>
[Dot42.DexImport("getSubmitPdu", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)Landroid/telephony/gsm/S" +
"msMessage$SubmitPdu;", AccessFlags = 9)]
public static global::Android.Telephony.Gsm.SmsMessage.SubmitPdu GetSubmitPdu(string @string, string string1, string string2, bool boolean) /* MethodBuilder.Create */
{
return default(global::Android.Telephony.Gsm.SmsMessage.SubmitPdu);
}
/// <java-name>
/// getSubmitPdu
/// </java-name>
[Dot42.DexImport("getSubmitPdu", "(Ljava/lang/String;Ljava/lang/String;S[BZ)Landroid/telephony/gsm/SmsMessage$Submi" +
"tPdu;", AccessFlags = 9)]
public static global::Android.Telephony.Gsm.SmsMessage.SubmitPdu GetSubmitPdu(string @string, string string1, short int16, sbyte[] sByte, bool boolean) /* MethodBuilder.Create */
{
return default(global::Android.Telephony.Gsm.SmsMessage.SubmitPdu);
}
/// <java-name>
/// getSubmitPdu
/// </java-name>
[Dot42.DexImport("getSubmitPdu", "(Ljava/lang/String;Ljava/lang/String;S[BZ)Landroid/telephony/gsm/SmsMessage$Submi" +
"tPdu;", AccessFlags = 9, IgnoreFromJava = true)]
public static global::Android.Telephony.Gsm.SmsMessage.SubmitPdu GetSubmitPdu(string @string, string string1, short int16, byte[] @byte, bool boolean) /* MethodBuilder.Create */
{
return default(global::Android.Telephony.Gsm.SmsMessage.SubmitPdu);
}
/// <java-name>
/// getServiceCenterAddress
/// </java-name>
[Dot42.DexImport("getServiceCenterAddress", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetServiceCenterAddress() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getOriginatingAddress
/// </java-name>
[Dot42.DexImport("getOriginatingAddress", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetOriginatingAddress() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getDisplayOriginatingAddress
/// </java-name>
[Dot42.DexImport("getDisplayOriginatingAddress", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetDisplayOriginatingAddress() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getMessageBody
/// </java-name>
[Dot42.DexImport("getMessageBody", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetMessageBody() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getMessageClass
/// </java-name>
[Dot42.DexImport("getMessageClass", "()Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 1)]
public virtual global::Android.Telephony.Gsm.SmsMessage.MessageClass GetMessageClass() /* MethodBuilder.Create */
{
return default(global::Android.Telephony.Gsm.SmsMessage.MessageClass);
}
/// <java-name>
/// getDisplayMessageBody
/// </java-name>
[Dot42.DexImport("getDisplayMessageBody", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetDisplayMessageBody() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getPseudoSubject
/// </java-name>
[Dot42.DexImport("getPseudoSubject", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetPseudoSubject() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getTimestampMillis
/// </java-name>
[Dot42.DexImport("getTimestampMillis", "()J", AccessFlags = 1)]
public virtual long GetTimestampMillis() /* MethodBuilder.Create */
{
return default(long);
}
/// <java-name>
/// isEmail
/// </java-name>
[Dot42.DexImport("isEmail", "()Z", AccessFlags = 1)]
public virtual bool IsEmail() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// getEmailBody
/// </java-name>
[Dot42.DexImport("getEmailBody", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetEmailBody() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getEmailFrom
/// </java-name>
[Dot42.DexImport("getEmailFrom", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetEmailFrom() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getProtocolIdentifier
/// </java-name>
[Dot42.DexImport("getProtocolIdentifier", "()I", AccessFlags = 1)]
public virtual int GetProtocolIdentifier() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// isReplace
/// </java-name>
[Dot42.DexImport("isReplace", "()Z", AccessFlags = 1)]
public virtual bool IsReplace() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// isCphsMwiMessage
/// </java-name>
[Dot42.DexImport("isCphsMwiMessage", "()Z", AccessFlags = 1)]
public virtual bool IsCphsMwiMessage() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// isMWIClearMessage
/// </java-name>
[Dot42.DexImport("isMWIClearMessage", "()Z", AccessFlags = 1)]
public virtual bool IsMWIClearMessage() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// isMWISetMessage
/// </java-name>
[Dot42.DexImport("isMWISetMessage", "()Z", AccessFlags = 1)]
public virtual bool IsMWISetMessage() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// isMwiDontStore
/// </java-name>
[Dot42.DexImport("isMwiDontStore", "()Z", AccessFlags = 1)]
public virtual bool IsMwiDontStore() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// getUserData
/// </java-name>
[Dot42.DexImport("getUserData", "()[B", AccessFlags = 1)]
public virtual sbyte[] JavaGetUserData() /* MethodBuilder.Create */
{
return default(sbyte[]);
}
/// <java-name>
/// getUserData
/// </java-name>
[Dot42.DexImport("getUserData", "()[B", AccessFlags = 1, IgnoreFromJava = true)]
public virtual byte[] GetUserData() /* MethodBuilder.Create */
{
return default(byte[]);
}
/// <java-name>
/// getPdu
/// </java-name>
[Dot42.DexImport("getPdu", "()[B", AccessFlags = 1)]
public virtual sbyte[] JavaGetPdu() /* MethodBuilder.Create */
{
return default(sbyte[]);
}
/// <java-name>
/// getPdu
/// </java-name>
[Dot42.DexImport("getPdu", "()[B", AccessFlags = 1, IgnoreFromJava = true)]
public virtual byte[] GetPdu() /* MethodBuilder.Create */
{
return default(byte[]);
}
/// <java-name>
/// getStatusOnSim
/// </java-name>
[Dot42.DexImport("getStatusOnSim", "()I", AccessFlags = 1)]
public virtual int GetStatusOnSim() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// getIndexOnSim
/// </java-name>
[Dot42.DexImport("getIndexOnSim", "()I", AccessFlags = 1)]
public virtual int GetIndexOnSim() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// getStatus
/// </java-name>
[Dot42.DexImport("getStatus", "()I", AccessFlags = 1)]
public virtual int GetStatus() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// isStatusReportMessage
/// </java-name>
[Dot42.DexImport("isStatusReportMessage", "()Z", AccessFlags = 1)]
public virtual bool IsStatusReportMessage() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// isReplyPathPresent
/// </java-name>
[Dot42.DexImport("isReplyPathPresent", "()Z", AccessFlags = 1)]
public virtual bool IsReplyPathPresent() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// getServiceCenterAddress
/// </java-name>
public string ServiceCenterAddress
{
[Dot42.DexImport("getServiceCenterAddress", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetServiceCenterAddress(); }
}
/// <java-name>
/// getOriginatingAddress
/// </java-name>
public string OriginatingAddress
{
[Dot42.DexImport("getOriginatingAddress", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetOriginatingAddress(); }
}
/// <java-name>
/// getDisplayOriginatingAddress
/// </java-name>
public string DisplayOriginatingAddress
{
[Dot42.DexImport("getDisplayOriginatingAddress", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetDisplayOriginatingAddress(); }
}
/// <java-name>
/// getMessageBody
/// </java-name>
public string MessageBody
{
[Dot42.DexImport("getMessageBody", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetMessageBody(); }
}
/// <java-name>
/// getDisplayMessageBody
/// </java-name>
public string DisplayMessageBody
{
[Dot42.DexImport("getDisplayMessageBody", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetDisplayMessageBody(); }
}
/// <java-name>
/// getPseudoSubject
/// </java-name>
public string PseudoSubject
{
[Dot42.DexImport("getPseudoSubject", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetPseudoSubject(); }
}
/// <java-name>
/// getTimestampMillis
/// </java-name>
public long TimestampMillis
{
[Dot42.DexImport("getTimestampMillis", "()J", AccessFlags = 1)]
get{ return GetTimestampMillis(); }
}
/// <java-name>
/// getEmailBody
/// </java-name>
public string EmailBody
{
[Dot42.DexImport("getEmailBody", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetEmailBody(); }
}
/// <java-name>
/// getEmailFrom
/// </java-name>
public string EmailFrom
{
[Dot42.DexImport("getEmailFrom", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetEmailFrom(); }
}
/// <java-name>
/// getProtocolIdentifier
/// </java-name>
public int ProtocolIdentifier
{
[Dot42.DexImport("getProtocolIdentifier", "()I", AccessFlags = 1)]
get{ return GetProtocolIdentifier(); }
}
/// <java-name>
/// getUserData
/// </java-name>
public byte[] UserData
{
[Dot42.DexImport("getUserData", "()[B", AccessFlags = 1, IgnoreFromJava = true)]
get{ return GetUserData(); }
}
/// <java-name>
/// getPdu
/// </java-name>
public byte[] Pdu
{
[Dot42.DexImport("getPdu", "()[B", AccessFlags = 1, IgnoreFromJava = true)]
get{ return GetPdu(); }
}
/// <java-name>
/// getStatusOnSim
/// </java-name>
public int StatusOnSim
{
[Dot42.DexImport("getStatusOnSim", "()I", AccessFlags = 1)]
get{ return GetStatusOnSim(); }
}
/// <java-name>
/// getIndexOnSim
/// </java-name>
public int IndexOnSim
{
[Dot42.DexImport("getIndexOnSim", "()I", AccessFlags = 1)]
get{ return GetIndexOnSim(); }
}
/// <java-name>
/// getStatus
/// </java-name>
public int Status
{
[Dot42.DexImport("getStatus", "()I", AccessFlags = 1)]
get{ return GetStatus(); }
}
/// <java-name>
/// android/telephony/gsm/SmsMessage$SubmitPdu
/// </java-name>
[Dot42.DexImport("android/telephony/gsm/SmsMessage$SubmitPdu", AccessFlags = 9)]
public partial class SubmitPdu
/* scope: __dot42__ */
{
/// <java-name>
/// encodedScAddress
/// </java-name>
[Dot42.DexImport("encodedScAddress", "[B", AccessFlags = 1)]
public sbyte[] EncodedScAddress;
/// <java-name>
/// encodedMessage
/// </java-name>
[Dot42.DexImport("encodedMessage", "[B", AccessFlags = 1)]
public sbyte[] EncodedMessage;
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public SubmitPdu() /* MethodBuilder.Create */
{
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
}
/// <java-name>
/// android/telephony/gsm/SmsMessage$MessageClass
/// </java-name>
[Dot42.DexImport("android/telephony/gsm/SmsMessage$MessageClass", AccessFlags = 16409, Signature = "Ljava/lang/Enum<Landroid/telephony/gsm/SmsMessage$MessageClass;>;")]
public sealed class MessageClass
/* scope: __dot42__ */
{
/// <java-name>
/// CLASS_0
/// </java-name>
[Dot42.DexImport("CLASS_0", "Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 16409)]
public static readonly MessageClass CLASS_0;
/// <java-name>
/// CLASS_1
/// </java-name>
[Dot42.DexImport("CLASS_1", "Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 16409)]
public static readonly MessageClass CLASS_1;
/// <java-name>
/// CLASS_2
/// </java-name>
[Dot42.DexImport("CLASS_2", "Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 16409)]
public static readonly MessageClass CLASS_2;
/// <java-name>
/// CLASS_3
/// </java-name>
[Dot42.DexImport("CLASS_3", "Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 16409)]
public static readonly MessageClass CLASS_3;
/// <java-name>
/// UNKNOWN
/// </java-name>
[Dot42.DexImport("UNKNOWN", "Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 16409)]
public static readonly MessageClass UNKNOWN;
private MessageClass() /* TypeBuilder.AddPrivateDefaultCtor */
{
}
}
}
/// <java-name>
/// android/telephony/gsm/SmsManager
/// </java-name>
[Dot42.DexImport("android/telephony/gsm/SmsManager", AccessFlags = 49)]
public sealed partial class SmsManager
/* scope: __dot42__ */
{
/// <java-name>
/// STATUS_ON_SIM_FREE
/// </java-name>
[Dot42.DexImport("STATUS_ON_SIM_FREE", "I", AccessFlags = 25)]
public const int STATUS_ON_SIM_FREE = 0;
/// <java-name>
/// STATUS_ON_SIM_READ
/// </java-name>
[Dot42.DexImport("STATUS_ON_SIM_READ", "I", AccessFlags = 25)]
public const int STATUS_ON_SIM_READ = 1;
/// <java-name>
/// STATUS_ON_SIM_UNREAD
/// </java-name>
[Dot42.DexImport("STATUS_ON_SIM_UNREAD", "I", AccessFlags = 25)]
public const int STATUS_ON_SIM_UNREAD = 3;
/// <java-name>
/// STATUS_ON_SIM_SENT
/// </java-name>
[Dot42.DexImport("STATUS_ON_SIM_SENT", "I", AccessFlags = 25)]
public const int STATUS_ON_SIM_SENT = 5;
/// <java-name>
/// STATUS_ON_SIM_UNSENT
/// </java-name>
[Dot42.DexImport("STATUS_ON_SIM_UNSENT", "I", AccessFlags = 25)]
public const int STATUS_ON_SIM_UNSENT = 7;
/// <java-name>
/// RESULT_ERROR_GENERIC_FAILURE
/// </java-name>
[Dot42.DexImport("RESULT_ERROR_GENERIC_FAILURE", "I", AccessFlags = 25)]
public const int RESULT_ERROR_GENERIC_FAILURE = 1;
/// <java-name>
/// RESULT_ERROR_RADIO_OFF
/// </java-name>
[Dot42.DexImport("RESULT_ERROR_RADIO_OFF", "I", AccessFlags = 25)]
public const int RESULT_ERROR_RADIO_OFF = 2;
/// <java-name>
/// RESULT_ERROR_NULL_PDU
/// </java-name>
[Dot42.DexImport("RESULT_ERROR_NULL_PDU", "I", AccessFlags = 25)]
public const int RESULT_ERROR_NULL_PDU = 3;
/// <java-name>
/// RESULT_ERROR_NO_SERVICE
/// </java-name>
[Dot42.DexImport("RESULT_ERROR_NO_SERVICE", "I", AccessFlags = 25)]
public const int RESULT_ERROR_NO_SERVICE = 4;
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal SmsManager() /* MethodBuilder.Create */
{
}
/// <java-name>
/// getDefault
/// </java-name>
[Dot42.DexImport("getDefault", "()Landroid/telephony/gsm/SmsManager;", AccessFlags = 25)]
public static global::Android.Telephony.Gsm.SmsManager GetDefault() /* MethodBuilder.Create */
{
return default(global::Android.Telephony.Gsm.SmsManager);
}
/// <java-name>
/// sendTextMessage
/// </java-name>
[Dot42.DexImport("sendTextMessage", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Landroid/app/PendingIntent" +
";Landroid/app/PendingIntent;)V", AccessFlags = 17)]
public void SendTextMessage(string @string, string string1, string string2, global::Android.App.PendingIntent pendingIntent, global::Android.App.PendingIntent pendingIntent1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// divideMessage
/// </java-name>
[Dot42.DexImport("divideMessage", "(Ljava/lang/String;)Ljava/util/ArrayList;", AccessFlags = 17, Signature = "(Ljava/lang/String;)Ljava/util/ArrayList<Ljava/lang/String;>;")]
public global::Java.Util.ArrayList<string> DivideMessage(string @string) /* MethodBuilder.Create */
{
return default(global::Java.Util.ArrayList<string>);
}
/// <java-name>
/// sendMultipartTextMessage
/// </java-name>
[Dot42.DexImport("sendMultipartTextMessage", "(Ljava/lang/String;Ljava/lang/String;Ljava/util/ArrayList;Ljava/util/ArrayList;Lj" +
"ava/util/ArrayList;)V", AccessFlags = 17, Signature = "(Ljava/lang/String;Ljava/lang/String;Ljava/util/ArrayList<Ljava/lang/String;>;Lja" +
"va/util/ArrayList<Landroid/app/PendingIntent;>;Ljava/util/ArrayList<Landroid/app" +
"/PendingIntent;>;)V")]
public void SendMultipartTextMessage(string @string, string string1, global::Java.Util.ArrayList<string> arrayList, global::Java.Util.ArrayList<global::Android.App.PendingIntent> arrayList1, global::Java.Util.ArrayList<global::Android.App.PendingIntent> arrayList2) /* MethodBuilder.Create */
{
}
/// <java-name>
/// sendDataMessage
/// </java-name>
[Dot42.DexImport("sendDataMessage", "(Ljava/lang/String;Ljava/lang/String;S[BLandroid/app/PendingIntent;Landroid/app/P" +
"endingIntent;)V", AccessFlags = 17)]
public void SendDataMessage(string @string, string string1, short int16, sbyte[] sByte, global::Android.App.PendingIntent pendingIntent, global::Android.App.PendingIntent pendingIntent1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// sendDataMessage
/// </java-name>
[Dot42.DexImport("sendDataMessage", "(Ljava/lang/String;Ljava/lang/String;S[BLandroid/app/PendingIntent;Landroid/app/P" +
"endingIntent;)V", AccessFlags = 17, IgnoreFromJava = true)]
public void SendDataMessage(string @string, string string1, short int16, byte[] @byte, global::Android.App.PendingIntent pendingIntent, global::Android.App.PendingIntent pendingIntent1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getDefault
/// </java-name>
public static global::Android.Telephony.Gsm.SmsManager Default
{
[Dot42.DexImport("getDefault", "()Landroid/telephony/gsm/SmsManager;", AccessFlags = 25)]
get{ return GetDefault(); }
}
}
/// <summary>
/// <para>Represents the cell location on a GSM phone. </para>
/// </summary>
/// <java-name>
/// android/telephony/gsm/GsmCellLocation
/// </java-name>
[Dot42.DexImport("android/telephony/gsm/GsmCellLocation", AccessFlags = 33)]
public partial class GsmCellLocation : global::Android.Telephony.CellLocation
/* scope: __dot42__ */
{
/// <summary>
/// <para>Empty constructor. Initializes the LAC and CID to -1. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public GsmCellLocation() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Initialize the object from a bundle. </para>
/// </summary>
[Dot42.DexImport("<init>", "(Landroid/os/Bundle;)V", AccessFlags = 1)]
public GsmCellLocation(global::Android.Os.Bundle bundle) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>gsm location area code, -1 if unknown, 0xffff max legal value </para>
/// </returns>
/// <java-name>
/// getLac
/// </java-name>
[Dot42.DexImport("getLac", "()I", AccessFlags = 1)]
public virtual int GetLac() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>gsm cell id, -1 if unknown, 0xffff max legal value </para>
/// </returns>
/// <java-name>
/// getCid
/// </java-name>
[Dot42.DexImport("getCid", "()I", AccessFlags = 1)]
public virtual int GetCid() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>On a UMTS network, returns the primary scrambling code of the serving cell.</para><para></para>
/// </summary>
/// <returns>
/// <para>primary scrambling code for UMTS, -1 if unknown or GSM </para>
/// </returns>
/// <java-name>
/// getPsc
/// </java-name>
[Dot42.DexImport("getPsc", "()I", AccessFlags = 1)]
public virtual int GetPsc() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Invalidate this object. The location area code and the cell id are set to -1. </para>
/// </summary>
/// <java-name>
/// setStateInvalid
/// </java-name>
[Dot42.DexImport("setStateInvalid", "()V", AccessFlags = 1)]
public virtual void SetStateInvalid() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Set the location area code and the cell id. </para>
/// </summary>
/// <java-name>
/// setLacAndCid
/// </java-name>
[Dot42.DexImport("setLacAndCid", "(II)V", AccessFlags = 1)]
public virtual void SetLacAndCid(int lac, int cid) /* MethodBuilder.Create */
{
}
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "()I", AccessFlags = 1)]
public override int GetHashCode() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)]
public override bool Equals(object o) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Set intent notifier Bundle based on service state</para><para></para>
/// </summary>
/// <java-name>
/// fillInNotifierBundle
/// </java-name>
[Dot42.DexImport("fillInNotifierBundle", "(Landroid/os/Bundle;)V", AccessFlags = 1)]
public virtual void FillInNotifierBundle(global::Android.Os.Bundle m) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>gsm location area code, -1 if unknown, 0xffff max legal value </para>
/// </returns>
/// <java-name>
/// getLac
/// </java-name>
public int Lac
{
[Dot42.DexImport("getLac", "()I", AccessFlags = 1)]
get{ return GetLac(); }
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>gsm cell id, -1 if unknown, 0xffff max legal value </para>
/// </returns>
/// <java-name>
/// getCid
/// </java-name>
public int Cid
{
[Dot42.DexImport("getCid", "()I", AccessFlags = 1)]
get{ return GetCid(); }
}
/// <summary>
/// <para>On a UMTS network, returns the primary scrambling code of the serving cell.</para><para></para>
/// </summary>
/// <returns>
/// <para>primary scrambling code for UMTS, -1 if unknown or GSM </para>
/// </returns>
/// <java-name>
/// getPsc
/// </java-name>
public int Psc
{
[Dot42.DexImport("getPsc", "()I", AccessFlags = 1)]
get{ return GetPsc(); }
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V8.Resources
{
/// <summary>Resource name for the <c>CustomAudience</c> resource.</summary>
public sealed partial class CustomAudienceName : gax::IResourceName, sys::IEquatable<CustomAudienceName>
{
/// <summary>The possible contents of <see cref="CustomAudienceName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/customAudiences/{custom_audience_id}</c>.
/// </summary>
CustomerCustomAudience = 1,
}
private static gax::PathTemplate s_customerCustomAudience = new gax::PathTemplate("customers/{customer_id}/customAudiences/{custom_audience_id}");
/// <summary>Creates a <see cref="CustomAudienceName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="CustomAudienceName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static CustomAudienceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new CustomAudienceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="CustomAudienceName"/> with the pattern
/// <c>customers/{customer_id}/customAudiences/{custom_audience_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="customAudienceId">The <c>CustomAudience</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="CustomAudienceName"/> constructed from the provided ids.</returns>
public static CustomAudienceName FromCustomerCustomAudience(string customerId, string customAudienceId) =>
new CustomAudienceName(ResourceNameType.CustomerCustomAudience, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), customAudienceId: gax::GaxPreconditions.CheckNotNullOrEmpty(customAudienceId, nameof(customAudienceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomAudienceName"/> with pattern
/// <c>customers/{customer_id}/customAudiences/{custom_audience_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="customAudienceId">The <c>CustomAudience</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CustomAudienceName"/> with pattern
/// <c>customers/{customer_id}/customAudiences/{custom_audience_id}</c>.
/// </returns>
public static string Format(string customerId, string customAudienceId) =>
FormatCustomerCustomAudience(customerId, customAudienceId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomAudienceName"/> with pattern
/// <c>customers/{customer_id}/customAudiences/{custom_audience_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="customAudienceId">The <c>CustomAudience</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CustomAudienceName"/> with pattern
/// <c>customers/{customer_id}/customAudiences/{custom_audience_id}</c>.
/// </returns>
public static string FormatCustomerCustomAudience(string customerId, string customAudienceId) =>
s_customerCustomAudience.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(customAudienceId, nameof(customAudienceId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="CustomAudienceName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/customAudiences/{custom_audience_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="customAudienceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="CustomAudienceName"/> if successful.</returns>
public static CustomAudienceName Parse(string customAudienceName) => Parse(customAudienceName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="CustomAudienceName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/customAudiences/{custom_audience_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customAudienceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="CustomAudienceName"/> if successful.</returns>
public static CustomAudienceName Parse(string customAudienceName, bool allowUnparsed) =>
TryParse(customAudienceName, allowUnparsed, out CustomAudienceName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CustomAudienceName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/customAudiences/{custom_audience_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="customAudienceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CustomAudienceName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string customAudienceName, out CustomAudienceName result) =>
TryParse(customAudienceName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CustomAudienceName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/customAudiences/{custom_audience_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customAudienceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CustomAudienceName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string customAudienceName, bool allowUnparsed, out CustomAudienceName result)
{
gax::GaxPreconditions.CheckNotNull(customAudienceName, nameof(customAudienceName));
gax::TemplatedResourceName resourceName;
if (s_customerCustomAudience.TryParseName(customAudienceName, out resourceName))
{
result = FromCustomerCustomAudience(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(customAudienceName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private CustomAudienceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customAudienceId = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomAudienceId = customAudienceId;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="CustomAudienceName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/customAudiences/{custom_audience_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="customAudienceId">The <c>CustomAudience</c> ID. Must not be <c>null</c> or empty.</param>
public CustomAudienceName(string customerId, string customAudienceId) : this(ResourceNameType.CustomerCustomAudience, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), customAudienceId: gax::GaxPreconditions.CheckNotNullOrEmpty(customAudienceId, nameof(customAudienceId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>CustomAudience</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string CustomAudienceId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerCustomAudience: return s_customerCustomAudience.Expand(CustomerId, CustomAudienceId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as CustomAudienceName);
/// <inheritdoc/>
public bool Equals(CustomAudienceName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(CustomAudienceName a, CustomAudienceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(CustomAudienceName a, CustomAudienceName b) => !(a == b);
}
public partial class CustomAudience
{
/// <summary>
/// <see cref="gagvr::CustomAudienceName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal CustomAudienceName ResourceNameAsCustomAudienceName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::CustomAudienceName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::CustomAudienceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
internal CustomAudienceName CustomAudienceName
{
get => string.IsNullOrEmpty(Name) ? null : gagvr::CustomAudienceName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Projection
// Description: The basic module for MapWindow version 6.0
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 8/14/2009 4:15:48 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// Name | Date | Comment
// --------------------|------------|------------------------------------------------------------
// Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL
// ********************************************************************************************************
#pragma warning disable 1591
namespace DotSpatial.Projections.GeographicCategories
{
/// <summary>
/// Oceans
/// </summary>
public class Oceans : CoordinateSystemCategory
{
#region Fields
public readonly ProjectionInfo AlaskanIslands;
public readonly ProjectionInfo AmericanSamoa1962;
public readonly ProjectionInfo Anguilla1957;
public readonly ProjectionInfo Anna1Astro1965;
public readonly ProjectionInfo Antigua1943;
public readonly ProjectionInfo AscensionIsland1958;
public readonly ProjectionInfo AstroBeaconE1945;
public readonly ProjectionInfo AstroDOS714;
public readonly ProjectionInfo AstronomicalStation1952;
public readonly ProjectionInfo AzoresCentral1948;
public readonly ProjectionInfo AzoresCentral1995;
public readonly ProjectionInfo AzoresOccidental1939;
public readonly ProjectionInfo AzoresOriental1940;
public readonly ProjectionInfo AzoresOriental1995;
public readonly ProjectionInfo BabSouth;
public readonly ProjectionInfo Barbados;
public readonly ProjectionInfo Barbados1938;
public readonly ProjectionInfo BellevueIGN;
public readonly ProjectionInfo Bermuda1957;
public readonly ProjectionInfo Bermuda2000;
public readonly ProjectionInfo CSG1967;
public readonly ProjectionInfo CantonAstro1966;
public readonly ProjectionInfo ChathamIslandAstro1971;
public readonly ProjectionInfo Combani1950;
public readonly ProjectionInfo DOS1968;
public readonly ProjectionInfo Dominica1945;
public readonly ProjectionInfo EasterIsland1967;
public readonly ProjectionInfo FortDesaix;
public readonly ProjectionInfo FortMarigot;
public readonly ProjectionInfo FortThomas1955;
public readonly ProjectionInfo GUX1Astro;
public readonly ProjectionInfo Gan1970;
public readonly ProjectionInfo GraciosaBaseSW1948;
public readonly ProjectionInfo GrandComoros;
public readonly ProjectionInfo Grenada1953;
public readonly ProjectionInfo Guam1963;
public readonly ProjectionInfo Hjorsey1955;
public readonly ProjectionInfo IGN53Mare;
public readonly ProjectionInfo IGN56Lifou;
public readonly ProjectionInfo IGN72GrandeTerre;
public readonly ProjectionInfo IGN72NukuHiva;
public readonly ProjectionInfo ISTS061Astro1968;
public readonly ProjectionInfo ISTS073Astro1969;
public readonly ProjectionInfo Jamaica1875;
public readonly ProjectionInfo Jamaica1969;
public readonly ProjectionInfo JohnstonIsland1961;
public readonly ProjectionInfo K01949;
public readonly ProjectionInfo KerguelenIsland1949;
public readonly ProjectionInfo KusaieAstro1951;
public readonly ProjectionInfo LC5Astro1961;
public readonly ProjectionInfo MOP78;
public readonly ProjectionInfo Madeira1936;
public readonly ProjectionInfo Mahe1971;
public readonly ProjectionInfo Majuro;
public readonly ProjectionInfo MidwayAstro1961;
public readonly ProjectionInfo Montserrat1958;
public readonly ProjectionInfo NEA74Noumea;
public readonly ProjectionInfo ObservMeteorologico1939;
public readonly ProjectionInfo OldHawaiian;
public readonly ProjectionInfo PicodeLasNieves;
public readonly ProjectionInfo PitcairnAstro1967;
public readonly ProjectionInfo PitondesNeiges;
public readonly ProjectionInfo Pohnpei;
public readonly ProjectionInfo PortoSanto1936;
public readonly ProjectionInfo PortoSanto1995;
public readonly ProjectionInfo PuertoRico;
public readonly ProjectionInfo RGFG1995;
public readonly ProjectionInfo RGNC1991;
public readonly ProjectionInfo RGR1992;
public readonly ProjectionInfo RRAF1991;
public readonly ProjectionInfo Reunion;
public readonly ProjectionInfo ST71Belep;
public readonly ProjectionInfo ST84IledesPins;
public readonly ProjectionInfo ST87Ouvea;
public readonly ProjectionInfo SaintPierreetMiquelon1950;
public readonly ProjectionInfo SainteAnne;
public readonly ProjectionInfo SantoDOS1965;
public readonly ProjectionInfo SaoBraz;
public readonly ProjectionInfo SapperHill1943;
public readonly ProjectionInfo SelvagemGrande1938;
public readonly ProjectionInfo StKitts1955;
public readonly ProjectionInfo StLucia1955;
public readonly ProjectionInfo StVincent1945;
public readonly ProjectionInfo Tahaa;
public readonly ProjectionInfo Tahiti;
public readonly ProjectionInfo TernIslandAstro1961;
public readonly ProjectionInfo TristanAstro1968;
public readonly ProjectionInfo VitiLevu1916;
public readonly ProjectionInfo WakeEniwetok1960;
public readonly ProjectionInfo WakeIslandAstro1952;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of Oceans
/// </summary>
public Oceans()
{
AlaskanIslands = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk66 +no_defs ");
AmericanSamoa1962 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk66 +no_defs ");
Anguilla1957 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk80 +no_defs ");
Anna1Astro1965 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=aust_SA +no_defs ");
Antigua1943 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk80 +no_defs ");
AscensionIsland1958 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
AstroBeaconE1945 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
AstroDOS714 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
AstronomicalStation1952 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
AzoresCentral1948 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
AzoresCentral1995 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
AzoresOccidental1939 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
AzoresOriental1940 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
AzoresOriental1995 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
BabSouth = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk66 +no_defs ");
Barbados = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk80 +no_defs ");
Barbados1938 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk80 +no_defs ");
BellevueIGN = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
Bermuda1957 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk66 +no_defs ");
Bermuda2000 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=WGS84 +no_defs ");
CantonAstro1966 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
ChathamIslandAstro1971 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
Combani1950 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
CSG1967 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
Dominica1945 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk80 +no_defs ");
DOS1968 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
EasterIsland1967 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
FortDesaix = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
FortMarigot = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
FortThomas1955 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk80 +no_defs ");
Gan1970 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
GraciosaBaseSW1948 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
GrandComoros = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
Grenada1953 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk80 +no_defs ");
Guam1963 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk66 +no_defs ");
GUX1Astro = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
Hjorsey1955 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
IGN53Mare = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
IGN56Lifou = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
IGN72GrandeTerre = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
IGN72NukuHiva = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
ISTS061Astro1968 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
ISTS073Astro1969 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
Jamaica1875 = ProjectionInfo.FromProj4String("+proj=longlat +a=6378249.138 +b=6356514.959419348 +no_defs ");
Jamaica1969 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk66 +no_defs ");
JohnstonIsland1961 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
K01949 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
KerguelenIsland1949 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
KusaieAstro1951 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
LC5Astro1961 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk66 +no_defs ");
Madeira1936 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
Mahe1971 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk80 +no_defs ");
Majuro = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk66 +no_defs ");
MidwayAstro1961 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
Montserrat1958 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk80 +no_defs ");
MOP78 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
NEA74Noumea = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
ObservMeteorologico1939 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
OldHawaiian = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk66 +no_defs ");
PicodeLasNieves = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
PitcairnAstro1967 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
PitondesNeiges = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
Pohnpei = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk66 +no_defs ");
PortoSanto1936 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
PortoSanto1995 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
PuertoRico = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk66 +no_defs ");
Reunion = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
RGFG1995 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=GRS80 +no_defs ");
RGNC1991 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
RGR1992 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=GRS80 +no_defs ");
RRAF1991 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=WGS84 +no_defs ");
SaintPierreetMiquelon1950 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk66 +no_defs ");
SainteAnne = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
SantoDOS1965 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
SaoBraz = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
SapperHill1943 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
SelvagemGrande1938 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
StKitts1955 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk80 +no_defs ");
StLucia1955 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk80 +no_defs ");
StVincent1945 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk80 +no_defs ");
ST71Belep = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
ST84IledesPins = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
ST87Ouvea = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
Tahaa = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
Tahiti = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
TernIslandAstro1961 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
TristanAstro1968 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
VitiLevu1916 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk80 +no_defs ");
WakeIslandAstro1952 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
WakeEniwetok1960 = ProjectionInfo.FromProj4String("+proj=longlat +a=6378270 +b=6356794.343434343 +no_defs ");
AlaskanIslands.GeographicInfo.Name = "GCS_Alaskan_Islands";
AmericanSamoa1962.GeographicInfo.Name = "GCS_American_Samoa_1962";
Anguilla1957.GeographicInfo.Name = "GCS_Anguilla_1957";
Anna1Astro1965.GeographicInfo.Name = "GCS_Anna_1_1965";
Antigua1943.GeographicInfo.Name = "GCS_Antigua_1943";
AscensionIsland1958.GeographicInfo.Name = "GCS_Ascension_Island_1958";
AstroBeaconE1945.GeographicInfo.Name = "GCS_Beacon_E_1945";
AstroDOS714.GeographicInfo.Name = "GCS_DOS_71_4";
AstronomicalStation1952.GeographicInfo.Name = "GCS_Astro_1952";
AzoresCentral1948.GeographicInfo.Name = "GCS_Azores_Central_1948";
AzoresCentral1995.GeographicInfo.Name = "GCS_Azores_Central_1995";
AzoresOccidental1939.GeographicInfo.Name = "GCS_Azores_Occidental_1939";
AzoresOriental1940.GeographicInfo.Name = "GCS_Azores_Oriental_1940";
AzoresOriental1995.GeographicInfo.Name = "GCS_Azores_Oriental_1995";
BabSouth.GeographicInfo.Name = "GCS_Bab_South";
Barbados.GeographicInfo.Name = "GCS_Barbados";
Barbados1938.GeographicInfo.Name = "GCS_Barbados_1938";
BellevueIGN.GeographicInfo.Name = "GCS_Bellevue_IGN";
Bermuda1957.GeographicInfo.Name = "GCS_Bermuda_1957";
Bermuda2000.GeographicInfo.Name = "GCS_Bermuda_2000";
CantonAstro1966.GeographicInfo.Name = "GCS_Canton_1966";
ChathamIslandAstro1971.GeographicInfo.Name = "GCS_Chatham_Island_1971";
Combani1950.GeographicInfo.Name = "GCS_Combani_1950";
CSG1967.GeographicInfo.Name = "GCS_CSG_1967";
Dominica1945.GeographicInfo.Name = "GCS_Dominica_1945";
DOS1968.GeographicInfo.Name = "GCS_DOS_1968";
EasterIsland1967.GeographicInfo.Name = "GCS_Easter_Island_1967";
FortDesaix.GeographicInfo.Name = "GCS_Fort_Desaix";
FortMarigot.GeographicInfo.Name = "GCS_Fort_Marigot";
FortThomas1955.GeographicInfo.Name = "GCS_Fort_Thomas_1955";
Gan1970.GeographicInfo.Name = "GCS_Gan_1970";
GraciosaBaseSW1948.GeographicInfo.Name = "GCS_Graciosa_Base_SW_1948";
GrandComoros.GeographicInfo.Name = "GCS_Grand_Comoros";
Grenada1953.GeographicInfo.Name = "GCS_Grenada_1953";
Guam1963.GeographicInfo.Name = "GCS_Guam_1963";
GUX1Astro.GeographicInfo.Name = "GCS_GUX_1";
Hjorsey1955.GeographicInfo.Name = "GCS_Hjorsey_1955";
IGN53Mare.GeographicInfo.Name = "GCS_IGN53_Mare";
IGN56Lifou.GeographicInfo.Name = "GCS_IGN56_Lifou";
IGN72GrandeTerre.GeographicInfo.Name = "GCS_IGN72_Grande_Terre";
IGN72NukuHiva.GeographicInfo.Name = "GCS_IGN72_Nuku_Hiva";
ISTS061Astro1968.GeographicInfo.Name = "GCS_ISTS_061_1968";
ISTS073Astro1969.GeographicInfo.Name = "GCS_ISTS_073_1969";
Jamaica1875.GeographicInfo.Name = "GCS_Jamaica_1875";
Jamaica1969.GeographicInfo.Name = "GCS_Jamaica_1969";
JohnstonIsland1961.GeographicInfo.Name = "GCS_Johnston_Island_1961";
K01949.GeographicInfo.Name = "GCS_K0_1949";
KerguelenIsland1949.GeographicInfo.Name = "GCS_Kerguelen_Island_1949";
KusaieAstro1951.GeographicInfo.Name = "GCS_Kusaie_1951";
LC5Astro1961.GeographicInfo.Name = "GCS_LC5_1961";
Madeira1936.GeographicInfo.Name = "GCS_Madeira_1936";
Mahe1971.GeographicInfo.Name = "GCS_Mahe_1971";
Majuro.GeographicInfo.Name = "GCS_Majuro";
MidwayAstro1961.GeographicInfo.Name = "GCS_Midway_1961";
Montserrat1958.GeographicInfo.Name = "GCS_Montserrat_1958";
MOP78.GeographicInfo.Name = "GCS_MOP78";
NEA74Noumea.GeographicInfo.Name = "GCS_NEA74_Noumea";
ObservMeteorologico1939.GeographicInfo.Name = "GCS_Observ_Meteorologico_1939";
OldHawaiian.GeographicInfo.Name = "GCS_Old_Hawaiian";
PicodeLasNieves.GeographicInfo.Name = "GCS_Pico_de_Las_Nieves";
PitcairnAstro1967.GeographicInfo.Name = "GCS_Pitcairn_1967";
PitondesNeiges.GeographicInfo.Name = "GCS_Piton_des_Neiges";
Pohnpei.GeographicInfo.Name = "GCS_Pohnpei";
PortoSanto1936.GeographicInfo.Name = "GCS_Porto_Santo_1936";
PortoSanto1995.GeographicInfo.Name = "GCS_Porto_Santo_1995";
PuertoRico.GeographicInfo.Name = "GCS_Puerto_Rico";
Reunion.GeographicInfo.Name = "GCS_Reunion";
RGFG1995.GeographicInfo.Name = "GCS_RGFG_1995";
RGNC1991.GeographicInfo.Name = "GCS_RGNC_1991";
RGR1992.GeographicInfo.Name = "GCS_RGR_1992";
RRAF1991.GeographicInfo.Name = "GCS_RRAF_1991";
SaintPierreetMiquelon1950.GeographicInfo.Name = "GCS_Saint_Pierre_et_Miquelon_1950";
SainteAnne.GeographicInfo.Name = "GCS_Sainte_Anne";
SantoDOS1965.GeographicInfo.Name = "GCS_Santo_DOS_1965";
SaoBraz.GeographicInfo.Name = "GCS_Sao_Braz";
SapperHill1943.GeographicInfo.Name = "GCS_Sapper_Hill_1943";
SelvagemGrande1938.GeographicInfo.Name = "GCS_Selvagem_Grande_1938";
StKitts1955.GeographicInfo.Name = "GCS_St_Kitts_1955";
StLucia1955.GeographicInfo.Name = "GCS_St_Lucia_1955";
StVincent1945.GeographicInfo.Name = "GCS_St_Vincent_1945";
ST71Belep.GeographicInfo.Name = "GCS_ST71_Belep";
ST84IledesPins.GeographicInfo.Name = "GCS_ST84_Ile_des_Pins";
ST87Ouvea.GeographicInfo.Name = "GCS_ST87_Ouvea";
Tahaa.GeographicInfo.Name = "GCS_Tahaa";
Tahiti.GeographicInfo.Name = "GCS_Tahiti";
TernIslandAstro1961.GeographicInfo.Name = "GCS_Tern_Island_1961";
TristanAstro1968.GeographicInfo.Name = "GCS_Tristan_1968";
VitiLevu1916.GeographicInfo.Name = "GCS_Viti_Levu_1916";
WakeIslandAstro1952.GeographicInfo.Name = "GCS_Wake_Island_1952";
WakeEniwetok1960.GeographicInfo.Name = "GCS_Wake_Eniwetok_1960";
AlaskanIslands.GeographicInfo.Datum.Name = "D_Alaskan_Islands";
AmericanSamoa1962.GeographicInfo.Datum.Name = "D_American_Samoa_1962";
Anguilla1957.GeographicInfo.Datum.Name = "D_Anguilla_1957";
Anna1Astro1965.GeographicInfo.Datum.Name = "D_Anna_1_1965";
Antigua1943.GeographicInfo.Datum.Name = "D_Antigua_1943";
AscensionIsland1958.GeographicInfo.Datum.Name = "D_Ascension_Island_1958";
AstroBeaconE1945.GeographicInfo.Datum.Name = "D_Beacon_E_1945";
AstroDOS714.GeographicInfo.Datum.Name = "D_DOS_71_4";
AstronomicalStation1952.GeographicInfo.Datum.Name = "D_Astro_1952";
AzoresCentral1948.GeographicInfo.Datum.Name = "D_Azores_Central_Islands_1948";
AzoresCentral1995.GeographicInfo.Datum.Name = "D_Azores_Central_Islands_1995";
AzoresOccidental1939.GeographicInfo.Datum.Name = "D_Azores_Occidental_Islands_1939";
AzoresOriental1940.GeographicInfo.Datum.Name = "D_Azores_Oriental_Islands_1940";
AzoresOriental1995.GeographicInfo.Datum.Name = "D_Azores_Oriental_Islands_1995";
BabSouth.GeographicInfo.Datum.Name = "D_Bab_South";
Barbados.GeographicInfo.Datum.Name = "D_Barbados";
Barbados1938.GeographicInfo.Datum.Name = "D_Barbados_1938";
BellevueIGN.GeographicInfo.Datum.Name = "D_Bellevue_IGN";
Bermuda1957.GeographicInfo.Datum.Name = "D_Bermuda_1957";
Bermuda2000.GeographicInfo.Datum.Name = "D_Bermuda_2000";
CantonAstro1966.GeographicInfo.Datum.Name = "D_Canton_1966";
ChathamIslandAstro1971.GeographicInfo.Datum.Name = "D_Chatham_Island_1971";
Combani1950.GeographicInfo.Datum.Name = "D_Combani_1950";
CSG1967.GeographicInfo.Datum.Name = "D_CSG_1967";
Dominica1945.GeographicInfo.Datum.Name = "D_Dominica_1945";
DOS1968.GeographicInfo.Datum.Name = "D_DOS_1968";
EasterIsland1967.GeographicInfo.Datum.Name = "D_Easter_Island_1967";
FortDesaix.GeographicInfo.Datum.Name = "D_Fort_Desaix";
FortMarigot.GeographicInfo.Datum.Name = "D_Fort_Marigot";
FortThomas1955.GeographicInfo.Datum.Name = "D_Fort_Thomas_1955";
Gan1970.GeographicInfo.Datum.Name = "D_Gan_1970";
GraciosaBaseSW1948.GeographicInfo.Datum.Name = "D_Graciosa_Base_SW_1948";
GrandComoros.GeographicInfo.Datum.Name = "D_Grand_Comoros";
Grenada1953.GeographicInfo.Datum.Name = "D_Grenada_1953";
Guam1963.GeographicInfo.Datum.Name = "D_Guam_1963";
GUX1Astro.GeographicInfo.Datum.Name = "D_GUX_1";
Hjorsey1955.GeographicInfo.Datum.Name = "D_Hjorsey_1955";
IGN53Mare.GeographicInfo.Datum.Name = "D_IGN53_Mare";
IGN56Lifou.GeographicInfo.Datum.Name = "D_IGN56_Lifou";
IGN72GrandeTerre.GeographicInfo.Datum.Name = "D_IGN72_Grande_Terre";
IGN72NukuHiva.GeographicInfo.Datum.Name = "D_IGN72_Nuku_Hiva";
ISTS061Astro1968.GeographicInfo.Datum.Name = "D_ISTS_061_1968";
ISTS073Astro1969.GeographicInfo.Datum.Name = "D_ISTS_073_1969";
Jamaica1875.GeographicInfo.Datum.Name = "D_Jamaica_1875";
Jamaica1969.GeographicInfo.Datum.Name = "D_Jamaica_1969";
JohnstonIsland1961.GeographicInfo.Datum.Name = "D_Johnston_Island_1961";
K01949.GeographicInfo.Datum.Name = "D_K0_1949";
KerguelenIsland1949.GeographicInfo.Datum.Name = "D_Kerguelen_Island_1949";
KusaieAstro1951.GeographicInfo.Datum.Name = "D_Kusaie_1951";
LC5Astro1961.GeographicInfo.Datum.Name = "D_LC5_1961";
Madeira1936.GeographicInfo.Datum.Name = "D_Madeira_1936";
Mahe1971.GeographicInfo.Datum.Name = "D_Mahe_1971";
Majuro.GeographicInfo.Datum.Name = "D_Majuro";
MidwayAstro1961.GeographicInfo.Datum.Name = "D_Midway_1961";
Montserrat1958.GeographicInfo.Datum.Name = "D_Montserrat_1958";
MOP78.GeographicInfo.Datum.Name = "D_MOP78";
NEA74Noumea.GeographicInfo.Datum.Name = "D_NEA74_Noumea";
ObservMeteorologico1939.GeographicInfo.Datum.Name = "D_Observ_Meteorologico_1939";
OldHawaiian.GeographicInfo.Datum.Name = "D_Old_Hawaiian";
PicodeLasNieves.GeographicInfo.Datum.Name = "D_Pico_de_Las_Nieves";
PitcairnAstro1967.GeographicInfo.Datum.Name = "D_Pitcairn_1967";
PitondesNeiges.GeographicInfo.Datum.Name = "D_Piton_des_Neiges";
Pohnpei.GeographicInfo.Datum.Name = "D_Pohnpei";
PortoSanto1936.GeographicInfo.Datum.Name = "D_Porto_Santo_1936";
PortoSanto1995.GeographicInfo.Datum.Name = "D_Porto_Santo_1995";
PuertoRico.GeographicInfo.Datum.Name = "D_Puerto_Rico";
Reunion.GeographicInfo.Datum.Name = "D_Reunion";
RGFG1995.GeographicInfo.Datum.Name = "D_RGFG_1995";
RGNC1991.GeographicInfo.Datum.Name = "D_RGNC_1991";
RGR1992.GeographicInfo.Datum.Name = "D_RGR_1992";
RRAF1991.GeographicInfo.Datum.Name = "D_RRAF_1991";
SaintPierreetMiquelon1950.GeographicInfo.Datum.Name = "D_Saint_Pierre_et_Miquelon_1950";
SainteAnne.GeographicInfo.Datum.Name = "D_Sainte_Anne";
SantoDOS1965.GeographicInfo.Datum.Name = "D_Santo_DOS_1965";
SaoBraz.GeographicInfo.Datum.Name = "D_Sao_Braz";
SapperHill1943.GeographicInfo.Datum.Name = "D_Sapper_Hill_1943";
SelvagemGrande1938.GeographicInfo.Datum.Name = "D_Selvagem_Grande_1938";
StKitts1955.GeographicInfo.Datum.Name = "D_St_Kitts_1955";
StLucia1955.GeographicInfo.Datum.Name = "D_St_Lucia_1955";
StVincent1945.GeographicInfo.Datum.Name = "D_St_Vincent_1945";
ST71Belep.GeographicInfo.Datum.Name = "D_ST71_Belep";
ST84IledesPins.GeographicInfo.Datum.Name = "D_ST84_Ile_des_Pins";
ST87Ouvea.GeographicInfo.Datum.Name = "D_ST87_Ouvea";
Tahaa.GeographicInfo.Datum.Name = "D_Tahaa";
Tahiti.GeographicInfo.Datum.Name = "D_Tahiti";
TernIslandAstro1961.GeographicInfo.Datum.Name = "D_Tern_Island_1961";
TristanAstro1968.GeographicInfo.Datum.Name = "D_Tristan_1968";
VitiLevu1916.GeographicInfo.Datum.Name = "D_Viti_Levu_1916";
WakeIslandAstro1952.GeographicInfo.Datum.Name = "D_Wake_Island_1952";
WakeEniwetok1960.GeographicInfo.Datum.Name = "D_Wake_Eniwetok_1960";
}
#endregion
}
}
#pragma warning restore 1591
| |
using YAF.Lucene.Net.Support;
namespace YAF.Lucene.Net.Search.Similarities
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AtomicReaderContext = YAF.Lucene.Net.Index.AtomicReaderContext;
using BytesRef = YAF.Lucene.Net.Util.BytesRef;
using FieldInvertState = YAF.Lucene.Net.Index.FieldInvertState;
using NumericDocValues = YAF.Lucene.Net.Index.NumericDocValues;
/// <summary>
/// Implementation of <see cref="Similarity"/> with the Vector Space Model.
/// <para/>
/// Expert: Scoring API.
/// <para/>TFIDFSimilarity defines the components of Lucene scoring.
/// Overriding computation of these components is a convenient
/// way to alter Lucene scoring.
///
/// <para/>Suggested reading:
/// <a href="http://nlp.stanford.edu/IR-book/html/htmledition/queries-as-vectors-1.html">
/// Introduction To Information Retrieval, Chapter 6</a>.
///
/// <para/>The following describes how Lucene scoring evolves from
/// underlying information retrieval models to (efficient) implementation.
/// We first brief on <i>VSM Score</i>,
/// then derive from it <i>Lucene's Conceptual Scoring Formula</i>,
/// from which, finally, evolves <i>Lucene's Practical Scoring Function</i>
/// (the latter is connected directly with Lucene classes and methods).
///
/// <para/>Lucene combines
/// <a href="http://en.wikipedia.org/wiki/Standard_Boolean_model">
/// Boolean model (BM) of Information Retrieval</a>
/// with
/// <a href="http://en.wikipedia.org/wiki/Vector_Space_Model">
/// Vector Space Model (VSM) of Information Retrieval</a> -
/// documents "approved" by BM are scored by VSM.
///
/// <para/>In VSM, documents and queries are represented as
/// weighted vectors in a multi-dimensional space,
/// where each distinct index term is a dimension,
/// and weights are
/// <a href="http://en.wikipedia.org/wiki/Tfidf">Tf-idf</a> values.
///
/// <para/>VSM does not require weights to be <i>Tf-idf</i> values,
/// but <i>Tf-idf</i> values are believed to produce search results of high quality,
/// and so Lucene is using <i>Tf-idf</i>.
/// <i>Tf</i> and <i>Idf</i> are described in more detail below,
/// but for now, for completion, let's just say that
/// for given term <i>t</i> and document (or query) <i>x</i>,
/// <i>Tf(t,x)</i> varies with the number of occurrences of term <i>t</i> in <i>x</i>
/// (when one increases so does the other) and
/// <i>idf(t)</i> similarly varies with the inverse of the
/// number of index documents containing term <i>t</i>.
///
/// <para/><i>VSM score</i> of document <i>d</i> for query <i>q</i> is the
/// <a href="http://en.wikipedia.org/wiki/Cosine_similarity">
/// Cosine Similarity</a>
/// of the weighted query vectors <i>V(q)</i> and <i>V(d)</i>:
/// <para/>
/// <list type="table">
/// <item>
/// <term>
/// <list type="table">
/// <item>
/// <term>cosine-similarity(q,d)   =  </term>
/// <term>
/// <table>
/// <item><term><small>V(q) · V(d)</small></term></item>
/// <item><term>–––––––––</term></item>
/// <item><term><small>|V(q)| |V(d)|</small></term></item>
/// </table>
/// </term>
/// </item>
/// </list>
/// </term>
/// </item>
/// <item>
/// <term>VSM Score</term>
/// </item>
/// </list>
/// <para/>
///
///
/// Where <i>V(q)</i> · <i>V(d)</i> is the
/// <a href="http://en.wikipedia.org/wiki/Dot_product">dot product</a>
/// of the weighted vectors,
/// and <i>|V(q)|</i> and <i>|V(d)|</i> are their
/// <a href="http://en.wikipedia.org/wiki/Euclidean_norm#Euclidean_norm">Euclidean norms</a>.
///
/// <para/>Note: the above equation can be viewed as the dot product of
/// the normalized weighted vectors, in the sense that dividing
/// <i>V(q)</i> by its euclidean norm is normalizing it to a unit vector.
///
/// <para/>Lucene refines <i>VSM score</i> for both search quality and usability:
/// <list type="bullet">
/// <item><description>Normalizing <i>V(d)</i> to the unit vector is known to be problematic in that
/// it removes all document length information.
/// For some documents removing this info is probably ok,
/// e.g. a document made by duplicating a certain paragraph <i>10</i> times,
/// especially if that paragraph is made of distinct terms.
/// But for a document which contains no duplicated paragraphs,
/// this might be wrong.
/// To avoid this problem, a different document length normalization
/// factor is used, which normalizes to a vector equal to or larger
/// than the unit vector: <i>doc-len-norm(d)</i>.
/// </description></item>
///
/// <item><description>At indexing, users can specify that certain documents are more
/// important than others, by assigning a document boost.
/// For this, the score of each document is also multiplied by its boost value
/// <i>doc-boost(d)</i>.
/// </description></item>
///
/// <item><description>Lucene is field based, hence each query term applies to a single
/// field, document length normalization is by the length of the certain field,
/// and in addition to document boost there are also document fields boosts.
/// </description></item>
///
/// <item><description>The same field can be added to a document during indexing several times,
/// and so the boost of that field is the multiplication of the boosts of
/// the separate additions (or parts) of that field within the document.
/// </description></item>
///
/// <item><description>At search time users can specify boosts to each query, sub-query, and
/// each query term, hence the contribution of a query term to the score of
/// a document is multiplied by the boost of that query term <i>query-boost(q)</i>.
/// </description></item>
///
/// <item><description>A document may match a multi term query without containing all
/// the terms of that query (this is correct for some of the queries),
/// and users can further reward documents matching more query terms
/// through a coordination factor, which is usually larger when
/// more terms are matched: <i>coord-factor(q,d)</i>.
/// </description></item>
/// </list>
///
/// <para/>Under the simplifying assumption of a single field in the index,
/// we get <i>Lucene's Conceptual scoring formula</i>:
///
/// <para/>
/// <list type="table">
/// <item>
/// <term>
/// <list type="table">
/// <item>
/// <term>
/// score(q,d)   =  
/// <font color="#FF9933">coord-factor(q,d)</font> ·  
/// <font color="#CCCC00">query-boost(q)</font> ·  
/// </term>
/// <term>
/// <list type="table">
/// <item><term><small><font color="#993399">V(q) · V(d)</font></small></term></item>
/// <item><term>–––––––––</term></item>
/// <item><term><small><font color="#FF33CC">|V(q)|</font></small></term></item>
/// </list>
/// </term>
/// <term>
///   ·   <font color="#3399FF">doc-len-norm(d)</font>
///   ·   <font color="#3399FF">doc-boost(d)</font>
/// </term>
/// </item>
/// </list>
/// </term>
/// </item>
/// <item>
/// <term>Lucene Conceptual Scoring Formula</term>
/// </item>
/// </list>
/// <para/>
///
///
/// <para/>The conceptual formula is a simplification in the sense that (1) terms and documents
/// are fielded and (2) boosts are usually per query term rather than per query.
///
/// <para/>We now describe how Lucene implements this conceptual scoring formula, and
/// derive from it <i>Lucene's Practical Scoring Function</i>.
///
/// <para/>For efficient score computation some scoring components
/// are computed and aggregated in advance:
///
/// <list type="bullet">
/// <item><description><i>Query-boost</i> for the query (actually for each query term)
/// is known when search starts.
/// </description></item>
///
/// <item><description>Query Euclidean norm <i>|V(q)|</i> can be computed when search starts,
/// as it is independent of the document being scored.
/// From search optimization perspective, it is a valid question
/// why bother to normalize the query at all, because all
/// scored documents will be multiplied by the same <i>|V(q)|</i>,
/// and hence documents ranks (their order by score) will not
/// be affected by this normalization.
/// There are two good reasons to keep this normalization:
/// <list type="bullet">
/// <item><description>Recall that
/// <a href="http://en.wikipedia.org/wiki/Cosine_similarity">
/// Cosine Similarity</a> can be used find how similar
/// two documents are. One can use Lucene for e.g.
/// clustering, and use a document as a query to compute
/// its similarity to other documents.
/// In this use case it is important that the score of document <i>d3</i>
/// for query <i>d1</i> is comparable to the score of document <i>d3</i>
/// for query <i>d2</i>. In other words, scores of a document for two
/// distinct queries should be comparable.
/// There are other applications that may require this.
/// And this is exactly what normalizing the query vector <i>V(q)</i>
/// provides: comparability (to a certain extent) of two or more queries.
/// </description></item>
///
/// <item><description>Applying query normalization on the scores helps to keep the
/// scores around the unit vector, hence preventing loss of score data
/// because of floating point precision limitations.
/// </description></item>
/// </list>
/// </description></item>
///
/// <item><description>Document length norm <i>doc-len-norm(d)</i> and document
/// boost <i>doc-boost(d)</i> are known at indexing time.
/// They are computed in advance and their multiplication
/// is saved as a single value in the index: <i>norm(d)</i>.
/// (In the equations below, <i>norm(t in d)</i> means <i>norm(field(t) in doc d)</i>
/// where <i>field(t)</i> is the field associated with term <i>t</i>.)
/// </description></item>
/// </list>
///
/// <para/><i>Lucene's Practical Scoring Function</i> is derived from the above.
/// The color codes demonstrate how it relates
/// to those of the <i>conceptual</i> formula:
///
/// <para/>
/// <list type="table">
/// <item>
/// <term>
/// <list type="table">
/// <item>
/// <term>
/// score(q,d)   =  
/// <a href="#formula_coord"><font color="#FF9933">coord(q,d)</font></a>   ·  
/// <a href="#formula_queryNorm"><font color="#FF33CC">queryNorm(q)</font></a>   ·  
/// </term>
/// <term><big><big><big>∑</big></big></big></term>
/// <term>
/// <big><big>(</big></big>
/// <a href="#formula_tf"><font color="#993399">tf(t in d)</font></a>   ·  
/// <a href="#formula_idf"><font color="#993399">idf(t)</font></a><sup>2</sup>   ·  
/// <a href="#formula_termBoost"><font color="#CCCC00">t.Boost</font></a>   ·  
/// <a href="#formula_norm"><font color="#3399FF">norm(t,d)</font></a>
/// <big><big>)</big></big>
/// </term>
/// </item>
/// <item>
/// <term></term>
/// <term><small>t in q</small></term>
/// <term></term>
/// </item>
/// </list>
/// </term>
/// </item>
/// <item>
/// <term>Lucene Practical Scoring Function</term>
/// </item>
/// </list>
///
/// <para/> where
/// <list type="number">
/// <item><description>
/// <a name="formula_tf"></a>
/// <b><i>tf(t in d)</i></b>
/// correlates to the term's <i>frequency</i>,
/// defined as the number of times term <i>t</i> appears in the currently scored document <i>d</i>.
/// Documents that have more occurrences of a given term receive a higher score.
/// Note that <i>tf(t in q)</i> is assumed to be <i>1</i> and therefore it does not appear in this equation,
/// However if a query contains twice the same term, there will be
/// two term-queries with that same term and hence the computation would still be correct (although
/// not very efficient).
/// The default computation for <i>tf(t in d)</i> in
/// DefaultSimilarity (<see cref="Lucene.Net.Search.Similarities.DefaultSimilarity.Tf(float)"/>) is:
///
/// <para/>
/// <list type="table">
/// <item>
/// <term>
/// tf(t in d)   =  
/// </term>
/// <term>
/// frequency<sup><big>½</big></sup>
/// </term>
/// </item>
/// </list>
/// <para/>
///
/// </description></item>
///
/// <item><description>
/// <a name="formula_idf"></a>
/// <b><i>idf(t)</i></b> stands for Inverse Document Frequency. this value
/// correlates to the inverse of <i>DocFreq</i>
/// (the number of documents in which the term <i>t</i> appears).
/// this means rarer terms give higher contribution to the total score.
/// <i>idf(t)</i> appears for <i>t</i> in both the query and the document,
/// hence it is squared in the equation.
/// The default computation for <i>idf(t)</i> in
/// DefaultSimilarity (<see cref="Lucene.Net.Search.Similarities.DefaultSimilarity.Idf(long, long)"/>) is:
///
/// <para/>
/// <list type="table">
/// <item>
/// <term>idf(t)   =  </term>
/// <term>1 + log <big>(</big></term>
/// <term>
/// <list type="table">
/// <item><term><small>NumDocs</small></term></item>
/// <item><term>–––––––––</term></item>
/// <item><term><small>DocFreq+1</small></term></item>
/// </list>
/// </term>
/// <term><big>)</big></term>
/// </item>
/// </list>
/// <para/>
///
/// </description></item>
///
/// <item><description>
/// <a name="formula_coord"></a>
/// <b><i>coord(q,d)</i></b>
/// is a score factor based on how many of the query terms are found in the specified document.
/// Typically, a document that contains more of the query's terms will receive a higher score
/// than another document with fewer query terms.
/// this is a search time factor computed in
/// coord(q,d) (<see cref="Coord(int, int)"/>)
/// by the Similarity in effect at search time.
/// <para/>
/// </description></item>
///
/// <item><description><b>
/// <a name="formula_queryNorm"></a>
/// <i>queryNorm(q)</i>
/// </b>
/// is a normalizing factor used to make scores between queries comparable.
/// this factor does not affect document ranking (since all ranked documents are multiplied by the same factor),
/// but rather just attempts to make scores from different queries (or even different indexes) comparable.
/// this is a search time factor computed by the Similarity in effect at search time.
///
/// The default computation in
/// DefaultSimilarity (<see cref="Lucene.Net.Search.Similarities.DefaultSimilarity.QueryNorm(float)"/>)
/// produces a <a href="http://en.wikipedia.org/wiki/Euclidean_norm#Euclidean_norm">Euclidean norm</a>:
///
/// <para/>
/// <list type="table">
/// <item>
/// <term>
/// queryNorm(q)   =  
/// queryNorm(sumOfSquaredWeights)
///   =  
/// </term>
/// <term>
/// <list type="table">
/// <item><term><big>1</big></term></item>
/// <item><term><big>––––––––––––––</big></term></item>
/// <item><term>sumOfSquaredWeights<sup><big>½</big></sup></term></item>
/// </list>
/// </term>
/// </item>
/// </list>
/// <para/>
///
/// The sum of squared weights (of the query terms) is
/// computed by the query <see cref="Lucene.Net.Search.Weight"/> object.
/// For example, a <see cref="Lucene.Net.Search.BooleanQuery"/>
/// computes this value as:
///
/// <para/>
/// <list type="table">
/// <item>
/// <term>
/// sumOfSquaredWeights   =  
/// q.Boost <sup><big>2</big></sup>
///  · 
/// </term>
/// <term><big><big><big>∑</big></big></big></term>
/// <term>
/// <big><big>(</big></big>
/// <a href="#formula_idf">idf(t)</a>  · 
/// <a href="#formula_termBoost">t.Boost</a>
/// <big><big>) <sup>2</sup> </big></big>
/// </term>
/// </item>
/// <item>
/// <term></term>
/// <term><small>t in q</small></term>
/// <term></term>
/// </item>
/// </list>
/// where sumOfSquaredWeights is <see cref="Weight.GetValueForNormalization()"/> and
/// q.Boost is <see cref="Query.Boost"/>
/// <para/>
/// </description></item>
///
/// <item><description>
/// <a name="formula_termBoost"></a>
/// <b><i>t.Boost</i></b>
/// is a search time boost of term <i>t</i> in the query <i>q</i> as
/// specified in the query text
/// (see <a href="{@docRoot}/../queryparser/org/apache/lucene/queryparser/classic/package-summary.html#Boosting_a_Term">query syntax</a>),
/// or as set by application calls to
/// <see cref="Lucene.Net.Search.Query.Boost"/>.
/// Notice that there is really no direct API for accessing a boost of one term in a multi term query,
/// but rather multi terms are represented in a query as multi
/// <see cref="Lucene.Net.Search.TermQuery"/> objects,
/// and so the boost of a term in the query is accessible by calling the sub-query
/// <see cref="Lucene.Net.Search.Query.Boost"/>.
/// <para/>
/// </description></item>
///
/// <item><description>
/// <a name="formula_norm"></a>
/// <b><i>norm(t,d)</i></b> encapsulates a few (indexing time) boost and length factors:
///
/// <list type="bullet">
/// <item><description><b>Field boost</b> - set
/// <see cref="Documents.Field.Boost"/>
/// before adding the field to a document.
/// </description></item>
/// <item><description><b>lengthNorm</b> - computed
/// when the document is added to the index in accordance with the number of tokens
/// of this field in the document, so that shorter fields contribute more to the score.
/// LengthNorm is computed by the <see cref="Similarity"/> class in effect at indexing.
/// </description></item>
/// </list>
/// The <see cref="ComputeNorm(FieldInvertState)"/> method is responsible for
/// combining all of these factors into a single <see cref="float"/>.
///
/// <para/>
/// When a document is added to the index, all the above factors are multiplied.
/// If the document has multiple fields with the same name, all their boosts are multiplied together:
///
/// <para/>
/// <list type="table">
/// <item>
/// <term>
/// norm(t,d)   =  
/// lengthNorm
///  · 
/// </term>
/// <term><big><big><big>∏</big></big></big></term>
/// <term><see cref="Index.IIndexableField.Boost"/></term>
/// </item>
/// <item>
/// <term></term>
/// <term><small>field <i><b>f</b></i> in <i>d</i> named as <i><b>t</b></i></small></term>
/// <term></term>
/// </item>
/// </list>
/// Note that search time is too late to modify this <i>norm</i> part of scoring,
/// e.g. by using a different <see cref="Similarity"/> for search.
/// </description></item>
/// </list>
/// </summary>
/// <seealso cref="Lucene.Net.Index.IndexWriterConfig.Similarity"/>
/// <seealso cref="IndexSearcher.Similarity"/>
public abstract class TFIDFSimilarity : Similarity
{
/// <summary>
/// Sole constructor. (For invocation by subclass
/// constructors, typically implicit.)
/// </summary>
public TFIDFSimilarity()
{
}
/// <summary>
/// Computes a score factor based on the fraction of all query terms that a
/// document contains. this value is multiplied into scores.
///
/// <para/>The presence of a large portion of the query terms indicates a better
/// match with the query, so implementations of this method usually return
/// larger values when the ratio between these parameters is large and smaller
/// values when the ratio between them is small.
/// </summary>
/// <param name="overlap"> The number of query terms matched in the document </param>
/// <param name="maxOverlap"> The total number of terms in the query </param>
/// <returns> A score factor based on term overlap with the query </returns>
public override abstract float Coord(int overlap, int maxOverlap);
/// <summary>
/// Computes the normalization value for a query given the sum of the squared
/// weights of each of the query terms. this value is multiplied into the
/// weight of each query term. While the classic query normalization factor is
/// computed as 1/sqrt(sumOfSquaredWeights), other implementations might
/// completely ignore sumOfSquaredWeights (ie return 1).
///
/// <para/>This does not affect ranking, but the default implementation does make scores
/// from different queries more comparable than they would be by eliminating the
/// magnitude of the <see cref="Query"/> vector as a factor in the score.
/// </summary>
/// <param name="sumOfSquaredWeights"> The sum of the squares of query term weights </param>
/// <returns> A normalization factor for query weights </returns>
public override abstract float QueryNorm(float sumOfSquaredWeights);
/// <summary>
/// Computes a score factor based on a term or phrase's frequency in a
/// document. This value is multiplied by the <see cref="Idf(long, long)"/>
/// factor for each term in the query and these products are then summed to
/// form the initial score for a document.
///
/// <para/>Terms and phrases repeated in a document indicate the topic of the
/// document, so implementations of this method usually return larger values
/// when <paramref name="freq"/> is large, and smaller values when <paramref name="freq"/>
/// is small.
/// </summary>
/// <param name="freq"> The frequency of a term within a document </param>
/// <returns> A score factor based on a term's within-document frequency </returns>
public abstract float Tf(float freq);
/// <summary>
/// Computes a score factor for a simple term and returns an explanation
/// for that score factor.
///
/// <para/>
/// The default implementation uses:
///
/// <code>
/// Idf(docFreq, searcher.MaxDoc);
/// </code>
///
/// Note that <see cref="CollectionStatistics.MaxDoc"/> is used instead of
/// <see cref="Lucene.Net.Index.IndexReader.NumDocs"/> because also
/// <see cref="TermStatistics.DocFreq"/> is used, and when the latter
/// is inaccurate, so is <see cref="CollectionStatistics.MaxDoc"/>, and in the same direction.
/// In addition, <see cref="CollectionStatistics.MaxDoc"/> is more efficient to compute
/// </summary>
/// <param name="collectionStats"> Collection-level statistics </param>
/// <param name="termStats"> Term-level statistics for the term </param>
/// <returns> An Explain object that includes both an idf score factor
/// and an explanation for the term. </returns>
public virtual Explanation IdfExplain(CollectionStatistics collectionStats, TermStatistics termStats)
{
long df = termStats.DocFreq;
long max = collectionStats.MaxDoc;
float idf = Idf(df, max);
return new Explanation(idf, "idf(docFreq=" + df + ", maxDocs=" + max + ")");
}
/// <summary>
/// Computes a score factor for a phrase.
///
/// <para/>
/// The default implementation sums the idf factor for
/// each term in the phrase.
/// </summary>
/// <param name="collectionStats"> Collection-level statistics </param>
/// <param name="termStats"> Term-level statistics for the terms in the phrase </param>
/// <returns> An Explain object that includes both an idf
/// score factor for the phrase and an explanation
/// for each term. </returns>
public virtual Explanation IdfExplain(CollectionStatistics collectionStats, TermStatistics[] termStats)
{
long max = collectionStats.MaxDoc;
float idf = 0.0f;
Explanation exp = new Explanation();
exp.Description = "idf(), sum of:";
foreach (TermStatistics stat in termStats)
{
long df = stat.DocFreq;
float termIdf = Idf(df, max);
exp.AddDetail(new Explanation(termIdf, "idf(docFreq=" + df + ", maxDocs=" + max + ")"));
idf += termIdf;
}
exp.Value = idf;
return exp;
}
/// <summary>
/// Computes a score factor based on a term's document frequency (the number
/// of documents which contain the term). This value is multiplied by the
/// <see cref="Tf(float)"/> factor for each term in the query and these products are
/// then summed to form the initial score for a document.
///
/// <para/>Terms that occur in fewer documents are better indicators of topic, so
/// implementations of this method usually return larger values for rare terms,
/// and smaller values for common terms.
/// </summary>
/// <param name="docFreq"> The number of documents which contain the term </param>
/// <param name="numDocs"> The total number of documents in the collection </param>
/// <returns> A score factor based on the term's document frequency </returns>
public abstract float Idf(long docFreq, long numDocs);
/// <summary>
/// Compute an index-time normalization value for this field instance.
/// <para/>
/// This value will be stored in a single byte lossy representation by
/// <see cref="EncodeNormValue(float)"/>.
/// </summary>
/// <param name="state"> Statistics of the current field (such as length, boost, etc) </param>
/// <returns> An index-time normalization value </returns>
public abstract float LengthNorm(FieldInvertState state);
public override sealed long ComputeNorm(FieldInvertState state)
{
float normValue = LengthNorm(state);
return EncodeNormValue(normValue);
}
/// <summary>
/// Decodes a normalization factor stored in an index.
/// </summary>
/// <see cref="EncodeNormValue(float)"/>
public abstract float DecodeNormValue(long norm);
/// <summary>
/// Encodes a normalization factor for storage in an index. </summary>
public abstract long EncodeNormValue(float f);
/// <summary>
/// Computes the amount of a sloppy phrase match, based on an edit distance.
/// this value is summed for each sloppy phrase match in a document to form
/// the frequency to be used in scoring instead of the exact term count.
///
/// <para/>A phrase match with a small edit distance to a document passage more
/// closely matches the document, so implementations of this method usually
/// return larger values when the edit distance is small and smaller values
/// when it is large.
/// </summary>
/// <seealso cref="PhraseQuery.Slop"/>
/// <param name="distance"> The edit distance of this sloppy phrase match </param>
/// <returns> The frequency increment for this match </returns>
public abstract float SloppyFreq(int distance);
/// <summary>
/// Calculate a scoring factor based on the data in the payload. Implementations
/// are responsible for interpreting what is in the payload. Lucene makes no assumptions about
/// what is in the byte array.
/// </summary>
/// <param name="doc"> The docId currently being scored. </param>
/// <param name="start"> The start position of the payload </param>
/// <param name="end"> The end position of the payload </param>
/// <param name="payload"> The payload byte array to be scored </param>
/// <returns> An implementation dependent float to be used as a scoring factor </returns>
public abstract float ScorePayload(int doc, int start, int end, BytesRef payload);
public override sealed SimWeight ComputeWeight(float queryBoost, CollectionStatistics collectionStats, params TermStatistics[] termStats)
{
Explanation idf = termStats.Length == 1 ? IdfExplain(collectionStats, termStats[0]) : IdfExplain(collectionStats, termStats);
return new IDFStats(collectionStats.Field, idf, queryBoost);
}
public override sealed SimScorer GetSimScorer(SimWeight stats, AtomicReaderContext context)
{
IDFStats idfstats = (IDFStats)stats;
return new TFIDFSimScorer(this, idfstats, context.AtomicReader.GetNormValues(idfstats.Field));
}
private sealed class TFIDFSimScorer : SimScorer
{
private readonly TFIDFSimilarity outerInstance;
private readonly IDFStats stats;
private readonly float weightValue;
private readonly NumericDocValues norms;
internal TFIDFSimScorer(TFIDFSimilarity outerInstance, IDFStats stats, NumericDocValues norms)
{
this.outerInstance = outerInstance;
this.stats = stats;
this.weightValue = stats.Value;
this.norms = norms;
}
public override float Score(int doc, float freq)
{
float raw = outerInstance.Tf(freq) * weightValue; // compute tf(f)*weight
return norms == null ? raw : raw * outerInstance.DecodeNormValue(norms.Get(doc)); // normalize for field
}
public override float ComputeSlopFactor(int distance)
{
return outerInstance.SloppyFreq(distance);
}
public override float ComputePayloadFactor(int doc, int start, int end, BytesRef payload)
{
return outerInstance.ScorePayload(doc, start, end, payload);
}
public override Explanation Explain(int doc, Explanation freq)
{
return outerInstance.ExplainScore(doc, freq, stats, norms);
}
}
/// <summary>
/// Collection statistics for the TF-IDF model. The only statistic of interest
/// to this model is idf.
/// </summary>
[ExceptionToClassNameConvention]
private class IDFStats : SimWeight
{
internal string Field { get; private set; }
/// <summary>
/// The idf and its explanation </summary>
internal Explanation Idf { get; private set; }
internal float QueryNorm { get; set; }
internal float QueryWeight { get; set; }
internal float QueryBoost { get; private set; }
internal float Value { get; set; }
public IDFStats(string field, Explanation idf, float queryBoost)
{
// TODO: Validate?
this.Field = field;
this.Idf = idf;
this.QueryBoost = queryBoost;
this.QueryWeight = idf.Value * queryBoost; // compute query weight
}
public override float GetValueForNormalization()
{
// TODO: (sorta LUCENE-1907) make non-static class and expose this squaring via a nice method to subclasses?
return QueryWeight * QueryWeight; // sum of squared weights
}
public override void Normalize(float queryNorm, float topLevelBoost)
{
this.QueryNorm = queryNorm * topLevelBoost;
QueryWeight *= this.QueryNorm; // normalize query weight
Value = QueryWeight * Idf.Value; // idf for document
}
}
private Explanation ExplainScore(int doc, Explanation freq, IDFStats stats, NumericDocValues norms)
{
Explanation result = new Explanation();
result.Description = "score(doc=" + doc + ",freq=" + freq + "), product of:";
// explain query weight
Explanation queryExpl = new Explanation();
queryExpl.Description = "queryWeight, product of:";
Explanation boostExpl = new Explanation(stats.QueryBoost, "boost");
if (stats.QueryBoost != 1.0f)
{
queryExpl.AddDetail(boostExpl);
}
queryExpl.AddDetail(stats.Idf);
Explanation queryNormExpl = new Explanation(stats.QueryNorm, "queryNorm");
queryExpl.AddDetail(queryNormExpl);
queryExpl.Value = boostExpl.Value * stats.Idf.Value * queryNormExpl.Value;
result.AddDetail(queryExpl);
// explain field weight
Explanation fieldExpl = new Explanation();
fieldExpl.Description = "fieldWeight in " + doc + ", product of:";
Explanation tfExplanation = new Explanation();
tfExplanation.Value = Tf(freq.Value);
tfExplanation.Description = "tf(freq=" + freq.Value + "), with freq of:";
tfExplanation.AddDetail(freq);
fieldExpl.AddDetail(tfExplanation);
fieldExpl.AddDetail(stats.Idf);
Explanation fieldNormExpl = new Explanation();
float fieldNorm = norms != null ? DecodeNormValue(norms.Get(doc)) : 1.0f;
fieldNormExpl.Value = fieldNorm;
fieldNormExpl.Description = "fieldNorm(doc=" + doc + ")";
fieldExpl.AddDetail(fieldNormExpl);
fieldExpl.Value = tfExplanation.Value * stats.Idf.Value * fieldNormExpl.Value;
result.AddDetail(fieldExpl);
// combine them
result.Value = queryExpl.Value * fieldExpl.Value;
if (queryExpl.Value == 1.0f)
{
return fieldExpl;
}
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using SIL.IO;
using SIL.Reporting;
namespace SIL.Settings
{
/// <summary>
/// A custom SettingsProvider implementation functional on both Windows and Linux (the default mono implementation was buggy and incomplete)
/// </summary>
/// <example>
/// var settingsProvider = new CrossPlatformSettingsProvider();
/// //optionally pre-check for problems
/// if(settingsProvider.CheckForErrorsInFile()) ...
/// </example>
public class CrossPlatformSettingsProvider : SettingsProvider, IApplicationSettingsProvider
{
//Protected only for unit testing. I can't get InternalsVisibleTo to work, possibly because of strong naming.
protected const string UserConfigFileName = "user.config";
private static readonly object LockObject = new Object();
protected string UserRoamingLocation = null;
protected string UserLocalLocation = null;
private static string CompanyAndProductPath;
private bool _reportReadingErrorsDirectlyToUser = true;
// May be overridden in a derived class to control where settings are looked for
// when that class is used as the provider. Must do any initialization before calls to GetCompanyAndProductPath,
// that is, before trying to use instances of the relevant settings.
protected virtual string ProductName
{
get { return null; }
}
/// <summary>
/// Indicates if the settings should be saved in roaming or local location, defaulted to false;
/// </summary>
public bool IsRoaming = false;
/// <summary>
/// Where we expect to find the config file. Protected for unit testing.
/// </summary>
protected string UserConfigLocation
{
get { return IsRoaming ? UserRoamingLocation : UserLocalLocation; }
}
private readonly Dictionary<string, string> _renamedSections;
/// <summary>
/// Default constructor for this provider class
/// </summary>
public CrossPlatformSettingsProvider()
{
_renamedSections = new Dictionary<string, string>();
UserRoamingLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
GetFullSettingsPath());
UserLocalLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
GetFullSettingsPath());
// When running multiple builds in parallel we have to use separate directories for
// each build, otherwise some unit tests might fail.
var buildagentSubdir = Environment.GetEnvironmentVariable("BUILDAGENT_SUBKEY");
if (!string.IsNullOrEmpty(buildagentSubdir))
{
UserRoamingLocation = Path.Combine(UserRoamingLocation, buildagentSubdir);
UserLocalLocation = Path.Combine(UserLocalLocation, buildagentSubdir);
}
}
/// <summary>
/// This Settings Provider will automatically delete a corrupted settings file, silently.
/// If you want to control when it does that, and get a message describing the problem
/// so that you can tell the user, call this before anything else touches the settings.
/// </summary>
/// <returns>an exception or null</returns>
public Exception CheckForErrorsInSettingsFile()
{
if(!_initialized)
throw new ApplicationException("CrossPlatformSettingsProvider: Call Initialize() before CheckForErrorsInFile()");
_reportReadingErrorsDirectlyToUser = false;
var dummy =SettingsXml;
return _lastReadingError;
}
public IDictionary<string, string> RenamedSections
{
get { return _renamedSections; }
}
public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
{
// ReSharper disable ConditionIsAlwaysTrueOrFalse
if(name != null && config != null) //ReSharper lies
// ReSharper restore ConditionIsAlwaysTrueOrFalse
{
base.Initialize(name, config);
}
_initialized = true;
}
private string GetFullSettingsPath()
{
var assembly = Assembly.GetEntryAssembly() ?? Assembly.GetCallingAssembly();
var basePath = GetCompanyAndProductPath(assembly);
CompanyAndProductPath = basePath;
return Path.Combine(basePath, assembly.GetName().Version.ToString());
}
private string GetCompanyAndProductPath(Assembly assembly)
{
var companyAttributes =
(AssemblyCompanyAttribute[])assembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), true);
var companyName = "NoCompanyNameInAssemblyInfo";
var productName = "NoProductNameInAssemblyInfo";
if(companyAttributes.Length > 0)
{
companyName = companyAttributes[0].Company;
}
if (ProductName != null)
productName = ProductName;
else
{
var productAttributes =
(AssemblyProductAttribute[])assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), true);
if(productAttributes.Length > 0)
{
productName = productAttributes[0].Product;
}
}
return Path.Combine(companyName, productName);
}
public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection collection)
{
lock(LockObject)
{
//Create new collection of values
var values = new SettingsPropertyValueCollection();
//Iterate through the settings to be retrieved
foreach(SettingsProperty setting in collection)
{
var value = new SettingsPropertyValue(setting);
value.IsDirty = false;
value.SerializedValue = GetValue(SettingsXml, context["GroupName"].ToString(), setting);
values.Add(value);
}
return values;
}
}
public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection)
{
lock(LockObject)
{
// We need to forget any cached version of the XML. Otherwise, when more than one lot of settings
// is saved in the same file, the provider that is doing the save for one of them may have stale
// (or missing) settings for the other. We want to write the dirty properties over a current
// version of everything else that has been saved in the file.
_settingsXml = null;
//Iterate through the settings to be stored, only dirty settings for this provider are in collection
foreach(SettingsPropertyValue propval in collection)
{
var groupName = context["GroupName"].ToString();
var groupNode = SettingsXml.SelectSingleNode("/configuration/userSettings/" + context["GroupName"]);
if(groupNode == null)
{
var parentNode = SettingsXml.SelectSingleNode("/configuration/userSettings");
groupNode = SettingsXml.CreateElement(groupName);
parentNode.AppendChild(groupNode);
}
var section = (XmlElement)SettingsXml.SelectSingleNode("/configuration/configSections/sectionGroup/section");
if(section == null)
{
var parentNode = SettingsXml.SelectSingleNode("/configuration/configSections/sectionGroup");
section = SettingsXml.CreateElement("section");
section.SetAttribute("name", groupName);
section.SetAttribute("type", String.Format("{0}, {1}", typeof(ClientSettingsSection), Assembly.GetAssembly(typeof(ClientSettingsSection))));
parentNode.AppendChild(section);
}
SetValue(groupNode, propval);
}
Directory.CreateDirectory(UserConfigLocation);
RobustIO.SaveXml(SettingsXml, Path.Combine(UserConfigLocation, UserConfigFileName));
}
}
private void SetValue(XmlNode groupNode, SettingsPropertyValue propVal)
{
// Paranoid check on data coming from .NET or Mono
if(propVal == null)
{
return;
}
XmlElement settingNode;
try
{
settingNode = (XmlElement)groupNode.SelectSingleNode("setting[@name='" + propVal.Name + "']");
}
catch(Exception)
{
settingNode = null;
}
//Check to see if the node exists, if so then set its new value
if(settingNode != null)
{
var valueNode = (XmlElement)settingNode.SelectSingleNode("value");
SetValueNodeContentsFromProp(propVal, valueNode);
}
else
{
settingNode = SettingsXml.CreateElement("setting");
settingNode.SetAttribute("name", propVal.Name);
settingNode.SetAttribute("serializeAs", propVal.Property.SerializeAs.ToString());
var valueNode = SettingsXml.CreateElement("value");
SetValueNodeContentsFromProp(propVal, valueNode);
settingNode.AppendChild(valueNode);
groupNode.AppendChild(settingNode);
}
}
private void SetValueNodeContentsFromProp(SettingsPropertyValue propVal, XmlElement valueNode)
{
if(valueNode == null)
{
throw new ArgumentNullException("valueNode");
}
if(propVal.Property.SerializeAs == SettingsSerializeAs.String)
{
// In some cases the serialized value in the propVal can return null.
// Set the contents of the setting xml to the empty string in that case.
var serializedValue = propVal.SerializedValue;
valueNode.InnerText = serializedValue != null ? serializedValue.ToString() : String.Empty;
}
else if(propVal.Property.SerializeAs == SettingsSerializeAs.Xml)
{
if(!String.IsNullOrEmpty(propVal.SerializedValue as String))
{
var subDoc = new XmlDocument();
subDoc.LoadXml((string)propVal.SerializedValue);
if(valueNode.FirstChild != null)
{
valueNode.RemoveChild(valueNode.FirstChild);
}
valueNode.AppendChild(SettingsXml.ImportNode(subDoc.DocumentElement, true));
}
}
else
{
throw new NotImplementedException("CrossPlatformSettingsProvider does not yet handle settings of "+
propVal.Property.SerializeAs);
}
}
public override string Name
{
get
{
return @"CrossPlatformLocalFileSettingsProvider";
}
}
public override string Description
{
get { return "@WorkingLocalFileProviderForWinAndMono"; }
}
public override string ApplicationName
{
get
{
var assembly = Assembly.GetEntryAssembly() ?? Assembly.GetCallingAssembly();
var assemblyAttributes = (AssemblyProductAttribute[])assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), true);
var appName = @"Product not set in AssemblyInfo";
if(assemblyAttributes.Length > 0)
{
appName = assemblyAttributes[0].Product;
}
return appName;
}
set { } //Do nothing
}
public SettingsPropertyValue GetPreviousVersion(SettingsContext context, SettingsProperty property)
{
var document = GetPreviousSettingsXml();
if(document == null)
{
return null;
}
var value = new SettingsPropertyValue(property);
value.IsDirty = false;
value.SerializedValue = GetValue(document, context["GroupName"].ToString(), property);
return value;
}
/// <summary>
/// Return the previous version settings document if there is one, otherwise null.
/// </summary>
/// <returns></returns>
private static XmlDocument GetPreviousSettingsXml()
{
XmlDocument document = null;
var appSettingsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
CompanyAndProductPath);
if(Directory.Exists(appSettingsPath))
{
var directoryList =
new List<string>(
Directory.EnumerateDirectories(appSettingsPath));
if(directoryList.Count > 0)
{
var assembly = Assembly.GetEntryAssembly() ?? Assembly.GetCallingAssembly();
directoryList.Sort(VersionDirectoryComparison);
var previousDirectory = directoryList[0];
if(previousDirectory.EndsWith(assembly.GetName().Version.ToString()))
{
if (directoryList.Count == 1)
{
// The only directory is for the current version; no need to upgrade.
return null;
}
previousDirectory = directoryList[1];
}
var settingsLocation = Path.Combine(previousDirectory, UserConfigFileName);
if(File.Exists(settingsLocation))
{
document = new XmlDocument();
try
{
document.Load(settingsLocation);
}
catch(Exception)
{
//Don't blow up if we can't load old settings, just lose them.
document = null;
Console.WriteLine(@"Failed to load old settings file.");
}
}
}
}
return document;
}
/// <summary>
/// Returns the directories in order based on finding the most recently modified user.config file (putting that first).
/// More specifically, a folder with a config file is 'less than' one that has none; if both have config files,
/// the most recently modified is less than the other.
/// This allows a new install to inherit settings from whatever pre-existing settings were last modified.
/// This in turn allows settings to be inherited across channels (like BloomAlpha and BloomSHRP) that may have
/// different version number sequences, and still a new install will get the most recent settings from any
/// previous versions. It works even if the version numbers are not in a consistent order.
/// </summary>
/// <remarks>Protected only for unit testing. I can't get InternalsVisibleTo to work, possibly because of strong naming.</remarks>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns></returns>
protected static int VersionDirectoryComparison(string first, string second)
{
var firstConfigPath = Path.Combine(first, UserConfigFileName);
var secondConfigPath = Path.Combine(second, UserConfigFileName);
if (!File.Exists(firstConfigPath))
{
if (File.Exists(secondConfigPath))
return 1; // second is 'less' (comes first)
return first.CompareTo(second); // arbitrary since neither is any use, but give a consistent result.
}
if (!File.Exists(secondConfigPath))
return -1; // first is less (comes first).
// Reversing the arguments like this means that second comes before first if it has a LARGER mod time.
return new FileInfo(secondConfigPath).LastWriteTimeUtc.CompareTo(new FileInfo(firstConfigPath).LastWriteTimeUtc);
}
/// <summary>
/// Verifies that each property has its provider set to <see cref="CrossPlatformSettingsProvider"/>
/// </summary>
public static void ValidateProperties(SettingsPropertyCollection properties)
{
foreach (SettingsProperty property in properties)
{
Debug.Assert(property.Provider is CrossPlatformSettingsProvider,
$"Property '{property.Name}' needs the Provider string set to {typeof(CrossPlatformSettingsProvider)}");
}
}
public void Reset(SettingsContext context)
{
lock(LockObject)
{
_settingsXml = null;
File.Delete(Path.Combine(UserConfigLocation, UserConfigFileName));
}
}
public void Upgrade(SettingsContext context, SettingsPropertyCollection properties)
{
lock (LockObject)
{
XmlDocument oldDoc = GetPreviousSettingsXml();
if (oldDoc != null)
{
if (_renamedSections.Count > 0)
{
XmlNode userSettingsNode = oldDoc.SelectSingleNode("configuration/userSettings");
if (userSettingsNode != null)
{
foreach (XmlElement sectionNode in userSettingsNode.ChildNodes.OfType<XmlElement>().ToArray())
{
string newName;
if (_renamedSections.TryGetValue(sectionNode.Name, out newName))
{
XmlElement newSectionNode = oldDoc.CreateElement(newName);
foreach (XmlNode child in sectionNode.ChildNodes)
newSectionNode.AppendChild(child.CloneNode(true));
userSettingsNode.ReplaceChild(newSectionNode, sectionNode);
}
}
}
}
Directory.CreateDirectory(UserConfigLocation);
oldDoc.Save(Path.Combine(UserConfigLocation, UserConfigFileName));
_settingsXml = oldDoc;
}
}
}
private object GetValue(XmlDocument settingsXml, String groupName, SettingsProperty setting)
{
var settingValue = setting.DefaultValue;
var valueNode = settingsXml.SelectSingleNode("configuration/userSettings/" + (String.IsNullOrEmpty(groupName) ? "/" : groupName) + "/setting[@name='" + setting.Name + "']");
if(valueNode != null)
{
if(setting.SerializeAs == SettingsSerializeAs.String)
{
settingValue = valueNode.InnerText;
}
else if(setting.SerializeAs == SettingsSerializeAs.Xml)
{
settingValue = valueNode.FirstChild.InnerXml;
}
}
return settingValue;
}
private XmlDocument _settingsXml;
private bool _initialized;
private XmlException _lastReadingError;
private XmlDocument SettingsXml
{
get
{
lock(LockObject)
{
if(_settingsXml == null)
{
_settingsXml = new XmlDocument();
var userConfigFilePath = Path.Combine(UserConfigLocation, UserConfigFileName);
if(File.Exists(userConfigFilePath))
{
try
{
_settingsXml.Load(Path.Combine(UserConfigLocation, UserConfigFileName));
return _settingsXml;
}
catch (XmlException e)
{
//a partial reading can leave the _settingsXml in a weird state. Start over:
_settingsXml = new XmlDocument();
Logger.WriteError("Problem with contents of " + userConfigFilePath, e);
//This ErrorReport was actually keeping Bloom from starting at all.
//It now calls CheckForErrorsInFile() which lets it control the messaging;
//that also sets this to false.
if(_reportReadingErrorsDirectlyToUser)
ErrorReport.ReportNonFatalExceptionWithMessage(e, "A settings file was corrupted. Some user settings may have been lost.");
_lastReadingError = e;
try
{
File.Copy(userConfigFilePath, userConfigFilePath + ".bad", true);
}
catch (Exception)
{
//not worth dying over
}
try
{
File.Delete(userConfigFilePath);
}
catch (Exception deletionError)
{
Logger.WriteError("Could not delete " + userConfigFilePath, deletionError);
ErrorReport.ReportFatalMessageWithStackTrace("Please delete the configuration file at " + userConfigFilePath + " and then re-run the program.");
throw deletionError;
}
}
}
//If there was no file, or if the file was corrupt create a new document
var dec = _settingsXml.CreateXmlDeclaration("1.0", "utf-8", string.Empty);
_settingsXml.AppendChild(dec);
var nodeRoot = _settingsXml.CreateNode(XmlNodeType.Element, "configuration", "");
var configSections = _settingsXml.CreateNode(XmlNodeType.Element, "configSections", "");
var sectionGroup = _settingsXml.CreateElement("sectionGroup");
sectionGroup.SetAttribute("name", "userSettings");
var userSettingsAssembly = Assembly.GetAssembly(typeof(UserSettingsGroup));
var typeValue = String.Format("{0}, {1}", typeof(UserSettingsGroup), userSettingsAssembly);
sectionGroup.SetAttribute("type", typeValue);
configSections.AppendChild(sectionGroup);
var userSettings = _settingsXml.CreateNode(XmlNodeType.Element, "userSettings", "");
nodeRoot.AppendChild(configSections);
nodeRoot.AppendChild(userSettings);
_settingsXml.AppendChild(nodeRoot);
}
return _settingsXml;
}
}
}
}
}
| |
//
// Paned.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using System.Windows.Markup;
namespace Xwt
{
[BackendType (typeof(IPanedBackend))]
public class Paned: Widget
{
Orientation direction;
Panel panel1;
Panel panel2;
EventHandler positionChanged;
protected new class WidgetBackendHost: Widget.WidgetBackendHost<Paned,IPanedBackend>, IContainerEventSink<Panel>, IPanedEventSink
{
protected override IBackend OnCreateBackend ()
{
IPanedBackend b = (IPanedBackend) base.OnCreateBackend ();
// We always want to listen this event because we use it
// to reallocate the children
if (!EngineBackend.HandlesSizeNegotiation)
b.EnableEvent (PanedEvent.PositionChanged);
return b;
}
protected override void OnBackendCreated ()
{
Backend.Initialize (Parent.direction);
base.OnBackendCreated ();
}
public void ChildChanged (Panel child, string hint)
{
((Paned)Parent).OnChildChanged (child, hint);
}
public void ChildReplaced (Panel child, Widget oldWidget, Widget newWidget)
{
((Paned)Parent).OnReplaceChild (child, oldWidget, newWidget);
}
public void OnPositionChanged ()
{
((Paned)Parent).NotifyPositionChanged ();
}
}
static Paned ()
{
MapEvent (PanedEvent.PositionChanged, typeof(Paned), "OnPositionChanged");
}
internal Paned (Orientation direction)
{
this.direction = direction;
panel1 = new Panel ((WidgetBackendHost)BackendHost, 1);
panel2 = new Panel ((WidgetBackendHost)BackendHost, 2);
}
protected override BackendHost CreateBackendHost ()
{
return new WidgetBackendHost ();
}
IPanedBackend Backend {
get { return (IPanedBackend) BackendHost.Backend; }
}
/// <summary>
/// Left or top panel
/// </summary>
public Panel Panel1 {
get { return panel1; }
}
/// <summary>
/// Right or bottom panel
/// </summary>
public Panel Panel2 {
get { return panel2; }
}
/// <summary>
/// Gets or sets the position of the panel separator
/// </summary>
/// <value>
/// The position.
/// </value>
public double Position {
get { return Backend.Position; }
set { Backend.Position = value; }
}
/// <summary>
/// Gets or sets the position of the panel separator as a fraction available size
/// </summary>
/// <value>
/// The position.
/// </value>
public double PositionFraction {
get {
return Backend.Position / ((direction == Orientation.Horizontal) ? ScreenBounds.Width : ScreenBounds.Height);
}
set { Backend.Position = ((direction == Orientation.Horizontal) ? ScreenBounds.Width : ScreenBounds.Height) * value; }
}
void OnReplaceChild (Panel panel, Widget oldChild, Widget newChild)
{
if (oldChild != null) {
Backend.RemovePanel (panel.NumPanel);
UnregisterChild (oldChild);
}
if (newChild != null) {
RegisterChild (newChild);
Backend.SetPanel (panel.NumPanel, (IWidgetBackend)GetBackend (newChild), panel.Resize, panel.Shrink);
UpdatePanel (panel);
}
}
/// <summary>
/// Removes a child widget
/// </summary>
/// <param name='child'>
/// A widget bound to one of the panels
/// </param>
public void Remove (Widget child)
{
if (panel1.Content == child)
panel1.Content = null;
else if (panel2.Content == child)
panel2.Content = null;
}
void OnChildChanged (Panel panel, object hint)
{
UpdatePanel (panel);
}
void UpdatePanel (Panel panel)
{
Backend.UpdatePanel (panel.NumPanel, panel.Resize, panel.Shrink);
}
void NotifyPositionChanged ()
{
if (!BackendHost.EngineBackend.HandlesSizeNegotiation) {
if (panel1.Content != null)
panel1.Content.Surface.Reallocate ();
if (panel2.Content != null)
panel2.Content.Surface.Reallocate ();
}
OnPositionChanged ();
}
protected virtual void OnPositionChanged ()
{
if (positionChanged != null)
positionChanged (this, EventArgs.Empty);
}
public event EventHandler PositionChanged {
add {
BackendHost.OnBeforeEventAdd (PanedEvent.PositionChanged, positionChanged);
positionChanged += value;
}
remove {
positionChanged -= value;
BackendHost.OnAfterEventRemove (PanedEvent.PositionChanged, positionChanged);
}
}
}
[ContentProperty("Child")]
public class Panel
{
IContainerEventSink<Panel> parent;
bool resize;
bool shrink;
int numPanel;
Widget child;
internal Panel (IContainerEventSink<Panel> parent, int numPanel)
{
this.parent = parent;
this.numPanel = numPanel;
}
/// <summary>
/// Gets or sets a value indicating whether this panel should be resized when the Paned container is resized.
/// </summary>
/// <value>
/// <c>true</c> if the panel has to be resized; otherwise, <c>false</c>.
/// </value>
public bool Resize {
get {
return this.resize;
}
set {
resize = value;
parent.ChildChanged (this, "Resize");
}
}
/// <summary>
/// Gets or sets a value indicating whether this panel can be made smaller than its min size
/// </summary>
/// <value>
/// <c>true</c> if the panel has to be shrinked; otherwise, <c>false</c>.
/// </value>
public bool Shrink {
get {
return this.shrink;
}
set {
shrink = value;
parent.ChildChanged (this, "Shrink");
}
}
/// <summary>
/// Gets or sets the content of the panel
/// </summary>
/// <value>
/// The content.
/// </value>
public Widget Content {
get {
return child;
}
set {
var old = child;
child = value;
parent.ChildReplaced (this, old, value);
}
}
internal int NumPanel {
get {
return this.numPanel;
}
set {
numPanel = value;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using WebApiFormat.Areas.HelpPage.ModelDescriptions;
using WebApiFormat.Areas.HelpPage.Models;
namespace WebApiFormat.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.