context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
*/
/*
** Author: Eric Veach, July 1994.
// C# Port port by: Lars Brubaker
// larsbrubaker@gmail.com
// Copyright (C) 2007
**
*/
namespace Manssiere.Core.Graphics.Tesselation.Tesselator
{
using System;
using C5;
public class Tesselator
{
/* The begin/end calls must be properly nested. We keep track of
* the current state to enforce the ordering.
*/
#region Delegates
public delegate void CallBeginDelegate(TriangleListType type);
public delegate void CallCombineDelegate(double[] coords3, int[] data4,
double[] weight4, out int outData);
public delegate void CallEdgeFlagDelegate(bool boundaryEdge);
public delegate void CallEndDelegate();
public delegate void CallMeshDelegate(Mesh mesh);
public delegate void CallVertexDelegate(int data);
#endregion
#region TriangleListType enum
public enum TriangleListType
{
LineLoop,
Triangles,
TriangleStrip,
TriangleFan
}
#endregion
#region WindingRuleType enum
public enum WindingRuleType
{
Odd,
NonZero,
Positive,
Negative,
ABS_GEQ_Two,
}
#endregion
private const int MAX_CACHE_SIZE = 100;
public const double MAX_COORD = 1.0e150;
private bool boundaryOnly; /* Extract contours, not triangles */
public int cacheCount; /* number of cached vertices */
public ContourVertex currentSweepVertex; /* current sweep event being processed */
public Dictionary edgeDictionary; /* edge dictionary for sweep line */
private bool emptyCache; /* empty cache on next vertex() call */
private HalfEdge lastHalfEdge; /* lastEdge.Org is the most recent vertex */
public Face lonelyTriList;
public Mesh mesh; /* stores the input contours, and eventually the tessellation itself */
private ProcessingState processingState; /* what begin/end calls have we seen? */
public VertexAndIndex[] simpleVertexCache = new VertexAndIndex[MAX_CACHE_SIZE]; /* the vertex data */
public IntervalHeap<ContourVertex> vertexPriorityQue = new IntervalHeap<ContourVertex>();
public WindingRuleType windingRule; // rule for determining polygon interior
public Tesselator()
{
/* Only initialize fields which can be changed by the api. Other fields
* are initialized where they are used.
*/
processingState = ProcessingState.Dormant;
windingRule = WindingRuleType.NonZero;
boundaryOnly = false;
}
public bool EdgeCallBackSet
{
get { return callEdgeFlag != null; }
}
public WindingRuleType WindingRule
{
get { return windingRule; }
set { windingRule = value; }
}
public bool BoundaryOnly
{
get { return boundaryOnly; }
set { boundaryOnly = value; }
}
public event CallCombineDelegate callCombine;
/*** state needed for rendering callbacks (see render.c) ***/
public event CallBeginDelegate callBegin;
public event CallEdgeFlagDelegate callEdgeFlag;
public event CallVertexDelegate callVertex;
public event CallEndDelegate callEnd;
public event CallMeshDelegate callMesh;
/*** state needed to cache single-contour polygons for renderCache() */
~Tesselator()
{
RequireState(ProcessingState.Dormant);
}
public bool IsWindingInside(int numCrossings)
{
switch (windingRule)
{
case WindingRuleType.Odd:
return (numCrossings & 1) != 0;
case WindingRuleType.NonZero:
return (numCrossings != 0);
case WindingRuleType.Positive:
return (numCrossings > 0);
case WindingRuleType.Negative:
return (numCrossings < 0);
case WindingRuleType.ABS_GEQ_Two:
return (numCrossings >= 2) || (numCrossings <= -2);
}
throw new Exception();
}
public void CallBegin(TriangleListType triangleType)
{
if (callBegin != null)
{
callBegin(triangleType);
}
}
public void CallVertex(int vertexData)
{
if (callVertex != null)
{
callVertex(vertexData);
}
}
public void CallEdegFlag(bool edgeState)
{
if (callEdgeFlag != null)
{
callEdgeFlag(edgeState);
}
}
public void CallEnd()
{
if (callEnd != null)
{
callEnd();
}
}
public void CallCombine(double[] coords3, int[] data4,
double[] weight4, out int outData)
{
outData = 0;
if (callCombine != null)
{
callCombine(coords3, data4, weight4, out outData);
}
}
private void GotoState(ProcessingState newProcessingState)
{
while (processingState != newProcessingState)
{
/* We change the current state one level at a time, to get to
* the desired state.
*/
if (processingState < newProcessingState)
{
switch (processingState)
{
case ProcessingState.Dormant:
throw new Exception("MISSING_BEGIN_POLYGON");
case ProcessingState.InPolygon:
throw new Exception("MISSING_BEGIN_CONTOUR");
default:
break;
}
}
else
{
switch (processingState)
{
case ProcessingState.InContour:
throw new Exception("MISSING_END_CONTOUR");
case ProcessingState.InPolygon:
throw new Exception("MISSING_END_POLYGON");
default:
break;
}
}
}
}
private void RequireState(ProcessingState state)
{
if (processingState != state)
{
GotoState(state);
}
}
public virtual void BeginPolygon()
{
RequireState(ProcessingState.Dormant);
processingState = ProcessingState.InPolygon;
cacheCount = 0;
emptyCache = false;
mesh = null;
}
public void BeginContour()
{
RequireState(ProcessingState.InPolygon);
processingState = ProcessingState.InContour;
lastHalfEdge = null;
if (cacheCount > 0)
{
// Just set a flag so we don't get confused by empty contours
emptyCache = true;
}
}
private bool AddVertex(double x, double y, int data)
{
HalfEdge e;
e = lastHalfEdge;
if (e == null)
{
/* Make a self-loop (one vertex, one edge). */
e = mesh.MakeEdge();
Mesh.meshSplice(e, e.otherHalfOfThisEdge);
}
else
{
/* Create a new vertex and edge which immediately follow e
* in the ordering around the left face.
*/
if (Mesh.meshSplitEdge(e) == null)
{
return false;
}
e = e.nextEdgeCCWAroundLeftFace;
}
/* The new vertex is now e.Org. */
e.originVertex.clientIndex = data;
e.originVertex.coords[0] = x;
e.originVertex.coords[1] = y;
/* The winding of an edge says how the winding number changes as we
* cross from the edge''s right face to its left face. We add the
* vertices in such an order that a CCW contour will add +1 to
* the winding number of the region inside the contour.
*/
e.winding = 1;
e.otherHalfOfThisEdge.winding = -1;
lastHalfEdge = e;
return true;
}
public void EmptyCache()
{
VertexAndIndex[] v = simpleVertexCache;
mesh = new Mesh();
for (int i = 0; i < cacheCount; i++)
{
AddVertex(v[i].x, v[i].y, v[i].vertexIndex);
}
cacheCount = 0;
emptyCache = false;
}
private void CacheVertex(double[] coords3, int data)
{
simpleVertexCache[cacheCount].vertexIndex = data;
simpleVertexCache[cacheCount].x = coords3[0];
simpleVertexCache[cacheCount].y = coords3[1];
++cacheCount;
}
public void AddVertex(double[] coords3, int data)
{
int i;
double x;
var clamped = new double[3];
RequireState(ProcessingState.InContour);
if (emptyCache)
{
EmptyCache();
lastHalfEdge = null;
}
for (i = 0; i < 3; ++i)
{
x = coords3[i];
if (x < -MAX_COORD)
{
throw new Exception("Your coordinate exceeded -" + MAX_COORD + ".");
}
if (x > MAX_COORD)
{
throw new Exception("Your coordinate exceeded " + MAX_COORD + ".");
}
clamped[i] = x;
}
if (mesh == null)
{
if (cacheCount < MAX_CACHE_SIZE)
{
CacheVertex(clamped, data);
return;
}
EmptyCache();
}
AddVertex(clamped[0], clamped[1], data);
}
public void EndContour()
{
RequireState(ProcessingState.InContour);
processingState = ProcessingState.InPolygon;
}
private void CheckOrientation()
{
double area;
Face curFace, faceHead = mesh.faceHead;
ContourVertex vHead = mesh.vertexHead;
HalfEdge curHalfEdge;
/* When we compute the normal automatically, we choose the orientation
* so that the the sum of the signed areas of all contours is non-negative.
*/
area = 0;
for (curFace = faceHead.nextFace; curFace != faceHead; curFace = curFace.nextFace)
{
curHalfEdge = curFace.halfEdgeThisIsLeftFaceOf;
if (curHalfEdge.winding <= 0)
{
continue;
}
do
{
area += (curHalfEdge.originVertex.x - curHalfEdge.directionVertex.x)
*(curHalfEdge.originVertex.y + curHalfEdge.directionVertex.y);
curHalfEdge = curHalfEdge.nextEdgeCCWAroundLeftFace;
} while (curHalfEdge != curFace.halfEdgeThisIsLeftFaceOf);
}
if (area < 0)
{
/* Reverse the orientation by flipping all the t-coordinates */
for (ContourVertex curVertex = vHead.nextVertex; curVertex != vHead; curVertex = curVertex.nextVertex)
{
curVertex.y = -curVertex.y;
}
}
}
private void ProjectPolygon()
{
ContourVertex v, vHead = mesh.vertexHead;
// Project the vertices onto the sweep plane
for (v = vHead.nextVertex; v != vHead; v = v.nextVertex)
{
v.x = v.coords[0];
v.y = -v.coords[1];
}
CheckOrientation();
}
public void EndPolygon()
{
RequireState(ProcessingState.InPolygon);
processingState = ProcessingState.Dormant;
if (mesh == null)
{
if (!EdgeCallBackSet && callMesh == null)
{
/* Try some special code to make the easy cases go quickly
* (eg. convex polygons). This code does NOT handle multiple contours,
* intersections, edge flags, and of course it does not generate
* an explicit mesh either.
*/
if (RenderCache())
{
return;
}
}
EmptyCache(); /* could've used a label*/
}
/* Determine the polygon normal and project vertices onto the plane
* of the polygon.
*/
ProjectPolygon();
/* __gl_computeInterior( this ) computes the planar arrangement specified
* by the given contours, and further subdivides this arrangement
* into regions. Each region is marked "inside" if it belongs
* to the polygon, according to the rule given by this.windingRule.
* Each interior region is guaranteed to be monotone.
*/
ActiveRegion.ComputeInterior(this);
bool rc = true;
/* If the user wants only the boundary contours, we throw away all edges
* except those which separate the interior from the exterior.
* Otherwise we tessellate all the regions marked "inside".
*/
if (boundaryOnly)
{
rc = mesh.SetWindingNumber(1, true);
}
else
{
rc = mesh.TessellateInterior();
}
mesh.CheckMesh();
if (callBegin != null || callEnd != null
|| callVertex != null || callEdgeFlag != null)
{
if (boundaryOnly)
{
RenderBoundary(mesh); /* output boundary contours */
}
else
{
RenderMesh(mesh); /* output strips and fans */
}
}
if (callMesh != null)
{
/* Throw away the exterior faces, so that all faces are interior.
* This way the user doesn't have to check the "inside" flag,
* and we don't need to even reveal its existence. It also leaves
* the freedom for an implementation to not generate the exterior
* faces in the first place.
*/
mesh.DiscardExterior();
callMesh(mesh); /* user wants the mesh itself */
mesh = null;
return;
}
mesh = null;
}
#region CodeFromRender
/************************ Strips and Fans decomposition ******************/
/* __gl_renderMesh( tess, mesh ) takes a mesh and breaks it into triangle
* fans, strips, and separate triangles. A substantial effort is made
* to use as few rendering primitives as possible (ie. to make the fans
* and strips as large as possible).
*
* The rendering output is provided as callbacks (see the api).
*/
private const int SIGN_INCONSISTENT = 2;
public void RenderMesh(Mesh mesh)
{
Face f;
/* Make a list of separate triangles so we can render them all at once */
lonelyTriList = null;
for (f = mesh.faceHead.nextFace; f != mesh.faceHead; f = f.nextFace)
{
f.marked = false;
}
for (f = mesh.faceHead.nextFace; f != mesh.faceHead; f = f.nextFace)
{
/* We examine all faces in an arbitrary order. Whenever we find
* an unprocessed face F, we output a group of faces including F
* whose size is maximum.
*/
if (f.isInterior && !f.marked)
{
RenderMaximumFaceGroup(f);
if (!f.marked)
{
throw new Exception();
}
}
}
if (lonelyTriList != null)
{
RenderLonelyTriangles(lonelyTriList);
lonelyTriList = null;
}
}
private void RenderMaximumFaceGroup(Face fOrig)
{
/* We want to find the largest triangle fan or strip of unmarked faces
* which includes the given face fOrig. There are 3 possible fans
* passing through fOrig (one centered at each vertex), and 3 possible
* strips (one for each CCW permutation of the vertices). Our strategy
* is to try all of these, and take the primitive which uses the most
* triangles (a greedy approach).
*/
HalfEdge e = fOrig.halfEdgeThisIsLeftFaceOf;
var max = new FaceCount(1, e, RenderTriangle);
FaceCount newFace;
max.size = 1;
max.eStart = e;
if (!EdgeCallBackSet)
{
newFace = MaximumFan(e);
if (newFace.size > max.size)
{
max = newFace;
}
newFace = MaximumFan(e.nextEdgeCCWAroundLeftFace);
if (newFace.size > max.size)
{
max = newFace;
}
newFace = MaximumFan(e.Lprev);
if (newFace.size > max.size)
{
max = newFace;
}
newFace = MaximumStrip(e);
if (newFace.size > max.size)
{
max = newFace;
}
newFace = MaximumStrip(e.nextEdgeCCWAroundLeftFace);
if (newFace.size > max.size)
{
max = newFace;
}
newFace = MaximumStrip(e.Lprev);
if (newFace.size > max.size)
{
max = newFace;
}
}
max.CallRender(this, max.eStart, max.size);
}
private FaceCount MaximumFan(HalfEdge eOrig)
{
/* eOrig.Lface is the face we want to render. We want to find the size
* of a maximal fan around eOrig.Org. To do this we just walk around
* the origin vertex as far as possible in both directions.
*/
var newFace = new FaceCount(0, null, RenderFan);
Face trail = null;
HalfEdge e;
for (e = eOrig; !e.leftFace.Marked(); e = e.nextEdgeCCWAroundOrigin)
{
Face.AddToTrail(ref e.leftFace, ref trail);
++newFace.size;
}
for (e = eOrig; !e.rightFace.Marked(); e = e.Oprev)
{
Face f = e.rightFace;
Face.AddToTrail(ref f, ref trail);
e.rightFace = f;
++newFace.size;
}
newFace.eStart = e;
Face.FreeTrail(ref trail);
return newFace;
}
private bool IsEven(int n)
{
return (((n) & 1) == 0);
}
private FaceCount MaximumStrip(HalfEdge eOrig)
{
/* Here we are looking for a maximal strip that contains the vertices
* eOrig.Org, eOrig.Dst, eOrig.Lnext.Dst (in that order or the
* reverse, such that all triangles are oriented CCW).
*
* Again we walk forward and backward as far as possible. However for
* strips there is a twist: to get CCW orientations, there must be
* an *even* number of triangles in the strip on one side of eOrig.
* We walk the strip starting on a side with an even number of triangles;
* if both side have an odd number, we are forced to shorten one side.
*/
var newFace = new FaceCount(0, null, RenderStrip);
int headSize = 0, tailSize = 0;
Face trail = null;
HalfEdge e, eTail, eHead;
for (e = eOrig; !e.leftFace.Marked(); ++tailSize, e = e.nextEdgeCCWAroundOrigin)
{
Face.AddToTrail(ref e.leftFace, ref trail);
++tailSize;
e = e.Dprev;
if (e.leftFace.Marked()) break;
Face.AddToTrail(ref e.leftFace, ref trail);
}
eTail = e;
for (e = eOrig; !e.rightFace.Marked(); ++headSize, e = e.Dnext)
{
Face f = e.rightFace;
Face.AddToTrail(ref f, ref trail);
e.rightFace = f;
++headSize;
e = e.Oprev;
if (e.rightFace.Marked()) break;
f = e.rightFace;
Face.AddToTrail(ref f, ref trail);
e.rightFace = f;
}
eHead = e;
newFace.size = tailSize + headSize;
if (IsEven(tailSize))
{
newFace.eStart = eTail.otherHalfOfThisEdge;
}
else if (IsEven(headSize))
{
newFace.eStart = eHead;
}
else
{
/* Both sides have odd length, we must shorten one of them. In fact,
* we must start from eHead to guarantee inclusion of eOrig.Lface.
*/
--newFace.size;
newFace.eStart = eHead.nextEdgeCCWAroundOrigin;
}
Face.FreeTrail(ref trail);
return newFace;
}
private void RenderTriangle(Tesselator tess, HalfEdge e, int size)
{
/* Just add the triangle to a triangle list, so we can render all
* the separate triangles at once.
*/
if (size != 1)
{
throw new Exception();
}
Face.AddToTrail(ref e.leftFace, ref lonelyTriList);
}
private void RenderLonelyTriangles(Face f)
{
/* Now we render all the separate triangles which could not be
* grouped into a triangle fan or strip.
*/
HalfEdge e;
bool newState = false;
bool edgeState = false; /* force edge state output for first vertex */
bool sentFirstEdge = false;
CallBegin(TriangleListType.Triangles);
for (; f != null; f = f.trail)
{
/* Loop once for each edge (there will always be 3 edges) */
e = f.halfEdgeThisIsLeftFaceOf;
do
{
if (EdgeCallBackSet)
{
/* Set the "edge state" to TRUE just before we output the
* first vertex of each edge on the polygon boundary.
*/
newState = !e.rightFace.isInterior;
if (edgeState != newState || !sentFirstEdge)
{
sentFirstEdge = true;
edgeState = newState;
CallEdegFlag(edgeState);
}
}
CallVertex(e.originVertex.clientIndex);
e = e.nextEdgeCCWAroundLeftFace;
} while (e != f.halfEdgeThisIsLeftFaceOf);
}
CallEnd();
}
private static void RenderFan(Tesselator tess, HalfEdge e, int size)
{
/* Render as many CCW triangles as possible in a fan starting from
* edge "e". The fan *should* contain exactly "size" triangles
* (otherwise we've goofed up somewhere).
*/
tess.CallBegin(TriangleListType.TriangleFan);
tess.CallVertex(e.originVertex.clientIndex);
tess.CallVertex(e.directionVertex.clientIndex);
while (!e.leftFace.Marked())
{
e.leftFace.marked = true;
--size;
e = e.nextEdgeCCWAroundOrigin;
tess.CallVertex(e.directionVertex.clientIndex);
}
if (size != 0)
{
throw new Exception();
}
tess.CallEnd();
}
private static void RenderStrip(Tesselator tess, HalfEdge halfEdge, int size)
{
/* Render as many CCW triangles as possible in a strip starting from
* edge "e". The strip *should* contain exactly "size" triangles
* (otherwise we've goofed up somewhere).
*/
tess.CallBegin(TriangleListType.TriangleStrip);
tess.CallVertex(halfEdge.originVertex.clientIndex);
tess.CallVertex(halfEdge.directionVertex.clientIndex);
while (!halfEdge.leftFace.Marked())
{
halfEdge.leftFace.marked = true;
--size;
halfEdge = halfEdge.Dprev;
tess.CallVertex(halfEdge.originVertex.clientIndex);
if (halfEdge.leftFace.Marked()) break;
halfEdge.leftFace.marked = true;
--size;
halfEdge = halfEdge.nextEdgeCCWAroundOrigin;
tess.CallVertex(halfEdge.directionVertex.clientIndex);
}
if (size != 0)
{
throw new Exception();
}
tess.CallEnd();
}
/************************ Boundary contour decomposition ******************/
/* Takes a mesh, and outputs one
* contour for each face marked "inside". The rendering output is
* provided as callbacks.
*/
public void RenderBoundary(Mesh mesh)
{
for (Face curFace = mesh.faceHead.nextFace; curFace != mesh.faceHead; curFace = curFace.nextFace)
{
if (curFace.isInterior)
{
CallBegin(TriangleListType.LineLoop);
HalfEdge curHalfEdge = curFace.halfEdgeThisIsLeftFaceOf;
do
{
CallVertex(curHalfEdge.originVertex.clientIndex);
curHalfEdge = curHalfEdge.nextEdgeCCWAroundLeftFace;
} while (curHalfEdge != curFace.halfEdgeThisIsLeftFaceOf);
CallEnd();
}
}
}
/************************ Quick-and-dirty decomposition ******************/
private int ComputeNormal(double[] norm3)
/*
* Check that each triangle in the fan from v0 has a
* consistent orientation with respect to norm3[]. If triangles are
* consistently oriented CCW, return 1; if CW, return -1; if all triangles
* are degenerate return 0; otherwise (no consistent orientation) return
* SIGN_INCONSISTENT.
*/
{
VertexAndIndex[] vCache = simpleVertexCache;
VertexAndIndex v0 = vCache[0];
int vcIndex;
double dot, xc, yc, xp, yp;
var n = new double[3];
int sign = 0;
/* Find the polygon normal. It is important to get a reasonable
* normal even when the polygon is self-intersecting (eg. a bowtie).
* Otherwise, the computed normal could be very tiny, but perpendicular
* to the true plane of the polygon due to numerical noise. Then all
* the triangles would appear to be degenerate and we would incorrectly
* decompose the polygon as a fan (or simply not render it at all).
*
* We use a sum-of-triangles normal algorithm rather than the more
* efficient sum-of-trapezoids method (used in CheckOrientation()
* in normal.c). This lets us explicitly reverse the signed area
* of some triangles to get a reasonable normal in the self-intersecting
* case.
*/
vcIndex = 1;
xc = vCache[vcIndex].x - v0.x;
yc = vCache[vcIndex].y - v0.y;
while (++vcIndex < cacheCount)
{
xp = xc;
yp = yc;
xc = vCache[vcIndex].x - v0.x;
yc = vCache[vcIndex].y - v0.y;
/* Compute (vp - v0) cross (vc - v0) */
n[0] = 0;
n[1] = 0;
n[2] = xp*yc - yp*xc;
dot = n[0]*norm3[0] + n[1]*norm3[1] + n[2]*norm3[2];
if (dot != 0)
{
/* Check the new orientation for consistency with previous triangles */
if (dot > 0)
{
if (sign < 0)
{
return SIGN_INCONSISTENT;
}
sign = 1;
}
else
{
if (sign > 0)
{
return SIGN_INCONSISTENT;
}
sign = -1;
}
}
}
return sign;
}
/* Takes a single contour and tries to render it
* as a triangle fan. This handles convex polygons, as well as some
* non-convex polygons if we get lucky.
*
* Returns TRUE if the polygon was successfully rendered. The rendering
* output is provided as callbacks (see the api).
*/
public bool RenderCache()
{
VertexAndIndex[] vCache = simpleVertexCache;
VertexAndIndex v0 = vCache[0];
var norm3 = new double[3];
int sign;
if (cacheCount < 3)
{
/* Degenerate contour -- no output */
return true;
}
norm3[0] = 0;
norm3[1] = 0;
norm3[2] = 1;
sign = ComputeNormal(norm3);
if (sign == SIGN_INCONSISTENT)
{
// Fan triangles did not have a consistent orientation
return false;
}
if (sign == 0)
{
// All triangles were degenerate
return true;
}
/* Make sure we do the right thing for each winding rule */
switch (windingRule)
{
case WindingRuleType.Odd:
case WindingRuleType.NonZero:
break;
case WindingRuleType.Positive:
if (sign < 0) return true;
break;
case WindingRuleType.Negative:
if (sign > 0) return true;
break;
case WindingRuleType.ABS_GEQ_Two:
return true;
}
CallBegin(BoundaryOnly
? TriangleListType.LineLoop
: (cacheCount > 3)
? TriangleListType.TriangleFan
: TriangleListType.Triangles);
CallVertex(v0.vertexIndex);
if (sign > 0)
{
for (int vcIndex = 1; vcIndex < cacheCount; ++vcIndex)
{
CallVertex(vCache[vcIndex].vertexIndex);
}
}
else
{
for (int vcIndex = cacheCount - 1; vcIndex > 0; --vcIndex)
{
CallVertex(vCache[vcIndex].vertexIndex);
}
}
CallEnd();
return true;
}
private class FaceCount
{
#region Delegates
public delegate void RenderDelegate(Tesselator tess, HalfEdge edge, int data);
#endregion
public HalfEdge eStart; /* edge where this primitive starts */
public int size; /* number of triangles used */
public FaceCount(int _size, HalfEdge _eStart, RenderDelegate _render)
{
size = _size;
eStart = _eStart;
render = _render;
}
private event RenderDelegate render;
// routine to render this primitive
public void CallRender(Tesselator tess, HalfEdge edge, int data)
{
render(tess, edge, data);
}
} ;
#endregion
#region Nested type: ProcessingState
private enum ProcessingState
{
Dormant,
InPolygon,
InContour
} ;
#endregion
#region Nested type: Vertex
public struct Vertex
{
public double x;
public double y;
}
#endregion
#region Nested type: VertexAndIndex
public struct VertexAndIndex
{
public int vertexIndex;
public double x;
public double y;
}
#endregion
} ;
}
| |
using NUnit.Framework;
using static NSelene.Selene;
namespace NSelene.Tests.Integration.SharedDriver.SeleneSpec
{
using System;
using System.Linq;
using Harness;
using OpenQA.Selenium;
[TestFixture]
public class SeleneElement_Clear_Specs : BaseTest
{
[Test]
public void Clear_WaitsForVisibility_OfInitiialyAbsent()
{
Configuration.Timeout = 0.6;
Configuration.PollDuringWaits = 0.1;
Given.OpenedEmptyPage();
var beforeCall = DateTime.Now;
Given.OpenedPageWithBodyTimedOut(
@"
<input value='abracadabra'></input>
",
300
);
S("input").Clear();
var afterCall = DateTime.Now;
Assert.AreEqual(
"",
Configuration.Driver
.FindElement(By.TagName("input")).GetAttribute("value")
);
Assert.AreEqual(
"",
Configuration.Driver
.FindElement(By.TagName("input")).GetProperty("value")
);
Assert.Greater(afterCall, beforeCall.AddSeconds(0.3));
Assert.Less(afterCall, beforeCall.AddSeconds(0.6));
}
[Test]
public void Clear_IsRenderedInError_OnAbsentElementFailure()
{
Configuration.Timeout = 0.25;
Configuration.PollDuringWaits = 0.1;
Given.OpenedEmptyPage();
try
{
S("input").Clear();
}
catch (TimeoutException error)
{
// TODO: shoud we check timing here too?
var lines = error.Message.Split("\n").Select(
item => item.Trim()
).ToList();
Assert.Contains("Timed out after 0.25s, while waiting for:", lines);
Assert.Contains("Browser.Element(input).ActualWebElement.Clear()", lines);
Assert.Contains("Reason:", lines);
Assert.Contains(
"no such element: Unable to locate element: "
+ "{\"method\":\"css selector\",\"selector\":\"input\"}"
,
lines
);
}
}
[Test]
public void Clear_IsRenderedInError_OnAbsentElementFailure_WhenCustomizedToWaitForNoOverlapFoundByJs()
{
Configuration.Timeout = 0.25;
Configuration.PollDuringWaits = 0.1;
Given.OpenedEmptyPage();
try
{
S("input").With(waitForNoOverlapFoundByJs: true).Clear();
}
catch (TimeoutException error)
{
// TODO: shoud we check timing here too?
var lines = error.Message.Split("\n").Select(
item => item.Trim()
).ToList();
Assert.Contains("Timed out after 0.25s, while waiting for:", lines);
Assert.Contains("Browser.Element(input).ActualNotOverlappedWebElement.Clear()", lines);
Assert.Contains("Reason:", lines);
Assert.Contains(
"no such element: Unable to locate element: "
+ "{\"method\":\"css selector\",\"selector\":\"input\"}"
,
lines
);
}
}
// [Test]
// public void Clear_PassesOnHidden_IfAllowed() // NOT IMPLEMENTED
// {
// Configuration.Timeout = 0.25;
// Configuration.PollDuringWaits = 0.1;
// Given.OpenedPageWithBody(
// @"
// <input value='abracadabra' style='display:none'></input>
// "
// );
// S("input").Clear();
// Assert.AreEqual(
// "",
// Configuration.Driver
// .FindElement(By.TagName("input")).GetAttribute("value")
// );
// Assert.AreEqual(
// "",
// Configuration.Driver
// .FindElement(By.TagName("input")).GetProperty("value")
// );
// }
[Test]
public void Clear_WaitsForVisibility_OfInitialyHidden()
{
Configuration.Timeout = 0.6;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<input value='abracadabra' style='display:none'></input>
"
);
var beforeCall = DateTime.Now;
Given.ExecuteScriptWithTimeout(
@"
document.getElementsByTagName('input')[0].style.display = 'block';
",
300
);
S("input").Clear();
var afterCall = DateTime.Now;
Assert.AreEqual(
"",
Configuration.Driver
.FindElement(By.TagName("input")).GetAttribute("value")
);
Assert.AreEqual(
"",
Configuration.Driver
.FindElement(By.TagName("input")).GetProperty("value")
);
Assert.Greater(afterCall, beforeCall.AddSeconds(0.3));
Assert.Less(afterCall, beforeCall.AddSeconds(0.6));
}
[Test]
public void Clear_IsRenderedInError_OnHiddenElementFailure()
{
Configuration.Timeout = 0.25;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<input value='abracadabra' style='display:none'></input>
"
);
try
{
S("input").Clear();
}
catch (TimeoutException error)
{
var lines = error.Message.Split("\n").Select(
item => item.Trim()
).ToList();
Assert.Contains("Timed out after 0.25s, while waiting for:", lines);
Assert.Contains("Browser.Element(input).ActualWebElement.Clear()", lines);
Assert.Contains("Reason:", lines);
Assert.Contains("element not interactable", lines);
Assert.AreEqual(
"abracadabra",
Configuration.Driver
.FindElement(By.TagName("input")).GetAttribute("value")
);
Assert.AreEqual(
"abracadabra",
Configuration.Driver
.FindElement(By.TagName("input")).GetProperty("value")
);
}
}
[Test]
public void Clear_IsRenderedInError_OnHiddenElementFailure_WhenCustomizedToWaitForNoOverlapFoundByJs()
{
Configuration.Timeout = 0.25;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<input value='abracadabra' style='display:none'></input>
"
);
try
{
S("input").With(waitForNoOverlapFoundByJs: true).Clear();
}
catch (TimeoutException error)
{
var lines = error.Message.Split("\n").Select(
item => item.Trim()
).ToList();
Assert.Contains("Timed out after 0.25s, while waiting for:", lines);
Assert.Contains("Browser.Element(input).ActualNotOverlappedWebElement.Clear()", lines);
Assert.Contains("Reason:", lines);
Assert.Contains("javascript error: element is not visible", lines);
Assert.AreEqual(
"abracadabra",
Configuration.Driver
.FindElement(By.TagName("input")).GetAttribute("value")
);
Assert.AreEqual(
"abracadabra",
Configuration.Driver
.FindElement(By.TagName("input")).GetProperty("value")
);
}
}
[Test]
public void Clear_WorksUnderOverlay_ByDefault()
{
Configuration.Timeout = 1.0;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<div
id='overlay'
style='
display:block;
position: fixed;
display: block;
width: 100%;
height: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.1);
z-index: 2;
cursor: pointer;
'
>
</div>
<input value='abracadabra'></input>
"
);
var beforeCall = DateTime.Now;
S("input").Clear();
var afterCall = DateTime.Now;
Assert.Less(afterCall, beforeCall.AddSeconds(0.5));
Assert.AreEqual(
"",
Configuration.Driver
.FindElement(By.TagName("input")).GetAttribute("value")
);
Assert.AreEqual(
"",
Configuration.Driver
.FindElement(By.TagName("input")).GetProperty("value")
);
}
[Test]
public void Clear_Waits_For_NoOverlay_WhenCustomized()
{
Configuration.Timeout = 1.0;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<div
id='overlay'
style='
display:block;
position: fixed;
display: block;
width: 100%;
height: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.1);
z-index: 2;
cursor: pointer;
'
>
</div>
<input value='abracadabra'></input>
"
);
var beforeCall = DateTime.Now;
Given.ExecuteScriptWithTimeout(
@"
document.getElementById('overlay').style.display = 'none';
",
300
);
S("input").With(waitForNoOverlapFoundByJs: true).Clear(); // TODO: this overlay works only for "overlayying at center of element", handle the "partial overlay" cases too!
var afterCall = DateTime.Now;
Assert.Greater(afterCall, beforeCall.AddSeconds(0.3));
Assert.Less(afterCall, beforeCall.AddSeconds(1.0));
Assert.AreEqual(
"",
Configuration.Driver
.FindElement(By.TagName("input")).GetAttribute("value")
);
Assert.AreEqual(
"",
Configuration.Driver
.FindElement(By.TagName("input")).GetProperty("value")
);
}
[Test]
public void Clear_IsRenderedInError_OnOverlappedWithOverlayFailure_WhenCustomizedToWaitForNoOverlapFoundByJs()
{
Configuration.Timeout = 0.25;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<div
id='overlay'
style='
display: block;
position: fixed;
display: block;
width: 100%;
height: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.1);
z-index: 2;
cursor: pointer;
'
>
</div>
<input value='abracadabra'></input>
"
);
try
{
S("input").With(waitForNoOverlapFoundByJs: true).Clear();
}
catch (TimeoutException error)
{
var lines = error.Message.Split("\n").Select(
item => item.Trim()
).ToList();
Assert.Contains("Timed out after 0.25s, while waiting for:", lines);
Assert.Contains("Browser.Element(input).ActualNotOverlappedWebElement.Clear()", lines);
Assert.Contains("Reason:", lines);
Assert.Contains("Element: <input value=\"abracadabra\">", lines);
Assert.NotNull(lines.Find(item => item.Contains(
"is overlapped by: <div id=\"overlay\" "
)));
}
}
}
}
| |
// 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.
////////////////////////////////////////////////////////////////////////////////
// JitHelpers
// Low-level Jit Helpers
////////////////////////////////////////////////////////////////////////////////
using System;
using System.Threading;
using System.Runtime;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
namespace System.Runtime.CompilerServices {
// Wrapper for address of a string variable on stack
internal struct StringHandleOnStack
{
private IntPtr m_ptr;
internal StringHandleOnStack(IntPtr pString)
{
m_ptr = pString;
}
}
// Wrapper for address of a object variable on stack
internal struct ObjectHandleOnStack
{
private IntPtr m_ptr;
internal ObjectHandleOnStack(IntPtr pObject)
{
m_ptr = pObject;
}
}
// Wrapper for StackCrawlMark
internal struct StackCrawlMarkHandle
{
private IntPtr m_ptr;
internal StackCrawlMarkHandle(IntPtr stackMark)
{
m_ptr = stackMark;
}
}
// Helper class to assist with unsafe pinning of arbitrary objects. The typical usage pattern is:
// fixed (byte * pData = &JitHelpers.GetPinningHelper(value).m_data)
// {
// ... pData is what Object::GetData() returns in VM ...
// }
internal class PinningHelper
{
public byte m_data;
}
internal class ArrayPinningHelper
{
public IntPtr m_lengthAndPadding;
public byte m_arrayData;
}
[FriendAccessAllowed]
internal static class JitHelpers
{
// The special dll name to be used for DllImport of QCalls
internal const string QCall = "QCall";
// Wraps object variable into a handle. Used to return managed strings from QCalls.
// s has to be a local variable on the stack.
[SecurityCritical]
static internal StringHandleOnStack GetStringHandleOnStack(ref string s)
{
return new StringHandleOnStack(UnsafeCastToStackPointer(ref s));
}
// Wraps object variable into a handle. Used to pass managed object references in and out of QCalls.
// o has to be a local variable on the stack.
[SecurityCritical]
static internal ObjectHandleOnStack GetObjectHandleOnStack<T>(ref T o) where T : class
{
return new ObjectHandleOnStack(UnsafeCastToStackPointer(ref o));
}
// Wraps StackCrawlMark into a handle. Used to pass StackCrawlMark to QCalls.
// stackMark has to be a local variable on the stack.
[SecurityCritical]
static internal StackCrawlMarkHandle GetStackCrawlMarkHandle(ref StackCrawlMark stackMark)
{
return new StackCrawlMarkHandle(UnsafeCastToStackPointer(ref stackMark));
}
#if _DEBUG
[SecurityCritical]
[FriendAccessAllowed]
static internal T UnsafeCast<T>(Object o) where T : class
{
T ret = UnsafeCastInternal<T>(o);
Contract.Assert(ret == (o as T), "Invalid use of JitHelpers.UnsafeCast!");
return ret;
}
// The IL body of this method is not critical, but its body will be replaced with unsafe code, so
// this method is effectively critical
[SecurityCritical]
static private T UnsafeCastInternal<T>(Object o) where T : class
{
// The body of this function will be replaced by the EE with unsafe code that just returns o!!!
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
static internal int UnsafeEnumCast<T>(T val) where T : struct // Actually T must be 4 byte (or less) enum
{
Contract.Assert(typeof(T).IsEnum
&& (Enum.GetUnderlyingType(typeof(T)) == typeof(int)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(uint)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(short)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(ushort)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(byte)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(sbyte)),
"Error, T must be an 4 byte (or less) enum JitHelpers.UnsafeEnumCast!");
return UnsafeEnumCastInternal<T>(val);
}
static private int UnsafeEnumCastInternal<T>(T val) where T : struct // Actually T must be 4 (or less) byte enum
{
// should be return (int) val; but C# does not allow, runtime does this magically
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
static internal long UnsafeEnumCastLong<T>(T val) where T : struct // Actually T must be 8 byte enum
{
Contract.Assert(typeof(T).IsEnum
&& (Enum.GetUnderlyingType(typeof(T)) == typeof(long)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(ulong)),
"Error, T must be an 8 byte enum JitHelpers.UnsafeEnumCastLong!");
return UnsafeEnumCastLongInternal<T>(val);
}
static private long UnsafeEnumCastLongInternal<T>(T val) where T : struct // Actually T must be 8 byte enum
{
// should be return (int) val; but C# does not allow, runtime does this magically
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
// Internal method for getting a raw pointer for handles in JitHelpers.
// The reference has to point into a local stack variable in order so it can not be moved by the GC.
[SecurityCritical]
static internal IntPtr UnsafeCastToStackPointer<T>(ref T val)
{
IntPtr p = UnsafeCastToStackPointerInternal<T>(ref val);
Contract.Assert(IsAddressInStack(p), "Pointer not in the stack!");
return p;
}
[SecurityCritical]
static private IntPtr UnsafeCastToStackPointerInternal<T>(ref T val)
{
// The body of this function will be replaced by the EE with unsafe code that just returns val!!!
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
#else // _DEBUG
// The IL body of this method is not critical, but its body will be replaced with unsafe code, so
// this method is effectively critical
[SecurityCritical]
[FriendAccessAllowed]
static internal T UnsafeCast<T>(Object o) where T : class
{
// The body of this function will be replaced by the EE with unsafe code that just returns o!!!
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
static internal int UnsafeEnumCast<T>(T val) where T : struct // Actually T must be 4 byte (or less) enum
{
// should be return (int) val; but C# does not allow, runtime does this magically
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
static internal long UnsafeEnumCastLong<T>(T val) where T : struct // Actually T must be 8 byte enum
{
// should be return (long) val; but C# does not allow, runtime does this magically
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
[SecurityCritical]
static internal IntPtr UnsafeCastToStackPointer<T>(ref T val)
{
// The body of this function will be replaced by the EE with unsafe code that just returns o!!!
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
#endif // _DEBUG
// Set the given element in the array without any type or range checks
[SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern static internal void UnsafeSetArrayElement(Object[] target, int index, Object element);
// Used for unsafe pinning of arbitrary objects.
[System.Security.SecurityCritical] // auto-generated
static internal PinningHelper GetPinningHelper(Object o)
{
// This cast is really unsafe - call the private version that does not assert in debug
#if _DEBUG
return UnsafeCastInternal<PinningHelper>(o);
#else
return UnsafeCast<PinningHelper>(o);
#endif
}
#if _DEBUG
[SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern static bool IsAddressInStack(IntPtr ptr);
#endif
#if FEATURE_SPAN_OF_T
static internal bool ByRefLessThan<T>(ref T refA, ref T refB)
{
// The body of this function will be replaced by the EE with unsafe code!!!
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
/// <returns>true if given type is reference type or value type that contains references</returns>
static internal bool ContainsReferences<T>()
{
// The body of this function will be replaced by the EE with unsafe code!!!
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
static internal ref T GetArrayData<T>(T[] array)
{
// The body of this function will be replaced by the EE with unsafe code!!!
// See getILIntrinsicImplementation for how this happens.
typeof(ArrayPinningHelper).ToString(); // Type used by the actual method body
throw new InvalidOperationException();
}
#endif // FEATURE_SPAN_OF_T
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public partial class ParallelQueryCombinationTests
{
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Aggregate_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Aggregate((x, y) => x));
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Aggregate(0, (x, y) => x + y));
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Aggregate(0, (x, y) => x + y, r => r));
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Aggregate(0, (a, x) => a + x, (l, r) => l + r, r => r));
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Aggregate(() => 0, (a, x) => a + x, (l, r) => l + r, r => r));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void All_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).All(x => true));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Any_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Any(x => true));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Average_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Average());
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Contains_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Contains(DefaultStart));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Count_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Count());
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).LongCount());
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Count(x => true));
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).LongCount(x => true));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void ElementAt_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, (start, count, ignore) => source.Item(start, count).WithCancellation(cs.Token)).ElementAt(0));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void ElementAtOrDefault_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, (start, count, ignore) => source.Item(start, count).WithCancellation(cs.Token)).ElementAtOrDefault(0));
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, (start, count, ignore) => source.Item(start, count).WithCancellation(cs.Token)).ElementAtOrDefault(DefaultSize + 1));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void First_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).First());
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).First(x => false));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void FirstOrDefault_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).FirstOrDefault());
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).FirstOrDefault(x => false));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void ForAll_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).ForAll(x => { }));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Last_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Last());
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Last(x => true));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void LastOrDefault_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, (start, count, ignore) => source.Item(start, count).WithCancellation(cs.Token)).LastOrDefault());
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).LastOrDefault(x => true));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Max_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, (start, count, ignore) => source.Item(start, count).WithCancellation(cs.Token)).Max());
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Min_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Min());
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void SequenceEqual_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).SequenceEqual(ParallelEnumerable.Range(0, 2)));
Functions.AssertIsCanceled(cs, () => ParallelEnumerable.Range(0, 2).SequenceEqual(operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item)));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Single_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Single());
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Single(x => false));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void SingleOrDefault_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).SingleOrDefault());
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).SingleOrDefault(x => false));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Sum_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Sum());
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void ToArray_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).ToArray());
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void ToDictionary_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).ToDictionary(x => x));
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).ToDictionary(x => x, y => y));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void ToList_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).ToList());
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void ToLookup_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).ToLookup(x => x));
Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).ToLookup(x => x, y => y));
}
}
}
| |
// 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.Security;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace System.IO
{
public partial class FileStream : Stream
{
// This is an internal object extending TaskCompletionSource with fields
// for all of the relevant data necessary to complete the IO operation.
// This is used by IOCallback and all of the async methods.
private unsafe sealed class FileStreamCompletionSource : TaskCompletionSource<int>
{
private const long NoResult = 0;
private const long ResultSuccess = (long)1 << 32;
private const long ResultError = (long)2 << 32;
private const long RegisteringCancellation = (long)4 << 32;
private const long CompletedCallback = (long)8 << 32;
private const ulong ResultMask = ((ulong)uint.MaxValue) << 32;
private static Action<object> s_cancelCallback;
private readonly FileStream _stream;
private readonly int _numBufferedBytes;
private readonly CancellationToken _cancellationToken;
private CancellationTokenRegistration _cancellationRegistration;
#if DEBUG
private bool _cancellationHasBeenRegistered;
#endif
private NativeOverlapped* _overlapped; // Overlapped class responsible for operations in progress when an appdomain unload occurs
private long _result; // Using long since this needs to be used in Interlocked APIs
// Using RunContinuationsAsynchronously for compat reasons (old API used Task.Factory.StartNew for continuations)
internal FileStreamCompletionSource(FileStream stream, int numBufferedBytes, byte[] bytes, CancellationToken cancellationToken)
: base(TaskCreationOptions.RunContinuationsAsynchronously)
{
_numBufferedBytes = numBufferedBytes;
_stream = stream;
_result = NoResult;
_cancellationToken = cancellationToken;
// Create the native overlapped. We try to use the preallocated overlapped if possible:
// it's possible if the byte buffer is the same one that's associated with the preallocated overlapped
// and if no one else is currently using the preallocated overlapped. This is the fast-path for cases
// where the user-provided buffer is smaller than the FileStream's buffer (such that the FileStream's
// buffer is used) and where operations on the FileStream are not being performed concurrently.
_overlapped = ReferenceEquals(bytes, _stream._buffer) && _stream.CompareExchangeCurrentOverlappedOwner(this, null) == null ?
_stream._fileHandle.ThreadPoolBinding.AllocateNativeOverlapped(_stream._preallocatedOverlapped) :
_stream._fileHandle.ThreadPoolBinding.AllocateNativeOverlapped(s_ioCallback, this, bytes);
Debug.Assert(_overlapped != null, "AllocateNativeOverlapped returned null");
}
internal NativeOverlapped* Overlapped
{
[SecurityCritical]get { return _overlapped; }
}
public void SetCompletedSynchronously(int numBytes)
{
ReleaseNativeResource();
TrySetResult(numBytes + _numBufferedBytes);
}
public void RegisterForCancellation()
{
#if DEBUG
Debug.Assert(!_cancellationHasBeenRegistered, "Cannot register for cancellation twice");
_cancellationHasBeenRegistered = true;
#endif
// Quick check to make sure that the cancellation token supports cancellation, and that the IO hasn't completed
if ((_cancellationToken.CanBeCanceled) && (_overlapped != null))
{
var cancelCallback = s_cancelCallback;
if (cancelCallback == null) s_cancelCallback = cancelCallback = Cancel;
// Register the cancellation only if the IO hasn't completed
long packedResult = Interlocked.CompareExchange(ref _result, RegisteringCancellation, NoResult);
if (packedResult == NoResult)
{
_cancellationRegistration = _cancellationToken.Register(cancelCallback, this);
// Switch the result, just in case IO completed while we were setting the registration
packedResult = Interlocked.Exchange(ref _result, NoResult);
}
else if (packedResult != CompletedCallback)
{
// Failed to set the result, IO is in the process of completing
// Attempt to take the packed result
packedResult = Interlocked.Exchange(ref _result, NoResult);
}
// If we have a callback that needs to be completed
if ((packedResult != NoResult) && (packedResult != CompletedCallback) && (packedResult != RegisteringCancellation))
{
CompleteCallback((ulong)packedResult);
}
}
}
internal void ReleaseNativeResource()
{
// Ensure that cancellation has been completed and cleaned up.
_cancellationRegistration.Dispose();
// Free the overlapped.
// NOTE: The cancellation must *NOT* be running at this point, or it may observe freed memory
// (this is why we disposed the registration above).
if (_overlapped != null)
{
_stream._fileHandle.ThreadPoolBinding.FreeNativeOverlapped(_overlapped);
_overlapped = null;
}
// Ensure we're no longer set as the current completion source (we may not have been to begin with).
// Only one operation at a time is eligible to use the preallocated overlapped,
_stream.CompareExchangeCurrentOverlappedOwner(null, this);
}
// When doing IO asynchronously (i.e. _isAsync==true), this callback is
// called by a free thread in the threadpool when the IO operation
// completes.
internal static unsafe void IOCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped)
{
// Extract the completion source from the overlapped. The state in the overlapped
// will either be a Win32FileStream (in the case where the preallocated overlapped was used),
// in which case the operation being completed is its _currentOverlappedOwner, or it'll
// be directly the FileStreamCompletion that's completing (in the case where the preallocated
// overlapped was already in use by another operation).
object state = ThreadPoolBoundHandle.GetNativeOverlappedState(pOverlapped);
FileStream fs = state as FileStream;
FileStreamCompletionSource completionSource = fs != null ?
fs._currentOverlappedOwner :
(FileStreamCompletionSource)state;
Debug.Assert(completionSource._overlapped == pOverlapped, "Overlaps don't match");
// Handle reading from & writing to closed pipes. While I'm not sure
// this is entirely necessary anymore, maybe it's possible for
// an async read on a pipe to be issued and then the pipe is closed,
// returning this error. This may very well be necessary.
ulong packedResult;
if (errorCode != 0 && errorCode != ERROR_BROKEN_PIPE && errorCode != ERROR_NO_DATA)
{
packedResult = ((ulong)ResultError | errorCode);
}
else
{
packedResult = ((ulong)ResultSuccess | numBytes);
}
// Stow the result so that other threads can observe it
// And, if no other thread is registering cancellation, continue
if (NoResult == Interlocked.Exchange(ref completionSource._result, (long)packedResult))
{
// Successfully set the state, attempt to take back the callback
if (Interlocked.Exchange(ref completionSource._result, CompletedCallback) != NoResult)
{
// Successfully got the callback, finish the callback
completionSource.CompleteCallback(packedResult);
}
// else: Some other thread stole the result, so now it is responsible to finish the callback
}
// else: Some other thread is registering a cancellation, so it *must* finish the callback
}
private void CompleteCallback(ulong packedResult) {
// Free up the native resource and cancellation registration
ReleaseNativeResource();
// Unpack the result and send it to the user
long result = (long)(packedResult & ResultMask);
if (result == ResultError)
{
int errorCode = unchecked((int)(packedResult & uint.MaxValue));
if (errorCode == Interop.Errors.ERROR_OPERATION_ABORTED)
{
TrySetCanceled(_cancellationToken.IsCancellationRequested ? _cancellationToken : new CancellationToken(true));
}
else
{
TrySetException(Win32Marshal.GetExceptionForWin32Error(errorCode));
}
}
else
{
Debug.Assert(result == ResultSuccess, "Unknown result");
TrySetResult((int)(packedResult & uint.MaxValue) + _numBufferedBytes);
}
}
private static void Cancel(object state)
{
// WARNING: This may potentially be called under a lock (during cancellation registration)
FileStreamCompletionSource completionSource = state as FileStreamCompletionSource;
Debug.Assert(completionSource != null, "Unknown state passed to cancellation");
Debug.Assert(completionSource._overlapped != null && !completionSource.Task.IsCompleted, "IO should not have completed yet");
// If the handle is still valid, attempt to cancel the IO
if (!completionSource._stream._fileHandle.IsInvalid &&
!Interop.Kernel32.CancelIoEx(completionSource._stream._fileHandle, completionSource._overlapped))
{
int errorCode = Marshal.GetLastWin32Error();
// ERROR_NOT_FOUND is returned if CancelIoEx cannot find the request to cancel.
// This probably means that the IO operation has completed.
if (errorCode != Interop.Errors.ERROR_NOT_FOUND)
{
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
}
}
}
}
| |
// 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.Reflection;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class CallFactoryTests
{
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
public static void CheckCallIsOptimizedInstance(int arity)
{
AssertCallIsOptimizedInstance(arity);
}
[Fact]
public static void CheckCallFactoryOptimisedInstanceNullArgumentList()
{
var instance = Expression.Constant(new MS());
var expr = Expression.Call(instance, typeof(MS).GetMethod(nameof(MS.I0)), default(Expression[]));
AssertInstanceMethodCall(0, expr);
}
[Fact]
public static void CheckCallFactoryOptimizationInstance2()
{
MethodCallExpression expr = Expression.Call(Expression.Parameter(typeof(MS)), typeof(MS).GetMethod("I2"), Expression.Constant(0), Expression.Constant(1));
AssertInstanceMethodCall(2, expr);
}
[Fact]
public static void CheckCallFactoryOptimizationInstance3()
{
MethodCallExpression expr = Expression.Call(Expression.Parameter(typeof(MS)), typeof(MS).GetMethod("I3"), Expression.Constant(0), Expression.Constant(1), Expression.Constant(2));
AssertInstanceMethodCall(3, expr);
}
[Fact]
public static void CheckCallFactoryInstanceN()
{
const int N = 4;
ParameterExpression obj = Expression.Parameter(typeof(MS));
ConstantExpression[] args = Enumerable.Range(0, N).Select(i => Expression.Constant(i)).ToArray();
MethodCallExpression expr = Expression.Call(obj, typeof(MS).GetMethod("I" + N), args);
if (!PlatformDetection.IsNetNative) // .NET Native blocks internal framework reflection.
{
Assert.Equal("InstanceMethodCallExpressionN", expr.GetType().Name);
}
Assert.Same(obj, expr.Object);
Assert.Equal(N, expr.ArgumentCount);
for (var i = 0; i < N; i++)
{
Assert.Same(args[i], expr.GetArgument(i));
}
Collections.ObjectModel.ReadOnlyCollection<Expression> arguments = expr.Arguments;
Assert.Same(arguments, expr.Arguments);
Assert.Equal(N, arguments.Count);
for (var i = 0; i < N; i++)
{
Assert.Same(args[i], arguments[i]);
}
MethodCallExpression updated = expr.Update(obj, arguments.ToList());
Assert.Same(expr, updated);
var visited = (MethodCallExpression)new NopVisitor().Visit(expr);
Assert.Same(expr, visited);
var visitedObj = (MethodCallExpression)new VisitorObj().Visit(expr);
Assert.NotSame(expr, visitedObj);
Assert.NotSame(obj, visitedObj.Object);
Assert.Same(arguments, visitedObj.Arguments);
var visitedArgs = (MethodCallExpression)new VisitorArgs().Visit(expr);
Assert.NotSame(expr, visitedArgs);
Assert.Same(obj, visitedArgs.Object);
Assert.NotSame(arguments, visitedArgs.Arguments);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
[InlineData(4)]
[InlineData(5)]
public static void CheckCallIsOptimizedStatic(int arity)
{
AssertCallIsOptimizedStatic(arity);
}
[Fact]
public static void CheckCallFactoryOptimisedStaticNullArgumentList() =>
AssertStaticMethodCall(0, Expression.Call(typeof(MS).GetMethod(nameof(MS.S0)), default(Expression[])));
[Fact]
public static void CheckCallFactoryOptimizationStatic1()
{
MethodCallExpression expr = Expression.Call(typeof(MS).GetMethod("S1"), Expression.Constant(0));
AssertStaticMethodCall(1, expr);
}
[Fact]
public static void CheckCallFactoryOptimizationStatic2()
{
MethodCallExpression expr1 = Expression.Call(typeof(MS).GetMethod("S2"), Expression.Constant(0), Expression.Constant(1));
MethodCallExpression expr2 = Expression.Call(null, typeof(MS).GetMethod("S2"), Expression.Constant(0), Expression.Constant(1));
AssertStaticMethodCall(2, expr1);
AssertStaticMethodCall(2, expr2);
}
[Fact]
public static void CheckCallFactoryOptimizationStatic3()
{
MethodCallExpression expr1 = Expression.Call(typeof(MS).GetMethod("S3"), Expression.Constant(0), Expression.Constant(1), Expression.Constant(2));
MethodCallExpression expr2 = Expression.Call(null, typeof(MS).GetMethod("S3"), Expression.Constant(0), Expression.Constant(1), Expression.Constant(2));
AssertStaticMethodCall(3, expr1);
AssertStaticMethodCall(3, expr2);
}
[Fact]
public static void CheckCallFactoryOptimizationStatic4()
{
MethodCallExpression expr = Expression.Call(typeof(MS).GetMethod("S4"), Expression.Constant(0), Expression.Constant(1), Expression.Constant(2), Expression.Constant(3));
AssertStaticMethodCall(4, expr);
}
[Fact]
public static void CheckCallFactoryOptimizationStatic5()
{
MethodCallExpression expr = Expression.Call(typeof(MS).GetMethod("S5"), Expression.Constant(0), Expression.Constant(1), Expression.Constant(2), Expression.Constant(3), Expression.Constant(4));
AssertStaticMethodCall(5, expr);
}
[Fact]
public static void CheckCallFactoryStaticN()
{
const int N = 6;
ConstantExpression[] args = Enumerable.Range(0, N).Select(i => Expression.Constant(i)).ToArray();
MethodCallExpression expr = Expression.Call(typeof(MS).GetMethod("S" + N), args);
if (!PlatformDetection.IsNetNative) // .NET Native blocks internal framework reflection.
{
Assert.Equal("MethodCallExpressionN", expr.GetType().Name);
}
Assert.Equal(N, expr.ArgumentCount);
for (var i = 0; i < N; i++)
{
Assert.Same(args[i], expr.GetArgument(i));
}
Collections.ObjectModel.ReadOnlyCollection<Expression> arguments = expr.Arguments;
Assert.Same(arguments, expr.Arguments);
Assert.Equal(N, arguments.Count);
for (var i = 0; i < N; i++)
{
Assert.Same(args[i], arguments[i]);
}
MethodCallExpression updated = expr.Update(null, arguments);
Assert.Same(expr, updated);
var visited = (MethodCallExpression)new NopVisitor().Visit(expr);
Assert.Same(expr, visited);
var visitedArgs = (MethodCallExpression)new VisitorArgs().Visit(expr);
Assert.NotSame(expr, visitedArgs);
Assert.Same(null, visitedArgs.Object);
Assert.NotSame(arguments, visitedArgs.Arguments);
}
[Fact]
public static void CheckArrayIndexOptimization1()
{
ParameterExpression instance = Expression.Parameter(typeof(int[]));
ConstantExpression[] args = new[] { Expression.Constant(0) };
MethodCallExpression expr = Expression.ArrayIndex(instance, args);
MethodInfo method = typeof(int[]).GetMethod("Get", BindingFlags.Public | BindingFlags.Instance);
AssertCallIsOptimized(expr, instance, method, args);
}
[Fact]
public static void CheckArrayIndexOptimization2()
{
ParameterExpression instance = Expression.Parameter(typeof(int[,]));
ConstantExpression[] args = new[] { Expression.Constant(0), Expression.Constant(0) };
MethodCallExpression expr = Expression.ArrayIndex(instance, args);
MethodInfo method = typeof(int[,]).GetMethod("Get", BindingFlags.Public | BindingFlags.Instance);
AssertCallIsOptimized(expr, instance, method, args);
}
private static void AssertCallIsOptimizedInstance(int n)
{
MethodInfo method = typeof(MS).GetMethod("I" + n);
AssertCallIsOptimized(method);
}
private static void AssertCallIsOptimizedStatic(int n)
{
MethodInfo method = typeof(MS).GetMethod("S" + n);
AssertCallIsOptimized(method);
}
private static void AssertCallIsOptimized(MethodInfo method)
{
ParameterExpression instance = method.IsStatic ? null : Expression.Parameter(method.DeclaringType);
int n = method.GetParameters().Length;
// Expression[] overload
{
ConstantExpression[] args = Enumerable.Range(0, n).Select(i => Expression.Constant(i)).ToArray();
MethodCallExpression expr = Expression.Call(instance, method, args);
AssertCallIsOptimized(expr, instance, method, args);
}
// IEnumerable<Expression> overload
{
List<ConstantExpression> args = Enumerable.Range(0, n).Select(i => Expression.Constant(i)).ToList();
MethodCallExpression expr = Expression.Call(instance, method, args);
AssertCallIsOptimized(expr, instance, method, args);
}
}
private static void AssertCallIsOptimized(MethodCallExpression expr, Expression instance, MethodInfo method, IReadOnlyList<Expression> args)
{
int n = method.GetParameters().Length;
MethodCallExpression updatedArgs = UpdateArgs(expr);
MethodCallExpression visitedArgs = VisitArgs(expr);
var updatedObj = default(MethodCallExpression);
var visitedObj = default(MethodCallExpression);
MethodCallExpression[] nodes;
if (instance == null)
{
nodes = new[] { expr, updatedArgs, visitedArgs };
}
else
{
updatedObj = UpdateObj(expr);
visitedObj = VisitObj(expr);
nodes = new[] { expr, updatedArgs, visitedArgs, updatedObj, visitedObj };
}
foreach (var node in nodes)
{
if (node != visitedObj && node != updatedObj)
{
Assert.Same(instance, node.Object);
}
Assert.Same(method, node.Method);
if (method.IsStatic)
{
AssertStaticMethodCall(n, node);
}
else
{
AssertInstanceMethodCall(n, node);
}
var argProvider = node as IArgumentProvider;
Assert.NotNull(argProvider);
Assert.Equal(n, argProvider.ArgumentCount);
Assert.Throws<ArgumentOutOfRangeException>(() => argProvider.GetArgument(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => argProvider.GetArgument(n));
if (node != visitedArgs) // our visitor clones argument nodes
{
for (var i = 0; i < n; i++)
{
Assert.Same(args[i], argProvider.GetArgument(i));
Assert.Same(args[i], node.Arguments[i]);
}
}
}
}
private static void AssertStaticMethodCall(int n, object obj)
{
if (!PlatformDetection.IsNetNative) // .NET Native blocks internal framework reflection.
{
AssertTypeName("MethodCallExpression" + n, obj);
}
}
private static void AssertInstanceMethodCall(int n, object obj)
{
if (!PlatformDetection.IsNetNative) // .NET Native blocks internal framework reflection.
{
AssertTypeName("InstanceMethodCallExpression" + n, obj);
}
}
private static void AssertTypeName(string expected, object obj)
{
Assert.Equal(expected, obj.GetType().Name);
}
private static MethodCallExpression UpdateArgs(MethodCallExpression node)
{
// Tests the call of Update to Expression.Call factories.
MethodCallExpression res = node.Update(node.Object, node.Arguments.ToArray());
Assert.Same(node, res);
return res;
}
[Fact]
public static void UpdateStaticNull()
{
MethodCallExpression expr = Expression.Call(typeof(MS).GetMethod(nameof(MS.S0)));
Assert.Same(expr, expr.Update(null, null));
for (int argNum = 1; argNum != 7; ++argNum)
{
ConstantExpression[] args = Enumerable.Range(0, argNum).Select(i => Expression.Constant(i)).ToArray();
expr = Expression.Call(typeof(MS).GetMethod("S" + argNum), args);
// Should attempt to create new expression, and fail due to incorrect arguments.
AssertExtensions.Throws<ArgumentException>("method", () => expr.Update(null, null));
}
}
[Fact]
public static void UpdateInstanceNull()
{
ConstantExpression instance = Expression.Constant(new MS());
MethodCallExpression expr = Expression.Call(instance, typeof(MS).GetMethod(nameof(MS.I0)));
Assert.Same(expr, expr.Update(instance, null));
for (int argNum = 1; argNum != 6; ++argNum)
{
ConstantExpression[] args = Enumerable.Range(0, argNum).Select(i => Expression.Constant(i)).ToArray();
expr = Expression.Call(instance, typeof(MS).GetMethod("I" + argNum), args);
// Should attempt to create new expression, and fail due to incorrect arguments.
AssertExtensions.Throws<ArgumentException>("method", () => expr.Update(instance, null));
}
}
[Fact]
public static void UpdateStaticExtraArguments()
{
for (int argNum = 0; argNum != 7; ++argNum)
{
ConstantExpression[] args = Enumerable.Range(0, argNum).Select(i => Expression.Constant(i)).ToArray();
MethodCallExpression expr = Expression.Call(typeof(MS).GetMethod("S" + argNum), args);
// Should attempt to create new expression, and fail due to incorrect arguments.
AssertExtensions.Throws<ArgumentException>("method", () => expr.Update(null, args.Append(Expression.Constant(-1))));
}
}
[Fact]
public static void UpdateInstanceExtraArguments()
{
ConstantExpression instance = Expression.Constant(new MS());
for (int argNum = 0; argNum != 6; ++argNum)
{
ConstantExpression[] args = Enumerable.Range(0, argNum).Select(i => Expression.Constant(i)).ToArray();
MethodCallExpression expr = Expression.Call(instance, typeof(MS).GetMethod("I" + argNum), args);
// Should attempt to create new expression, and fail due to incorrect arguments.
AssertExtensions.Throws<ArgumentException>("method", () => expr.Update(instance, args.Append(Expression.Constant(-1))));
}
}
[Fact]
public static void UpdateStaticDifferentArguments()
{
for (int argNum = 1; argNum != 7; ++argNum)
{
ConstantExpression[] args = Enumerable.Range(0, argNum).Select(i => Expression.Constant(i)).ToArray();
MethodCallExpression expr = Expression.Call(typeof(MS).GetMethod("S" + argNum), args);
ConstantExpression[] newArgs = new ConstantExpression[argNum];
for (int i = 0; i != argNum; ++i)
{
args.CopyTo(newArgs, 0);
newArgs[i] = Expression.Constant(i);
Assert.NotSame(expr, expr.Update(null, newArgs));
}
}
}
[Fact]
public static void UpdateInstanceDifferentArguments()
{
ConstantExpression instance = Expression.Constant(new MS());
for (int argNum = 1; argNum != 6; ++argNum)
{
ConstantExpression[] args = Enumerable.Range(0, argNum).Select(i => Expression.Constant(i)).ToArray();
MethodCallExpression expr = Expression.Call(instance, typeof(MS).GetMethod("I" + argNum), args);
ConstantExpression[] newArgs = new ConstantExpression[argNum];
for (int i = 0; i != argNum; ++i)
{
args.CopyTo(newArgs, 0);
newArgs[i] = Expression.Constant(i);
Assert.NotSame(expr, expr.Update(instance, newArgs));
}
}
}
private static MethodCallExpression UpdateObj(MethodCallExpression node)
{
// Tests the call of Update to Expression.Call factories.
MethodCallExpression res = node.Update(new VisitorObj().Visit(node.Object), node.Arguments);
Assert.NotSame(node, res);
return res;
}
private static MethodCallExpression VisitArgs(MethodCallExpression node)
{
// Tests dispatch of ExpressionVisitor into Rewrite method which calls Expression.Call factories.
return (MethodCallExpression)new VisitorArgs().Visit(node);
}
private static MethodCallExpression VisitObj(MethodCallExpression node)
{
// Tests dispatch of ExpressionVisitor into Rewrite method which calls Expression.Call factories.
return (MethodCallExpression)new VisitorObj().Visit(node);
}
class NopVisitor : ExpressionVisitor
{
}
class VisitorArgs : ExpressionVisitor
{
protected override Expression VisitConstant(ConstantExpression node)
{
return Expression.Constant(node.Value, node.Type); // clones
}
}
class VisitorObj : ExpressionVisitor
{
protected override Expression VisitParameter(ParameterExpression node)
{
return Expression.Parameter(node.Type, node.Name); // clones
}
}
}
public class MS
{
public void I0() { }
public void I1(int a) { }
public void I2(int a, int b) { }
public void I3(int a, int b, int c) { }
public void I4(int a, int b, int c, int d) { }
public void I5(int a, int b, int c, int d, int e) { }
public static void S0() { }
public static void S1(int a) { }
public static void S2(int a, int b) { }
public static void S3(int a, int b, int c) { }
public static void S4(int a, int b, int c, int d) { }
public static void S5(int a, int b, int c, int d, int e) { }
public static void S6(int a, int b, int c, int d, int e, int f) { }
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Microsoft.Data.OData.Atom
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
#if ODATALIB_ASYNC
using System.Threading.Tasks;
#endif
using System.Xml;
using Microsoft.Data.Edm;
using Microsoft.Data.Edm.Library;
using Microsoft.Data.OData.Metadata;
using o = Microsoft.Data.OData;
#endregion Namespaces
/// <summary>
/// OData writer for the ATOM format.
/// </summary>
internal sealed class ODataAtomWriter : ODataWriterCore
{
/// <summary>Value for the atom:updated element.</summary>
/// <remarks>
/// The writer will use the same default value for the atom:updated element in a given payload. While there is no requirement for this,
/// it saves us from re-querying the system time and converting it to string every time we write an item.
/// </remarks>
private readonly string updatedTime = ODataAtomConvert.ToAtomString(DateTimeOffset.UtcNow);
/// <summary>The output context to write to.</summary>
private readonly ODataAtomOutputContext atomOutputContext;
/// <summary>The serializer to write payload with.</summary>
private readonly ODataAtomEntryAndFeedSerializer atomEntryAndFeedSerializer;
/// <summary>
/// Constructor creating an OData writer using the ATOM format.
/// </summary>
/// <param name="atomOutputContext">The output context to write to.</param>
/// <param name="writingFeed">True if the writer is created for writing a feed; false when it is created for writing an entry.</param>
internal ODataAtomWriter(ODataAtomOutputContext atomOutputContext, bool writingFeed)
: base(atomOutputContext, writingFeed)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(atomOutputContext != null, "atomOutputContext != null");
this.atomOutputContext = atomOutputContext;
if (this.atomOutputContext.MessageWriterSettings.AtomStartEntryXmlCustomizationCallback != null)
{
Debug.Assert(
this.atomOutputContext.MessageWriterSettings.AtomEndEntryXmlCustomizationCallback != null,
"We should have verified that both start end end XML customization callbacks are specified.");
this.atomOutputContext.InitializeWriterCustomization();
}
this.atomEntryAndFeedSerializer = new ODataAtomEntryAndFeedSerializer(this.atomOutputContext);
}
/// <summary>
/// Enumeration of ATOM element flags, used to keep track of which elements were already written.
/// </summary>
private enum AtomElement
{
/// <summary>The atom:id element.</summary>
Id = 0x1,
/// <summary>The atom:link with rel='self'.</summary>
ReadLink = 0x2,
/// <summary>The atom:link with rel='edit'.</summary>
EditLink = 0x4,
}
/// <summary>
/// Returns the current AtomEntryScope.
/// </summary>
private AtomEntryScope CurrentEntryScope
{
get
{
AtomEntryScope currentAtomEntryScope = this.CurrentScope as AtomEntryScope;
Debug.Assert(currentAtomEntryScope != null, "Asking for AtomEntryScope when the current scope is not an AtomEntryScope.");
return currentAtomEntryScope;
}
}
/// <summary>
/// Returns the current AtomFeedScope.
/// </summary>
private AtomFeedScope CurrentFeedScope
{
get
{
AtomFeedScope currentAtomFeedScope = this.CurrentScope as AtomFeedScope;
Debug.Assert(currentAtomFeedScope != null, "Asking for AtomFeedScope when the current scope is not an AtomFeedScope.");
return currentAtomFeedScope;
}
}
/// <summary>
/// Check if the object has been disposed; called from all public API methods. Throws an ObjectDisposedException if the object
/// has already been disposed.
/// </summary>
protected override void VerifyNotDisposed()
{
this.atomOutputContext.VerifyNotDisposed();
}
/// <summary>
/// Flush the output.
/// </summary>
protected override void FlushSynchronously()
{
this.atomOutputContext.Flush();
}
#if ODATALIB_ASYNC
/// <summary>
/// Flush the output.
/// </summary>
/// <returns>Task representing the pending flush operation.</returns>
protected override Task FlushAsynchronously()
{
return this.atomOutputContext.FlushAsync();
}
#endif
/// <summary>
/// Start writing an OData payload.
/// </summary>
protected override void StartPayload()
{
this.atomEntryAndFeedSerializer.WritePayloadStart();
}
/// <summary>
/// Finish writing an OData payload.
/// </summary>
protected override void EndPayload()
{
this.atomEntryAndFeedSerializer.WritePayloadEnd();
}
/// <summary>
/// Start writing an entry.
/// </summary>
/// <param name="entry">The entry to write.</param>
protected override void StartEntry(ODataEntry entry)
{
this.CheckAndWriteParentNavigationLinkStartForInlineElement();
Debug.Assert(
this.ParentNavigationLink == null || !this.ParentNavigationLink.IsCollection.Value,
"We should have already verified that the IsCollection matches the actual content of the link (feed/entry).");
if (entry == null)
{
Debug.Assert(this.ParentNavigationLink != null, "When entry == null, it has to be an expanded single entry navigation.");
// this is a null expanded single entry and it is null, an empty <m:inline /> will be written.
return;
}
this.StartEntryXmlCustomization(entry);
// <entry>
this.atomOutputContext.XmlWriter.WriteStartElement(AtomConstants.AtomNamespacePrefix, AtomConstants.AtomEntryElementName, AtomConstants.AtomNamespace);
if (this.IsTopLevel)
{
this.atomEntryAndFeedSerializer.WriteBaseUriAndDefaultNamespaceAttributes();
}
string etag = entry.ETag;
if (etag != null)
{
// TODO, ckerer: if this is a top-level entry also put the ETag into the headers.
ODataAtomWriterUtils.WriteETag(this.atomOutputContext.XmlWriter, etag);
}
AtomEntryScope currentEntryScope = this.CurrentEntryScope;
AtomEntryMetadata entryMetadata = entry.Atom();
// Write the id if it's available here.
// If it's not available here we will try to write it at the end of the entry again.
string entryId = entry.Id;
if (entryId != null)
{
this.atomEntryAndFeedSerializer.WriteEntryId(entryId);
currentEntryScope.SetWrittenElement(AtomElement.Id);
}
// <category term="type" scheme="odatascheme"/>
// If no type information is provided, don't include the category element for type at all
// NOTE: the validation of the type name is done by the core writer.
string typeName = entry.TypeName;
SerializationTypeNameAnnotation serializationTypeNameAnnotation = entry.GetAnnotation<SerializationTypeNameAnnotation>();
if (serializationTypeNameAnnotation != null)
{
typeName = serializationTypeNameAnnotation.TypeName;
}
this.atomEntryAndFeedSerializer.WriteEntryTypeName(typeName, entryMetadata);
// Write the edit link if it's available here.
// If it's not available here we will try to write it at the end of the entry again.
Uri editLink = entry.EditLink;
if (editLink != null)
{
this.atomEntryAndFeedSerializer.WriteEntryEditLink(editLink, entryMetadata);
currentEntryScope.SetWrittenElement(AtomElement.EditLink);
}
// Write the self link if it's available here.
// If it's not available here we will try to write it at the end of the entry again.
Uri readLink = entry.ReadLink;
if (readLink != null)
{
this.atomEntryAndFeedSerializer.WriteEntryReadLink(readLink, entryMetadata);
currentEntryScope.SetWrittenElement(AtomElement.ReadLink);
}
}
/// <summary>
/// Finish writing an entry.
/// </summary>
/// <param name="entry">The entry to write.</param>
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "The coupling is intentional here.")]
protected override void EndEntry(ODataEntry entry)
{
Debug.Assert(
this.ParentNavigationLink == null || !this.ParentNavigationLink.IsCollection.Value,
"We should have already verified that the IsCollection matches the actual content of the link (feed/entry).");
if (entry == null)
{
Debug.Assert(this.ParentNavigationLink != null, "When entry == null, it has to be an expanded single entry navigation.");
// this is a null expanded single entry and it is null, an empty <m:inline /> will be written.
this.CheckAndWriteParentNavigationLinkEndForInlineElement();
return;
}
IEdmEntityType entryType = this.EntryEntityType;
// Initialize the property value cache and cache the entry properties.
EntryPropertiesValueCache propertyValueCache = new EntryPropertiesValueCache(entry);
// NOTE: when writing, we assume the model has been validated already and thus pass int.MaxValue for the maxMappingCount.
ODataEntityPropertyMappingCache epmCache = this.atomOutputContext.Model.EnsureEpmCache(entryType, /*maxMappingCount*/ int.MaxValue);
// Populate the property value cache based on the EPM source tree information.
// We do this since we need to write custom EPM after the properties below and don't
// want to cache all properties just for the case that they are used in a custom EPM.
if (epmCache != null)
{
EpmWriterUtils.CacheEpmProperties(propertyValueCache, epmCache.EpmSourceTree);
}
// Get the projected properties annotation
ProjectedPropertiesAnnotation projectedProperties = entry.GetAnnotation<ProjectedPropertiesAnnotation>();
AtomEntryScope currentEntryScope = this.CurrentEntryScope;
AtomEntryMetadata entryMetadata = entry.Atom();
if (!currentEntryScope.IsElementWritten(AtomElement.Id))
{
// NOTE: We write even null id, in that case we generate an empty atom:id element.
this.atomEntryAndFeedSerializer.WriteEntryId(entry.Id);
}
Uri editLink = entry.EditLink;
if (editLink != null && !currentEntryScope.IsElementWritten(AtomElement.EditLink))
{
this.atomEntryAndFeedSerializer.WriteEntryEditLink(editLink, entryMetadata);
}
Uri readLink = entry.ReadLink;
if (readLink != null && !currentEntryScope.IsElementWritten(AtomElement.ReadLink))
{
this.atomEntryAndFeedSerializer.WriteEntryReadLink(readLink, entryMetadata);
}
// write entry metadata including syndication EPM
AtomEntryMetadata epmEntryMetadata = null;
if (epmCache != null)
{
ODataVersionChecker.CheckEntityPropertyMapping(this.atomOutputContext.Version, entryType, this.atomOutputContext.Model);
epmEntryMetadata = EpmSyndicationWriter.WriteEntryEpm(
epmCache.EpmTargetTree,
propertyValueCache,
entryType.ToTypeReference().AsEntity(),
this.atomOutputContext);
}
this.atomEntryAndFeedSerializer.WriteEntryMetadata(entryMetadata, epmEntryMetadata, this.updatedTime);
// stream properties
IEnumerable<ODataProperty> streamProperties = propertyValueCache.EntryStreamProperties;
if (streamProperties != null)
{
foreach (ODataProperty streamProperty in streamProperties)
{
this.atomEntryAndFeedSerializer.WriteStreamProperty(
streamProperty,
entryType,
this.DuplicatePropertyNamesChecker,
projectedProperties);
}
}
// association links
IEnumerable<ODataAssociationLink> associationLinks = entry.AssociationLinks;
if (associationLinks != null)
{
foreach (ODataAssociationLink associationLink in associationLinks)
{
this.atomEntryAndFeedSerializer.WriteAssociationLink(
associationLink,
entryType,
this.DuplicatePropertyNamesChecker,
projectedProperties);
}
}
// actions
IEnumerable<ODataAction> actions = entry.Actions;
if (actions != null)
{
foreach (ODataAction action in actions)
{
ValidationUtils.ValidateOperationNotNull(action, true);
this.atomEntryAndFeedSerializer.WriteOperation(action);
}
}
// functions
IEnumerable<ODataFunction> functions = entry.Functions;
if (functions != null)
{
foreach (ODataFunction function in functions)
{
ValidationUtils.ValidateOperationNotNull(function, false);
this.atomEntryAndFeedSerializer.WriteOperation(function);
}
}
// write the content
this.WriteEntryContent(
entry,
entryType,
propertyValueCache,
epmCache == null ? null : epmCache.EpmSourceTree.Root,
projectedProperties);
// write custom EPM
if (epmCache != null)
{
EpmCustomWriter.WriteEntryEpm(
this.atomOutputContext.XmlWriter,
epmCache.EpmTargetTree,
propertyValueCache,
entryType.ToTypeReference().AsEntity(),
this.atomOutputContext);
}
// </entry>
this.atomOutputContext.XmlWriter.WriteEndElement();
this.EndEntryXmlCustomization(entry);
this.CheckAndWriteParentNavigationLinkEndForInlineElement();
}
/// <summary>
/// Start writing a feed.
/// </summary>
/// <param name="feed">The feed to write.</param>
protected override void StartFeed(ODataFeed feed)
{
Debug.Assert(feed != null, "feed != null");
Debug.Assert(
this.ParentNavigationLink == null || !this.ParentNavigationLink.IsCollection.HasValue || this.ParentNavigationLink.IsCollection.Value,
"We should have already verified that the IsCollection matches the actual content of the link (feed/entry).");
this.CheckAndWriteParentNavigationLinkStartForInlineElement();
// <atom:feed>
this.atomOutputContext.XmlWriter.WriteStartElement(AtomConstants.AtomNamespacePrefix, AtomConstants.AtomFeedElementName, AtomConstants.AtomNamespace);
if (this.IsTopLevel)
{
this.atomEntryAndFeedSerializer.WriteBaseUriAndDefaultNamespaceAttributes();
if (feed.Count.HasValue)
{
this.atomEntryAndFeedSerializer.WriteCount(feed.Count.Value, false);
}
}
bool authorWritten;
this.atomEntryAndFeedSerializer.WriteFeedMetadata(feed, this.updatedTime, out authorWritten);
this.CurrentFeedScope.AuthorWritten = authorWritten;
}
/// <summary>
/// Finish writing a feed.
/// </summary>
/// <param name="feed">The feed to write.</param>
protected override void EndFeed(ODataFeed feed)
{
Debug.Assert(feed != null, "feed != null");
Debug.Assert(
this.ParentNavigationLink == null || this.ParentNavigationLink.IsCollection.Value,
"We should have already verified that the IsCollection matches the actual content of the link (feed/entry).");
AtomFeedScope currentFeedScope = this.CurrentFeedScope;
if (!currentFeedScope.AuthorWritten && currentFeedScope.EntryCount == 0)
{
// Write an empty author if there were no entries, since the feed must have an author if the entries don't have one as per ATOM spec
this.atomEntryAndFeedSerializer.WriteFeedDefaultAuthor();
}
this.atomEntryAndFeedSerializer.WriteFeedNextPageLink(feed);
// </atom:feed>
this.atomOutputContext.XmlWriter.WriteEndElement();
this.CheckAndWriteParentNavigationLinkEndForInlineElement();
}
/// <summary>
/// Start writing a navigation link.
/// </summary>
/// <param name="navigationLink">The navigation link to write.</param>
protected override void WriteDeferredNavigationLink(ODataNavigationLink navigationLink)
{
Debug.Assert(navigationLink != null, "navigationLink != null");
Debug.Assert(this.atomOutputContext.WritingResponse, "Deferred links are only supported in response, we should have verified this already.");
this.WriteNavigationLinkStart(navigationLink, null);
this.WriteNavigationLinkEnd();
}
/// <summary>
/// Start writing a navigation link with content.
/// </summary>
/// <param name="navigationLink">The navigation link to write.</param>
protected override void StartNavigationLinkWithContent(ODataNavigationLink navigationLink)
{
Debug.Assert(navigationLink != null, "navigationLink != null");
// In requests, a navigation link can have multiple items in its content (in the OM view), either entity reference links or expanded entry/feed.
// For each of these we need to write a separate atom:link element. So we can't write the start of the atom:link element here
// instead we postpone writing it till the first item in the content.
// In response, only one item can occur, but for simplicity we will keep the behavior the same as for request and thus postpone writing the atom:link
// start element as well.
// Note that the writer core guarantees that this method (and the matching EndNavigationLinkWithContent) is only called for navigation links
// which actually have some content. The only case where navigation link doesn't have a content is in response, in which case this method won't
// be called, instead the WriteDeferredNavigationLink is called.
}
/// <summary>
/// Finish writing a navigation link with content.
/// </summary>
/// <param name="navigationLink">The navigation link to write.</param>
protected override void EndNavigationLinkWithContent(ODataNavigationLink navigationLink)
{
Debug.Assert(navigationLink != null, "navigationLink != null");
// We do not write the end element for atom:link here, since we need to write it for each item in the content separately.
// See the detailed description in the StartNavigationLinkWithContent for details.
}
/// <summary>
/// Write an entity reference link.
/// </summary>
/// <param name="parentNavigationLink">The parent navigation link which is being written around the entity reference link.</param>
/// <param name="entityReferenceLink">The entity reference link to write.</param>
protected override void WriteEntityReferenceInNavigationLinkContent(ODataNavigationLink parentNavigationLink, ODataEntityReferenceLink entityReferenceLink)
{
Debug.Assert(parentNavigationLink != null, "parentNavigationLink != null");
Debug.Assert(entityReferenceLink != null, "entityReferenceLink != null");
Debug.Assert(entityReferenceLink.Url != null, "We should have already verifies that the Url specified on the entity reference link is not null.");
this.WriteNavigationLinkStart(parentNavigationLink, entityReferenceLink.Url);
this.WriteNavigationLinkEnd();
}
/// <summary>
/// Create a new feed scope.
/// </summary>
/// <param name="feed">The feed for the new scope.</param>
/// <param name="skipWriting">true if the content of the scope to create should not be written.</param>
/// <returns>The newly create scope.</returns>
protected override FeedScope CreateFeedScope(ODataFeed feed, bool skipWriting)
{
return new AtomFeedScope(feed, skipWriting);
}
/// <summary>
/// Create a new entry scope.
/// </summary>
/// <param name="entry">The entry for the new scope.</param>
/// <param name="skipWriting">true if the content of the scope to create should not be written.</param>
/// <returns>The newly create scope.</returns>
protected override EntryScope CreateEntryScope(ODataEntry entry, bool skipWriting)
{
return new AtomEntryScope(entry, skipWriting, this.atomOutputContext.WritingResponse, this.atomOutputContext.MessageWriterSettings.WriterBehavior);
}
/// <summary>
/// Write the content of the given entry.
/// </summary>
/// <param name="entry">The entry for which to write properties.</param>
/// <param name="entryType">The <see cref="IEdmEntityType"/> of the entry (or null if not metadata is available).</param>
/// <param name="propertiesValueCache">The cache of properties.</param>
/// <param name="rootSourcePathSegment">The root of the EPM source tree, if there's an EPM applied.</param>
/// <param name="projectedProperties">Set of projected properties, or null if all properties should be written.</param>
private void WriteEntryContent(
ODataEntry entry,
IEdmEntityType entryType,
EntryPropertiesValueCache propertiesValueCache,
EpmSourcePathSegment rootSourcePathSegment,
ProjectedPropertiesAnnotation projectedProperties)
{
Debug.Assert(entry != null, "entry != null");
Debug.Assert(propertiesValueCache != null, "propertiesValueCache != null");
ODataStreamReferenceValue mediaResource = entry.MediaResource;
if (mediaResource == null)
{
// <content type="application/xml">
this.atomOutputContext.XmlWriter.WriteStartElement(
AtomConstants.AtomNamespacePrefix,
AtomConstants.AtomContentElementName,
AtomConstants.AtomNamespace);
this.atomOutputContext.XmlWriter.WriteAttributeString(
AtomConstants.AtomTypeAttributeName,
MimeConstants.MimeApplicationXml);
this.atomEntryAndFeedSerializer.AssertRecursionDepthIsZero();
this.atomEntryAndFeedSerializer.WriteProperties(
entryType,
propertiesValueCache.EntryProperties,
false /* isWritingCollection */,
this.atomEntryAndFeedSerializer.WriteEntryPropertiesStart,
this.atomEntryAndFeedSerializer.WriteEntryPropertiesEnd,
this.DuplicatePropertyNamesChecker,
propertiesValueCache,
rootSourcePathSegment,
projectedProperties);
this.atomEntryAndFeedSerializer.AssertRecursionDepthIsZero();
// </content>
this.atomOutputContext.XmlWriter.WriteEndElement();
}
else
{
WriterValidationUtils.ValidateStreamReferenceValue(mediaResource, true);
this.atomEntryAndFeedSerializer.WriteEntryMediaEditLink(mediaResource);
if (mediaResource.ReadLink != null)
{
// <content type="type" src="src">
this.atomOutputContext.XmlWriter.WriteStartElement(
AtomConstants.AtomNamespacePrefix,
AtomConstants.AtomContentElementName,
AtomConstants.AtomNamespace);
Debug.Assert(!string.IsNullOrEmpty(mediaResource.ContentType), "The default stream content type should have been validated by now. If we have a read link we must have a non-empty content type as well.");
this.atomOutputContext.XmlWriter.WriteAttributeString(
AtomConstants.AtomTypeAttributeName,
mediaResource.ContentType);
this.atomOutputContext.XmlWriter.WriteAttributeString(
AtomConstants.MediaLinkEntryContentSourceAttributeName,
this.atomEntryAndFeedSerializer.UriToUrlAttributeValue(mediaResource.ReadLink));
// </content>
this.atomOutputContext.XmlWriter.WriteEndElement();
}
this.atomEntryAndFeedSerializer.AssertRecursionDepthIsZero();
this.atomEntryAndFeedSerializer.WriteProperties(
entryType,
propertiesValueCache.EntryProperties,
false /* isWritingCollection */,
this.atomEntryAndFeedSerializer.WriteEntryPropertiesStart,
this.atomEntryAndFeedSerializer.WriteEntryPropertiesEnd,
this.DuplicatePropertyNamesChecker,
propertiesValueCache,
rootSourcePathSegment,
projectedProperties);
this.atomEntryAndFeedSerializer.AssertRecursionDepthIsZero();
}
}
/// <summary>
/// Writes the navigation link start atom:link element including the m:inline element if there's a parent navigation link.
/// </summary>
private void CheckAndWriteParentNavigationLinkStartForInlineElement()
{
Debug.Assert(this.State == WriterState.Entry || this.State == WriterState.Feed, "Only entry or feed can be written into a link with inline.");
ODataNavigationLink parentNavigationLink = this.ParentNavigationLink;
if (parentNavigationLink != null)
{
// We postponed writing the surrounding atom:link and m:inline until now since in request a single navigation link can have
// multiple items in its content, each of which is written as a standalone atom:link. Thus the StartNavigationLinkWithContent is only called
// once, but we may need to write multiple atom:link elements.
// write the start element of the link
this.WriteNavigationLinkStart(parentNavigationLink, null);
// <m:inline>
this.atomOutputContext.XmlWriter.WriteStartElement(
AtomConstants.ODataMetadataNamespacePrefix,
AtomConstants.ODataInlineElementName,
AtomConstants.ODataMetadataNamespace);
}
}
/// <summary>
/// Writes the navigation link end m:inline and end atom:link elements if there's a parent navigation link.
/// </summary>
private void CheckAndWriteParentNavigationLinkEndForInlineElement()
{
Debug.Assert(this.State == WriterState.Entry || this.State == WriterState.Feed, "Only entry or feed can be written into a link with inline.");
ODataNavigationLink parentNavigationLink = this.ParentNavigationLink;
if (parentNavigationLink != null)
{
// We postponed writing the surrounding atom:link and m:inline until now since in request a single navigation link can have
// multiple items in its content, each of which is written as a standalone atom:link. Thus the EndNavigationLinkWithContent is only called
// once, but we may need to write multiple atom:link elements.
// </m:inline>
this.atomOutputContext.XmlWriter.WriteEndElement();
// </atom:link>
this.WriteNavigationLinkEnd();
}
}
/// <summary>
/// Writes the navigation link's start element and atom metadata.
/// </summary>
/// <param name="navigationLink">The navigation link to write.</param>
/// <param name="navigationLinkUrlOverride">Url to use for the navigation link. If this is specified the Url property on the <paramref name="navigationLink"/>
/// will be ignored. If this parameter is null, the Url from the navigation link is used.</param>
private void WriteNavigationLinkStart(ODataNavigationLink navigationLink, Uri navigationLinkUrlOverride)
{
// IsCollection is required for ATOM
if (!navigationLink.IsCollection.HasValue)
{
throw new ODataException(o.Strings.ODataWriterCore_LinkMustSpecifyIsCollection);
}
// Navigation link must specify the Url
// NOTE: we currently only require a non-null Url for ATOM payloads and non-expanded navigation links in JSON.
// There is no place in JSON to write a Url if the navigation link is expanded. We can't change that for v1 and v2; we
// might fix the protocol for v3.
if (navigationLink.Url == null)
{
throw new ODataException(o.Strings.ODataWriter_NavigationLinkMustSpecifyUrl);
}
this.atomEntryAndFeedSerializer.WriteNavigationLinkStart(navigationLink, navigationLinkUrlOverride);
}
/// <summary>
/// Writes custom extensions and the end element for a navigation link
/// </summary>
private void WriteNavigationLinkEnd()
{
// </atom:link>
this.atomOutputContext.XmlWriter.WriteEndElement();
}
/// <summary>
/// Determines if XML customization should be applied to the entry and applies it.
/// </summary>
/// <param name="entry">The entry to apply the customization to.</param>
/// <remarks>This method must be called before anything is written for the entry in question.</remarks>
private void StartEntryXmlCustomization(ODataEntry entry)
{
// If we are to customize the XML, replace the writers here:
if (this.atomOutputContext.MessageWriterSettings.AtomStartEntryXmlCustomizationCallback != null)
{
XmlWriter entryWriter = this.atomOutputContext.MessageWriterSettings.AtomStartEntryXmlCustomizationCallback(
entry,
this.atomOutputContext.XmlWriter);
if (entryWriter != null)
{
if (object.ReferenceEquals(this.atomOutputContext.XmlWriter, entryWriter))
{
throw new ODataException(o.Strings.ODataAtomWriter_StartEntryXmlCustomizationCallbackReturnedSameInstance);
}
}
else
{
entryWriter = this.atomOutputContext.XmlWriter;
}
this.atomOutputContext.PushCustomWriter(entryWriter);
}
}
/// <summary>
/// Ends XML customization for the entry (if one was applied).
/// </summary>
/// <param name="entry">The entry to end the customization for.</param>
/// <remarks>This method must be called after all the XML for a given entry is written.</remarks>
private void EndEntryXmlCustomization(ODataEntry entry)
{
if (this.atomOutputContext.MessageWriterSettings.AtomStartEntryXmlCustomizationCallback != null)
{
XmlWriter entryWriter = this.atomOutputContext.PopCustomWriter();
if (!object.ReferenceEquals(this.atomOutputContext.XmlWriter, entryWriter))
{
this.atomOutputContext.MessageWriterSettings.AtomEndEntryXmlCustomizationCallback(entry, entryWriter, this.atomOutputContext.XmlWriter);
}
}
}
/// <summary>
/// A scope for an feed.
/// </summary>
private sealed class AtomFeedScope : FeedScope
{
/// <summary>true if the author element was already written, false otherwise.</summary>
private bool authorWritten;
/// <summary>
/// Constructor to create a new feed scope.
/// </summary>
/// <param name="feed">The feed for the new scope.</param>
/// <param name="skipWriting">true if the content of the scope to create should not be written.</param>
internal AtomFeedScope(ODataFeed feed, bool skipWriting)
: base(feed, skipWriting)
{
DebugUtils.CheckNoExternalCallers();
}
/// <summary>
/// true if the author element was already written, false otherwise.
/// </summary>
internal bool AuthorWritten
{
get
{
DebugUtils.CheckNoExternalCallers();
return this.authorWritten;
}
set
{
DebugUtils.CheckNoExternalCallers();
this.authorWritten = value;
}
}
}
/// <summary>
/// A scope for an entry in ATOM writer.
/// </summary>
private sealed class AtomEntryScope : EntryScope
{
/// <summary>Bit field of the ATOM elements written so far.</summary>
private int alreadyWrittenElements;
/// <summary>
/// Constructor to create a new entry scope.
/// </summary>
/// <param name="entry">The entry for the new scope.</param>
/// <param name="skipWriting">true if the content of the scope to create should not be written.</param>
/// <param name="writingResponse">true if we are writing a response, false if it's a request.</param>
/// <param name="writerBehavior">The <see cref="ODataWriterBehavior"/> instance controlling the behavior of the writer.</param>
internal AtomEntryScope(ODataEntry entry, bool skipWriting, bool writingResponse, ODataWriterBehavior writerBehavior)
: base(entry, skipWriting, writingResponse, writerBehavior)
{
DebugUtils.CheckNoExternalCallers();
}
/// <summary>
/// Marks the <paramref name="atomElement"/> as written in this entry scope.
/// </summary>
/// <param name="atomElement">The ATOM element which was written.</param>
internal void SetWrittenElement(AtomElement atomElement)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(!this.IsElementWritten(atomElement), "Can't write the same element twice.");
this.alreadyWrittenElements |= (int)atomElement;
}
/// <summary>
/// Determines if the <paramref name="atomElement"/> was already written for this entry scope.
/// </summary>
/// <param name="atomElement">The ATOM element to test for.</param>
/// <returns>true if the <paramref name="atomElement"/> was already written for this entry scope; false otherwise.</returns>
internal bool IsElementWritten(AtomElement atomElement)
{
DebugUtils.CheckNoExternalCallers();
return (this.alreadyWrittenElements & (int)atomElement) == (int)atomElement;
}
}
}
}
| |
namespace ExpressionKit.Unwrap
{
using System;
using System.Linq;
using System.Linq.Expressions;
/// <summary>
/// Extensions for runtime expansion of expressions.
/// </summary>
public static class Wax
{
/// <summary>
/// Inject a constant directly into the query.
/// </summary>
/// <typeparam name="TValue">
/// The type of the result.
/// </typeparam>
/// <param name="value">
/// The value to inject. It must not rely on
/// parameters local to the query.
/// </param>
/// <returns>
/// If this method is executed outside of an expression,
/// it will throw an instance of <see cref="NotImplementedException"/>.
/// </returns>
[ConstantValueMethod]
public static TValue Constant<TValue>(this TValue value)
{
throw new NotImplementedException();
}
/// <summary>
/// Invoke an expression with a single parameter.
/// </summary>
/// <typeparam name="TParameter">
/// The type of the parameter.
/// </typeparam>
/// <typeparam name="TResult">
/// The return type of the expression.
/// </typeparam>
/// <param name="expression">
/// The expression to invoke.
/// </param>
/// <param name="parameter">
/// The parameter to pass to the expression.
/// </param>
/// <returns>
/// The result of the expression.
/// </returns>
/// <remarks>
/// When used in an expression, this call can be unwrapped.
/// This method should not be used outside of an unwrapped expression.
/// </remarks>
[UnwrappableMethod]
public static TResult Expand<TParameter, TResult>(
this Expression<Func<TParameter, TResult>> expression,
TParameter parameter)
{
throw new InvalidOperationException();
}
/// <summary>
/// Invoke an expression with two parameters.
/// </summary>
/// <typeparam name="TParam1">
/// The first parameter type.
/// </typeparam>
/// <typeparam name="TParam2">
/// The second parameter type.
/// </typeparam>
/// <typeparam name="TResult">
/// The return type of the expression.
/// </typeparam>
/// <param name="expression">
/// The expression to invoke.
/// </param>
/// <param name="param1">
/// The first parameter.
/// </param>
/// <param name="param2">
/// The second parameter.
/// </param>
/// <returns>
/// The result of the expression.
/// </returns>
/// <remarks>
/// When used in an expression, this call can be unwrapped.
/// This method should not be used outside of an unwrapped expression.
/// </remarks>
[UnwrappableMethod]
public static TResult Expand<TParam1, TParam2, TResult>(
this Expression<Func<TParam1, TParam2, TResult>> expression,
TParam1 param1,
TParam2 param2)
{
throw new InvalidOperationException();
}
/// <summary>
/// Unwraps any <see cref="Expand{TParameter, TResult}(Expression{Func{TParameter, TResult}}, TParameter)"/>
/// calls
/// within the given expression.
/// </summary>
/// <typeparam name="TParam">
/// The first parameter type.
/// </typeparam>
/// <typeparam name="TResult">
/// The return type of the expression.
/// </typeparam>
/// <param name="expression">
/// The expression to unwrap.
/// </param>
/// <returns>
/// The unwrapped expression.
/// </returns>
public static Expression<Func<TParam, TResult>> Unwrap<TParam, TResult>(
this Expression<Func<TParam, TResult>> expression)
{
return new UnwrapVisitor()
.Visit(expression)
as Expression<Func<TParam, TResult>>;
}
/// <summary>
/// Combines a call to <see cref="Unwrap{TParam, TResult}(Expression{Func{TParam, TResult}})"/>
/// with a call to
/// <see cref="System.Linq.Queryable.Select{TSource, TResult}(IQueryable{TSource}, Expression{Func{TSource, TResult}})"/>.
/// </summary>
/// <typeparam name="TSource">
/// The type of the source of elements.
/// </typeparam>
/// <typeparam name="TResult">
/// The type of the projected value.
/// </typeparam>
/// <param name="source">
/// The source of elements.
/// </param>
/// <param name="expression">
/// The projector.
/// </param>
/// <returns>
/// A collection.
/// </returns>
/// <remarks>
/// Can be useful for anonymously typed objects.
/// </remarks>
public static IQueryable<TResult> UnwrappedSelect<TSource, TResult>(
this IQueryable<TSource> source,
Expression<Func<TSource, TResult>> expression)
{
return source.Select(expression.Unwrap());
}
/// <summary>
/// Combines a call to <see cref="Unwrap{TParam, TResult}(Expression{Func{TParam, TResult}})"/>
/// with a call to
/// <see cref="System.Linq.Queryable.Where{TSource}(IQueryable{TSource}, Expression{Func{TSource, Boolean}})"/>.
/// </summary>
/// <typeparam name="TSource">
/// The type of the source of elements.
/// </typeparam>
/// <param name="source">
/// The source of elements.
/// </param>
/// <param name="filter">
/// The filter.
/// </param>
/// <returns>
/// A collection.
/// </returns>
/// <remarks>
/// Can be useful for anonymously typed objects.
/// </remarks>
public static IQueryable<TSource> UnwrappedWhere<TSource>(
this IQueryable<TSource> source,
Expression<Func<TSource, bool>> filter)
{
return source.Where(filter.Unwrap());
}
/// <summary>
/// Unwraps any <see cref="Expand{TParameter, TResult}(Expression{Func{TParameter, TResult}}, TParameter)"/>
/// calls
/// within the given expression.
/// </summary>
/// <typeparam name="TParam1">
/// The first parameter type.
/// </typeparam>
/// <typeparam name="TParam2">
/// The second parameter type.
/// </typeparam>
/// <typeparam name="TValue">
/// The return type of the expression.
/// </typeparam>
/// <param name="expression">
/// The expression to unwrap.
/// </param>
/// <returns>
/// The unwrapped expression.
/// </returns>
public static Expression<Func<TParam1, TParam2, TValue>> Unwrap<TParam1, TParam2, TValue>(
this Expression<Func<TParam1, TParam2, TValue>> expression)
{
return new UnwrapVisitor()
.Visit(expression)
as Expression<Func<TParam1, TParam2, TValue>>;
}
/// <summary>
/// An expression that simply returns false.
/// </summary>
/// <typeparam name="TParam">
/// The type of the parameter.
/// </typeparam>
/// <returns>
/// An expression.
/// </returns>
public static Expression<Func<TParam, bool>> False<TParam>()
{
return model => false;
}
/// <summary>
/// An expression that simply returns true.
/// </summary>
/// <typeparam name="TParam">
/// The type of the parameter.
/// </typeparam>
/// <returns>
/// An expression.
/// </returns>
public static Expression<Func<TParam, bool>> True<TParam>()
{
return model => true;
}
/// <summary>
/// Combine two predicates with boolean OR logic.
/// </summary>
/// <typeparam name="TParam">
/// The type of parameter for each expression.
/// </typeparam>
/// <param name="expression">
/// The first expression.
/// </param>
/// <param name="condition">
/// The second expression, only evaluated if the
/// first returns false.
/// </param>
/// <returns>
/// An expression.
/// </returns>
public static Expression<Func<TParam, bool>> Or<TParam>(
this Expression<Func<TParam, bool>> expression,
Expression<Func<TParam, bool>> condition)
{
var replaced = new ReplaceVisitor(
condition.Parameters[0],
expression.Parameters[0])
.Visit(condition.Body);
return Expression.Lambda<Func<TParam, bool>>(
Expression.OrElse(
expression.Body,
replaced),
expression.Parameters);
}
/// <summary>
/// Combine two predicates with boolean AND logic.
/// </summary>
/// <typeparam name="TParam">
/// The type of parameter for each expression.
/// </typeparam>
/// <param name="expression">
/// The first expression.
/// </param>
/// <param name="condition">
/// The second expression, not evaluated if the
/// first returns false.
/// </param>
/// <returns>
/// An expression.
/// </returns>
public static Expression<Func<TParam, bool>> And<TParam>(
this Expression<Func<TParam, bool>> expression,
Expression<Func<TParam, bool>> condition)
{
var replaced = new ReplaceVisitor(
condition.Parameters[0],
expression.Parameters[0])
.Visit(condition.Body);
return Expression.Lambda<Func<TParam, bool>>(
Expression.AndAlso(
expression.Body,
replaced),
expression.Parameters);
}
/// <summary>
/// Combine a series of expressions with boolean AND logic.
/// </summary>
/// <typeparam name="TParam">
/// The type of parameter for every expression.
/// </typeparam>
/// <param name="expressions">
/// The expressions.
/// </param>
/// <returns>
/// An expression.
/// </returns>
public static Expression<Func<TParam, bool>> All<TParam>(
params Expression<Func<TParam, bool>>[] expressions)
{
var head = expressions.First();
var tail = expressions.Skip(1);
foreach (var expression in tail)
head = head.And(expression);
return head;
}
/// <summary>
/// Combine a series of expressions with boolean OR logic.
/// </summary>
/// <typeparam name="TParam">
/// The type of parameter for every expression.
/// </typeparam>
/// <param name="expressions">
/// The expressions.
/// </param>
/// <returns>
/// An expression.
/// </returns>
public static Expression<Func<TParam, bool>> Any<TParam>(
params Expression<Func<TParam, bool>>[] expressions)
{
var head = expressions.First();
var tail = expressions.Skip(1);
foreach (var expression in tail)
head = head.Or(expression);
return head;
}
/// <summary>
/// Invert a boolean expression.
/// </summary>
/// <typeparam name="TParam">
/// The type of parameter for the expression.
/// </typeparam>
/// <param name="predicate">
/// The expression.
/// </param>
/// <returns>
/// An expression.
/// </returns>
public static Expression<Func<TParam, bool>> Inverse<TParam>(
this Expression<Func<TParam, bool>> predicate)
{
return Expression.Lambda<Func<TParam, bool>>(
new InvertVisitor().Visit(predicate.Body),
predicate.Parameters);
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoad.Business.ERCLevel
{
/// <summary>
/// B07_RegionColl (editable child list).<br/>
/// This is a generated base class of <see cref="B07_RegionColl"/> business object.
/// </summary>
/// <remarks>
/// This class is child of <see cref="B06_Country"/> editable child object.<br/>
/// The items of the collection are <see cref="B08_Region"/> objects.
/// </remarks>
[Serializable]
public partial class B07_RegionColl : BusinessListBase<B07_RegionColl, B08_Region>
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="B08_Region"/> item from the collection.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to be removed.</param>
public void Remove(int region_ID)
{
foreach (var b08_Region in this)
{
if (b08_Region.Region_ID == region_ID)
{
Remove(b08_Region);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="B08_Region"/> item is in the collection.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to search for.</param>
/// <returns><c>true</c> if the B08_Region is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int region_ID)
{
foreach (var b08_Region in this)
{
if (b08_Region.Region_ID == region_ID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="B08_Region"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to search for.</param>
/// <returns><c>true</c> if the B08_Region is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int region_ID)
{
foreach (var b08_Region in DeletedList)
{
if (b08_Region.Region_ID == region_ID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="B08_Region"/> item of the <see cref="B07_RegionColl"/> collection, based on item key properties.
/// </summary>
/// <param name="region_ID">The Region_ID.</param>
/// <returns>A <see cref="B08_Region"/> object.</returns>
public B08_Region FindB08_RegionByParentProperties(int region_ID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].Region_ID.Equals(region_ID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="B07_RegionColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="B07_RegionColl"/> collection.</returns>
internal static B07_RegionColl NewB07_RegionColl()
{
return DataPortal.CreateChild<B07_RegionColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="B07_RegionColl"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="B07_RegionColl"/> object.</returns>
internal static B07_RegionColl GetB07_RegionColl(SafeDataReader dr)
{
B07_RegionColl obj = new B07_RegionColl();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="B07_RegionColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public B07_RegionColl()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads all <see cref="B07_RegionColl"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
var args = new DataPortalHookArgs(dr);
OnFetchPre(args);
while (dr.Read())
{
Add(B08_Region.GetB08_Region(dr));
}
OnFetchPost(args);
RaiseListChangedEvents = rlce;
}
/// <summary>
/// Loads <see cref="B08_Region"/> items on the B07_RegionObjects collection.
/// </summary>
/// <param name="collection">The grand parent <see cref="B05_CountryColl"/> collection.</param>
internal void LoadItems(B05_CountryColl collection)
{
foreach (var item in this)
{
var obj = collection.FindB06_CountryByParentProperties(item.parent_Country_ID);
var rlce = obj.B07_RegionObjects.RaiseListChangedEvents;
obj.B07_RegionObjects.RaiseListChangedEvents = false;
obj.B07_RegionObjects.Add(item);
obj.B07_RegionObjects.RaiseListChangedEvents = rlce;
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Vevo;
using Vevo.Base.Domain;
using Vevo.Deluxe.Domain;
using Vevo.Domain;
using Vevo.Domain.Products;
using Vevo.Domain.Stores;
using Vevo.Shared.DataAccess;
using Vevo.Shared.Utilities;
using Vevo.WebUI;
public partial class AdminAdvanced_MainControls_ProductList : AdminAdvancedBaseListControl
{
#region Private
private const int ProductIDColumnIndex = 1;
private const int StockColumnIndex = 5;
private const int RetailColumnIndex = 7;
private const int ReviewColumnIndex = 9;
private string _sortPage = "ProductSorting.ascx";
private string RootCategoryValue
{
get
{
if (!KeyUtilities.IsMultistoreLicense())
return DataAccessContext.Configurations.GetValue(
"RootCategory",
DataAccessContext.StoreRepository.GetOne( Store.RegularStoreID ) );
else
return uxCategoryFilterDrop.SelectedRootValue;
}
}
private void SetUpSearchFilter()
{
IList<TableSchemaItem> list = DataAccessContext.ProductRepository.GetTableSchema();
uxSearchFilter.SetUpSchema( list, "UrlName",
"UseDefaultMetaKeyword", "UseDefaultMetaDescription",
"UseDefaultPrice", "UseDefaultRetailPrice",
"UseDefaultWholeSalePrice", "UseDefaultWholeSalePrice2", "UseDefaultWholeSalePrice3" );
}
private void PopulateControls()
{
if (!MainContext.IsPostBack)
{
RefreshGrid();
}
if (uxGridProduct.Rows.Count > 0)
{
DeleteVisible( true );
uxPagingControl.Visible = true;
}
else
{
DeleteVisible( false );
uxPagingControl.Visible = false;
}
if (!IsAdminModifiable())
{
uxAddButton.Visible = false;
uxeBayListing.Visible = false;
DeleteVisible( false );
}
uxSortButton.Visible = IsAdminViewable( _sortPage );
if (!KeyUtilities.IsDeluxeLicense( DataAccessHelper.DomainRegistrationkey, DataAccessHelper.DomainName ))
{
uxeBayListing.Visible = false;
}
}
private void DeleteVisible( bool value )
{
uxDeleteButton.Visible = value;
if (value)
{
if (AdminConfig.CurrentTestMode == AdminConfig.TestMode.Normal)
{
uxDeleteConfirmButton.TargetControlID = "uxDeleteButton";
uxConfirmModalPopup.TargetControlID = "uxDeleteButton";
}
else
{
uxDeleteConfirmButton.TargetControlID = "uxDummyButton";
uxConfirmModalPopup.TargetControlID = "uxDummyButton";
}
}
else
{
uxDeleteConfirmButton.TargetControlID = "uxDummyButton";
uxConfirmModalPopup.TargetControlID = "uxDummyButton";
}
}
private bool IsAnyOptionOutOfStock( string productID )
{
Product product = DataAccessContext.ProductRepository.GetOne(
uxLanguageControl.CurrentCulture, productID, new StoreRetriever().GetCurrentStoreID() );
return product.IsOutOfStock();
}
private void SetUpGridSupportControls()
{
if (!MainContext.IsPostBack)
{
uxPagingControl.ItemsPerPages = AdminConfig.ProductItemsPerPage;
SetUpSearchFilter();
uxCategoryFilterDrop.CultureID = uxLanguageControl.CurrentCultureID;
}
RegisterGridView( uxGridProduct, "ProductID" );
RegisterLanguageControl( uxLanguageControl );
RegisterSearchFilter( uxSearchFilter );
RegisterPagingControl( uxPagingControl );
RegisterCategoryFilterDrop( uxCategoryFilterDrop );
uxLanguageControl.BubbleEvent += new EventHandler( uxLanguageControl_BubbleEvent );
uxSearchFilter.BubbleEvent += new EventHandler( uxSearchFilter_BubbleEvent );
uxPagingControl.BubbleEvent += new EventHandler( uxPagingControl_BubbleEvent );
uxCategoryFilterDrop.BubbleEvent += new EventHandler( uxCategoryFilterDrop_BubbleEvent );
}
#endregion
protected void Page_Load( object sender, EventArgs e )
{
SetUpGridSupportControls();
}
protected void Page_PreRender( object sender, EventArgs e )
{
PopulateControls();
}
protected void uxAddButton_Click( object sender, EventArgs e )
{
ProductImageData.Clear();
MainContext.RedirectMainControl( "ProductAdd.ascx" );
}
protected void uxDeleteButton_Click( object sender, EventArgs e )
{
try
{
bool deleted = false;
foreach (GridViewRow row in uxGridProduct.Rows)
{
CheckBox deleteCheck = (CheckBox) row.FindControl( "uxCheck" );
if (deleteCheck.Checked)
{
string id = row.Cells[ProductIDColumnIndex].Text.Trim();
DataAccessContext.ProductRepository.Delete( id );
DataAccessContextDeluxe.PromotionProductRepository.DeleteByProductID( id );
DataAccessContextDeluxe.ProductSubscriptionRepository.DeleteByProductID( id );
deleted = true;
}
}
uxStatusHidden.Value = "Deleted";
if (deleted)
{
uxMessage.DisplayMessage( Resources.ProductMessages.DeleteSuccess );
}
}
catch (Exception ex)
{
uxMessage.DisplayException( ex );
}
RefreshGrid();
if (uxGridProduct.Rows.Count == 0 && uxPagingControl.CurrentPage >= uxPagingControl.NumberOfPages)
{
uxPagingControl.CurrentPage = uxPagingControl.NumberOfPages;
RefreshGrid();
}
}
protected void uxSortButton_Click( object sender, EventArgs e )
{
MainContext.RedirectMainControl( _sortPage );
}
protected void uxeBayListing_Click( object sender, EventArgs e )
{
try
{
string queryStringID = String.Empty;
ArrayList selectedIsKit = new ArrayList();
foreach (GridViewRow row in uxGridProduct.Rows)
{
CheckBox deleteCheck = (CheckBox) row.FindControl( "uxCheck" );
if (deleteCheck.Checked)
{
string productID = row.Cells[ProductIDColumnIndex].Text.Trim();
if (DataAccessContext.ProductRepository.CheckIsProductKitByProductID( productID ))
selectedIsKit.Add( productID );
queryStringID += productID + ",";
}
}
if (selectedIsKit.Count > 0)
{
string errorMsg = "Cannot list to eBay because the following Product(s) is Product Kit:<br/>";
for (int i = 0; i < selectedIsKit.Count; i++)
{
errorMsg += selectedIsKit[i];
if ((i + 1) != selectedIsKit.Count)
errorMsg += ", ";
}
uxMessage.DisplayError( errorMsg );
return;
}
if(!String.IsNullOrEmpty(queryStringID))
MainContext.RedirectMainControl( "EBayListingReview.ascx", "ProductID=" + queryStringID );
}
catch (Exception ex)
{
uxMessage.DisplayException( ex );
}
}
protected void uxGridProduct_DataBound( object sender, EventArgs e )
{
GridView grid = (GridView) sender;
if (!CatalogUtilities.IsRetailMode)
{
grid.Columns[RetailColumnIndex].Visible = false;
}
if (!DataAccessContext.Configurations.GetBoolValue( "UseStockControl" ))
grid.Columns[StockColumnIndex].Visible = false;
}
protected void uxGridProduct_RowDataBound( object sender, GridViewRowEventArgs e )
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string productID = e.Row.Cells[ProductIDColumnIndex].Text.Trim();
int result;
if (DataAccessContext.Configurations.GetBoolValue( "UseStockControl" ))
{
//Product product = (Product) e.Row.DataItem;
//if (product.IsOutOfStock())
//{
// foreach (TableCell cell in e.Row.Cells)
// {
// cell.Style.Add( "color", "#ff0000" );
// }
//}
if (int.TryParse( productID, out result ))
{
if (IsAnyOptionOutOfStock( productID ))
{
foreach (TableCell cell in e.Row.Cells)
{
cell.Style.Add( "color", "#ff0000" );
}
}
}
}
if (e.Row.RowIndex > -1)
{
if ((e.Row.RowIndex % 2) == 0)
{
// Even
e.Row.Attributes.Add( "onmouseover", "this.className='DefaultGridRowStyleHover'" );
e.Row.Attributes.Add( "onmouseout", "this.className='DefaultGridRowStyle'" );
}
else
{
// Odd
e.Row.Attributes.Add( "onmouseover", "this.className='DefaultGridRowStyleHover'" );
e.Row.Attributes.Add( "onmouseout", "this.className='DefaultGridAlternatingRowStyle'" );
}
}
}
}
protected string GetStockText( string sumStock, object isGiftCertificate, object useInventory )
{
if (!ConvertUtilities.ToBoolean( useInventory ))
return "-";
else
return sumStock;
}
protected decimal GetPrice( object productID )
{
Product product = DataAccessContext.ProductRepository.GetOne( StoreContext.Culture, (string) productID, StoreContext.CurrentStore.StoreID );
ProductPrice productPrice = product.GetProductPrice( StoreContext.CurrentStore.StoreID );
return productPrice.Price;
}
protected decimal GetRetailPrice( object productID )
{
Product product = DataAccessContext.ProductRepository.GetOne( StoreContext.Culture, (string) productID, StoreContext.CurrentStore.StoreID );
ProductPrice productPrice = product.GetProductPrice( StoreContext.CurrentStore.StoreID );
return productPrice.RetailPrice;
}
protected override void RefreshGrid()
{
int totalItems;
string storeID = new StoreRetriever().GetCurrentStoreID();
uxGridProduct.DataSource = DataAccessContext.ProductRepository.SearchProduct(
uxLanguageControl.CurrentCulture,
uxCategoryFilterDrop.SelectedValue,
GridHelper.GetFullSortText(),
uxSearchFilter.SearchFilterObj,
uxPagingControl.StartIndex,
uxPagingControl.EndIndex,
out totalItems,
storeID,
RootCategoryValue );
uxPagingControl.NumberOfPages = (int) Math.Ceiling( (double) totalItems / uxPagingControl.ItemsPerPages );
uxGridProduct.DataBind();
}
}
| |
// Copyright 2020 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using CommandLine;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V10.Common;
using Google.Ads.GoogleAds.V10.Errors;
using Google.Ads.GoogleAds.V10.Resources;
using Google.Ads.GoogleAds.V10.Services;
using static Google.Ads.GoogleAds.V10.Enums.OfflineUserDataJobStatusEnum.Types;
using static Google.Ads.GoogleAds.V10.Enums.OfflineUserDataJobTypeEnum.Types;
namespace Google.Ads.GoogleAds.Examples.V10
{
/// <summary>
/// This code example uploads offline data for store sales transactions.
/// This feature is only available to allowlisted accounts. See
/// https://support.google.com/google-ads/answer/7620302 for more details.
/// </summary>
public class UploadStoreSalesTransactions : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="UploadStoreSalesTransactions"/> example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The Google Ads customer ID for which the call is made.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The Google Ads customer ID for which the call is made.")]
public long CustomerId { get; set; }
/// <summary>
/// The ID of a store sales conversion action.
/// </summary>
[Option("conversionActionId", Required = true, HelpText =
"The ID of a store sales conversion action.")]
public long ConversionActionId { get; set; }
/// <summary>
/// The type of user data in the job (first or third party). If you have an official
/// store sales partnership with Google, use StoreSalesUploadThirdParty. Otherwise,
/// use StoreSalesUploadFirstParty or omit this parameter.
/// </summary>
[Option("offlineUserDataJobType", Required = false, HelpText =
"The type of user data in the job (first or third party). If you have an" +
" official store sales partnership with Google, use " +
"StoreSalesUploadThirdParty. Otherwise, use StoreSalesUploadFirstParty or " +
"omit this parameter.",
Default = OfflineUserDataJobType.StoreSalesUploadFirstParty)]
public OfflineUserDataJobType OfflineUserDataJobType { get; set; }
/// <summary>
/// Optional (but recommended) external ID to identify the offline user data job.
/// </summary>
[Option("externalId", Required = false, HelpText =
"Optional (but recommended) external ID to identify the offline user data job.",
Default = null)]
public long? ExternalId { get; set; }
/// <summary>
/// Date and time the advertiser uploaded data to the partner. Only required if
/// uploading third party data.
/// </summary>
[Option("advertiserUploadDateTime", Required = false, HelpText =
"Date and time the advertiser uploaded data to the partner. Only required if " +
"uploading third party data.", Default = null)]
public string AdvertiserUploadDateTime { get; set; }
/// <summary>
/// Version of partner IDs to be used for uploads. Only required if uploading third
/// party data.
/// </summary>
[Option("bridgeMapVersionId", Required = false, HelpText =
"Version of partner IDs to be used for uploads. Only required if uploading " +
"third party data.", Default = null)]
public string BridgeMapVersionId { get; set; }
/// <summary>
/// ID of the third party partner. Only required if uploading third party data.
/// </summary>
[Option("partnerId", Required = false, HelpText =
"ID of the third party partner. Only required if uploading third party data.",
Default = null)]
public long? PartnerId { get; set; }
/// <summary>
/// Optional custom key name. Only required if uploading data with custom key and
/// values.
/// </summary>
[Option("customKey", Required = false, HelpText =
"Optional custom key name. Only required if uploading data with custom key and" +
" values.", Default = null)]
public string CustomKey { get; set; }
/// <summary>
/// A unique identifier of a product, either the Merchant Center Item ID or Global Trade
/// Item Number (GTIN). Only required if uploading with item attributes.
/// </summary>
[Option("itemId", Required = false, HelpText =
"A unique identifier of a product, either the Merchant Center Item ID or " +
"Global Trade Item Number (GTIN). Only required if uploading with item " +
"attributes.",
Default = null)]
public string ItemId { get; set; }
/// <summary>
/// A Merchant Center Account ID. Only required if uploading with item attributes.
/// </summary>
[Option("merchantCenterAccountId", Required = false, HelpText =
"A Merchant Center Account ID. Only required if uploading with item " +
"attributes.",
Default = null)]
public long? MerchantCenterAccountId { get; set; }
/// <summary>
/// A two-letter country code of the location associated with the feed where your items
/// are uploaded. Only required if uploading with item attributes.
/// For a list of country codes see:
/// https://developers.google.com/google-ads/api/reference/data/codes-formats#expandable-16
/// </summary>
[Option("countryCode", Required = false, HelpText =
"A two-letter country code of the location associated with the feed where your " +
"items are uploaded. Only required if uploading with item attributes.\nFor a " +
"list of country codes see: " +
"https://developers.google.com/google-ads/api/reference/data/codes-formats#expandable-16",
Default = null)]
public string CountryCode { get; set; }
/// <summary>
/// A two-letter language code of the language associated with the feed where your items
/// are uploaded. Only required if uploading with item attributes. For a list of
/// language codes see:
/// https://developers.google.com/google-ads/api/reference/data/codes-formats#expandable-7
/// </summary>
[Option("languageCode", Required = false, HelpText =
"A two-letter language code of the language associated with the feed where " +
"your items are uploaded. Only required if uploading with item attributes.\n" +
"For a list of language codes see: " +
"https://developers.google.com/google-ads/api/reference/data/codes-formats#expandable-7",
Default = null)]
public string LanguageCode { get; set; }
/// <summary>
/// The number of items sold. Can only be set when at least one other item attribute has
/// been provided. Only required if uploading with item attributes.
/// </summary>
[Option("quantity", Required = false, HelpText =
"The number of items sold. Only required if uploading with item attributes.",
Default = 1)]
public long Quantity { get; set; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
Options options = new Options();
Parser.Default.ParseArguments<Options>(args).MapResult(
delegate(Options o)
{
options = o;
return 0;
}, delegate(IEnumerable<Error> errors)
{
// The Google Ads customer ID for which the call is made.
options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE");
// The ID of a store sales conversion action.
options.ConversionActionId = long.Parse("INSERT_CONVERSION_ACTION_ID_HERE");
// The type of user data in the job (first or third party). If you have an
// official store sales partnership with Google, use StoreSalesUploadThirdParty.
// Otherwise, use StoreSalesUploadFirstParty or omit this parameter.
options.OfflineUserDataJobType =
OfflineUserDataJobType.StoreSalesUploadFirstParty;
// Optional (but recommended) external ID to identify the offline user data job.
options.ExternalId = long.Parse("INSERT_EXTERNAL_ID_HERE");
// Date and time the advertiser uploaded data to the partner. Only required
// if uploading third party data.
options.AdvertiserUploadDateTime = "INSERT_ADVERTISER_UPLOAD_DATE_TIME_HERE";
// Version of partner IDs to be used for uploads. Only required if uploading
// third party data.
options.BridgeMapVersionId = "INSERT_BRIDGE_MAP_VERSION_ID_HERE";
// ID of the third party partner. Only required if uploading third party data.
options.PartnerId = long.Parse("INSERT_PARTNER_ID_HERE");
// Optional custom key name. Only required if uploading data with custom key
// and values.
options.CustomKey = "INSERT_CUSTOM_KEY_HERE";
// A unique identifier of a product, either the Merchant Center Item ID or Global Trade
// Item Number (GTIN). Only required if uploading with item attributes.
options.ItemId = "INSERT_ITEM_ID_HERE";
// A Merchant Center Account ID. Only required if uploading with item
// attributes.
options.MerchantCenterAccountId =
long.Parse("INSERT_MERCHANT_CENTER_ACCOUNT_ID_HERE");
// A two-letter country code of the location associated with the feed where your
// items are uploaded. Only required if uploading with item attributes.
options.CountryCode = "INSERT_COUNTRY_CODE_HERE";
// A two-letter language code of the language associated with the feed where
// your items are uploaded. Only required if uploading with item attributes.
options.LanguageCode = "INSERT_LANGUAGE_CODE_HERE";
// The number of items sold. Only required if uploading with item attributes.
options.Quantity = long.Parse("INSERT_QUANTITY_HERE");
return 0;
});
UploadStoreSalesTransactions codeExample = new UploadStoreSalesTransactions();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.ConversionActionId,
options.OfflineUserDataJobType, options.ExternalId,
options.AdvertiserUploadDateTime, options.BridgeMapVersionId, options.PartnerId,
options.CustomKey, options.ItemId, options.MerchantCenterAccountId,
options.CountryCode,
options.LanguageCode, options.Quantity);
}
// Gets a digest for generating hashed values using SHA-256. You must normalize and hash the
// the value for any field where the name begins with "hashed". See the normalizeAndHash()
// method.
private static readonly SHA256 _digest = SHA256.Create();
// If uploading data with custom key and values, specify the value:
private const string CUSTOM_VALUE = "INSERT_CUSTOM_VALUE_HERE";
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"This code example uploads offline data for store sales transactions. This feature " +
"is only available to allowlisted accounts. See " +
"https://support.google.com/google-ads/answer/7620302 for more details.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="conversionActionId">The ID of a store sales conversion action.</param>
/// <param name="offlineUserDataJobType">The type of user data in the job (first or third
/// party). If you have an official store sales partnership with Google, use
/// StoreSalesUploadThirdParty. Otherwise, use StoreSalesUploadFirstParty or
/// omit this parameter.</param>
/// <param name="externalId">Optional (but recommended) external ID to identify the offline
/// user data job.</param>
/// <param name="advertiserUploadDateTime">Date and time the advertiser uploaded data to the
/// partner. Only required if uploading third party data.</param>
/// <param name="bridgeMapVersionId">Version of partner IDs to be used for uploads. Only
/// required if uploading third party data.</param>
/// <param name="partnerId">ID of the third party partner. Only required if uploading third
/// party data.</param>
/// <param name="customKey">Optional custom key name. Only required if uploading data
/// with custom key and values.</param>
/// <param name="itemId">A unique identifier of a product, either the Merchant Center Item
/// ID or Global Trade Item Number (GTIN). Only required if uploading with item
/// attributes.</param>
/// <param name="merchantCenterAccountId">A Merchant Center Account ID. Only required if uploading with
/// item attributes.</param>
/// <param name="countryCode">A two-letter country code of the location associated with the
/// feed where your items are uploaded. Only required if uploading with item
/// attributes.</param>
/// <param name="languageCode">A two-letter language code of the language associated with
/// the feed where your items are uploaded. Only required if uploading with item
/// attributes.</param>
/// <param name="quantity">The number of items sold. Only required if uploading with item
/// attributes.</param>
public void Run(GoogleAdsClient client, long customerId, long conversionActionId,
OfflineUserDataJobType offlineUserDataJobType, long? externalId,
string advertiserUploadDateTime, string bridgeMapVersionId, long? partnerId,
string customKey, string itemId, long? merchantCenterAccountId, string countryCode,
string languageCode, long quantity)
{
// Get the OfflineUserDataJobServiceClient.
OfflineUserDataJobServiceClient offlineUserDataJobServiceClient =
client.GetService(Services.V10.OfflineUserDataJobService);
// Ensure that a valid job type is provided.
if (offlineUserDataJobType != OfflineUserDataJobType.StoreSalesUploadFirstParty &
offlineUserDataJobType != OfflineUserDataJobType.StoreSalesUploadThirdParty)
{
Console.WriteLine("Invalid job type specified, defaulting to First Party.");
offlineUserDataJobType = OfflineUserDataJobType.StoreSalesUploadFirstParty;
}
try
{
// Creates an offline user data job for uploading transactions.
string offlineUserDataJobResourceName =
CreateOfflineUserDataJob(offlineUserDataJobServiceClient, customerId,
offlineUserDataJobType, externalId, advertiserUploadDateTime,
bridgeMapVersionId, partnerId, customKey);
// Adds transactions to the job.
AddTransactionsToOfflineUserDataJob(offlineUserDataJobServiceClient, customerId,
offlineUserDataJobResourceName, conversionActionId, customKey, itemId,
merchantCenterAccountId, countryCode, languageCode, quantity);
// Issues an asynchronous request to run the offline user data job.
offlineUserDataJobServiceClient.RunOfflineUserDataJobAsync(
offlineUserDataJobResourceName);
Console.WriteLine("Sent request to asynchronously run offline user data job " +
$"{offlineUserDataJobResourceName}.");
// Offline user data jobs may take up to 24 hours to complete, so instead of waiting
// for the job to complete, retrieves and displays the job status once and then
// prints the query to use to check the job again later.
CheckJobStatus(client, customerId, offlineUserDataJobResourceName);
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
/// <summary>
/// Creates an offline user data job for uploading store sales transactions.
/// </summary>
/// <param name="offlineUserDataJobServiceClient">The offline user data job service
/// client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="offlineUserDataJobType">The type of user data in the job (first or third
/// party). If you have an official store sales partnership with Google, use
/// StoreSalesUploadThirdParty. Otherwise, use StoreSalesUploadFirstParty or
/// omit this parameter.</param>
/// <param name="externalId">Optional (but recommended) external ID to identify the offline
/// user data job.</param>
/// <param name="advertiserUploadDateTime">Date and time the advertiser uploaded data to the
/// partner. Only required if uploading third party data.</param>
/// <param name="bridgeMapVersionId">Version of partner IDs to be used for uploads. Only
/// required if uploading third party data.</param>
/// <param name="partnerId">ID of the third party partner. Only required if uploading third
/// party data.</param>
/// <param name="customKey">The custom key, or null if not uploading data with custom key
/// and value.</param>
/// <returns>The resource name of the created job.</returns>
private string CreateOfflineUserDataJob(
OfflineUserDataJobServiceClient offlineUserDataJobServiceClient, long customerId,
OfflineUserDataJobType offlineUserDataJobType, long? externalId,
string advertiserUploadDateTime, string bridgeMapVersionId, long? partnerId,
string customKey)
{
// TIP: If you are migrating from the AdWords API, please note that Google Ads API uses
// the term "fraction" instead of "rate". For example, loyaltyRate in the AdWords API is
// called loyaltyFraction in the Google Ads API.
// Please refer to https://support.google.com/google-ads/answer/7506124 for additional
// details.
StoreSalesMetadata storeSalesMetadata = new StoreSalesMetadata()
{
// Sets the fraction of your overall sales that you (or the advertiser, in the third
// party case) can associate with a customer (email, phone number, address, etc.) in
// your database or loyalty program.
// For example, set this to 0.7 if you have 100 transactions over 30 days, and out
// of those 100 transactions, you can identify 70 by an email address or phone
// number.
LoyaltyFraction = 0.7,
// Sets the fraction of sales you're uploading out of the overall sales that you (or
// the advertiser, in the third party case) can associate with a customer. In most
// cases, you will set this to 1.0.
// Continuing the example above for loyalty fraction, a value of 1.0 here indicates
// that you are uploading all 70 of the transactions that can be identified by an
// email address or phone number.
TransactionUploadFraction = 1.0
};
// Apply the custom key if provided.
if (!string.IsNullOrEmpty(customKey))
{
storeSalesMetadata.CustomKey = customKey;
}
// Creates additional metadata required for uploading third party data.
if (offlineUserDataJobType == OfflineUserDataJobType.StoreSalesUploadThirdParty)
{
StoreSalesThirdPartyMetadata storeSalesThirdPartyMetadata =
new StoreSalesThirdPartyMetadata()
{
// The date/time must be in the format "yyyy-MM-dd hh:mm:ss".
AdvertiserUploadDateTime = advertiserUploadDateTime,
// Sets the fraction of transactions you received from the advertiser that
// have valid formatting and values. This captures any transactions the
// advertiser provided to you but which you are unable to upload to Google
// due to formatting errors or missing data.
// In most cases, you will set this to 1.0.
ValidTransactionFraction = 1.0,
// Sets the fraction of valid transactions (as defined above) you received
// from the advertiser that you (the third party) have matched to an
// external user ID on your side.
// In most cases, you will set this to 1.0.
PartnerMatchFraction = 1.0,
// Sets the fraction of transactions you (the third party) are uploading out
// of the transactions you received from the advertiser that meet both of
// the following criteria:
// 1. Are valid in terms of formatting and values. See valid transaction
// fraction above.
// 2. You matched to an external user ID on your side. See partner match
// fraction above.
// In most cases, you will set this to 1.0.
PartnerUploadFraction = 1.0,
// Sets the version of partner IDs to be used for uploads.
// Please speak with your Google representative to get the values to use for
// the bridge map version and partner IDs.
BridgeMapVersionId = bridgeMapVersionId,
};
// Sets the third party partner ID uploading the transactions.
if (partnerId.HasValue)
{
storeSalesThirdPartyMetadata.PartnerId = partnerId.Value;
}
storeSalesMetadata.ThirdPartyMetadata = storeSalesThirdPartyMetadata;
}
// Creates a new offline user data job.
OfflineUserDataJob offlineUserDataJob = new OfflineUserDataJob()
{
Type = offlineUserDataJobType,
StoreSalesMetadata = storeSalesMetadata
};
if (externalId.HasValue)
{
offlineUserDataJob.ExternalId = externalId.Value;
}
// Issues a request to create the offline user data job.
CreateOfflineUserDataJobResponse createOfflineUserDataJobResponse =
offlineUserDataJobServiceClient.CreateOfflineUserDataJob(
customerId.ToString(), offlineUserDataJob);
string offlineUserDataJobResourceName = createOfflineUserDataJobResponse.ResourceName;
Console.WriteLine("Created an offline user data job with resource name: " +
$"{offlineUserDataJobResourceName}.");
return offlineUserDataJobResourceName;
}
/// <summary>
/// Adds operations to a job for a set of sample transactions.
/// </summary>
/// <param name="offlineUserDataJobServiceClient">The offline user data job service
/// client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="offlineUserDataJobResourceName">The resource name of the job to which to
/// add transactions.</param>
/// <param name="conversionActionId">The ID of a store sales conversion action.</param>
/// <param name="customKey">The custom key, or null if not uploading data with custom key
/// and value.</param>
/// <param name="itemId">A unique identifier of a product, or null if not uploading with
/// item attributes.</param>
/// <param name="merchantCenterAccountId">A Merchant Center Account ID, or null if not
/// uploading with item attributes.</param>
/// <param name="countryCode">A two-letter country code, or null if not uploading with
/// item attributes.</param>
/// <param name="languageCode">A two-letter language code, or null if not uploading with
/// item attributes.</param>
/// <param name="quantity">The number of items sold, or null if not uploading with
/// item attributes.</param>
private void AddTransactionsToOfflineUserDataJob(
OfflineUserDataJobServiceClient offlineUserDataJobServiceClient, long customerId,
string offlineUserDataJobResourceName, long conversionActionId, string customKey,
string itemId, long? merchantCenterAccountId, string countryCode, string languageCode,
long quantity)
{
// Constructions an operation for each transaction.
List<OfflineUserDataJobOperation> userDataJobOperations =
BuildOfflineUserDataJobOperations(customerId, conversionActionId, customKey, itemId,
merchantCenterAccountId, countryCode, languageCode, quantity);
// [START enable_warnings_1]
// Constructs a request with partial failure enabled to add the operations to the
// offline user data job, and enable_warnings set to true to retrieve warnings.
AddOfflineUserDataJobOperationsRequest request =
new AddOfflineUserDataJobOperationsRequest()
{
EnablePartialFailure = true,
ResourceName = offlineUserDataJobResourceName,
Operations = { userDataJobOperations },
EnableWarnings = true,
};
AddOfflineUserDataJobOperationsResponse response = offlineUserDataJobServiceClient
.AddOfflineUserDataJobOperations(request);
// [END enable_warnings_1]
// Prints the status message if any partial failure error is returned.
// NOTE: The details of each partial failure error are not printed here, you can refer
// to the example HandlePartialFailure.cs to learn more.
if (response.PartialFailureError != null)
{
Console.WriteLine($"Encountered {response.PartialFailureError.Details.Count} " +
$"partial failure errors while adding {userDataJobOperations.Count} " +
"operations to the offline user data job: " +
$"'{response.PartialFailureError.Message}'. Only the successfully added " +
"operations will be executed when the job runs.");
}
else
{
Console.WriteLine($"Successfully added {userDataJobOperations.Count} operations " +
"to the offline user data job.");
}
// [START enable_warnings_2]
// Prints the number of warnings if any warnings are returned. You can access
// details of each warning using the same approach you'd use for partial failure
// errors.
if (request.EnableWarnings && response.Warnings != null)
{
// Extracts the warnings from the response.
GoogleAdsFailure warnings = response.Warnings;
Console.WriteLine($"{warnings.Errors.Count} warning(s) occurred");
}
// [END enable_warnings_2]
}
/// <summary>
/// Creates a list of offline user data job operations for sample transactions.
/// </summary>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="conversionActionId">The ID of a store sales conversion action.</param>
/// <param name="customKey">The custom key, or null if not uploading data with custom key
/// and value.</param>
/// <param name="itemId">A unique identifier of a product, or null if not uploading with
/// item attributes.</param>
/// <param name="merchantCenterAccountId">A Merchant Center Account ID, or null if not
/// uploading with item attributes.</param>
/// <param name="countryCode">A two-letter country code, or null if not uploading with
/// item attributes.</param>
/// <param name="languageCode">A two-letter language code, or null if not uploading with
/// item attributes.</param>
/// <param name="quantity">The number of items sold, or null if not uploading with
/// item attributes.</param>
/// <returns>A list of operations.</returns>
private List<OfflineUserDataJobOperation> BuildOfflineUserDataJobOperations(long customerId,
long conversionActionId, string customKey, string itemId, long? merchantCenterAccountId,
string countryCode, string languageCode, long quantity)
{
// Create the first transaction for upload based on an email address and state.
UserData userDataWithEmailAddress = new UserData()
{
UserIdentifiers =
{
new UserIdentifier()
{
// Email addresses must be normalized and hashed.
HashedEmail = NormalizeAndHash("customer@example.com")
},
new UserIdentifier()
{
AddressInfo = new OfflineUserAddressInfo()
{
State = "NY"
}
},
},
TransactionAttribute = new TransactionAttribute()
{
ConversionAction =
ResourceNames.ConversionAction(customerId, conversionActionId),
CurrencyCode = "USD",
// Converts the transaction amount from $200 USD to micros.
// If item attributes are provided, this value represents the total value of the
// items after multiplying the unit price per item by the quantity provided in
// the ItemAttribute.
TransactionAmountMicros = 200L * 1_000_000L,
// Specifies the date and time of the transaction. The format is
// "YYYY-MM-DD HH:MM:SS[+HH:MM]", where [+HH:MM] is an optional
// timezone offset from UTC. If the offset is absent, the API will
// use the account's timezone as default. Examples: "2018-03-05 09:15:00"
// or "2018-02-01 14:34:30+03:00".
TransactionDateTime =
DateTime.Today.AddDays(-2).ToString("yyyy-MM-dd HH:mm:ss")
}
};
// Set the custom value if a custom key was provided.
if (!string.IsNullOrEmpty(customKey))
{
userDataWithEmailAddress.TransactionAttribute.CustomValue = CUSTOM_VALUE;
}
// Creates the second transaction for upload based on a physical address.
UserData userDataWithPhysicalAddress = new UserData()
{
UserIdentifiers =
{
new UserIdentifier()
{
AddressInfo = new OfflineUserAddressInfo()
{
// Names must be normalized and hashed.
HashedFirstName = NormalizeAndHash("John"),
HashedLastName = NormalizeAndHash("Doe"),
CountryCode = "US",
PostalCode = "10011"
}
}
},
TransactionAttribute = new TransactionAttribute()
{
ConversionAction =
ResourceNames.ConversionAction(customerId, conversionActionId),
CurrencyCode = "EUR",
// Converts the transaction amount from 450 EUR to micros.
TransactionAmountMicros = 450L * 1_000_000L,
// Specifies the date and time of the transaction. This date and time will be
// interpreted by the API using the Google Ads customer's time zone.
// The date/time must be in the format "yyyy-MM-dd hh:mm:ss".
// e.g. "2020-05-14 19:07:02".
TransactionDateTime = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss")
}
};
// Set the item attribute if provided.
if (!string.IsNullOrEmpty(itemId))
{
userDataWithPhysicalAddress.TransactionAttribute.ItemAttribute = new ItemAttribute
{
ItemId = itemId,
MerchantId = merchantCenterAccountId.Value,
CountryCode = countryCode,
LanguageCode = languageCode,
// Quantity field should only be set when at least one of the other item
// attributes is present.
Quantity = quantity
};
}
// Creates the operations to add the two transactions.
List<OfflineUserDataJobOperation> operations = new List<OfflineUserDataJobOperation>()
{
new OfflineUserDataJobOperation()
{
Create = userDataWithEmailAddress
},
new OfflineUserDataJobOperation()
{
Create = userDataWithPhysicalAddress
}
};
return operations;
}
/// <summary>
/// Normalizes and hashes a string value.
/// </summary>
/// <param name="value">The value to normalize and hash.</param>
/// <returns>The normalized and hashed value.</returns>
private static string NormalizeAndHash(string value)
{
return ToSha256String(_digest, ToNormalizedValue(value));
}
/// <summary>
/// Hash a string value using SHA-256 hashing algorithm.
/// </summary>
/// <param name="digest">Provides the algorithm for SHA-256.</param>
/// <param name="value">The string value (e.g. an email address) to hash.</param>
/// <returns>The hashed value.</returns>
private static string ToSha256String(SHA256 digest, string value)
{
byte[] digestBytes = digest.ComputeHash(Encoding.UTF8.GetBytes(value));
// Convert the byte array into an unhyphenated hexadecimal string.
return BitConverter.ToString(digestBytes).Replace("-", string.Empty);
}
/// <summary>
/// Removes leading and trailing whitespace and converts all characters to
/// lower case.
/// </summary>
/// <param name="value">The value to normalize.</param>
/// <returns>The normalized value.</returns>
private static string ToNormalizedValue(string value)
{
return value.Trim().ToLower();
}
/// <summary>
/// Retrieves, checks, and prints the status of the offline user data job.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="offlineUserDataJobResourceName">The resource name of the job whose status
/// you wish to check.</param>
private void CheckJobStatus(GoogleAdsClient client, long customerId,
string offlineUserDataJobResourceName)
{
GoogleAdsServiceClient googleAdsServiceClient =
client.GetService(Services.V10.GoogleAdsService);
string query = $@"SELECT offline_user_data_job.resource_name,
offline_user_data_job.id,
offline_user_data_job.status,
offline_user_data_job.type,
offline_user_data_job.failure_reason
FROM offline_user_data_job
WHERE offline_user_data_job.resource_name = '{offlineUserDataJobResourceName}'";
// Issues the query and gets the GoogleAdsRow containing the job from the response.
GoogleAdsRow googleAdsRow = googleAdsServiceClient.Search(
customerId.ToString(), query).First();
OfflineUserDataJob offlineUserDataJob = googleAdsRow.OfflineUserDataJob;
OfflineUserDataJobStatus jobStatus = offlineUserDataJob.Status;
Console.WriteLine($"Offline user data job ID {offlineUserDataJob.Id} with type " +
$"'{offlineUserDataJob.Type}' has status {offlineUserDataJob.Status}.");
if (jobStatus == OfflineUserDataJobStatus.Failed)
{
Console.WriteLine($"\tFailure reason: {offlineUserDataJob.FailureReason}");
}
else if (jobStatus == OfflineUserDataJobStatus.Pending |
jobStatus == OfflineUserDataJobStatus.Running)
{
Console.WriteLine("\nTo check the status of the job periodically, use the" +
$"following GAQL query with GoogleAdsService.Search:\n{query}\n");
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.GraphAlgorithms;
using Microsoft.Msagl.Core.Layout;
using Microsoft.Msagl.Layout.Layered;
using Microsoft.Msagl.Core;
namespace Microsoft.Msagl.Prototype.Phylo {
internal class PhyloTreeLayoutCalclulation : AlgorithmBase{
Anchor[] anchors;
ProperLayeredGraph properLayeredGraph;
Database dataBase;
PhyloTree tree;
BasicGraph<Node, IntEdge> intGraph;
LayerArrays layerArrays;
SortedDictionary<int, double> gridLayerOffsets = new SortedDictionary<int, double>();
double[] layerOffsets;
double cellSize;
Dictionary<Node, double> nodeOffsets = new Dictionary<Node, double>();
Dictionary<Node, int> nodesToIndices = new Dictionary<Node, int>();
int[] originalNodeToGridLayerIndices;
Dictionary<int, int> gridLayerToLayer=new Dictionary<int,int>();
///// <summary>
///// the layout responsible for the algorithm parameters
///// </summary>
internal SugiyamaLayoutSettings LayoutSettings { get; private set; }
internal PhyloTreeLayoutCalclulation(PhyloTree phyloTreeP, SugiyamaLayoutSettings settings, BasicGraph<Node, IntEdge> intGraphP, Database dataBase) {
this.dataBase = dataBase;
this.tree = phyloTreeP;
this.LayoutSettings = settings;
this.intGraph = intGraphP;
originalNodeToGridLayerIndices = new int[intGraph.Nodes.Count];
}
protected override void RunInternal() {
DefineCellSize();
CalculateOriginalNodeToGridLayerIndices();
CreateLayerArraysAndProperLayeredGraph();
FillDataBase();
RunXCoordinateAssignmentsByBrandes();
CalcTheBoxFromAnchors();
StretchIfNeeded();
ProcessPositionedAnchors();
// SugiyamaLayoutSettings.ShowDataBase(this.dataBase);
RouteSplines();
}
private void StretchIfNeeded() {
if (this.LayoutSettings.AspectRatio != 0) {
double aspectRatio = this.tree.Width / this.tree.Height;
StretchToDesiredAspectRatio(aspectRatio, LayoutSettings.AspectRatio);
}
}
private void StretchToDesiredAspectRatio(double aspectRatio, double desiredAR) {
if (aspectRatio > desiredAR)
StretchInYDirection(aspectRatio / desiredAR);
else if (aspectRatio < desiredAR)
StretchInXDirection(desiredAR / aspectRatio);
}
private void StretchInYDirection(double scaleFactor) {
double center = (this.tree.BoundingBox.Top + this.tree.BoundingBox.Bottom) / 2;
foreach (Anchor a in this.dataBase.Anchors) {
a.BottomAnchor *= scaleFactor;
a.TopAnchor *= scaleFactor;
a.Y = center + scaleFactor * (a.Y - center);
}
double h = this.tree.Height * scaleFactor;
this.tree.BoundingBox = new Rectangle(this.tree.BoundingBox.Left, center + h / 2, this.tree.BoundingBox.Right, center - h / 2);
}
private void StretchInXDirection(double scaleFactor) {
double center = (this.tree.BoundingBox.Left + this.tree.BoundingBox.Right) / 2;
foreach (Anchor a in this.dataBase.Anchors) {
a.LeftAnchor *= scaleFactor;
a.RightAnchor *= scaleFactor;
a.X = center + scaleFactor * (a.X - center);
}
double w = this.tree.Width * scaleFactor;
this.tree.BoundingBox =
new Rectangle(center - w / 2, tree.BoundingBox.Top,
center + w / 2, this.tree.BoundingBox.Bottom);
}
private void DefineCellSize() {
double min = double.MaxValue;
foreach (PhyloEdge e in this.tree.Edges)
min = Math.Min(min, e.Length);
this.cellSize=0.3*min;
}
private void CalculateOriginalNodeToGridLayerIndices() {
InitNodesToIndices();
FillNodeOffsets();
foreach (KeyValuePair<Node, double> kv in this.nodeOffsets) {
int nodeIndex = this.nodesToIndices[kv.Key];
int gridLayerIndex=originalNodeToGridLayerIndices[nodeIndex] = GetGridLayerIndex(kv.Value);
if (!gridLayerOffsets.ContainsKey(gridLayerIndex))
gridLayerOffsets[gridLayerIndex] = kv.Value;
}
}
private int GetGridLayerIndex(double len) {
return (int)(len / this.cellSize + 0.5);
}
private void InitNodesToIndices() {
for (int i = 0; i < this.intGraph.Nodes.Count; i++)
nodesToIndices[intGraph.Nodes[i]] = i;
}
private void FillNodeOffsets() {
FillNodeOffsets(0.0, tree.Root);
}
private void FillNodeOffsets(double p, Node node) {
nodeOffsets[node] = p;
foreach (PhyloEdge e in node.OutEdges)
FillNodeOffsets(p+e.Length, e.Target);
}
private void FillDataBase() {
foreach (IntEdge e in intGraph.Edges)
dataBase.RegisterOriginalEdgeInMultiedges(e);
SizeAnchors();
FigureYCoordinates();
}
private void FigureYCoordinates() {
double m = GetMultiplier();
int root = nodesToIndices[tree.Root];
CalculateAnchorsY(root,m,0);
for (int i = intGraph.NodeCount; i < dataBase.Anchors.Length; i++)
dataBase.Anchors[i].Y = -m * layerOffsets[layerArrays.Y[i]];
//fix layer offsets
for (int i = 0; i < layerOffsets.Length; i++)
layerOffsets[i] *= m;
}
private double GetMultiplier() {
double m = 1;
for (int i = layerArrays.Layers.Length - 1; i > 0; i--) {
double nm = GetMultiplierBetweenLayers(i);
if (nm > m)
m = nm;
}
return m;
}
private double GetMultiplierBetweenLayers(int i) {
int a = FindLowestBottomOnLayer(i);
int b = FindHighestTopOnLayer(i - 1);
double ay = NodeY(i, a);
double by = NodeY(i - 1, b);
// we need to have m*(a[y]-b[y])>=anchors[a].BottomAnchor+anchors[b].TopAnchor+layerSeparation;
double diff = ay - by;
if (diff < 0)
throw new InvalidOperationException();
double nm = (dataBase.Anchors[a].BottomAnchor + dataBase.Anchors[b].TopAnchor + LayoutSettings.LayerSeparation) / diff;
if (nm > 1)
return nm;
return 1;
}
private int FindHighestTopOnLayer(int layerIndex) {
int[] layer = layerArrays.Layers[layerIndex];
int ret = layer[0];
double top = NodeY(layerIndex, ret) + dataBase.Anchors[ret].TopAnchor;
for (int i = 1; i < layer.Length; i++) {
int node=layer[i];
double nt = NodeY(layerIndex, node) + dataBase.Anchors[node].TopAnchor;
if (nt > top) {
top = nt;
ret = node;
}
}
return ret;
}
private int FindLowestBottomOnLayer(int layerIndex) {
int[] layer = layerArrays.Layers[layerIndex];
int ret = layer[0];
double bottom = NodeY(layerIndex, ret) - dataBase.Anchors[ret].BottomAnchor;
for (int i = 1; i < layer.Length; i++) {
int node = layer[i];
double nb = NodeY(layerIndex, node) - dataBase.Anchors[node].BottomAnchor;
if (nb < bottom) {
bottom = nb;
ret = node;
}
}
return ret;
}
private double NodeY(int layer, int node) {
return - (IsOriginal(node) ? nodeOffsets[intGraph.Nodes[node]] : layerOffsets[layer]);
}
private bool IsOriginal(int node) {
return node < intGraph.NodeCount;
}
private void CalculateAnchorsY(int node, double m, double y) {
//go over original nodes
dataBase.Anchors[node].Y = -y;
foreach (IntEdge e in intGraph.OutEdges(node))
CalculateAnchorsY(e.Target, m, y + e.Edge.Length * m);
}
private void SizeAnchors() {
dataBase.Anchors = anchors = new Anchor[properLayeredGraph.NodeCount];
for (int i = 0; i < anchors.Length; i++)
anchors[i] = new Anchor(LayoutSettings.LabelCornersPreserveCoefficient);
//go over the old vertices
for (int i = 0; i < intGraph.NodeCount; i++)
CalcAnchorsForOriginalNode(i);
//go over virtual vertices
foreach (IntEdge intEdge in dataBase.AllIntEdges) {
if (intEdge.LayerEdges != null) {
foreach (LayerEdge layerEdge in intEdge.LayerEdges) {
int v = layerEdge.Target;
if (v != intEdge.Target) {
Anchor anchor = anchors[v];
if (!dataBase.MultipleMiddles.Contains(v)) {
anchor.LeftAnchor = anchor.RightAnchor = VirtualNodeWidth / 2.0f;
anchor.TopAnchor = anchor.BottomAnchor = VirtualNodeHeight / 2.0f;
} else {
anchor.LeftAnchor = anchor.RightAnchor = VirtualNodeWidth * 4;
anchor.TopAnchor = anchor.BottomAnchor = VirtualNodeHeight / 2.0f;
}
}
}
//fix label vertices
if (intEdge.Edge.Label!=null) {
int lj = intEdge.LayerEdges[intEdge.LayerEdges.Count / 2].Source;
Anchor a = anchors[lj];
double w = intEdge.LabelWidth, h = intEdge.LabelHeight;
a.RightAnchor = w;
a.LeftAnchor = LayoutSettings.NodeSeparation;
if (a.TopAnchor < h / 2.0)
a.TopAnchor = a.BottomAnchor = h / 2.0;
a.LabelToTheRightOfAnchorCenter = true;
}
}
}
}
/// <summary>
/// the width of dummy nodes
/// </summary>
static double VirtualNodeWidth {
get {
return 1;
}
}
/// <summary>
/// the height of dummy nodes
/// </summary>
double VirtualNodeHeight {
get {
return LayoutSettings.MinNodeHeight * 1.5f / 8;
}
}
void CalcAnchorsForOriginalNode(int i) {
double leftAnchor = 0;
double rightAnchor = leftAnchor;
double topAnchor = 0;
double bottomAnchor = topAnchor;
//that's what we would have without the label and multiedges
if (intGraph.Nodes != null) {
Node node = intGraph.Nodes[i];
ExtendStandardAnchors(ref leftAnchor, ref rightAnchor, ref topAnchor, ref bottomAnchor, node);
}
RightAnchorMultiSelfEdges(i, ref rightAnchor, ref topAnchor, ref bottomAnchor);
double hw = LayoutSettings.MinNodeWidth / 2;
if (leftAnchor < hw)
leftAnchor = hw;
if (rightAnchor < hw)
rightAnchor = hw;
double hh = LayoutSettings.MinNodeHeight / 2;
if (topAnchor < hh)
topAnchor = hh;
if (bottomAnchor < hh)
bottomAnchor = hh;
anchors[i] = new Anchor(leftAnchor, rightAnchor, topAnchor, bottomAnchor, this.intGraph.Nodes[i], LayoutSettings.LabelCornersPreserveCoefficient)
{Padding = this.intGraph.Nodes[i].Padding};
#if TEST_MSAGL
//anchors[i].Id = this.intGraph.Nodes[i].Id;
#endif
}
private static void ExtendStandardAnchors(ref double leftAnchor, ref double rightAnchor, ref double topAnchor, ref double bottomAnchor, Node node) {
double w = node.Width;
double h = node.Height;
w /= 2.0;
h /= 2.0;
rightAnchor = leftAnchor = w;
topAnchor = bottomAnchor = h;
}
private void RightAnchorMultiSelfEdges(int i, ref double rightAnchor, ref double topAnchor, ref double bottomAnchor) {
double delta = WidthOfSelfeEdge(i, ref rightAnchor, ref topAnchor, ref bottomAnchor);
rightAnchor += delta;
}
private double WidthOfSelfeEdge(int i, ref double rightAnchor, ref double topAnchor, ref double bottomAnchor) {
double delta = 0;
List<IntEdge> multiedges = dataBase.GetMultiedge(i, i);
//it could be a multiple self edge
if (multiedges.Count > 0) {
foreach (IntEdge e in multiedges) {
if (e.Edge.Label != null) {
rightAnchor += e.Edge.Label.Width;
if (topAnchor < e.Edge.Label.Height / 2.0)
topAnchor = bottomAnchor = e.Edge.Label.Height / 2.0f;
}
}
delta += (LayoutSettings.NodeSeparation + LayoutSettings.MinNodeWidth) * multiedges.Count;
}
return delta;
}
private void RouteSplines() {
Layout.Layered.Routing routing = new Layout.Layered.Routing(LayoutSettings, this.tree, dataBase, this.layerArrays, this.properLayeredGraph, null);
routing.Run();
}
private void RunXCoordinateAssignmentsByBrandes() {
XCoordsWithAlignment.CalculateXCoordinates(this.layerArrays, this.properLayeredGraph, this.tree.Nodes.Count, this.dataBase.Anchors, this.LayoutSettings.NodeSeparation);
}
private void CreateLayerArraysAndProperLayeredGraph() {
int numberOfLayers = this.gridLayerOffsets.Count;
this.layerOffsets=new double[numberOfLayers];
int i = numberOfLayers-1;
foreach (KeyValuePair<int, double> kv in this.gridLayerOffsets) {
layerOffsets[i] = kv.Value;
gridLayerToLayer[kv.Key] = i--;
}
int nOfNodes=CountTotalNodesIncludingVirtual(nodesToIndices[tree.Root]);
////debugging !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//int tt = 0;
//foreach (IntEdge ie in this.intGraph.Edges)
// tt += this.OriginalNodeLayer(ie.Source) - this.OriginalNodeLayer(ie.Target) - 1;
//if (tt + this.intGraph.Nodes.Count != nOfNodes)
// throw new Exception();
int[] layering = new int[nOfNodes];
List<int>[] layers = new List<int>[numberOfLayers];
for (i = 0; i < numberOfLayers; i++)
layers[i] = new List<int>();
WalkTreeAndInsertLayerEdges(layering, layers);
this.layerArrays = new LayerArrays(layering);
int[][]ll=layerArrays.Layers=new int[numberOfLayers][];
i = 0;
foreach (List<int> layer in layers) {
ll[i++] = layer.ToArray();
}
this.properLayeredGraph = new ProperLayeredGraph(intGraph);
}
private int CountTotalNodesIncludingVirtual(int node) {
int ret = 1;
foreach (IntEdge edge in this.intGraph.OutEdges(node))
ret += NumberOfVirtualNodesOnEdge(edge) + CountTotalNodesIncludingVirtual(edge.Target);
return ret;
}
private int NumberOfVirtualNodesOnEdge(IntEdge edge) {
return OriginalNodeLayer(edge.Source) - OriginalNodeLayer(edge.Target) - 1;
}
private int OriginalNodeLayer(int node) {
return gridLayerToLayer[originalNodeToGridLayerIndices[node]];
}
private void WalkTreeAndInsertLayerEdges(int[] layering, List<int>[] layers) {
int virtualNode = this.intGraph.NodeCount;
int root = nodesToIndices[tree.Root];
int l;
layering[root] = l = OriginalNodeLayer(root);
layers[l].Add(root);
WalkTreeAndInsertLayerEdges(layering, layers, root , ref virtualNode);
}
private void WalkTreeAndInsertLayerEdges(int[] layering, List<int>[] layers, int node, ref int virtualNode) {
foreach (IntEdge edge in this.intGraph.OutEdges(node))
InsertLayerEdgesForEdge(edge, layering, ref virtualNode, layers);
}
private void InsertLayerEdgesForEdge(IntEdge edge, int[] layering, ref int virtualNode, List<int>[] layers) {
int span = OriginalNodeLayer(edge.Source) - OriginalNodeLayer(edge.Target);
edge.LayerEdges=new LayerEdge[span];
for (int i = 0; i < span; i++)
edge.LayerEdges[i] = new LayerEdge(GetSource(i, edge, ref virtualNode), GetTarget(i, span, edge, virtualNode), edge.CrossingWeight);
int l = OriginalNodeLayer(edge.Source) - 1;
for (int i = 0; i < span; i++) {
int node=edge.LayerEdges[i].Target;
layering[node] = l;
layers[l--].Add(node);
}
WalkTreeAndInsertLayerEdges(layering, layers, edge.Target, ref virtualNode);
}
static private int GetTarget(int i, int span, IntEdge edge, int virtualNode) {
if (i < span-1)
return virtualNode;
return edge.Target;
}
static private int GetSource(int i, IntEdge edge, ref int virtualNode) {
if (i > 0)
return virtualNode++;
return edge.Source;
}
void ProcessPositionedAnchors() {
for (int i = 0; i < this.tree.Nodes.Count; i++)
intGraph.Nodes[i].Center=anchors[i].Origin;
}
private void CalcTheBoxFromAnchors() {
if (anchors.Length > 0) {
Rectangle box = new Rectangle(anchors[0].Left, anchors[0].Top, anchors[0].Right, anchors[0].Bottom);
for (int i = 1; i < anchors.Length; i++) {
Anchor a = anchors[i];
box.Add(a.LeftTop);
box.Add(a.RightBottom);
}
double m = Math.Max(box.Width, box.Height);
double delta = this.tree.Margins / 100.0 * m;
Point del = new Point(-delta, delta);
box.Add(box.LeftTop + del);
box.Add(box.RightBottom - del);
this.tree.BoundingBox = box;
}
}
}
}
| |
// ----------------------------------------------------------------------------
// <copyright file="PhotonView.cs" company="Exit Games GmbH">
// PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH
// </copyright>
// <summary>
//
// </summary>
// <author>developer@exitgames.com</author>
// ----------------------------------------------------------------------------
using UnityEngine;
using System.Reflection;
#if UNITY_EDITOR
using UnityEditor;
#endif
public enum ViewSynchronization { Off, ReliableDeltaCompressed, Unreliable, UnreliableOnChange }
public enum OnSerializeTransform { OnlyPosition, OnlyRotation, OnlyScale, PositionAndRotation, All }
public enum OnSerializeRigidBody { OnlyVelocity, OnlyAngularVelocity, All }
/// <summary>Defines the OnPhotonSerializeView method, so it's easy to implement (correctly) for observable scripts.</summary>
public interface IPunObservable { void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info); }
/// <summary>
/// PUN's NetworkView replacement class for networking. Use it like a NetworkView.
/// </summary>
/// \ingroup publicApi
[AddComponentMenu("Miscellaneous/Photon View &v")]
public class PhotonView : Photon.MonoBehaviour
{
#if UNITY_EDITOR
[ContextMenu("Open PUN Wizard")]
void OpenPunWizard()
{
EditorApplication.ExecuteMenuItem("Window/Photon Unity Networking");
}
#endif
public int subId;
public int ownerId;
public int group = 0;
protected internal bool mixedModeIsReliable = false;
// NOTE: this is now an integer because unity won't serialize short (needed for instantiation). we SEND only a short though!
// NOTE: prefabs have a prefixBackup of -1. this is replaced with any currentLevelPrefix that's used at runtime. instantiated GOs get their prefix set pre-instantiation (so those are not -1 anymore)
public int prefix
{
get
{
if (this.prefixBackup == -1 && PhotonNetwork.networkingPeer != null)
{
this.prefixBackup = PhotonNetwork.networkingPeer.currentLevelPrefix;
}
return this.prefixBackup;
}
set { this.prefixBackup = value; }
}
// this field is serialized by unity. that means it is copied when instantiating a persistent obj into the scene
public int prefixBackup = -1;
/// <summary>
/// This is the instantiationData that was passed when calling PhotonNetwork.Instantiate* (if that was used to spawn this prefab)
/// </summary>
public object[] instantiationData
{
get
{
if (!this.didAwake)
{
// even though viewID and instantiationID are setup before the GO goes live, this data can't be set. as workaround: fetch it if needed
this.instantiationDataField = PhotonNetwork.networkingPeer.FetchInstantiationData(this.instantiationId);
}
return this.instantiationDataField;
}
set { this.instantiationDataField = value; }
}
private object[] instantiationDataField;
/// <summary>
/// For internal use only, don't use
/// </summary>
protected internal object[] lastOnSerializeDataSent = null;
/// <summary>
/// For internal use only, don't use
/// </summary>
protected internal object[] lastOnSerializeDataReceived = null;
public Component observed;
public ViewSynchronization synchronization;
public OnSerializeTransform onSerializeTransformOption = OnSerializeTransform.PositionAndRotation;
public OnSerializeRigidBody onSerializeRigidBodyOption = OnSerializeRigidBody.All;
/// <summary>
/// The ID of the PhotonView. Identifies it in a networked game (per room).
/// </summary>
/// <remarks>See: [Network Instantiation](@ref instantiateManual)</remarks>
public int viewID
{
get { return ownerId * PhotonNetwork.MAX_VIEW_IDS + subId; }
set
{
// if ID was 0 for an awakened PhotonView, the view should add itself into the networkingPeer.photonViewList after setup
bool viewMustRegister = this.didAwake && this.subId == 0;
// TODO: decide if a viewID can be changed once it wasn't 0. most likely that is not a good idea
// check if this view is in networkingPeer.photonViewList and UPDATE said list (so we don't keep the old viewID with a reference to this object)
// PhotonNetwork.networkingPeer.RemovePhotonView(this, true);
this.ownerId = value / PhotonNetwork.MAX_VIEW_IDS;
this.subId = value % PhotonNetwork.MAX_VIEW_IDS;
if (viewMustRegister)
{
PhotonNetwork.networkingPeer.RegisterPhotonView(this);
}
//Debug.Log("Set viewID: " + value + " -> owner: " + this.ownerId + " subId: " + this.subId);
}
}
public int instantiationId; // if the view was instantiated with a GO, this GO has a instantiationID (first view's viewID)
/// <summary>True if the PhotonView was loaded with the scene (game object) or instantiated with InstantiateSceneObject.</summary>
/// <remarks>
/// Scene objects are not owned by a particular player but belong to the scene. Thus they don't get destroyed when their
/// creator leaves the game and the current Master Client can control them (whoever that is).
/// The ownerId is 0 (player IDs are 1 and up).
/// </remarks>
public bool isSceneView
{
get { return this.ownerId == 0; }
}
/// <summary>
/// The owner of a PhotonView is the player who created the GameObject with that view. Objects in the scene don't have an owner.
/// </summary>
public PhotonPlayer owner
{
get { return PhotonPlayer.Find(this.ownerId); }
}
public int OwnerActorNr
{
get { return this.ownerId; }
}
/// <summary>
/// True if the PhotonView is "mine" and can be controlled by this client.
/// </summary>
/// <remarks>
/// PUN has an ownership concept that defines who can control and destroy each PhotonView.
/// True in case the owner matches the local PhotonPlayer.
/// True if this is a scene photonview on the Master client.
/// </remarks>
public bool isMine
{
get
{
return (this.ownerId == PhotonNetwork.player.ID) || (this.isSceneView && PhotonNetwork.isMasterClient);
}
}
private bool didAwake;
protected internal bool destroyedByPhotonNetworkOrQuit;
/// <summary>Called by Unity on start of the application and does a setup the PhotonView.</summary>
protected internal void Awake()
{
// registration might be too late when some script (on this GO) searches this view BUT GetPhotonView() can search ALL in that case
PhotonNetwork.networkingPeer.RegisterPhotonView(this);
this.instantiationDataField = PhotonNetwork.networkingPeer.FetchInstantiationData(this.instantiationId);
this.didAwake = true;
}
protected internal void OnApplicationQuit()
{
destroyedByPhotonNetworkOrQuit = true; // on stop-playing its ok Destroy is being called directly (not by PN.Destroy())
}
protected internal void OnDestroy()
{
if (!this.destroyedByPhotonNetworkOrQuit)
{
PhotonNetwork.networkingPeer.LocalCleanPhotonView(this);
}
if (!this.destroyedByPhotonNetworkOrQuit && !Application.isLoadingLevel)
{
if (this.instantiationId > 0)
{
// if this viewID was not manually assigned (and we're not shutting down or loading a level), you should use PhotonNetwork.Destroy() to get rid of GOs with PhotonViews
Debug.LogError("OnDestroy() seems to be called without PhotonNetwork.Destroy()?! GameObject: " + this.gameObject + " Application.isLoadingLevel: " + Application.isLoadingLevel);
}
else
{
// this seems to be a manually instantiated PV. if it's local, we could warn if the ID is not in the allocated-list
if (this.viewID <= 0)
{
Debug.LogWarning(string.Format("OnDestroy manually allocated PhotonView {0}. The viewID is 0. Was it ever (manually) set?", this));
}
else if (this.isMine && !PhotonNetwork.manuallyAllocatedViewIds.Contains(this.viewID))
{
Debug.LogWarning(string.Format("OnDestroy manually allocated PhotonView {0}. The viewID is local (isMine) but not in manuallyAllocatedViewIds list. Use UnAllocateViewID() after you destroyed the PV.", this));
}
}
}
if (PhotonNetwork.networkingPeer.instantiatedObjects.ContainsKey(this.instantiationId))
{
// Unity destroys GOs and PVs at the end of a frame. In worst case, a instantiate created a new view with the same id. Let's compare the associated GameObject.
GameObject instGo = PhotonNetwork.networkingPeer.instantiatedObjects[this.instantiationId];
bool instanceIsThisOne = (instGo == this.gameObject);
if (instanceIsThisOne)
{
Debug.LogWarning(string.Format("OnDestroy for PhotonView {0} but GO is still in instantiatedObjects. instantiationId: {1}. Use PhotonNetwork.Destroy(). {2} Identical with this: {3} PN.Destroyed called for this PV: {4}", this, this.instantiationId, Application.isLoadingLevel ? "Loading new scene caused this." : "", instanceIsThisOne, destroyedByPhotonNetworkOrQuit));
}
}
}
private MethodInfo OnSerializeMethodInfo;
private bool failedToFindOnSerialize;
internal protected void ExecuteOnSerialize(PhotonStream pStream, PhotonMessageInfo info)
{
if (this.failedToFindOnSerialize)
{
return;
}
if (this.OnSerializeMethodInfo == null)
{
if (!NetworkingPeer.GetMethod(this.observed as MonoBehaviour, PhotonNetworkingMessage.OnPhotonSerializeView.ToString(), out this.OnSerializeMethodInfo))
{
Debug.LogError("The observed monobehaviour (" + this.observed.name + ") of this PhotonView does not implement OnPhotonSerializeView()!");
this.failedToFindOnSerialize = true;
return;
}
}
this.OnSerializeMethodInfo.Invoke((object)this.observed, new object[] { pStream, info });
}
/// <summary>
/// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client).
/// </summary>
/// <remarks>
/// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN.
/// It enables you to make every client in a room call a specific method.
///
/// RPC calls can target "All" or the "Others".
/// Usually, the target "All" gets executed locally immediately after sending the RPC.
/// The "*ViaServer" options send the RPC to the server and execute it on this client when it's sent back.
/// Of course, calls are affected by this client's lag and that of remote clients.
///
/// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the
/// originating client.
///
/// See: [Remote Procedure Calls](@ref rpcManual).
/// </remarks>
/// <param name="methodName">The name of a fitting method that was has the RPC attribute.</param>
/// <param name="target">The group of targets and the way the RPC gets sent.</param>
/// <param name="parameters">The parameters that the RPC method has (must fit this call!).</param>
public void RPC(string methodName, PhotonTargets target, params object[] parameters)
{
if(PhotonNetwork.networkingPeer.hasSwitchedMC && target == PhotonTargets.MasterClient)
{
PhotonNetwork.RPC(this, methodName, PhotonNetwork.masterClient, parameters);
}
else
{
PhotonNetwork.RPC(this, methodName, target, parameters);
}
}
/// <summary>
/// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client).
/// </summary>
/// <remarks>
/// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN.
/// It enables you to make every client in a room call a specific method.
///
/// This method allows you to make an RPC calls on a specific player's client.
/// Of course, calls are affected by this client's lag and that of remote clients.
///
/// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the
/// originating client.
///
/// See: [Remote Procedure Calls](@ref rpcManual).
/// </remarks>
/// <param name="methodName">The name of a fitting method that was has the RPC attribute.</param>
/// <param name="targetPlayer">The group of targets and the way the RPC gets sent.</param>
/// <param name="parameters">The parameters that the RPC method has (must fit this call!).</param>
public void RPC(string methodName, PhotonPlayer targetPlayer, params object[] parameters)
{
PhotonNetwork.RPC(this, methodName, targetPlayer, parameters);
}
public static PhotonView Get(Component component)
{
return component.GetComponent<PhotonView>();
}
public static PhotonView Get(GameObject gameObj)
{
return gameObj.GetComponent<PhotonView>();
}
public static PhotonView Find(int viewID)
{
return PhotonNetwork.networkingPeer.GetPhotonView(viewID);
}
public override string ToString()
{
return string.Format("View ({3}){0} on {1} {2}", this.viewID, (this.gameObject != null) ? this.gameObject.name : "GO==null", (this.isSceneView) ? "(scene)" : string.Empty, this.prefix);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureParameterGrouping
{
using Fixtures.Azure;
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>
/// ParameterGroupingOperations operations.
/// </summary>
internal partial class ParameterGroupingOperations : IServiceOperations<AutoRestParameterGroupingTestService>, IParameterGroupingOperations
{
/// <summary>
/// Initializes a new instance of the ParameterGroupingOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ParameterGroupingOperations(AutoRestParameterGroupingTestService client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestParameterGroupingTestService
/// </summary>
public AutoRestParameterGroupingTestService Client { get; private set; }
/// <summary>
/// Post a bunch of required parameters grouped
/// </summary>
/// <param name='parameterGroupingPostRequiredParameters'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="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> PostRequiredWithHttpMessagesAsync(ParameterGroupingPostRequiredParameters parameterGroupingPostRequiredParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (parameterGroupingPostRequiredParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameterGroupingPostRequiredParameters");
}
if (parameterGroupingPostRequiredParameters != null)
{
parameterGroupingPostRequiredParameters.Validate();
}
int body = default(int);
if (parameterGroupingPostRequiredParameters != null)
{
body = parameterGroupingPostRequiredParameters.Body;
}
string customHeader = default(string);
if (parameterGroupingPostRequiredParameters != null)
{
customHeader = parameterGroupingPostRequiredParameters.CustomHeader;
}
int? query = default(int?);
if (parameterGroupingPostRequiredParameters != null)
{
query = parameterGroupingPostRequiredParameters.Query;
}
string path = default(string);
if (parameterGroupingPostRequiredParameters != null)
{
path = parameterGroupingPostRequiredParameters.Path;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("body", body);
tracingParameters.Add("customHeader", customHeader);
tracingParameters.Add("query", query);
tracingParameters.Add("path", path);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostRequired", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/postRequired/{path}").ToString();
_url = _url.Replace("{path}", System.Uri.EscapeDataString(path));
List<string> _queryParameters = new List<string>();
if (query != null)
{
_queryParameters.Add(string.Format("query={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(query, Client.SerializationSettings).Trim('"'))));
}
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("POST");
_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 (customHeader != null)
{
if (_httpRequest.Headers.Contains("customHeader"))
{
_httpRequest.Headers.Remove("customHeader");
}
_httpRequest.Headers.TryAddWithoutValidation("customHeader", customHeader);
}
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;
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(body, 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;
}
/// <summary>
/// Post a bunch of optional parameters grouped
/// </summary>
/// <param name='parameterGroupingPostOptionalParameters'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostOptionalWithHttpMessagesAsync(ParameterGroupingPostOptionalParameters parameterGroupingPostOptionalParameters = default(ParameterGroupingPostOptionalParameters), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string customHeader = default(string);
if (parameterGroupingPostOptionalParameters != null)
{
customHeader = parameterGroupingPostOptionalParameters.CustomHeader;
}
int? query = default(int?);
if (parameterGroupingPostOptionalParameters != null)
{
query = parameterGroupingPostOptionalParameters.Query;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("customHeader", customHeader);
tracingParameters.Add("query", query);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostOptional", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/postOptional").ToString();
List<string> _queryParameters = new List<string>();
if (query != null)
{
_queryParameters.Add(string.Format("query={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(query, Client.SerializationSettings).Trim('"'))));
}
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("POST");
_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 (customHeader != null)
{
if (_httpRequest.Headers.Contains("customHeader"))
{
_httpRequest.Headers.Remove("customHeader");
}
_httpRequest.Headers.TryAddWithoutValidation("customHeader", customHeader);
}
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();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Post parameters from multiple different parameter groups
/// </summary>
/// <param name='firstParameterGroup'>
/// Additional parameters for the operation
/// </param>
/// <param name='parameterGroupingPostMultiParamGroupsSecondParamGroup'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostMultiParamGroupsWithHttpMessagesAsync(FirstParameterGroup firstParameterGroup = default(FirstParameterGroup), ParameterGroupingPostMultiParamGroupsSecondParamGroup parameterGroupingPostMultiParamGroupsSecondParamGroup = default(ParameterGroupingPostMultiParamGroupsSecondParamGroup), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string headerOne = default(string);
if (firstParameterGroup != null)
{
headerOne = firstParameterGroup.HeaderOne;
}
int? queryOne = default(int?);
if (firstParameterGroup != null)
{
queryOne = firstParameterGroup.QueryOne;
}
string headerTwo = default(string);
if (parameterGroupingPostMultiParamGroupsSecondParamGroup != null)
{
headerTwo = parameterGroupingPostMultiParamGroupsSecondParamGroup.HeaderTwo;
}
int? queryTwo = default(int?);
if (parameterGroupingPostMultiParamGroupsSecondParamGroup != null)
{
queryTwo = parameterGroupingPostMultiParamGroupsSecondParamGroup.QueryTwo;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("headerOne", headerOne);
tracingParameters.Add("queryOne", queryOne);
tracingParameters.Add("headerTwo", headerTwo);
tracingParameters.Add("queryTwo", queryTwo);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostMultiParamGroups", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/postMultipleParameterGroups").ToString();
List<string> _queryParameters = new List<string>();
if (queryOne != null)
{
_queryParameters.Add(string.Format("query-one={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(queryOne, Client.SerializationSettings).Trim('"'))));
}
if (queryTwo != null)
{
_queryParameters.Add(string.Format("query-two={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(queryTwo, Client.SerializationSettings).Trim('"'))));
}
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("POST");
_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 (headerOne != null)
{
if (_httpRequest.Headers.Contains("header-one"))
{
_httpRequest.Headers.Remove("header-one");
}
_httpRequest.Headers.TryAddWithoutValidation("header-one", headerOne);
}
if (headerTwo != null)
{
if (_httpRequest.Headers.Contains("header-two"))
{
_httpRequest.Headers.Remove("header-two");
}
_httpRequest.Headers.TryAddWithoutValidation("header-two", headerTwo);
}
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();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Post parameters with a shared parameter group object
/// </summary>
/// <param name='firstParameterGroup'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostSharedParameterGroupObjectWithHttpMessagesAsync(FirstParameterGroup firstParameterGroup = default(FirstParameterGroup), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string headerOne = default(string);
if (firstParameterGroup != null)
{
headerOne = firstParameterGroup.HeaderOne;
}
int? queryOne = default(int?);
if (firstParameterGroup != null)
{
queryOne = firstParameterGroup.QueryOne;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("headerOne", headerOne);
tracingParameters.Add("queryOne", queryOne);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostSharedParameterGroupObject", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/sharedParameterGroupObject").ToString();
List<string> _queryParameters = new List<string>();
if (queryOne != null)
{
_queryParameters.Add(string.Format("query-one={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(queryOne, Client.SerializationSettings).Trim('"'))));
}
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("POST");
_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 (headerOne != null)
{
if (_httpRequest.Headers.Contains("header-one"))
{
_httpRequest.Headers.Remove("header-one");
}
_httpRequest.Headers.TryAddWithoutValidation("header-one", headerOne);
}
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();
_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;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using log4net.Config;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Monitoring;
using OpenSim.Framework.Servers;
using System;
using System.IO;
using System.Reflection;
using System.Xml;
namespace OpenSim.Server.Base
{
public class ServicesServerBase : ServerBase
{
// Command line args
//
protected string[] m_Arguments;
// Logger
//
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Run flag
//
private bool m_Running = true;
// Handle all the automagical stuff
//
public ServicesServerBase(string prompt, string[] args)
: base()
{
// Save raw arguments
m_Arguments = args;
// Read command line
ArgvConfigSource argvConfig = new ArgvConfigSource(args);
argvConfig.AddSwitch("Startup", "console", "c");
argvConfig.AddSwitch("Startup", "logfile", "l");
argvConfig.AddSwitch("Startup", "inifile", "i");
argvConfig.AddSwitch("Startup", "prompt", "p");
argvConfig.AddSwitch("Startup", "logconfig", "g");
// Automagically create the ini file name
string fileName = Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location);
string iniFile = fileName + ".ini";
string logConfig = null;
IConfig startupConfig = argvConfig.Configs["Startup"];
if (startupConfig != null)
{
// Check if a file name was given on the command line
iniFile = startupConfig.GetString("inifile", iniFile);
// Check if a prompt was given on the command line
prompt = startupConfig.GetString("prompt", prompt);
// Check for a Log4Net config file on the command line
logConfig = startupConfig.GetString("logconfig", logConfig);
}
// Find out of the file name is a URI and remote load it if possible.
// Load it as a local file otherwise.
Uri configUri;
try
{
if (Uri.TryCreate(iniFile, UriKind.Absolute, out configUri) &&
configUri.Scheme == Uri.UriSchemeHttp)
{
XmlReader r = XmlReader.Create(iniFile);
Config = new XmlConfigSource(r);
}
else
{
Config = new IniConfigSource(iniFile);
}
}
catch (Exception e)
{
System.Console.WriteLine("Error reading from config source. {0}", e.Message);
Environment.Exit(1);
}
// Merge OpSys env vars
m_log.Info("[CONFIG]: Loading environment variables for Config");
Util.MergeEnvironmentToConfig(Config);
// Merge the configuration from the command line into the loaded file
Config.Merge(argvConfig);
// Refresh the startupConfig post merge
if (Config.Configs["Startup"] != null)
{
startupConfig = Config.Configs["Startup"];
}
ConfigDirectory = startupConfig.GetString("ConfigDirectory", ".");
prompt = startupConfig.GetString("Prompt", prompt);
// Allow derived classes to load config before the console is opened.
ReadConfig();
// Create main console
string consoleType = "local";
if (startupConfig != null)
consoleType = startupConfig.GetString("console", consoleType);
if (consoleType == "basic")
{
MainConsole.Instance = new CommandConsole(prompt);
}
else if (consoleType == "rest")
{
MainConsole.Instance = new RemoteConsole(prompt);
((RemoteConsole)MainConsole.Instance).ReadConfig(Config);
}
else
{
MainConsole.Instance = new LocalConsole(prompt);
}
m_console = MainConsole.Instance;
if (logConfig != null)
{
FileInfo cfg = new FileInfo(logConfig);
XmlConfigurator.Configure(cfg);
}
else
{
XmlConfigurator.Configure();
}
LogEnvironmentInformation();
RegisterCommonAppenders(startupConfig);
if (startupConfig.GetString("PIDFile", String.Empty) != String.Empty)
{
CreatePIDFile(startupConfig.GetString("PIDFile"));
}
RegisterCommonCommands();
RegisterCommonComponents(Config);
// Allow derived classes to perform initialization that
// needs to be done after the console has opened
Initialise();
}
public string ConfigDirectory
{
get;
private set;
}
public bool Running
{
get { return m_Running; }
}
public virtual int Run()
{
Watchdog.Enabled = true;
MemoryWatchdog.Enabled = true;
while (m_Running)
{
try
{
MainConsole.Instance.Prompt();
}
catch (Exception e)
{
m_log.ErrorFormat("Command error: {0}", e);
}
}
RemovePIDFile();
return 0;
}
protected virtual void Initialise()
{
}
protected virtual void ReadConfig()
{
}
protected override void ShutdownSpecific()
{
m_Running = false;
m_log.Info("[CONSOLE] Quitting");
base.ShutdownSpecific();
}
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// 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 Newtonsoft.Json;
using Sensus.Shared.UI.UiProperties;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using Syncfusion.SfChart.XForms;
using System.Threading.Tasks;
using Sensus.Shared.Context;
namespace Sensus.Shared.Probes
{
/// <summary>
/// An abstract probe.
/// </summary>
public abstract class Probe
{
#region static members
public static List<Probe> GetAll()
{
List<Probe> probes = null;
// the reflection stuff we do below (at least on android) needs to be run on the main thread.
SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(() =>
{
probes = Assembly.GetExecutingAssembly().GetTypes().Where(t => !t.IsAbstract && t.IsSubclassOf(typeof(Probe))).Select(t => Activator.CreateInstance(t) as Probe).OrderBy(p => p.DisplayName).ToList();
});
return probes;
}
#endregion
/// <summary>
/// Fired when the most recently sensed datum is changed, regardless of whether the datum was stored.
/// </summary>
public event EventHandler<Tuple<Datum, Datum>> MostRecentDatumChanged;
private bool _enabled;
private bool _running;
private Datum _mostRecentDatum;
private Protocol _protocol;
private bool _storeData;
private DateTimeOffset _mostRecentStoreTimestamp;
private bool _originallyEnabled;
private List<Tuple<bool, DateTime>> _startStopTimes;
private List<DateTime> _successfulHealthTestTimes;
private List<ChartDataPoint> _chartData;
private int _maxChartDataCount;
private bool _runLocalCommitOnStore;
private readonly object _locker = new object();
[JsonIgnore]
public abstract string DisplayName { get; }
[JsonIgnore]
public abstract string CollectionDescription { get; }
[OnOffUiProperty("Enabled:", true, 2)]
public bool Enabled
{
get { return _enabled; }
set
{
if (value != _enabled)
{
_enabled = value;
// _protocol can be null when deserializing the probe -- if Enabled is set before Protocol
if (_protocol != null && _protocol.Running)
{
if (_enabled)
StartAsync();
else
StopAsync();
}
}
}
}
/// <summary>
/// Gets or sets whether or not this probe was originally enabled within the protocol. Some probes can become disabled when
/// attempting to start them. For example, the temperature probe might not be supported on all hardware and will thus become
/// disabled after its failed initialization. Thus, we need a separate variable (other than Enabled) to tell us whether the
/// probe was originally enabled. We use this value to calculate participation levels and also to restore the probe before
/// sharing it with others (e.g., since other people might have temperature hardware in their devices).
/// </summary>
/// <value>Whether or not this probe was enabled the first time the protocol was started.</value>
public bool OriginallyEnabled
{
get
{
return _originallyEnabled;
}
set
{
_originallyEnabled = value;
}
}
[JsonIgnore]
public bool Running
{
get { return _running; }
}
/// <summary>
/// Gets or sets the datum that was most recently sensed, regardless of whether the datum was stored.
/// </summary>
/// <value>The most recent datum.</value>
[JsonIgnore]
public Datum MostRecentDatum
{
get { return _mostRecentDatum; }
set
{
if (value != _mostRecentDatum)
{
Datum previousDatum = _mostRecentDatum;
_mostRecentDatum = value;
if (MostRecentDatumChanged != null)
MostRecentDatumChanged(this, new Tuple<Datum, Datum>(previousDatum, _mostRecentDatum));
}
}
}
[JsonIgnore]
public DateTimeOffset MostRecentStoreTimestamp
{
get { return _mostRecentStoreTimestamp; }
}
public Protocol Protocol
{
get { return _protocol; }
set { _protocol = value; }
}
[OnOffUiProperty("Store Data:", true, 3)]
public bool StoreData
{
get { return _storeData; }
set { _storeData = value; }
}
[JsonIgnore]
public abstract Type DatumType { get; }
[JsonIgnore]
protected abstract float RawParticipation { get; }
/// <summary>
/// Gets a list of times at which the probe was started (tuple bool = True) and stopped (tuple bool = False). Only includes
/// those that have occurred within the protocol's participation horizon.
/// </summary>
/// <value>The start stop times.</value>
public List<Tuple<bool, DateTime>> StartStopTimes
{
get { return _startStopTimes; }
}
/// <summary>
/// Gets the successful health test times. Only includes those that have occurred within the
/// protocol's participation horizon.
/// </summary>
/// <value>The successful health test times.</value>
public List<DateTime> SuccessfulHealthTestTimes
{
get { return _successfulHealthTestTimes; }
}
[EntryIntegerUiProperty("Max Chart Data Count:", true, 50)]
public int MaxChartDataCount
{
get
{
return _maxChartDataCount;
}
set
{
if (value > 0)
_maxChartDataCount = value;
// trim chart data collection
lock (_chartData)
{
while (_chartData.Count > 0 && _chartData.Count > _maxChartDataCount)
_chartData.RemoveAt(0);
}
}
}
[OnOffUiProperty("Run Local Commit On Store:", true, 14)]
public bool RunLocalCommitOnStore
{
get
{
return _runLocalCommitOnStore;
}
set
{
_runLocalCommitOnStore = value;
}
}
protected Probe()
{
_enabled = _running = false;
_storeData = true;
_startStopTimes = new List<Tuple<bool, DateTime>>();
_successfulHealthTestTimes = new List<DateTime>();
_maxChartDataCount = 10;
_chartData = new List<ChartDataPoint>(_maxChartDataCount + 1);
}
/// <summary>
/// Initializes this probe. Throws an exception if initialization fails.
/// </summary>
protected virtual void Initialize()
{
lock (_chartData)
{
_chartData.Clear();
}
_mostRecentDatum = null;
_mostRecentStoreTimestamp = DateTimeOffset.UtcNow; // mark storage delay from initialization of probe
}
/// <summary>
/// Gets the participation level for the current probe. If this probe was originally enabled within the protocol, then
/// this will be a value between 0 and 1, with 1 indicating perfect participation and 0 indicating no participation. If
/// this probe was not originally enabled within the protocol, then the returned value will be null, indicating that this
/// probe should not be included in calculations of overall protocol participation. Probes can become disabled if they
/// are not supported on the current device or if the user refuses to initialize them (e.g., by not signing into Facebook).
/// Although they become disabled, they were originally enabled within the protocol and participation should reflect this.
/// Lastly, this will return null if the probe is not storing its data, as might be the case if a probe is enabled in order
/// to trigger scripts but not told to store its data.
/// </summary>
/// <returns>The participation level (null, or somewhere 0-1).</returns>
public float? GetParticipation()
{
if (_originallyEnabled && _storeData)
return Math.Min(RawParticipation, 1); // raw participations can be > 1, e.g. in the case of polling probes that the user can cause to poll repeatedly. cut off at 1 to maintain the interpretation of 1 as perfect participation.
else
return null;
}
protected void StartAsync()
{
new Thread(() =>
{
try
{
Start();
}
catch (Exception)
{
}
}).Start();
}
/// <summary>
/// Start this instance, throwing an exception if anything goes wrong. If an exception is thrown, the caller can assume that any relevant
/// information will have already been logged and displayed. Thus, the caller doesn't need to do anything with the exception information.
/// </summary>
public void Start()
{
try
{
InternalStart();
}
catch (Exception startException)
{
// stop probe to clean up any inconsistent state information
try
{
Stop();
}
catch (Exception stopException)
{
SensusServiceHelper.Get().Logger.Log("Failed to stop probe after failing to start it: " + stopException.Message, LoggingLevel.Normal, GetType());
}
string message = "Failed to start probe \"" + GetType().Name + "\": " + startException.Message;
SensusServiceHelper.Get().Logger.Log(message, LoggingLevel.Normal, GetType());
SensusServiceHelper.Get().FlashNotificationAsync(message, duration: TimeSpan.FromSeconds(4));
// disable probe if it is not supported on the device (or if the user has elected not to enable it -- e.g., by refusing to log into facebook)
if (startException is NotSupportedException)
Enabled = false;
throw startException;
}
}
/// <summary>
/// Throws an exception if start fails. Should be called first within child-class overrides. This should only be called within Start. This setup
/// allows for child-class overrides, but since InternalStart is protected, it cannot be called from the outside. Outsiders only have access to
/// Start (perhaps via Enabled), which takes care of any exceptions arising from the entire chain of InternalStart overrides.
/// </summary>
protected virtual void InternalStart()
{
lock (_locker)
{
if (_running)
SensusServiceHelper.Get().Logger.Log("Attempted to start probe, but it was already running.", LoggingLevel.Normal, GetType());
else
{
SensusServiceHelper.Get().Logger.Log("Starting.", LoggingLevel.Normal, GetType());
Initialize();
_running = true;
lock (_startStopTimes)
{
_startStopTimes.Add(new Tuple<bool, DateTime>(true, DateTime.Now));
_startStopTimes.RemoveAll(t => t.Item2 < Protocol.ParticipationHorizon);
}
}
}
}
public virtual Task StoreDatumAsync(Datum datum, CancellationToken cancellationToken)
{
// track the most recent datum and call timestamp regardless of whether the datum is null or whether we're storing data
MostRecentDatum = datum;
_mostRecentStoreTimestamp = DateTimeOffset.UtcNow;
// datum is allowed to be null, indicating the the probe attempted to obtain data but it didn't find any (in the case of polling probes).
if (datum != null)
{
datum.ProtocolId = Protocol.Id;
if (_storeData)
{
ChartDataPoint chartDataPoint = GetChartDataPointFromDatum(datum);
if (chartDataPoint != null)
{
lock (_chartData)
{
_chartData.Add(chartDataPoint);
while (_chartData.Count > 0 && _chartData.Count > _maxChartDataCount)
_chartData.RemoveAt(0);
}
}
return _protocol.LocalDataStore.AddAsync(datum, cancellationToken, _runLocalCommitOnStore);
}
}
return Task.FromResult(false);
}
protected void StopAsync()
{
new Thread(() =>
{
try
{
Stop();
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log("Failed to stop: " + ex.Message, LoggingLevel.Normal, GetType());
}
}).Start();
}
/// <summary>
/// Should be called first within child-class overrides.
/// </summary>
public virtual void Stop()
{
lock (_locker)
{
if (_running)
{
SensusServiceHelper.Get().Logger.Log("Stopping.", LoggingLevel.Normal, GetType());
_running = false;
lock (_startStopTimes)
{
_startStopTimes.Add(new Tuple<bool, DateTime>(false, DateTime.Now));
_startStopTimes.RemoveAll(t => t.Item2 < Protocol.ParticipationHorizon);
}
}
else
SensusServiceHelper.Get().Logger.Log("Attempted to stop probe, but it wasn't running.", LoggingLevel.Normal, GetType());
}
}
public void Restart()
{
lock (_locker)
{
Stop();
Start();
}
}
public virtual bool TestHealth(ref string error, ref string warning, ref string misc)
{
bool restart = false;
if (!_running)
{
restart = true;
error += "Probe \"" + GetType().FullName + "\" is not running." + Environment.NewLine;
}
return restart;
}
public virtual void Reset()
{
if (_running)
throw new Exception("Cannot reset probe while it is running.");
lock (_chartData)
{
_chartData.Clear();
}
lock (_startStopTimes)
{
_startStopTimes.Clear();
}
lock (_successfulHealthTestTimes)
{
_successfulHealthTestTimes.Clear();
}
_mostRecentDatum = null;
_mostRecentStoreTimestamp = DateTimeOffset.MinValue;
}
public SfChart GetChart()
{
ChartSeries series = GetChartSeries();
if (series == null)
return null;
// provide the series with a copy of the chart data. if we provide the actual list, then the
// chart wants to auto-update the display on subsequent additions to the list. if this happens,
// then we'll need to update the list on the UI thread so that the chart is redrawn correctly.
// and if this is the case then we're in trouble because xamarin forms is not always initialized
// when the list is updated with probed data (if the activity is killed).
lock (_chartData)
{
series.ItemsSource = _chartData.ToList();
}
SfChart chart = new SfChart
{
PrimaryAxis = GetChartPrimaryAxis(),
SecondaryAxis = GetChartSecondaryAxis(),
};
chart.Series.Add(series);
chart.ChartBehaviors.Add(new ChartZoomPanBehavior
{
EnablePanning = true,
EnableZooming = true,
EnableDoubleTap = true
});
return chart;
}
protected abstract ChartSeries GetChartSeries();
protected abstract ChartAxis GetChartPrimaryAxis();
protected abstract RangeAxisBase GetChartSecondaryAxis();
protected abstract ChartDataPoint GetChartDataPointFromDatum(Datum datum);
}
}
| |
using System;
using System.Collections;
using System.Data;
using Epi.DataSets;
namespace Epi.Data.Services
{
/// <summary>
/// Manages AppData database.
/// </summary>
public class AppData
{
#region Private Data
private ArrayList fieldTypes = null;
//private DataSets.AppDataSet.SettingsDataTable settingsDataTable;
//private DataSets.AppDataSet.ModulesDataTable modulesDataTable;
//private DataSets.AppDataSet.RecordProcessingScopesDataTable recordProcessingScopesDataTable;
//private DataSets.AppDataSet.RepresentationsOfMissingDataTable representationsOfMissingDataTable;
//private DataSets.AppDataSet.RepresentationsOfNoDataTable representationsOfNoDataTable;
//private DataSets.AppDataSet.RepresentationsOfYesDataTable representationsOfYesDataTable;
//private DataSets.AppDataSet.StatisticsLevelsDataTable statisticsLevelsDataTable;
//private DataSets.AppDataSet.DataPatternsDataTable dataPatternsDataTable;
//private DataSets.AppDataSet.DataTypesDataTable dataTypesDataTable;
//private DataSets.AppDataSet.FieldTypesDataTable fieldTypesDataTable;
//private DataSets.AppDataSet.FontStylesDataTable fontStylesDataTable;
//private DataSets.AppDataSet.ListTreatmentTypesDataTable listTreatmentTypesDataTable;
//private DataSets.AppDataSet.SourceControlTypesDataTable sourceControlTypesDataTable;
//private DataSets.AppDataSet.CommandGroupsDataTable commandGroupsDataTable;
//private DataSets.AppDataSet.CommandsDataTable commandsDataTable;
//private DataSets.AppDataSet.DialogFormatsDataTable dialogFormatsDataTable;
//private DataSets.AppDataSet.VariableScopesDataTable variableScopesDataTable;
//private DataSets.AppDataSet.SupportedAggregatesDataTable supportedAggregatesDataTable;
//private DataSets.AppDataSet.ReservedWordsDataTable reservedWordsDataTable;
//private DataSets.AppDataSet.LayerRenderTypesDataTable layerRenderTypesDataTable;
#endregion Private Data
#region Constructors
private static AppData instance;
/// <summary>
/// Reference to AppData object.
/// </summary>
public static AppData Instance
{
get
{
if (instance == null)
{
instance = new AppData();
}
return instance;
}
}
#endregion Constructors
#region Public Properties
#region Generated Code
private DataSets.AppDataSet.CommandGroupsDataTable commandGroupsDataTable;
/// <summary>
/// Command Groups Data Table in Application DataSet
/// </summary>
public DataSets.AppDataSet.CommandGroupsDataTable CommandGroupsDataTable
{
get
{
if (commandGroupsDataTable == null)
{
commandGroupsDataTable = new DataSets.AppDataSet.CommandGroupsDataTable();
commandGroupsDataTable.AddCommandGroupsRow(1, @"Data", 1);
commandGroupsDataTable.AddCommandGroupsRow(2, @"Variables", 2);
commandGroupsDataTable.AddCommandGroupsRow(3, @"Select/If", 3);
commandGroupsDataTable.AddCommandGroupsRow(4, @"Statistics", 4);
commandGroupsDataTable.AddCommandGroupsRow(5, @"Advanced Statistics", 5);
commandGroupsDataTable.AddCommandGroupsRow(6, @"Output", 6);
commandGroupsDataTable.AddCommandGroupsRow(7, @"User-Defined Commands", 7);
commandGroupsDataTable.AddCommandGroupsRow(8, @"User Interaction", 8);
commandGroupsDataTable.AddCommandGroupsRow(9, @"Options", 9);
}
return (commandGroupsDataTable);
}
}
private DataSets.AppDataSet.CommandsDataTable commandsDataTable;
/// <summary>
/// Commands Data Table in Application DataSet
/// </summary>
public DataSets.AppDataSet.CommandsDataTable CommandsDataTable
{
get
{
if (commandsDataTable == null)
{
commandsDataTable = new DataSets.AppDataSet.CommandsDataTable();
commandsDataTable.AddCommandsRow(1, @"Read", 1, 1);
//commandsDataTable.AddCommandsRow(2, @"SQLExec", 2, 1);
//commandsDataTable.AddCommandsRow(4, @"RecordSet", 3, 1);
commandsDataTable.AddCommandsRow(2, @"Relate", 2, 1);
commandsDataTable.AddCommandsRow(3, @"Write (Export)", 3, 1);
commandsDataTable.AddCommandsRow(4, @"Merge", 4, 1);
commandsDataTable.AddCommandsRow(5, @"Delete File/Table", 5, 1);
commandsDataTable.AddCommandsRow(6, @"Delete Records", 6, 1);
commandsDataTable.AddCommandsRow(7, @"Undelete Records", 7, 1);
commandsDataTable.AddCommandsRow(1, @"Define", 1, 2);
commandsDataTable.AddCommandsRow(2, @"DefineGroup", 2, 2);
commandsDataTable.AddCommandsRow(3, @"Undefine", 3, 2);
commandsDataTable.AddCommandsRow(4, @"Assign", 4, 2);
commandsDataTable.AddCommandsRow(5, @"Recode", 5, 2);
commandsDataTable.AddCommandsRow(6, @"Display", 6, 2);
commandsDataTable.AddCommandsRow(1, @"Select", 1, 3);
commandsDataTable.AddCommandsRow(2, @"Cancel Select", 2, 3);
commandsDataTable.AddCommandsRow(3, @"If", 3, 3);
commandsDataTable.AddCommandsRow(4, @"Sort", 4, 3);
commandsDataTable.AddCommandsRow(5, @"Cancel Sort", 5, 3);
commandsDataTable.AddCommandsRow(1, @"List", 1, 4);
commandsDataTable.AddCommandsRow(2, @"Frequencies", 2, 4);
commandsDataTable.AddCommandsRow(3, @"Tables", 3, 4);
//commandsDataTable.AddCommandsRow(4, @"Match", 4, 4);
commandsDataTable.AddCommandsRow(5, @"Means", 5, 4);
commandsDataTable.AddCommandsRow(6, @"Summarize", 6, 4);
commandsDataTable.AddCommandsRow(7, @"Graph", 7, 4);
//commandsDataTable.AddCommandsRow(8, @"Map", 8, 4);
commandsDataTable.AddCommandsRow(1, @"Linear Regression", 1, 5);
commandsDataTable.AddCommandsRow(2, @"Logistic Regression", 2, 5);
commandsDataTable.AddCommandsRow(3, @"Kaplan-Meier Survival", 3, 5);
commandsDataTable.AddCommandsRow(4, @"Cox Proportional Hazards", 4, 5);
commandsDataTable.AddCommandsRow(5, @"Complex Sample Frequencies", 5, 5);
commandsDataTable.AddCommandsRow(6, @"Complex Sample Tables", 6, 5);
commandsDataTable.AddCommandsRow(7, @"Complex Sample Means", 7, 5);
commandsDataTable.AddCommandsRow(1, @"Header", 1, 6);
commandsDataTable.AddCommandsRow(2, @"Type", 2, 6);
commandsDataTable.AddCommandsRow(3, @"RouteOut", 3, 6);
commandsDataTable.AddCommandsRow(4, @"CloseOut", 4, 6);
commandsDataTable.AddCommandsRow(5, @"PrintOut", 5, 6);
//commandsDataTable.AddCommandsRow(6, @"Reports", 6, 6);
commandsDataTable.AddCommandsRow(7, @"Storing Output", 7, 6);
commandsDataTable.AddCommandsRow(1, @"Define Command", 1, 7);
commandsDataTable.AddCommandsRow(2, @"User Command", 2, 7);
commandsDataTable.AddCommandsRow(3, @"Run Saved Program", 3, 7);
commandsDataTable.AddCommandsRow(4, @"Execute File", 4, 7);
commandsDataTable.AddCommandsRow(1, @"Dialog", 1, 8);
commandsDataTable.AddCommandsRow(2, @"Beep", 2, 8);
//commandsDataTable.AddCommandsRow(3, @"Help", 3, 8);
commandsDataTable.AddCommandsRow(4, @"Quit Program", 4, 8);
commandsDataTable.AddCommandsRow(1, @"Set", 1, 9);
//commandsDataTable.AddCommandsRow(2, @"Define Group", 2, 2);
}
return (commandsDataTable);
}
}
private DataSets.AppDataSet.DataPatternsDataTable dataPatternsDataTable;
/// <summary>
/// Data Patterns Data Table in Application DataSet
/// </summary>
public DataSets.AppDataSet.DataPatternsDataTable DataPatternsDataTable
{
get
{
if (dataPatternsDataTable == null)
{
dataPatternsDataTable = new DataSets.AppDataSet.DataPatternsDataTable();
int patternId = 0;
dataPatternsDataTable.AddDataPatternsRow(++patternId, 1, @"None", String.Empty, String.Empty);
dataPatternsDataTable.AddDataPatternsRow(++patternId, 1, @"#", @"#", @"#");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 1, @"##", @"##", @"##");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 1, @"###", @"###", @"###");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 1, @"####", @"####", @"####");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 1, @"##.##", @"##.##", @"##.##");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 1, @"##.###", @"##.###", @"##.###");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 3, @"MM-DD-YYYY", @"##-##-####", @"MM-dd-yyyy");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 3, @"DD-MM-YYYY", @"##-##-####", @"dd-MM-yyyy");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 3, @"YYYY-MM-DD", @"####-##-##", @"yyyy-MM-dd");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 4, @"HH:MM AMPM", @"##:## ??", @"hh:mm tt");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 4, @"HH:MM", @"##:##", @"HH:mm");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 4, @"HH:MM:SS AMPM", @"##:##:## ??", @"hh:mm:ss tt");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 4, @"HH:MM:SS", @"##:##:##", @"HH:mm:ss");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 5, @"MM-DD-YYYY HH:MM AMPM", @"##-##-#### ##:## ??", @"MM-dd-yyyy hh:mm tt");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 5, @"DD-MM-YYYY HH:MM AMPM", @"##-##-#### ##:## ??", @"dd-MM-yyyy hh:mm tt");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 5, @"YYYY-MM-DD HH:MM AMPM", @"####-##-## ##:## ??", @"yyyy-MM-dd hh:mm tt");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 5, @"MM-DD-YYYY HH:MM", @"##-##-#### ##:##", @"MM-dd-yyyy HH:mm");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 5, @"DD-MM-YYYY HH:MM", @"##-##-#### ##:##", @"dd-MM-yyyy HH:mm");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 5, @"YYYY-MM-DD HH:MM", @"####-##-## ##:##", @"yyyy-MM-dd HH:mm");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 5, @"MM-DD-YYYY HH:MM:SS AMPM", @"##-##-#### ##:##:## ??", @"MM-dd-yyyy hh:mm:ss tt");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 5, @"DD-MM-YYYY HH:MM:SS AMPM", @"##-##-#### ##:##:## ??", @"dd-MM-yyyy hh:mm:ss tt");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 5, @"YYYY-MM-DD HH:MM:SS AMPM", @"####-##-## ##:##:## ??", @"yyyy-MM-dd hh:mm:ss tt");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 5, @"MM-DD-YYYY HH:MM:SS", @"##-##-#### ##:##:##", @"MM-dd-yyyy HH:mm:ss");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 5, @"DD-MM-YYYY HH:MM:SS", @"##-##-#### ##:##:##", @"dd-MM-yyyy HH:mm:ss");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 5, @"YYYY-MM-DD HH:MM:SS", @"####-##-## ##:##:##", @"yyyy-MM-dd HH:mm:ss");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 7, @"None", @"CCCCCCCCCCCCCCCCCCCC", @"CCCCCCCCCCCCCCCCCCCC");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 7, @"Numeric", @"####################", @"####################");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 7, @"###-####", @"###-####", @"###-####");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 7, @"###-###-####", @"###-###-####", @"###-###-####");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 7, @"###-###-###-####", @"###-###-###-####", @"###-###-###-####");
dataPatternsDataTable.AddDataPatternsRow(++patternId, 7, @"#-###-###-###-####", @"#-###-###-###-####", @"#-###-###-###-####");
}
return (dataPatternsDataTable);
}
}
private DataSets.AppDataSet.DataTypesDataTable dataTypesDataTable;
/// <summary>
/// Data Types Data Table in Application DataSet
/// </summary>
public DataSets.AppDataSet.DataTypesDataTable DataTypesDataTable
{
get
{
if (dataTypesDataTable == null)
{
dataTypesDataTable = new DataSets.AppDataSet.DataTypesDataTable();
dataTypesDataTable.AddDataTypesRow(1, true, false, true, @"Number", @"NUMERIC");
dataTypesDataTable.AddDataTypesRow(2, false, true, false, @"Text", @"TEXTINPUT");
dataTypesDataTable.AddDataTypesRow(3, false, false, true, @"Date", @"DATEFORMAT");
dataTypesDataTable.AddDataTypesRow(4, false, false, false, @"Time", @"TIMEFORMAT");
dataTypesDataTable.AddDataTypesRow(5, false, false, false, @"DateTime", @"DATETIMEFORMAT");
dataTypesDataTable.AddDataTypesRow(6, false, false, false, @"Boolean", @"YN");
dataTypesDataTable.AddDataTypesRow(7, true, false, false, @"PhoneNumber", @"TEXTINPUT");
dataTypesDataTable.AddDataTypesRow(8, false, false, false, @"YesNo", @"YN");
dataTypesDataTable.AddDataTypesRow(9, false, false, false, @"Unknown", string.Empty);
dataTypesDataTable.AddDataTypesRow(10, false, false, false, @"GUID", @"TEXTINPUT");
dataTypesDataTable.AddDataTypesRow(0, false, false, false, @"Object", @"DLLOBJECT");
}
return (dataTypesDataTable);
}
}
private DataSets.AppDataSet.DialogFormatsDataTable dialogFormatsDataTable;
/// <summary>
/// Dialog Formats Data Table in Application DataSet
/// </summary>
public DataSets.AppDataSet.DialogFormatsDataTable DialogFormatsDataTable
{
get
{
if (dialogFormatsDataTable == null)
{
dialogFormatsDataTable = new DataSets.AppDataSet.DialogFormatsDataTable();
dialogFormatsDataTable.AddDialogFormatsRow(1, @"Text Entry", 1, @"TEXTINPUT");
dialogFormatsDataTable.AddDialogFormatsRow(2, @"Multiple Choice", 2, @"<StringList>");
dialogFormatsDataTable.AddDialogFormatsRow(3, @"Variable List", 3, @"DBVARIABLES");
dialogFormatsDataTable.AddDialogFormatsRow(4, @"View List", 4, @"DBVIEWS");
dialogFormatsDataTable.AddDialogFormatsRow(5, @"Database List", 5, @"DATABASES");
dialogFormatsDataTable.AddDialogFormatsRow(6, @"File Open", 6, @"READ");
dialogFormatsDataTable.AddDialogFormatsRow(7, @"File Save", 7, @"WRITE");
}
return (dialogFormatsDataTable);
}
}
private DataSets.AppDataSet.FieldTypesDataTable fieldTypesDataTable;
/// <summary>
/// Field Types Data Table in Application DataSet
/// </summary>
public DataSets.AppDataSet.FieldTypesDataTable FieldTypesDataTable
{
get
{
if (fieldTypesDataTable == null)
{
fieldTypesDataTable = new DataSets.AppDataSet.FieldTypesDataTable();
fieldTypesDataTable.AddFieldTypesRow(1, @"Text", false, true, true, true, true, false, false, false, true, true, true, 2, false, 0);
fieldTypesDataTable.AddFieldTypesRow(2, @"Label/Title", false, false, false, false, false, false, false, false, false, false, false, 9, false, 0);
fieldTypesDataTable.AddFieldTypesRow(3, @"Text (Uppercase)", false, true, true, true, true, false, false, false, true, false, false, 2, false, 0);
fieldTypesDataTable.AddFieldTypesRow(4, @"Multiline", false, false, true, true, true, false, false, false, true, false, false, 2, false, 0);
fieldTypesDataTable.AddFieldTypesRow(5, @"Number", true, false, true, true, true, false, false, true, true, false, true, 1, false, 2);
fieldTypesDataTable.AddFieldTypesRow(6, @"Phone Number", true, false, true, true, true, false, false, false, true, false, true, 7, false, 7);
fieldTypesDataTable.AddFieldTypesRow(7, @"Date", true, false, true, true, true, false, false, true, true, false, true, 3, false, 9);
fieldTypesDataTable.AddFieldTypesRow(8, @"Time", true, false, true, true, true, false, false, false, true, false, true, 4, false, 14);
fieldTypesDataTable.AddFieldTypesRow(9, @"Date/Time", true, false, true, true, true, false, false, false, true, false, true, 5, false, 16);
fieldTypesDataTable.AddFieldTypesRow(10, @"Checkbox", false, false, true, false, true, false, false, false, false, false, true, 6, false, 0);
fieldTypesDataTable.AddFieldTypesRow(11, @"Yes/No", false, false, true, true, true, false, false, false, true, false, true, 8, false, 0);
fieldTypesDataTable.AddFieldTypesRow(12, @"Option", false, false, false, false, false, false, false, false, false, false, false, 2, false, 0);
fieldTypesDataTable.AddFieldTypesRow(13, @"Command Button", false, false, false, false, false, false, false, false, true, false, false, 9, false, 0);
fieldTypesDataTable.AddFieldTypesRow(14, @"Image", false, false, false, false, false, false, true, false, false, false, false, 0, false, 0);
fieldTypesDataTable.AddFieldTypesRow(15, @"Mirror", false, false, false, false, false, false, false, false, true, false, false, 9, false, 0);
fieldTypesDataTable.AddFieldTypesRow(16, @"Grid", false, false, false, false, false, false, false, false, false, false, false, 9, false, 0);
fieldTypesDataTable.AddFieldTypesRow(17, @"Legal Values", false, false, true, true, true, false, false, false, true, true, true, 9, false, 0);
fieldTypesDataTable.AddFieldTypesRow(18, @"Codes", false, false, true, true, true, false, false, false, true, true, false, 9, false, 0);
fieldTypesDataTable.AddFieldTypesRow(19, @"Comment Legal", false, false, true, true, true, false, false, false, true, true, true, 9, false, 0);
fieldTypesDataTable.AddFieldTypesRow(20, @"Relate", false, false, false, false, false, false, false, false, true, false, false, 9, false, 0);
fieldTypesDataTable.AddFieldTypesRow(21, @"Group", false, false, false, false, false, false, false, false, false, false, false, 9, false, 0);
fieldTypesDataTable.AddFieldTypesRow(22, @"RecStatus", false, false, false, false, false, false, false, false, false, false, false, 1, true, 0);
fieldTypesDataTable.AddFieldTypesRow(23, @"UniqueKey", false, false, false, false, false, false, false, false, false, false, false, 1, true, 0);
fieldTypesDataTable.AddFieldTypesRow(24, @"ForeignKey", false, false, false, false, false, false, false, false, false, false, false, 1, true, 0);
fieldTypesDataTable.AddFieldTypesRow(25, @"GUID", false, false, false, false, false, false, false, false, false, false, false, 10, false, 0);
fieldTypesDataTable.AddFieldTypesRow(26, @"GlobalRecordId", false, false, false, false, false, false, false, false, false, false, false, 2, false, 0);
fieldTypesDataTable.AddFieldTypesRow(27, @"List", false, false, true, true, true, false, false, false, true, true, false, 9, false, 0);
fieldTypesDataTable.AddFieldTypesRow(99, @"Unknown", false, false, false, false, false, false, false, false, false, false, false, 9, false, 0);
}
return (fieldTypesDataTable);
}
}
private DataSets.AppDataSet.FontStylesDataTable fontStylesDataTable;
/// <summary>
/// Variable Scopes Data Table in Application DataSet
/// </summary>
public DataSets.AppDataSet.FontStylesDataTable FontStylesDataTable
{
get
{
if (fontStylesDataTable == null)
{
fontStylesDataTable = new DataSets.AppDataSet.FontStylesDataTable();
fontStylesDataTable.AddFontStylesRow(1, @"Regular");
fontStylesDataTable.AddFontStylesRow(2, @"Italic");
fontStylesDataTable.AddFontStylesRow(3, @"Bold");
fontStylesDataTable.AddFontStylesRow(4, @"Bold Italic");
}
return (fontStylesDataTable);
}
}
private DataSets.AppDataSet.LayerRenderTypesDataTable layerRenderTypesDataTable;
/// <summary>
/// Layer Render Types Data Table in Application DataSet
/// </summary>
public DataSets.AppDataSet.LayerRenderTypesDataTable LayerRenderTypesDataTable
{
get
{
if (layerRenderTypesDataTable == null)
{
layerRenderTypesDataTable = new DataSets.AppDataSet.LayerRenderTypesDataTable();
layerRenderTypesDataTable.AddLayerRenderTypesRow(1, @"Simple");
layerRenderTypesDataTable.AddLayerRenderTypesRow(2, @"Choropleth");
layerRenderTypesDataTable.AddLayerRenderTypesRow(3, @"Dot Density");
layerRenderTypesDataTable.AddLayerRenderTypesRow(4, @"Unique Values");
}
return (layerRenderTypesDataTable);
}
}
private DataSets.AppDataSet.ListTreatmentTypesDataTable listTreatmentTypesDataTable;
/// <summary>
/// List Treatment Types Data Table in Application DataSet
/// </summary>
public DataSets.AppDataSet.ListTreatmentTypesDataTable ListTreatmentTypesDataTable
{
get
{
if (listTreatmentTypesDataTable == null)
{
listTreatmentTypesDataTable = new DataSets.AppDataSet.ListTreatmentTypesDataTable();
listTreatmentTypesDataTable.AddListTreatmentTypesRow(1, @"Legal Values");
listTreatmentTypesDataTable.AddListTreatmentTypesRow(2, @"Comment Legal");
}
return (listTreatmentTypesDataTable);
}
}
private DataSets.AppDataSet.ModulesDataTable modulesDataTable;
/// <summary>
/// Modules Data Table in Application DataSet
/// </summary>
public DataSets.AppDataSet.ModulesDataTable ModulesDataTable
{
get
{
if (modulesDataTable == null)
{
modulesDataTable = new DataSets.AppDataSet.ModulesDataTable();
modulesDataTable.AddModulesRow(1, @"General", 1, @"EpiInfo", @"General", string.Empty, string.Empty);
modulesDataTable.AddModulesRow(2, @"Menu", 2, @"Menu", @"Menu", string.Empty, string.Empty);
modulesDataTable.AddModulesRow(3, @"Make View", 3, @"MakeView", @"Make View", @"Epi.MakeView", @"Epi.MakeView.Forms.MakeView");
modulesDataTable.AddModulesRow(4, @"Enter", 4, @"Enter", @"Enter Data", @"Epi.Enter", @"Epi.Enter.Forms.Enter");
modulesDataTable.AddModulesRow(5, @"Analysis", 5, @"Analysis", @"Analyze Data", @"Epi.Analysis", @"Epi.Analysis.Forms.Analysis");
modulesDataTable.AddModulesRow(6, @"EpiMap", 6, @"EpiMap", @"Create Maps", @"Epi.Map", @"Epi.Map.Forms.EpiMap");
}
return (modulesDataTable);
}
}
private DataSets.AppDataSet.RecordProcessingScopesDataTable recordProcessingScopesDataTable;
/// <summary>
/// Record Processing Scopes Data Table in Application DataSet
/// </summary>
public DataSets.AppDataSet.RecordProcessingScopesDataTable RecordProcessingScopesDataTable
{
get
{
if (recordProcessingScopesDataTable == null)
{
recordProcessingScopesDataTable = new DataSets.AppDataSet.RecordProcessingScopesDataTable();
recordProcessingScopesDataTable.AddRecordProcessingScopesRow(1, @"Normal (undeleted)", @"UNDELETED", 1);
recordProcessingScopesDataTable.AddRecordProcessingScopesRow(2, @"Deleted", @"DELETED", 2);
recordProcessingScopesDataTable.AddRecordProcessingScopesRow(3, @"Both", @"BOTH", 3);
}
return (recordProcessingScopesDataTable);
}
}
private DataSets.AppDataSet.RepresentationsOfMissingDataTable representationsOfMissingDataTable;
/// <summary>
/// Representations Of Missing Data Table in Application DataSet
/// </summary>
public DataSets.AppDataSet.RepresentationsOfMissingDataTable RepresentationsOfMissingDataTable
{
get
{
if (representationsOfMissingDataTable == null)
{
representationsOfMissingDataTable = new DataSets.AppDataSet.RepresentationsOfMissingDataTable();
representationsOfMissingDataTable.AddRepresentationsOfMissingRow(1, @"Missing", 1);
representationsOfMissingDataTable.AddRepresentationsOfMissingRow(2, @"Unknown", 2);
representationsOfMissingDataTable.AddRepresentationsOfMissingRow(3, @"(.)", 3);
}
return (representationsOfMissingDataTable);
}
}
private DataSets.AppDataSet.RepresentationsOfNoDataTable representationsOfNoDataTable;
/// <summary>
/// Representations Of No Data Table in Application DataSet
/// </summary>
public DataSets.AppDataSet.RepresentationsOfNoDataTable RepresentationsOfNoDataTable
{
get
{
if (representationsOfNoDataTable == null)
{
representationsOfNoDataTable = new DataSets.AppDataSet.RepresentationsOfNoDataTable();
representationsOfNoDataTable.AddRepresentationsOfNoRow(1, @"No", 1);
representationsOfNoDataTable.AddRepresentationsOfNoRow(2, @"False", 2);
representationsOfNoDataTable.AddRepresentationsOfNoRow(3, @"(-)", 3);
}
return (representationsOfNoDataTable);
}
}
private DataSets.AppDataSet.RepresentationsOfYesDataTable representationsOfYesDataTable;
/// <summary>
/// Representations Of Yes Data Table in Application DataSet
/// </summary>
public DataSets.AppDataSet.RepresentationsOfYesDataTable RepresentationsOfYesDataTable
{
get
{
if (representationsOfYesDataTable == null)
{
representationsOfYesDataTable = new DataSets.AppDataSet.RepresentationsOfYesDataTable();
representationsOfYesDataTable.AddRepresentationsOfYesRow(1, @"Yes", 1);
representationsOfYesDataTable.AddRepresentationsOfYesRow(2, @"True", 2);
representationsOfYesDataTable.AddRepresentationsOfYesRow(3, @"(+)", 3);
}
return (representationsOfYesDataTable);
}
}
private DataSets.AppDataSet.ReservedWordsDataTable reservedWordsDataTable;
/// <summary>
/// Reservered Words Data Table in Application DataSet
/// </summary>
public DataSets.AppDataSet.ReservedWordsDataTable ReservedWordsDataTable
{
get
{
if (reservedWordsDataTable == null)
{
int index = 1;
reservedWordsDataTable = new DataSets.AppDataSet.ReservedWordsDataTable();
reservedWordsDataTable.AddReservedWordsRow(index++, @"ABSOLUTE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ACTION", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ADA", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ADD", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ALL", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ALLOCATE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ALPHANUMERIC", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ALTER", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ALWAYS", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"and", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ANY", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"APPEND", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ARE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"AS", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"asc", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ASCENDING", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ASSERTION", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ASSIGN", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"AT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"AUTHORIZATION", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"AUTOINCREMENT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"AUTOSEARCH", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"AVG", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"BEEP", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"BEGIN", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"BETWEEN", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"BINARY", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"bit", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"BIT_LENGTH", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"BITMAP", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"BOOLEAN", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"BOTH", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"BY", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"byte", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CANCEL", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CASCADE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CASCADED", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CASE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CATALOG", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"char", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CHAR_LENGTH", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CHARACTER", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CHARACTER_LENGTH", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CHECK", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CLEAR", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CLIPBOARD", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CLOSE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CLOSEOUT", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CMD", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"COALESCE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CODE ", @"D");
reservedWordsDataTable.AddReservedWordsRow(index++, @"COLLATE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"COLLATION", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"COLUMN", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"COLUMNSIZE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"COMBINE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"COMMANDLINE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"COMMIT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"COMPRESS", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CONNECT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CONNECTION", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"constraint", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CONSTRAINTS", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CONTINUE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CONVERT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CORRESPONDING", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"count", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"COUNTER", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"COXPH", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CREATE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CROSS", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CURRENCY", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CURRENT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CURRENT_DATE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CURRENT_TIME", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CURRENT_TIMESTAMP", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CURRENT_USER", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"CURSOR", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DATABASE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DATABASES", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"date", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DATEFORMAT", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"datetime", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DAY", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DBVALUES", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DBVARIABLES", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DBVIEWS", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DEALLOCATE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DEC", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"decimal", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DECLARE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DECOMPRESS", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DEFAULT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DEFERRABLE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DEFERRED", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DEFINE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"delete", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DELETED", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DENOMINATOR", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"desc", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DESCENDING", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DESCRIBE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DESCRIPTOR", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DIALOG", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DISALLOW", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DISCONNECT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DISPLAY", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DISTINCT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DISTINCTROW", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DLLOBJECT", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DOMAIN", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"double", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"DROP", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ELSE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ELSEIF", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"END", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ENDBEFORE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"END-EXEC", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"EQV", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ESCAPE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"EXCEPT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"EXCEPTION", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"EXEC", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"EXECUTE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"EXISTS", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"EXIT", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"EXTERNAL", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"EXTRACT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"FALSE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"FETCH", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"FIELDVAR", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"FILESPEC", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"FIRST", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"FKEY", @"H");
reservedWordsDataTable.AddReservedWordsRow(index++, @"float", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"FLOAT4", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"FLOAT8", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"FOR", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"FOREIGN", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"FORTRAN", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"FOUND", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"FREQ", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"FREQGRAPH", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"from", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"FULL", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"GENERAL", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"GET", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"GLOBAL", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"GLOBALID ", @"D");
reservedWordsDataTable.AddReservedWordsRow(index++, @"GO", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"GOTO", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"GRANT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"GRAPH", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"GRAPHTYPE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"GRIDLINES", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"GRIDTABLE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"GROUP", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"GROUPVAR", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"GUID", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"HAVING", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"HEADER", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"HELP", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"HIDE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"HIVALUE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"HOUR", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"HYPERLINKS", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"identity", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"IEEEDOUBLE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"IEEESINGLE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"IF", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"IGNORE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"IMMEDIATE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"IMP", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"in", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"INCLUDE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"INDEX", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"INDICATOR", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"INITIALLY", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"INNER", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"INPUT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"INSENSITIVE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"INSERT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"int", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"integer", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"INTEGER1", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"INTEGER2", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"INTEGER4", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"INTERSECT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"INTERVAL", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"INTO", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"IS", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ISOLATION", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"JOIN", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"KEY", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"KEYVARS", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"KMSURVIVAL", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"LANGUAGE", @"D");
reservedWordsDataTable.AddReservedWordsRow(index++, @"LAST", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"LEADING", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"LEFT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"LET", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"LEVEL", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"like", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"LINENUMBERS", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"LINKNAME", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"LIST", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"LOCAL", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"LOGICAL", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"LOGICAL1", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"LOGISTIC", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"LONG", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"LONGBINARY", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"LONGTEXT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"LOVALUE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"LOWER", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"MAP", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"MATCH", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"MATCHING", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"MATCHVAR", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"MAX", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"MEANS", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"MEMO", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"MERGE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"min", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"MINUTE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"MISSING", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"MOD", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"MODDATE ", @"D");
reservedWordsDataTable.AddReservedWordsRow(index++, @"MODULE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"MODUSER ", @"D");
reservedWordsDataTable.AddReservedWordsRow(index++, @"money", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"MONTH", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"MULTIGRAPH", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"NAMES", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"NATURAL", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"nchar", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"NEWPAGE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"NEWRECORD", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"NEXT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"NO", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"NOIMAGE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"NOINTERCEPT", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"NONE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"NOT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"NOWRAP", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"null", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"NULLIF", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"NUMBER", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"numeric", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"OCTET_LENGTH", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"OF", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"OFF", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"OLEOBJECT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"on", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ONLY", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"OPEN", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"OPTION", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"or", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ORDER", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"OUTER", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"OUTPUT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"OUTTABLE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"OVERLAPS", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"OVERLAYNEXT", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"OWNERACCESS", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"PAD", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"PARAMETERS", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"PARTIAL", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"PASCAL", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"PERCENT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"PERCENTS", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"PERMANENT", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"PGMNAME", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"PIVOT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"POSITION", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"PRECISION", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"PREPARE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"PRESERVE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"PRIMARY", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"PRINTOUT", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"PRIOR", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"PRIVILEGES", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"PROCEDURE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"PROCESS", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"PSUVAR", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"PUBLIC", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"PVALUE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"QUIT", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"READ", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"real", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"RECDELETED", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"RECODE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"RECORDCOUNT", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"RECSTATUS", @"H");
reservedWordsDataTable.AddReservedWordsRow(index++, @"references", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"REGRESS", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"RELATE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"RELATIVE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"REPEAT", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"REPLACE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"REPORT", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"REPORTDATA", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"RESPONSEVAR", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"RESTRICT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"REVOKE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"RIGHT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ROLLBACK", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ROUTEOUT", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ROWS", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"RUNPGM", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"RUNSILENT", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SCHEMA", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SCROLL", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SECOND", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SECTION", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SELECT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SESSION", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SESSION_USER", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"set", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SHORT", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SHOWOBSERVED", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SHOWPROMPTS", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SHOWSINGLECASES", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"single", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SIZE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"smallint", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SOME", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SORT", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SPACE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SQL", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SQLCA", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SQLCODE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SQLERROR", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SQLNULL", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SQLREAL", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SQLSTATE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SQLSTRING", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SQLWARNING", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"STARTFROM", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"STATISTICS", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"STATUSBAR", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"STDEV", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"STDEVP", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"STRATAVAR", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SUBSTRING", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SUM", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SUMOF", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SYSTEM_USER", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SYSTEMDATE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"SYSTEMTIME", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"TABLE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"TABLEID", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"TABLES", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"TEMPLATE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"TEMPORARY", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"text", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"TEXTFONT", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"TEXTINPUT", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"THEN", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"THREED", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"TIME", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"timestamp", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"TIMEUNIT", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"TIMEVAR", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"TIMEZONE_HOUR", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"TIMEZONE_MINUTE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"TITLETEXT", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"TO", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"TOP", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"TRAILING", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"TRANSACTION", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"TRANSFORM", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"TRANSLATE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"TREE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"TRIM", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"TYPEOUT", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"UNDEFINE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"UNDELETE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"UNHIDE", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"UNION", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"UNIQUE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"UNIQUEKEY", @"H");
reservedWordsDataTable.AddReservedWordsRow(index++, @"UNKNOWN", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"update", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"UPPER", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"USAGE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"USEBROWSER", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"USER", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"USING", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"VALUE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"values", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"VALUEVAR", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"VAR", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"varbinary", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"varchar", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"VARP", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"VARYING", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"VIEW", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"VIEWNAME", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"WEIGHTVAR", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"WHEN", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"WHENEVER", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"where", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"WITH", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"WORK", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"WRITE", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"XOR", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"YEAR", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"YESNO", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"YN", @"A");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ZONE", @"B");
// JavaScript keywords
reservedWordsDataTable.AddReservedWordsRow(index++, @"alert", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"isFinite", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"personalbar", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Anchor", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"isNan", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Plugin", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Area", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"java", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"print", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"arguments", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"JavaArray", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"prompt", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Array", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"JavaClass", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"prototype", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"assign", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"JavaObject", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Radio", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"blur", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"JavaPackage", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"ref", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Boolean", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"length", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"RegExp", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Button", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Link", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"releaseEvents", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"callee", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"location", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Reset", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"caller", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Location", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"resizeBy", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"captureEvents", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"locationbar", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"resizeTo", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Checkbox", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Math", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"routeEvent", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"clearInterval", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"menubar", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"scroll", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"clearTimeout", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"MimeType", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"scrollbars", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"close", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"moveBy", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"scrollBy", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"closed", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"moveTo", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"scrollTo", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"confirm", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"name", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Select", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"constructor", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"NaN", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"self", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Date", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"navigate", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"setInterval", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"defaultStatus", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"navigator", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"setTimeout", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"document", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Navigator", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"status", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Document", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"netscape", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"statusbar", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Element", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Number", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"stop", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"escape", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Object", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"String", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"eval", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"onBlur", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Submit", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"FileUpload", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"onError", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"sun", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"find", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"onFocus", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"taint", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"focus", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"onLoad", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Text", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Form", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"onUnload", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Textarea", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Frame", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"open", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"toolbar", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Frames", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"opener", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"top", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Function", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Option", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"toString", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"getClass", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"outerHeight", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"unescape", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Hidden", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"OuterWidth", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"untaint", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"history", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Packages", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"unwatch", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"History", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"pageXoffset", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"valueOf", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"home", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"pageYoffset", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"watch", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Image", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"parent", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"window", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Infinity", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"parseFloat", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Window", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"InnerHeight", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"parseInt", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"InnerWidth", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"Password", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"catch", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"enum", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"throw", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"class", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"extends", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"try", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"const", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"finally", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"debugger", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"super", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"abstract", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"implements", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"protected", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"boolean", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"instanceOf", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"public", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"byte", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"int", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"short", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"char", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"interface", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"static", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"double", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"long", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"synchronized", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"false", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"native", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"throws", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"final", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"null", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"transient", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"float", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"package", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"true", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"goto", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"private", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"break", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"export", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"return", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"case", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"for", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"switch", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"comment", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"function", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"this", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"continue", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"if", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"typeof", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"default", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"import", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"var", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"delete", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"in", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"void", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"do", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"label", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"while", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"else", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"new", @"B");
reservedWordsDataTable.AddReservedWordsRow(index++, @"with", @"B");
}
return (reservedWordsDataTable);
}
}
private DataSets.AppDataSet.SettingsDataTable settingsDataTable;
/// <summary>
/// Settings Data Table in Application DataSet
/// </summary>
public DataSets.AppDataSet.SettingsDataTable SettingsDataTable
{
get
{
if (settingsDataTable == null)
{
settingsDataTable = new DataSets.AppDataSet.SettingsDataTable();
settingsDataTable.AddSettingsRow(1, @"BackgroundImage", @"C:\Epi_Info");
settingsDataTable.AddSettingsRow(2, @"MRUProjectsCount", @"4");
settingsDataTable.AddSettingsRow(3, @"Language", @"English");
settingsDataTable.AddSettingsRow(4, @"RepresentationOfYes", @"Yes");
settingsDataTable.AddSettingsRow(5, @"RepresentationOfNo", @"No");
settingsDataTable.AddSettingsRow(6, @"RepresentationOfMissing", @"Missing");
settingsDataTable.AddSettingsRow(7, @"StatisticsLevel", @"2");
settingsDataTable.AddSettingsRow(8, @"RecordProcessingScope", @"2");
settingsDataTable.AddSettingsRow(9, @"ShowCompletePrompt", @"true");
settingsDataTable.AddSettingsRow(10, @"ShowSelection", @"true");
settingsDataTable.AddSettingsRow(11, @"ShowGraphics", @"true");
settingsDataTable.AddSettingsRow(12, @"ShowPercents", @"true");
settingsDataTable.AddSettingsRow(13, @"ShowTables", @"true");
settingsDataTable.AddSettingsRow(14, @"ShowHyperlinks", @"true");
settingsDataTable.AddSettingsRow(15, @"IncludeMissingValues", @"false");
settingsDataTable.AddSettingsRow(16, @"SnapToGrid", @"true");
settingsDataTable.AddSettingsRow(17, @"EditorFontName", @"Verdana");
settingsDataTable.AddSettingsRow(18, @"EditorFontSize", @"8.25");
settingsDataTable.AddSettingsRow(17, @"ControlFontName", @"Arial");
settingsDataTable.AddSettingsRow(18, @"ControlFontSize", @"11.25");
settingsDataTable.AddSettingsRow(19, @"DefaultDatabaseFormat", @"2");
settingsDataTable.AddSettingsRow(20, @"WorkingDirectory", @"C:\Temp");
settingsDataTable.AddSettingsRow(21, @"ProjectDirectory", @"C:\Documents and Settings\kkm4\My Documents\Epi Info Projects");
settingsDataTable.AddSettingsRow(22, @"MRUViewsCount", @"4");
settingsDataTable.AddSettingsRow(22, @"MRUDataSourcesCount", @"5");
settingsDataTable.AddSettingsRow(23, @"DefaultDataFormat", @"3");
}
return (settingsDataTable);
}
}
private DataSets.AppDataSet.SourceControlTypesDataTable sourceControlTypesDataTable;
/// <summary>
/// Source Control Types Data Table in Application DataSet
/// </summary>
public DataSets.AppDataSet.SourceControlTypesDataTable SourceControlTypesDataTable
{
get
{
if (sourceControlTypesDataTable == null)
{
sourceControlTypesDataTable = new DataSets.AppDataSet.SourceControlTypesDataTable();
sourceControlTypesDataTable.AddSourceControlTypesRow(1, @"Codes");
sourceControlTypesDataTable.AddSourceControlTypesRow(2, @"Mirror");
}
return (sourceControlTypesDataTable);
}
}
private DataSets.AppDataSet.StatisticsLevelsDataTable statisticsLevelsDataTable;
/// <summary>
/// Statistics Levels Data Table in Application DataSet
/// </summary>
public DataSets.AppDataSet.StatisticsLevelsDataTable StatisticsLevelsDataTable
{
get
{
if (statisticsLevelsDataTable == null)
{
statisticsLevelsDataTable = new DataSets.AppDataSet.StatisticsLevelsDataTable();
statisticsLevelsDataTable.AddStatisticsLevelsRow(1, @"None", @"NONE", 1);
statisticsLevelsDataTable.AddStatisticsLevelsRow(2, @"Minimal", @"MINIMAL", 2);
statisticsLevelsDataTable.AddStatisticsLevelsRow(3, @"Intermediate", @"INTERMEDIATE", 3);
statisticsLevelsDataTable.AddStatisticsLevelsRow(4, @"Advanced", @"COMPLETE", 4);
}
return (statisticsLevelsDataTable);
}
}
private DataSets.AppDataSet.SupportedAggregatesDataTable supportedAggregatesDataTable;
/// <summary>
/// Supported Aggregates Data Table in Application DataSet
/// </summary>
public DataSets.AppDataSet.SupportedAggregatesDataTable SupportedAggregatesDataTable
{
get
{
if (supportedAggregatesDataTable == null)
{
supportedAggregatesDataTable = new DataSets.AppDataSet.SupportedAggregatesDataTable();
supportedAggregatesDataTable.AddSupportedAggregatesRow(1, @"Average", 1);
supportedAggregatesDataTable.AddSupportedAggregatesRow(2, @"Count", 2);
supportedAggregatesDataTable.AddSupportedAggregatesRow(3, @"First", 3);
supportedAggregatesDataTable.AddSupportedAggregatesRow(4, @"Last", 4);
supportedAggregatesDataTable.AddSupportedAggregatesRow(5, @"Maximum", 5);
supportedAggregatesDataTable.AddSupportedAggregatesRow(6, @"Minimum", 6);
supportedAggregatesDataTable.AddSupportedAggregatesRow(7, @"StdDev", 7);
//supportedAggregatesDataTable.AddSupportedAggregatesRow(8, @"StdDev(Pop)", 8);
supportedAggregatesDataTable.AddSupportedAggregatesRow(9, @"Sum", 9);
supportedAggregatesDataTable.AddSupportedAggregatesRow(10, @"Var", 10);
//supportedAggregatesDataTable.AddSupportedAggregatesRow(11, @"Var(Pop)", 11);
}
return (supportedAggregatesDataTable);
}
}
private DataSets.AppDataSet.VariableScopesDataTable variableScopesDataTable;
/// <summary>
/// Variable Scopes Data Table in Application DataSet
/// </summary>
public DataSets.AppDataSet.VariableScopesDataTable VariableScopesDataTable
{
get
{
if (variableScopesDataTable == null)
{
variableScopesDataTable = new DataSets.AppDataSet.VariableScopesDataTable();
variableScopesDataTable.AddVariableScopesRow(4, @"Standard", 1, true);
variableScopesDataTable.AddVariableScopesRow(2, @"Global", 2, false);
variableScopesDataTable.AddVariableScopesRow(1, @"Permanent", 3, false);
variableScopesDataTable.AddVariableScopesRow(0, @"Undefined", 0, false);
variableScopesDataTable.AddVariableScopesRow(16, @"DataSource", 4, false);
variableScopesDataTable.AddVariableScopesRow(32, @"DataSourceAssigned", 5, false);
}
return (variableScopesDataTable);
}
}
#endregion Generated Code
#endregion Public Properties
#region Private Properties
private ArrayList FieldTypes
{
get
{
if (fieldTypes == null)
{
fieldTypes = new ArrayList();
foreach (AppDataSet.FieldTypesRow row in FieldTypesDataTable.Rows)
{
FieldType fieldType = new FieldType(row);
fieldTypes.Add(fieldType);
}
}
return (fieldTypes);
}
}
#endregion Private Properties
#region Public Methods
/// <summary>
/// Get Record Processessing Scope By Id
/// </summary>
/// <param name="id">The id of the Record ProcessingS cope</param>
/// <returns>Record ProcessingS copes Row</returns>
public AppDataSet.RecordProcessingScopesRow GetRecordProcessessingScopeById(RecordProcessingScope id)
{
foreach (AppDataSet.RecordProcessingScopesRow row in this.RecordProcessingScopesDataTable.Rows)
{
if (row.Id == (short)id)
{
return row;
}
}
throw new GeneralException("Invalid Scope Id");
}
/// <summary>
/// A row that contains the Statistics Levels and names
/// </summary>
/// <param name="id">Statistics Level enumeration.</param>
/// <returns>Statistics Levels Row</returns>
public AppDataSet.StatisticsLevelsRow GetStatisticsLevelById(StatisticsLevel id)
{
foreach (AppDataSet.StatisticsLevelsRow row in this.StatisticsLevelsDataTable.Rows)
{
if (row.Id == (short)id)
{
return row;
}
}
throw new System.ApplicationException("Invalid Statistics Level Id");
}
/// <summary>
/// Checks to see if a word already exists as a reserved word
/// </summary>
/// <param name="word">Possible reserved word</param>
/// <returns>Returns status as to whether word already exists as a reserved word</returns>
public bool IsReservedWord(string word)
{
#region Input Validation
if (string.IsNullOrEmpty(word))
{
throw new ArgumentNullException("word");
}
#endregion
DataView dv = ReservedWordsDataTable.DefaultView;
dv.RowFilter = ReservedWordsDataTable.NameColumn.ColumnName + " = '" + word + "'";
return (dv.Count > 0);
}
#endregion Public Methods
#region Nested Types
/// <summary>
/// Field Type class
/// </summary>
public class FieldType
{
#region Constructors
/// <summary>
/// Default Constructor
/// </summary>
public FieldType()
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="row">Field Types row in application dataset.</param>
public FieldType(AppDataSet.FieldTypesRow row)
{
inner = row;
}
#endregion Constructors
#region Fields
private AppDataSet.FieldTypesRow inner;
#endregion Fields
#region Public Properties
/// <summary>
/// Internal Field Types row.
/// </summary>
public AppDataSet.FieldTypesRow Inner
{
get
{
return inner;
}
}
#endregion Public Properties
}
#endregion
}
}
| |
using Aardvark.Base;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Aardvark.Base.Coder
{
/// <summary>
/// A class for reading binary files in an Aardvark specific format.
/// </summary>
public partial class BinaryReadingCoder
: BaseReadingCoder, ICoder, IDisposable, IReadingCoder
{
private StreamCodeReader m_reader;
private string m_fileName;
private readonly int m_coderVersion;
private bool m_disposeStream;
#region Constructors
public BinaryReadingCoder(Stream stream) : base()
{
m_reader = new StreamCodeReader(stream, Encoding.UTF8);
m_fileName = null;
var identifier = m_reader.ReadString();
if (identifier != "Aardvark")
throw new InvalidOperationException(
"attempted read on a file of a format unknown to "
+ "Aardvark");
m_coderVersion = m_reader.ReadInt32();
if (m_coderVersion < 0
|| m_coderVersion > c_coderVersion)
throw new InvalidOperationException(
"attempted read on an Aardvark file with an "
+ "unsupported coder version");
/* var size = */m_reader.ReadInt64();
m_disposeStream = false;
}
public BinaryReadingCoder(string fileName)
: this(File.OpenRead(fileName))
{
m_fileName = fileName;
m_disposeStream = true;
}
#endregion
#region Static Convenience Functions
public static object ReadFirstObject(string fileName)
{
object first = null;
using (var coder = new BinaryReadingCoder(fileName))
coder.Code(ref first);
return first;
}
public static object ReadFirstObject(Stream stream)
{
object first = null;
using (var coder = new BinaryReadingCoder(stream))
coder.Code(ref first);
return first;
}
public static T ReadFirst<T>(string fileName)
{
T first = default(T);
using (var coder = new BinaryReadingCoder(fileName))
coder.CodeT(ref first);
return first;
}
public static T ReadFirst<T>(Stream stream)
{
T first = default(T);
using (var coder = new BinaryReadingCoder(stream))
coder.CodeT(ref first);
return first;
}
#endregion
#region ICoder Members
public string FileName
{
get { return m_fileName; }
set { m_fileName = value; }
}
public int CoderVersion { get { return m_coderVersion; } }
public int StreamVersion { get { return m_version; } }
public int MemoryVersion { get { return m_typeInfoStack.Peek().Version; } }
internal bool TryGetTypeInfo(string name, out TypeInfo ti)
{
if (m_typeInfoOfName.TryGetValue(name, out ti)) return true;
if (TypeInfo.OfName.TryGetValue(name, out ti)) return true;
return TypeInfo.TryGetOfFullName(name, out ti);
}
private void AddRef(object obj)
{
int count = m_refs.Count;
m_refs.Add(obj);
if ((m_debugMode & CoderDebugMode.ReportReferences) != 0)
{
Report.Line("{0,32} 0x{1:x}", count, obj.GetHashCode());
}
}
private object UseRef(int refNum)
{
object obj = m_refs[refNum];
if ((m_debugMode & CoderDebugMode.ReportReferences) != 0)
{
Report.Line("{0,32} * 0x{1:x}", refNum, obj.GetHashCode());
}
return obj;
}
private object UseRef(Guid guid)
{
// TODO
return null;
}
public void Code(ref object obj)
{
var typeName = m_reader.ReadString();
TypeInfo newTypeInfo = null;
TypeInfo typeInfo;
if (TryGetTypeInfo(typeName, out typeInfo))
{
if (typeInfo.Type == typeof(TypeCoder.Null))
{
if ((typeInfo.Options & TypeInfo.Option.Active) != 0)
{
obj = null;
return;
}
else
throw new Exception("cannot decode null object "
+ "- change by configuring coder with "
+ "\"coder.Add(TypeCoder.Default.Null);\"");
}
if (typeInfo.Type == typeof(TypeCoder.Reference))
{
if ((typeInfo.Options & TypeInfo.Option.Active) != 0)
{
if (CoderVersion < 5)
obj = UseRef(m_reader.ReadInt32());
else
{
obj = UseRef(m_reader.ReadGuid());
}
return;
}
else
throw new Exception(
"cannot decode multiply referenced object "
+ "- change by configuring coder with "
+ "\"coder.Add(TypeCoder.Default.Reference);\"");
}
}
else
{
typeInfo = new TypeInfo(typeName, Type.GetType(typeName),
TypeInfo.Option.Size | TypeInfo.Option.Version);
if ((m_debugMode & CoderDebugMode.ReportQualifiedNames) != 0)
Report.Line("qualified name \"{0}\"", typeName);
}
if ((typeInfo.Options & TypeInfo.Option.Version) != 0)
{
m_versionStack.Push(m_version);
m_version = m_reader.ReadInt32();
if (m_version < typeInfo.Version)
{
TypeInfo oldTypeInfo;
if (typeInfo.VersionMap.TryGetValue(m_version, out oldTypeInfo))
{
newTypeInfo = typeInfo; typeInfo = oldTypeInfo;
}
}
}
long end = 0;
if ((typeInfo.Options & TypeInfo.Option.Size) != 0)
end = m_reader.ReadInt64() + m_reader.BaseStream.Position;
if (typeInfo.Type != null)
{
if (! TypeCoder.ReadPrimitive(this, typeInfo.Type, ref obj))
{
if ((typeInfo.Options & TypeInfo.Option.Ignore) != 0)
{
m_reader.BaseStream.Position = end;
obj = null;
}
else
{
var codedVersion = m_version;
m_typeInfoStack.Push(typeInfo);
if (typeInfo.Creator != null)
obj = typeInfo.Creator();
else
obj = FastObjectFactory.ObjectFactory(typeInfo.Type)();
if ((m_debugMode & CoderDebugMode.ReportObjects) != 0)
{
Report.Line("{0,-34} 0x{1:x}", typeName, obj.GetHashCode());
}
if (m_doRefs) AddRef(obj);
#region code fields based on supported interface
var fcobj = obj as IFieldCodeable;
if (fcobj != null)
{
CodeFields(typeInfo.Type, codedVersion, fcobj);
if (typeInfo.ProxyType != null)
{
obj = typeInfo.Proxy2ObjectFun(fcobj);
}
else
{
var tmobj = obj as ITypedMap;
if (tmobj != null) CodeFields(typeInfo.Type, tmobj);
}
if ((typeInfo.Options & TypeInfo.Option.Size) != 0)
m_reader.BaseStream.Position = end;
}
else
{
if ((typeInfo.Options & TypeInfo.Option.Size) != 0)
{
m_reader.BaseStream.Position = end;
Report.Warn(
"skipping object of uncodeable type \"{0}\"",
typeName);
obj = null;
}
else
throw new Exception(
"cannot skip uncodeable object of type \""
+ typeName + '"');
}
var aobj = obj as IAwakeable;
if (aobj != null) aobj.Awake(codedVersion); // codedVersion
#endregion
m_typeInfoStack.Pop();
}
}
}
else
{
if ((typeInfo.Options & TypeInfo.Option.Size) != 0)
{
m_reader.BaseStream.Position = end;
Report.Warn("skipping object of unknown type " + typeName);
obj = null;
}
else
throw new Exception(
"cannot skip object of unknown type \""
+ typeName + '"');
}
if ((typeInfo.Options & TypeInfo.Option.Version) != 0)
{
m_version = m_versionStack.Pop();
if (obj != null && newTypeInfo != null)
{
var source = new Convertible(typeInfo.Name, obj);
var target = new Convertible(newTypeInfo.Name, null);
source.ConvertInto(target);
obj = target.Data;
}
}
}
public void CodeFields(Type type, int version, IFieldCodeable obj)
{
FieldCoder[] fca = FieldCoderArray.Get(m_coderVersion, type, version, obj);
if ((m_debugMode & CoderDebugMode.ReportFields) == 0)
{
foreach (var fc in fca)
fc.Code(this, obj);
}
else
{
foreach (var fc in fca)
{
Report.Line(" {0}", fc.Name);
fc.Code(this, obj);
}
}
}
public void CodeFields(Type type, ITypedMap obj)
{
TypeOfString fieldTypeMap = FieldTypeMap.Get(type, obj);
int fieldCount = m_reader.ReadInt32();
while (fieldCount-- > 0)
{
string fieldName = m_reader.ReadString();
if ((m_debugMode & CoderDebugMode.ReportFields) != 0)
Report.Line(" {0}", fieldName);
object value = null;
bool directlyCodeable = m_reader.ReadBoolean();
if (directlyCodeable)
{
Type fieldType;
if (!fieldTypeMap.TryGetValue(fieldName, out fieldType))
throw new InvalidOperationException(String.Format("Could not get type of field \"{0}\"", fieldName));
// this can happen if a SymMap is used and a field has been removed
TypeCoder.Read(this, fieldType, ref value);
}
else
Code(ref value);
obj[fieldName] = value;
}
}
public void CodeT<T>(ref T obj)
{
object o = default(T);
var type = typeof(T);
if (type == typeof(Array))
Code(ref o);
else
TypeCoder.Read(this, type, ref o);
obj = (T)o;
}
public object ReferenceObject(int refNum)
{
return null;
}
private bool CodeNull<T>(ref T value) where T: class
{
bool isNonNull = m_reader.ReadBoolean();
if (isNonNull) return false;
value = null;
return true;
}
public int CodeCount<T>(ref T value, Func<int, T> creator) where T : class
{
int count = m_reader.ReadInt32();
if (count < 0)
{
switch (count)
{
case -1:
value = null; return -1;
case -2:
int refNum = m_reader.ReadInt32();
if (refNum >= m_refs.Count)
{
Report.Warn("skipping invalid reference to " + refNum);
value = null; return -1;
}
value = (T)UseRef(refNum);
return -2;
default:
Report.Warn("encountered invalid count of " + count);
value = null; return -1;
}
}
value = creator(count);
if (m_doRefs) AddRef(value);
return count;
}
private long CodeLong(long intValue)
{
return ((intValue & (long)int.MaxValue) << 32) + (long)m_reader.ReadUInt32();
}
/// <summary>
/// Backward compatible extension for coding collections with 64-bit lengths.
/// </summary>
public long CodeCountLong<T>(ref T value, Func<long, T> creator) where T : class
{
long count = m_reader.ReadInt32();
if (count < 0)
{
switch (count)
{
case -1:
value = null; return -1L;
case -2:
int refNum = m_reader.ReadInt32();
if (refNum >= m_refs.Count)
{
Report.Warn("skipping invalid reference to " + refNum);
value = null;
}
else
value = (T)UseRef(refNum);
return -2L;
default:
count = CodeLong(count);
break;
}
}
value = creator(count);
if (m_doRefs) AddRef(value);
return count;
}
/// <summary>
/// Backward compatible extension for coding collections with 64-bit lengths.
/// </summary>
public long[] CodeCountArray<T>(ref T value, Func<long[], T> creator) where T : class
{
long intCount = m_reader.ReadInt32();
long[] countArray = null;
if (intCount >= 0)
countArray = intCount.IntoArray();
if (intCount < 0)
{
switch (intCount)
{
case -1:
value = null; return (-1L).IntoArray();
case -2:
int refNum = m_reader.ReadInt32();
if (refNum >= m_refs.Count)
{
Report.Warn("skipping invalid reference to " + refNum);
value = null;
}
else
value = (T)UseRef(refNum);
return (-2L).IntoArray();
case -3:
case -4:
var dim = -intCount - 1;
countArray = new long[dim];
for (int d = 0; d < dim; d++)
{
long ci = m_reader.ReadInt32();
countArray[d] = ci >= 0 ? ci : CodeLong(ci);
}
break;
default:
countArray = CodeLong(intCount).IntoArray();
break;
}
}
value = creator(countArray);
if (m_doRefs) AddRef(value);
return countArray;
}
private long CodeCountLong<T>(ref T[] array)
{
return CodeCountLong(ref array, n => new T[n]);
}
private long[] CodeCountLong<T>(ref T[,] array)
{
return CodeCountArray(ref array, ca => new T[ca[0], ca[1]]);
}
private long[] CodeCountLong<T>(ref T[,,] array)
{
return CodeCountArray(ref array, ca => new T[ca[0], ca[1], ca[2]]);
}
private long CodeCountLong<T>(ref T[][] array)
{
return CodeCountLong(ref array, c => new T[c][]);
}
private long CodeCountLong<T>(ref T[][][] array)
{
return CodeCountLong(ref array, c => new T[c][][]);
}
private int CodeCount<T>(ref List<T> list)
{
return CodeCount(ref list, n => new List<T>(n));
}
public void CodeTArray<T>(ref T[] value)
{
long count = CodeCountLong(ref value);
if (count < 1) return;
for (long i = 0; i < count; i++) CodeT(ref value[i]);
}
public void CodeList_of_T_<T>(ref List<T> value)
{
int count = CodeCount(ref value);
if (count < 1) return;
while (count-- > 0)
{
object o = default(T); Code(ref o); value.Add((T)o);
}
}
public void CodeHashSet_of_T_<T>(ref HashSet<T> value)
{
int count = CodeCount(ref value, c => new HashSet<T>());
if (count < 1) return;
while (count-- > 0)
{
object o = default(T); Code(ref o); value.Add((T)o);
}
}
public void Code(Type t, ref object o)
{
TypeCoder.Read(this, t, ref o);
}
private static Array CreateArray(Type t, long[] countArray)
{
t = t.GetElementType();
switch (countArray.Length)
{
case 1: return Array.CreateInstance(t, countArray[0]);
case 2: return Array.CreateInstance(t, countArray[0], countArray[1]);
case 3: return Array.CreateInstance(t, countArray[0], countArray[1], countArray[2]);
}
throw new ArgumentException("cannot decode array with more than 3 dimensions");
}
public void Code(Type t, ref Array array)
{
long[] countArray = CodeCountArray(ref array, ca => CreateArray(t, ca));
long c0 = countArray[0]; if (c0 < 1) return;
if (countArray.Length == 1)
{
for (int i = 0; i < c0; i++)
{
object o = null; Code(ref o); array.SetValue(o, i);
}
return;
}
var c1 = countArray[1]; if (c1 < 1) return;
if (countArray.Length == 2)
{
for (long i = 0; i < c0; i++)
for (long j = 0; j < c1; j++)
{
object o = null; Code(ref o); array.SetValue(o, i, j);
}
return;
}
var c2 = countArray[3]; if (c2 < 1) return;
if (countArray.Length == 3)
{
for (long i = 0; i < c0; i++)
for (long j = 0; j < c1; j++)
for (long k = 0; k < c2; k++)
{
object o = null; Code(ref o); array.SetValue(o, i, j, k);
}
return;
}
throw new ArgumentException("cannot decode array with more than 3 dimensions");
}
public void CodeOld(Type t, ref Array array)
{
int count = CodeCount(ref array,
n => (Array)Activator.CreateInstance(t, n));
if (count < 1) return;
for (int i = 0; i < count; i++)
{
object o = null;
Code(ref o);
array.SetValue(o, i);
}
}
public void Code(Type t, ref IList list)
{
int count = CodeCount(ref list,
n => (IList)Activator.CreateInstance(t, n));
if (count < 1) return;
while (count-- > 0)
{
object o = null;
Code(ref o);
list.Add(o);
}
}
public void Code(Type t, ref IDictionary dict)
{
int count = CodeCount(ref dict,
n => (IDictionary)Activator.CreateInstance(t, n));
if (count < 1) return;
Type[] subTypeArray = t.GetGenericArguments();
while (count-- > 0)
{
object key = null;
TypeCoder.Read(this, subTypeArray[0], ref key);
object val = null;
TypeCoder.Read(this, subTypeArray[1], ref val);
dict[key] = val;
}
}
public void Code(Type t, ref ICountableDict dict)
{
int count = CodeCount(ref dict,
n => (ICountableDict)Activator.CreateInstance(t, n));
if (count < 1) return;
var keyType = dict.KeyType;
var valueType = dict.ValueType;
while (count-- > 0)
{
object key = null;
TypeCoder.Read(this, keyType, ref key);
object val = null;
TypeCoder.Read(this, valueType, ref val);
dict.AddObject(key, val);
}
}
public void Code(Type t, ref ICountableDictSet dictSet)
{
int count = CodeCount(ref dictSet,
n => (ICountableDictSet)Activator.CreateInstance(t, n));
if (count < 1) return;
var keyType = dictSet.KeyType;
while (count-- > 0)
{
object key = null;
TypeCoder.Read(this, keyType, ref key);
dictSet.AddObject(key);
}
}
public void Code(Type t, ref IArrayVector value)
{
value = (IArrayVector)FastObjectFactory.ObjectFactory(t)();
Array array = null; Code(value.ArrayType, ref array); value.Array = array;
long origin = 0L; CodeLong(ref origin); value.Origin = origin;
long length = 0L; CodeLong(ref length); value.Size = length;
long delta = 0L; CodeLong(ref delta); value.Delta = delta;
}
public void Code(Type t, ref IArrayMatrix value)
{
value = (IArrayMatrix)FastObjectFactory.ObjectFactory(t)();
Array array = null; Code(value.ArrayType, ref array); value.Array = array;
long origin = 0L; CodeLong(ref origin); value.Origin = origin;
V2l length = default(V2l); CodeV2l(ref length); value.Size = length;
V2l delta = default(V2l); CodeV2l(ref delta); value.Delta = delta;
}
public void Code(Type t, ref IArrayVolume value)
{
value = (IArrayVolume)FastObjectFactory.ObjectFactory(t)();
Array array = null; Code(value.ArrayType, ref array); value.Array = array;
long origin = 0L; CodeLong(ref origin); value.Origin = origin;
V3l length = default(V3l); CodeV3l(ref length); value.Size = length;
V3l delta = default(V3l); CodeV3l(ref delta); value.Delta = delta;
}
public void Code(Type t, ref IArrayTensor4 value)
{
value = (IArrayTensor4)FastObjectFactory.ObjectFactory(t)();
Array array = null; Code(value.ArrayType, ref array); value.Array = array;
long origin = 0L; CodeLong(ref origin); value.Origin = origin;
V4l length = default(V4l); CodeV4l(ref length); value.Size = length;
V4l delta = default(V4l); CodeV4l(ref delta); value.Delta = delta;
}
public void Code(Type t, ref IArrayTensorN value)
{
value = (IArrayTensorN)FastObjectFactory.ObjectFactory(t)();
Array array = null; Code(value.ArrayType, ref array); value.Array = array;
long origin = 0L; CodeLong(ref origin); value.Origin = origin;
long[] length = null; CodeLongArray(ref length); value.Size = length;
long[] delta = null; CodeLongArray(ref delta); value.Delta = delta;
}
public void CodeHashSet(Type t, ref object obj)
{
throw new NotImplementedException("only possible whith a non-generic ISet interface)");
}
public void CodeEnum(Type type, ref object value)
{
Type systemType = Enum.GetUnderlyingType(type);
var reader = TypeCoder.TypeReaderMap[systemType];
object obj = reader(this);
value = Enum.ToObject(type, obj);
}
#endregion
#region Code Primitives
public void CodeBool(ref bool value)
{
value = m_reader.ReadBoolean();
}
public void CodeByte(ref byte value)
{
value = m_reader.ReadByte();
}
public void CodeSByte(ref sbyte value)
{
value = m_reader.ReadSByte();
}
public void CodeShort(ref short value)
{
value = m_reader.ReadInt16();
}
public void CodeUShort(ref ushort value)
{
value = m_reader.ReadUInt16();
}
public void CodeInt(ref int value)
{
value = m_reader.ReadInt32();
}
public void CodeUInt(ref uint value)
{
value = m_reader.ReadUInt32();
}
public void CodeLong(ref long value)
{
value = m_reader.ReadInt64();
}
public void CodeULong(ref ulong value)
{
value = m_reader.ReadUInt64();
}
public void CodeFloat(ref float value)
{
value = m_reader.ReadSingle();
}
public void CodeDouble(ref double value)
{
value = m_reader.ReadDouble();
}
public void CodeChar(ref char value)
{
value = m_reader.ReadChar();
}
public void CodeString(ref string value)
{
if (m_coderVersion == 0)
value = m_reader.ReadString();
else
{
if (CodeNull(ref value)) return;
value = m_reader.ReadString();
}
}
public void CodeType(ref Type value)
{
var typeName = m_reader.ReadString();
TypeInfo ti;
if (TryGetTypeInfo(typeName, out ti))
value = ti.Type;
else
value = Type.GetType(typeName);
}
public void CodeGuid(ref Guid value) { value = m_reader.ReadGuid(); }
public void CodeSymbol(ref Symbol value) { value = m_reader.ReadSymbol(); }
public void CodeGuidSymbol(ref Symbol value) { value = m_reader.ReadGuidSymbol(); }
public void CodePositiveSymbol(ref Symbol value) { value = m_reader.ReadPositiveSymbol(); }
public void CodeIntSet(ref IntSet set)
{
int count = CodeCount(ref set, n => new IntSet(n));
if (count < 1) return;
while (count-- > 0) set.Add(m_reader.ReadInt32());
}
public void CodeSymbolSet(ref SymbolSet set)
{
int count = CodeCount(ref set, n => new SymbolSet(n));
if (count < 1) return;
while (count-- > 0) set.Add(m_reader.ReadSymbol());
}
public void CodeFraction(ref Fraction value)
{
long numerator = m_reader.ReadInt64();
long denominator = m_reader.ReadInt64();
value = new Fraction(numerator, denominator);
}
public void CodeCircle2d(ref Circle2d v)
{
CodeV2d(ref v.Center); CodeDouble(ref v.Radius);
}
public void CodeLine2d(ref Line2d v)
{
CodeV2d(ref v.P0); CodeV2d(ref v.P1);
}
public void CodeLine3d(ref Line3d v)
{
CodeV3d(ref v.P0); CodeV3d(ref v.P1);
}
public void CodePlane2d(ref Plane2d v)
{
CodeV2d(ref v.Normal); CodeDouble(ref v.Distance);
}
public void CodePlane3d(ref Plane3d v)
{
CodeV3d(ref v.Normal); CodeDouble(ref v.Distance);
}
public void CodePlaneWithPoint3d(ref PlaneWithPoint3d v)
{
CodeV3d(ref v.Normal); CodeV3d(ref v.Point);
}
public void CodeQuad2d(ref Quad2d v)
{
CodeV2d(ref v.P0); CodeV2d(ref v.P1); CodeV2d(ref v.P2); CodeV2d(ref v.P3);
}
public void CodeQuad3d(ref Quad3d v)
{
CodeV3d(ref v.P0); CodeV3d(ref v.P1); CodeV3d(ref v.P2); CodeV3d(ref v.P3);
}
public void CodeRay2d(ref Ray2d v)
{
CodeV2d(ref v.Origin); CodeV2d(ref v.Direction);
}
public void CodeRay3d(ref Ray3d v)
{
CodeV3d(ref v.Origin); CodeV3d(ref v.Direction);
}
public void CodeSphere3d(ref Sphere3d v)
{
CodeV3d(ref v.Center); CodeDouble(ref v.Radius);
}
public void CodeTriangle2d(ref Triangle2d v)
{
CodeV2d(ref v.P0); CodeV2d(ref v.P1); CodeV2d(ref v.P2);
}
public void CodeTriangle3d(ref Triangle3d v)
{
CodeV3d(ref v.P0); CodeV3d(ref v.P1); CodeV3d(ref v.P2);
}
public void CodeCameraExtrinsics(ref CameraExtrinsics v)
{
var rotation = default(M33d); var translation = default(V3d);
CodeM33d(ref rotation); CodeV3d(ref translation);
v = new CameraExtrinsics(rotation, translation);
}
public void CodeCameraIntrinsics(ref CameraIntrinsics v)
{
var focalLength = default(V2d); var principalPoint = default(V2d);
double skew = 0.0, k1 = 0.0, k2 = 0.0, k3 = 0.0, p1 = 0.0, p2 = 0.0;
CodeV2d(ref focalLength); CodeV2d(ref principalPoint);
CodeDouble(ref skew);
CodeDouble(ref k1); CodeDouble(ref k2); CodeDouble(ref k3);
CodeDouble(ref p1); CodeDouble(ref p1);
v = new CameraIntrinsics(focalLength, principalPoint, skew, k1, k2, k3, p1, p2);
}
#endregion
#region Code Arrays
public void CodeStructArray<T>(ref T[] value)
where T : struct
{
long count = CodeCountLong(ref value);
if (count < 1) return;
m_reader.ReadArray(value, 0, count);
}
public void CodeBoolArray(ref bool[] value)
{
long count = CodeCountLong(ref value);
if (count < 1) return;
for (long i = 0; i < count; i++) value[i] = m_reader.ReadBoolean();
}
public void CodeByteArray(ref byte[] value)
{
long count = CodeCountLong(ref value);
if (count < 1) return;
m_reader.ReadArray(value, 0, count);
}
public void CodeSByteArray(ref sbyte[] value)
{
long count = CodeCountLong(ref value);
if (count < 1) return;
m_reader.ReadArray(value, 0, count);
}
public void CodeShortArray(ref short[] value)
{
long count = CodeCountLong(ref value);
if (count < 1) return;
m_reader.ReadArray(value, 0, count);
}
public void CodeUShortArray(ref ushort[] value)
{
long count = CodeCountLong(ref value);
if (count < 1) return;
m_reader.ReadArray(value, 0, count);
}
public void CodeIntArray(ref int[] value)
{
long count = CodeCountLong(ref value);
if (count < 1) return;
m_reader.ReadArray(value, 0, count);
}
public void CodeUIntArray(ref uint[] value)
{
long count = CodeCountLong(ref value);
if (count < 1) return;
m_reader.ReadArray(value, 0, count);
}
public void CodeLongArray(ref long[] value)
{
long count = CodeCountLong(ref value);
if (count < 1) return;
m_reader.ReadArray(value, 0, count);
}
public void CodeULongArray(ref ulong[] value)
{
long count = CodeCountLong(ref value);
if (count < 1) return;
m_reader.ReadArray(value, 0, count);
}
public void CodeFloatArray(ref float[] value)
{
long count = CodeCountLong(ref value);
if (count < 1) return;
m_reader.ReadArray(value, 0, count);
}
public void CodeDoubleArray(ref double[] value)
{
long count = CodeCountLong(ref value);
if (count < 1) return;
m_reader.ReadArray(value, 0, count);
}
public void CodeCharArray(ref char[] value)
{
long count = CodeCountLong(ref value);
if (count < 1) return;
for (long i = 0; i < count; i++) value[i] = m_reader.ReadChar();
}
public void CodeStringArray(ref string[] value)
{
long count = CodeCountLong(ref value);
if (count < 1) return;
for (long i = 0; i < count; i++) value[i] = m_reader.ReadString();
}
public void CodeTypeArray(ref Type[] value)
{
long count = CodeCountLong(ref value);
if (count < 1) return;
for (long i = 0; i < count; i++)
{
var typeName = m_reader.ReadString();
TypeInfo ti;
if (TryGetTypeInfo(typeName, out ti))
value[i] = ti.Type;
else
value[i] = Type.GetType(typeName);
}
}
public void CodeGuidArray(ref Guid[] value)
{
long count = CodeCountLong(ref value);
if (count < 1) return;
for (long i = 0; i < count; i++) CodeGuid(ref value[i]);
}
public void CodeSymbolArray(ref Symbol[] value)
{
long count = CodeCountLong(ref value);
if (count < 1) return;
for (long i = 0; i < count; i++) CodeSymbol(ref value[i]);
}
public void CodeFractionArray(ref Fraction[] value)
{
long count = CodeCountLong(ref value);
if (count < 1) return;
m_reader.ReadArray(value, 0, count);
}
#endregion
#region Code Lists
public void CodeStructList<T>(ref List<T> value)
where T : struct
{
int count = CodeCount(ref value);
if (count < 1) return;
m_reader.ReadList(value, 0, count);
}
public void CodeList_of_Bool_(ref List<bool> value)
{
int count = CodeCount(ref value);
if (count < 1) return;
while (count-- > 0) value.Add(m_reader.ReadBoolean());
}
public void CodeList_of_Byte_(ref List<byte> value)
{
int count = CodeCount(ref value);
if (count < 1) return;
while (count-- > 0) value.Add(m_reader.ReadByte());
}
public void CodeList_of_SByte_(ref List<sbyte> value)
{
int count = CodeCount(ref value);
if (count < 1) return;
m_reader.ReadList(value, 0, count);
}
public void CodeList_of_Short_(ref List<short> value)
{
int count = CodeCount(ref value);
if (count < 1) return;
m_reader.ReadList(value, 0, count);
}
public void CodeList_of_UShort_(ref List<ushort> value)
{
int count = CodeCount(ref value);
if (count < 1) return;
m_reader.ReadList(value, 0, count);
}
public void CodeList_of_Int_(ref List<int> value)
{
int count = CodeCount(ref value);
if (count < 1) return;
m_reader.ReadList(value, 0, count);
}
public void CodeList_of_UInt_(ref List<uint> value)
{
int count = CodeCount(ref value);
if (count < 1) return;
m_reader.ReadList(value, 0, count);
}
public void CodeList_of_Long_(ref List<long> value)
{
int count = CodeCount(ref value);
if (count < 1) return;
m_reader.ReadList(value, 0, count);
}
public void CodeList_of_ULong_(ref List<ulong> value)
{
int count = CodeCount(ref value);
if (count < 1) return;
m_reader.ReadList(value, 0, count);
}
public void CodeList_of_Float_(ref List<float> value)
{
int count = CodeCount(ref value);
if (count < 1) return;
m_reader.ReadList(value, 0, count);
}
public void CodeList_of_Double_(ref List<double> value)
{
int count = CodeCount(ref value);
if (count < 1) return;
m_reader.ReadList(value, 0, count);
}
public void CodeList_of_Char_(ref List<char> value)
{
int count = CodeCount(ref value);
if (count < 1) return;
while (count-- > 0) value.Add(m_reader.ReadChar());
}
public void CodeList_of_String_(ref List<string> value)
{
int count = CodeCount(ref value);
if (count < 1) return;
while (count-- > 0) value.Add(m_reader.ReadString());
//for (int i = 0; i < count; i++) value[i] = m_reader.ReadString();
}
public void CodeList_of_Type_(ref List<Type> value)
{
int count = CodeCount(ref value);
if (count < 1) return;
for (int i = 0; i < count; i++)
{
var typeName = m_reader.ReadString();
TypeInfo ti;
if (TryGetTypeInfo(typeName, out ti))
value.Add(ti.Type);
else
value.Add(Type.GetType(typeName));
}
}
public void CodeList_of_Guid_(ref List<Guid> value)
{
int count = CodeCount(ref value);
if (count < 1) return;
//while (count-- > 0) value.Add(new Guid(m_reader.ReadString()));
for (int i = 0; i < count; i++)
{
var m = new Guid();
CodeGuid(ref m);
value.Add(m);
//value[i] = new Guid(m_reader.ReadString());
}
}
public void CodeList_of_Symbol_(ref List<Symbol> value)
{
int count = CodeCount(ref value);
if (count < 1) return;
for (int i = 0; i < count; i++)
{
var m = default(Symbol);
CodeSymbol(ref m);
value.Add(m);
}
}
public void CodeList_of_Fraction_(ref List<Fraction> value)
{
int count = CodeCount(ref value);
if (count < 1) return;
m_reader.ReadList(value, 0, count);
}
#endregion
#region IDisposable Members
public void Dispose()
{
// dispose reader
if (m_disposeStream)
m_reader.BaseStream.Dispose();
}
#endregion
}
}
| |
namespace EffectParameterEditor
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.label3 = new System.Windows.Forms.Label();
this.parametersBox = new System.Windows.Forms.ComboBox();
this.effectPropGrid = new System.Windows.Forms.PropertyGrid();
this.label2 = new System.Windows.Forms.Label();
this.effectBox = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.meshPartBox = new System.Windows.Forms.ComboBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.modelPropGrid = new System.Windows.Forms.PropertyGrid();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loadModelToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loadEffectToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loadParametersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.loadMaterialToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveMaterialToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveParxFileDialog = new System.Windows.Forms.SaveFileDialog();
this.openParxFileDialog = new System.Windows.Forms.OpenFileDialog();
this.openModelDialog = new System.Windows.Forms.OpenFileDialog();
this.openEffectDialog = new System.Windows.Forms.OpenFileDialog();
this.saveMaterialDialog = new System.Windows.Forms.SaveFileDialog();
this.openMaterialDialog = new System.Windows.Forms.OpenFileDialog();
this.modelViewControl1 = new EffectParameterEditor.Controls.ModelViewControl();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.groupBox3.SuspendLayout();
this.groupBox1.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.Location = new System.Drawing.Point(0, 24);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.groupBox3);
this.splitContainer1.Panel1.Controls.Add(this.groupBox1);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.modelViewControl1);
this.splitContainer1.Size = new System.Drawing.Size(845, 555);
this.splitContainer1.SplitterDistance = 259;
this.splitContainer1.TabIndex = 0;
//
// groupBox3
//
this.groupBox3.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox3.Controls.Add(this.label3);
this.groupBox3.Controls.Add(this.parametersBox);
this.groupBox3.Controls.Add(this.effectPropGrid);
this.groupBox3.Controls.Add(this.label2);
this.groupBox3.Controls.Add(this.effectBox);
this.groupBox3.Controls.Add(this.label1);
this.groupBox3.Controls.Add(this.meshPartBox);
this.groupBox3.Location = new System.Drawing.Point(4, 195);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(251, 357);
this.groupBox3.TabIndex = 3;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Part";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(6, 96);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(60, 13);
this.label3.TabIndex = 7;
this.label3.Text = "Parameters";
//
// parametersBox
//
this.parametersBox.FormattingEnabled = true;
this.parametersBox.Location = new System.Drawing.Point(6, 112);
this.parametersBox.Name = "parametersBox";
this.parametersBox.Size = new System.Drawing.Size(239, 21);
this.parametersBox.TabIndex = 6;
this.parametersBox.SelectedIndexChanged += new System.EventHandler(this.parametersBox_SelectedIndexChanged);
//
// effectPropGrid
//
this.effectPropGrid.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.effectPropGrid.Location = new System.Drawing.Point(3, 139);
this.effectPropGrid.Name = "effectPropGrid";
this.effectPropGrid.Size = new System.Drawing.Size(248, 218);
this.effectPropGrid.TabIndex = 1;
this.effectPropGrid.PropertyValueChanged += new System.Windows.Forms.PropertyValueChangedEventHandler(this.effectPropGrid_PropertyValueChanged);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(6, 56);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(35, 13);
this.label2.TabIndex = 5;
this.label2.Text = "Effect";
//
// effectBox
//
this.effectBox.FormattingEnabled = true;
this.effectBox.Location = new System.Drawing.Point(6, 72);
this.effectBox.Name = "effectBox";
this.effectBox.Size = new System.Drawing.Size(239, 21);
this.effectBox.TabIndex = 4;
this.effectBox.SelectedIndexChanged += new System.EventHandler(this.effectBox_SelectedIndexChanged);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(63, 13);
this.label1.TabIndex = 3;
this.label1.Text = "Current Part";
//
// meshPartBox
//
this.meshPartBox.FormattingEnabled = true;
this.meshPartBox.Location = new System.Drawing.Point(6, 32);
this.meshPartBox.Name = "meshPartBox";
this.meshPartBox.Size = new System.Drawing.Size(239, 21);
this.meshPartBox.TabIndex = 2;
this.meshPartBox.SelectedIndexChanged += new System.EventHandler(this.meshPartBox_SelectedIndexChanged);
//
// groupBox1
//
this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox1.Controls.Add(this.modelPropGrid);
this.groupBox1.Location = new System.Drawing.Point(4, 4);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(252, 185);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Model";
//
// modelPropGrid
//
this.modelPropGrid.Dock = System.Windows.Forms.DockStyle.Fill;
this.modelPropGrid.Location = new System.Drawing.Point(3, 16);
this.modelPropGrid.Name = "modelPropGrid";
this.modelPropGrid.Size = new System.Drawing.Size(246, 166);
this.modelPropGrid.TabIndex = 0;
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(845, 24);
this.menuStrip1.TabIndex = 1;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.loadModelToolStripMenuItem,
this.loadEffectToolStripMenuItem,
this.loadParametersToolStripMenuItem,
this.toolStripSeparator1,
this.loadMaterialToolStripMenuItem,
this.saveMaterialToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20);
this.fileToolStripMenuItem.Text = "&File";
//
// loadModelToolStripMenuItem
//
this.loadModelToolStripMenuItem.Name = "loadModelToolStripMenuItem";
this.loadModelToolStripMenuItem.Size = new System.Drawing.Size(166, 22);
this.loadModelToolStripMenuItem.Text = "Load &Model";
this.loadModelToolStripMenuItem.Click += new System.EventHandler(this.loadModelToolStripMenuItem_Click);
//
// loadEffectToolStripMenuItem
//
this.loadEffectToolStripMenuItem.Name = "loadEffectToolStripMenuItem";
this.loadEffectToolStripMenuItem.Size = new System.Drawing.Size(166, 22);
this.loadEffectToolStripMenuItem.Text = "Load &Effect";
this.loadEffectToolStripMenuItem.Click += new System.EventHandler(this.loadEffectToolStripMenuItem_Click);
//
// loadParametersToolStripMenuItem
//
this.loadParametersToolStripMenuItem.Name = "loadParametersToolStripMenuItem";
this.loadParametersToolStripMenuItem.Size = new System.Drawing.Size(166, 22);
this.loadParametersToolStripMenuItem.Text = "Load &Parameters";
this.loadParametersToolStripMenuItem.Click += new System.EventHandler(this.loadParametersToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(163, 6);
//
// loadMaterialToolStripMenuItem
//
this.loadMaterialToolStripMenuItem.Name = "loadMaterialToolStripMenuItem";
this.loadMaterialToolStripMenuItem.Size = new System.Drawing.Size(166, 22);
this.loadMaterialToolStripMenuItem.Text = "&Load Material";
this.loadMaterialToolStripMenuItem.Click += new System.EventHandler(this.loadMaterialToolStripMenuItem_Click);
//
// saveMaterialToolStripMenuItem
//
this.saveMaterialToolStripMenuItem.Name = "saveMaterialToolStripMenuItem";
this.saveMaterialToolStripMenuItem.Size = new System.Drawing.Size(166, 22);
this.saveMaterialToolStripMenuItem.Text = "&Save Material";
this.saveMaterialToolStripMenuItem.ToolTipText = "Save the material, and changes to all parameters";
this.saveMaterialToolStripMenuItem.Click += new System.EventHandler(this.saveMaterialToolStripMenuItem_Click);
//
// saveParxFileDialog
//
this.saveParxFileDialog.DefaultExt = "fxparx";
this.saveParxFileDialog.Filter = "Parameter files (*.fxparx)|*.fxparx";
//
// openParxFileDialog
//
this.openParxFileDialog.DefaultExt = "fxparx";
this.openParxFileDialog.Filter = "Parameter files (*.fxparx)|*.fxparx";
//
// openModelDialog
//
this.openModelDialog.DefaultExt = "x";
this.openModelDialog.Filter = "X Model (*.x)|*.x|XNB Model (*.xnb)|*.xnb";
//
// openEffectDialog
//
this.openEffectDialog.DefaultExt = "fx";
this.openEffectDialog.Filter = "HLSL Effect (*.fx)|*.fx";
//
// saveMaterialDialog
//
this.saveMaterialDialog.DefaultExt = "matx";
this.saveMaterialDialog.Filter = "FRB Material (*.matx)|*.matx";
//
// openMaterialDialog
//
this.openMaterialDialog.DefaultExt = "matx";
this.openMaterialDialog.Filter = "FRB Material (*.matx)|*.matx";
//
// modelViewControl1
//
this.modelViewControl1.BackgroundColor = new Microsoft.Xna.Framework.Graphics.Color(((byte)(0)), ((byte)(0)), ((byte)(0)), ((byte)(255)));
this.modelViewControl1.CurrentModel = null;
this.modelViewControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.modelViewControl1.Location = new System.Drawing.Point(0, 0);
this.modelViewControl1.Name = "modelViewControl1";
this.modelViewControl1.Size = new System.Drawing.Size(582, 555);
this.modelViewControl1.StatusStrip = null;
this.modelViewControl1.TabIndex = 0;
this.modelViewControl1.Text = "modelViewControl1";
this.modelViewControl1.PreviewKeyDown += new System.Windows.Forms.PreviewKeyDownEventHandler(this.modelViewControl1_PreviewKeyDown);
this.modelViewControl1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.modelViewControl1_MouseDown);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(845, 579);
this.Controls.Add(this.splitContainer1);
this.Controls.Add(this.menuStrip1);
this.Name = "Form1";
this.Text = "Form1";
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.ResumeLayout(false);
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.PropertyGrid effectPropGrid;
private System.Windows.Forms.PropertyGrid modelPropGrid;
private EffectParameterEditor.Controls.ModelViewControl modelViewControl1;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.SaveFileDialog saveParxFileDialog;
private System.Windows.Forms.ToolStripMenuItem loadParametersToolStripMenuItem;
private System.Windows.Forms.OpenFileDialog openParxFileDialog;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem loadModelToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem loadEffectToolStripMenuItem;
private System.Windows.Forms.OpenFileDialog openModelDialog;
private System.Windows.Forms.OpenFileDialog openEffectDialog;
private System.Windows.Forms.ComboBox meshPartBox;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ComboBox effectBox;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ComboBox parametersBox;
private System.Windows.Forms.ToolStripMenuItem saveMaterialToolStripMenuItem;
private System.Windows.Forms.SaveFileDialog saveMaterialDialog;
private System.Windows.Forms.ToolStripMenuItem loadMaterialToolStripMenuItem;
private System.Windows.Forms.OpenFileDialog openMaterialDialog;
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Orleans.CodeGeneration;
using Orleans.Runtime;
using Orleans.Serialization;
namespace UnitTests.Grains
{
public enum IntEnum
{
Value1,
Value2,
Value3
}
public enum UShortEnum : ushort
{
Value1,
Value2,
Value3
}
public enum CampaignEnemyType : sbyte
{
None = -1,
Brute = 0,
Enemy1,
Enemy2,
Enemy3,
Enemy4,
}
public class UnserializableException : Exception
{
public UnserializableException(string message) : base(message)
{ }
[CopierMethod]
static private object Copy(object input, ICopyContext context)
{
return input;
}
}
[Serializable]
public class Unrecognized
{
public int A { get; set; }
public int B { get; set; }
}
[Serializable]
public class ClassWithCustomCopier
{
public int IntProperty { get; set; }
public string StringProperty { get; set; }
public static int CopyCounter { get; set; }
static ClassWithCustomCopier()
{
CopyCounter = 0;
}
[CopierMethod]
private static object Copy(object input, ICopyContext context)
{
CopyCounter++;
var obj = input as ClassWithCustomCopier;
return new ClassWithCustomCopier() { IntProperty = obj.IntProperty, StringProperty = obj.StringProperty };
}
}
[Serializable]
public class ClassWithCustomSerializer
{
public int IntProperty { get; set; }
public string StringProperty { get; set; }
public static int SerializeCounter { get; set; }
public static int DeserializeCounter { get; set; }
static ClassWithCustomSerializer()
{
SerializeCounter = 0;
DeserializeCounter = 0;
}
[SerializerMethod]
private static void Serialize(object input, ISerializationContext context, Type expected)
{
SerializeCounter++;
var obj = input as ClassWithCustomSerializer;
var stream = context.StreamWriter;
stream.Write(obj.IntProperty);
stream.Write(obj.StringProperty);
}
[DeserializerMethod]
private static object Deserialize(Type expected, IDeserializationContext context)
{
DeserializeCounter++;
var result = new ClassWithCustomSerializer();
var stream = context.StreamReader;
result.IntProperty = stream.ReadInt();
result.StringProperty = stream.ReadString();
return result;
}
}
public class FakeSerializer1 : IExternalSerializer
{
public static bool IsSupportedTypeCalled { get; private set; }
public static bool DeepCopyCalled { get; private set; }
public static bool SerializeCalled { get; private set; }
public static bool DeserializeCalled { get; private set; }
public static IList<Type> SupportedTypes { get; set; }
public static void Reset()
{
IsSupportedTypeCalled = DeepCopyCalled = SerializeCalled = DeserializeCalled = false;
}
public bool IsSupportedType(Type itemType)
{
IsSupportedTypeCalled = true;
return SupportedTypes == null ? false : SupportedTypes.Contains(itemType);
}
public object DeepCopy(object source, ICopyContext context)
{
DeepCopyCalled = true;
return source;
}
public void Serialize(object item, ISerializationContext context, Type expectedType)
{
SerializeCalled = true;
}
public object Deserialize(Type expectedType, IDeserializationContext context)
{
DeserializeCalled = true;
return null;
}
}
public class FakeSerializer2 : IExternalSerializer
{
public static bool IsSupportedTypeCalled { get; private set; }
public static bool DeepCopyCalled { get; private set; }
public static bool SerializeCalled { get; private set; }
public static bool DeserializeCalled { get; private set; }
public static IList<Type> SupportedTypes { get; set; }
public static void Reset()
{
IsSupportedTypeCalled = DeepCopyCalled = SerializeCalled = DeserializeCalled = false;
}
public bool IsSupportedType(Type itemType)
{
IsSupportedTypeCalled = true;
return SupportedTypes == null ? false : SupportedTypes.Contains(itemType);
}
public object DeepCopy(object source, ICopyContext context)
{
DeepCopyCalled = true;
return source;
}
public void Serialize(object item, ISerializationContext context, Type expectedType)
{
SerializeCalled = true;
}
public object Deserialize(Type expectedType, IDeserializationContext context)
{
DeserializeCalled = true;
return null;
}
}
public class FakeTypeToSerialize
{
public int SomeValue { get; set; }
public static bool CopyWasCalled { get; private set; }
public static bool SerializeWasCalled { get; private set; }
public static bool DeserializeWasCalled { get; private set; }
public static void Reset()
{
CopyWasCalled = SerializeWasCalled = DeserializeWasCalled = false;
}
[CopierMethod]
private static object Copy(object input, ICopyContext context)
{
CopyWasCalled = true;
return input;
}
[SerializerMethod]
private static void Serialize(object input, ISerializationContext context, Type expected)
{
SerializeWasCalled = true;
}
[DeserializerMethod]
private static object Deserialize(Type expected, IDeserializationContext context)
{
DeserializeWasCalled = true;
return null;
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AdventureWorks.UILogic.Models;
using AdventureWorks.UILogic.Services;
using AdventureWorks.UILogic.Tests.Mocks;
using AdventureWorks.UILogic.ViewModels;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Windows.UI.Xaml.Navigation;
using Prism.Windows.Navigation;
namespace AdventureWorks.UILogic.Tests.ViewModels
{
[TestClass]
public class CheckoutSummaryPageViewModelFixture
{
[TestMethod]
public void SubmitValidOrder_NavigatesToOrderConfirmation()
{
bool navigateCalled = false;
bool clearCartCalled = false;
var navigationService = new MockNavigationService();
navigationService.NavigateDelegate = (s, o) =>
{
Assert.AreEqual("OrderConfirmation", s);
navigateCalled = true;
return true;
};
var accountService = new MockAccountService()
{
VerifySavedCredentialsAsyncDelegate = () => Task.FromResult<UserInfo>(new UserInfo())
};
var orderService = new MockOrderService()
{
// the order is valid, it can be processed
ProcessOrderAsyncDelegate = (o) => Task.FromResult(true)
};
var resourcesService = new MockResourceLoader()
{
GetStringDelegate = (key) => key
};
var shoppingCartRepository = new MockShoppingCartRepository();
shoppingCartRepository.ClearCartAsyncDelegate = () =>
{
clearCartCalled = true;
return Task.Delay(0);
};
var target = new CheckoutSummaryPageViewModel(navigationService, orderService, null, null, null, shoppingCartRepository, accountService, resourcesService, null, null);
target.SubmitCommand.Execute();
Assert.IsTrue(navigateCalled);
Assert.IsTrue(clearCartCalled);
}
[TestMethod]
public void SubmitInvalidOrder_CallsErrorDialog()
{
bool successDialogCalled = false;
bool errorDialogCalled = false;
var navigationService = new MockNavigationService();
var accountService = new MockAccountService()
{
VerifySavedCredentialsAsyncDelegate = () => Task.FromResult<UserInfo>(new UserInfo())
};
var orderService = new MockOrderService()
{
// the order is invalid, it cannot be processed
ProcessOrderAsyncDelegate = (o) =>
{
var modelValidationResult = new ModelValidationResult();
modelValidationResult.ModelState.Add("someKey", new List<string>() { "the value of someKey is invalid" });
throw new ModelValidationException(modelValidationResult);
}
};
var resourcesService = new MockResourceLoader()
{
GetStringDelegate = (key) => key
};
var alertService = new MockAlertMessageService()
{
ShowAsyncDelegate = (dialogTitle, dialogMessage) =>
{
successDialogCalled = dialogTitle.ToLower().Contains("purchased");
errorDialogCalled = !successDialogCalled;
return Task.FromResult(successDialogCalled);
}
};
var target = new CheckoutSummaryPageViewModel(navigationService, orderService, null, null, null, null, accountService, resourcesService, alertService, null);
target.SubmitCommand.Execute();
Assert.IsFalse(successDialogCalled);
Assert.IsTrue(errorDialogCalled);
}
[TestMethod]
public void Submit_WhenAnonymous_ShowsSignInControl()
{
bool showSignInCalled = false;
var accountService = new MockAccountService()
{
VerifySavedCredentialsAsyncDelegate = () => Task.FromResult<UserInfo>(null)
};
var signInUserControlViewModel = new MockSignInUserControlViewModel()
{
OpenDelegate = (a) => showSignInCalled = true
};
var target = new CheckoutSummaryPageViewModel(new MockNavigationService(), null, null, null, null, null, accountService, null, null, signInUserControlViewModel);
target.SubmitCommand.Execute();
Assert.IsTrue(showSignInCalled);
}
[TestMethod]
public void SelectShippingMethod_Recalculates_Order()
{
var shippingMethods = new List<ShippingMethod>() { new ShippingMethod() { Id = 1, Cost = 0 } };
var shoppingCartItems = new List<ShoppingCartItem>() { new ShoppingCartItem() { Quantity = 1, Currency = "USD", Product = new Product() } };
var order = new Order()
{
ShoppingCart = new ShoppingCart(shoppingCartItems) { Currency = "USD", TotalPrice = 100 },
ShippingAddress = new Address(),
BillingAddress = new Address(),
PaymentMethod = new PaymentMethod() { CardNumber = "1234" },
ShippingMethod = shippingMethods.First()
};
var shippingMethodService = new MockShippingMethodService()
{
GetShippingMethodsAsyncDelegate = () => Task.FromResult<IEnumerable<ShippingMethod>>(shippingMethods)
};
var orderRepository = new MockOrderRepository() { CurrentOrder = order };
var shoppingCartRepository = new MockShoppingCartRepository();
shoppingCartRepository.GetShoppingCartAsyncDelegate = () => Task.FromResult(order.ShoppingCart);
var checkoutDataRepository = new MockCheckoutDataRepository();
checkoutDataRepository.GetShippingAddressAsyncDelegate = s => Task.FromResult(new Address());
checkoutDataRepository.GetBillingAddressAsyncDelegate = s => Task.FromResult(new Address());
checkoutDataRepository.GetPaymentMethodDelegate = s => Task.FromResult(new PaymentMethod{CardNumber = "1234"});
var target = new CheckoutSummaryPageViewModel(new MockNavigationService(), new MockOrderService(), orderRepository, shippingMethodService,
checkoutDataRepository, shoppingCartRepository,
new MockAccountService(), new MockResourceLoader(), null, null);
target.OnNavigatedTo(new NavigatedToEventArgs { Parameter = null, NavigationMode = NavigationMode.New }, null);
Assert.AreEqual("$0.00", target.ShippingCost);
Assert.AreEqual("$100.00", target.OrderSubtotal);
Assert.AreEqual("$100.00", target.GrandTotal);
target.SelectedShippingMethod = new ShippingMethod() { Cost = 10 };
Assert.AreEqual("$10.00", target.ShippingCost);
Assert.AreEqual("$100.00", target.OrderSubtotal);
Assert.AreEqual("$110.00", target.GrandTotal);
}
[TestMethod]
public void SelectCheckoutData_Opens_AppBar()
{
var shippingMethods = new List<ShippingMethod>() { new ShippingMethod() { Id = 1, Cost = 0 } };
var shoppingCartItems = new List<ShoppingCartItem>() { new ShoppingCartItem() { Quantity = 1, Currency = "USD", Product = new Product() } };
var order = new Order()
{
ShoppingCart = new ShoppingCart(shoppingCartItems) { Currency = "USD", FullPrice = 100 },
ShippingAddress = new Address(),
BillingAddress = new Address(),
PaymentMethod = new PaymentMethod() { CardNumber = "1234" },
ShippingMethod = shippingMethods.First()
};
var shippingMethodService = new MockShippingMethodService()
{
GetShippingMethodsAsyncDelegate = () => Task.FromResult<IEnumerable<ShippingMethod>>(shippingMethods)
};
var orderRepository = new MockOrderRepository() { CurrentOrder = order};
var shoppingCartRepository = new MockShoppingCartRepository();
shoppingCartRepository.GetShoppingCartAsyncDelegate = () => Task.FromResult(order.ShoppingCart);
var checkoutDataRepository = new MockCheckoutDataRepository();
checkoutDataRepository.GetShippingAddressAsyncDelegate = s => Task.FromResult(new Address());
checkoutDataRepository.GetBillingAddressAsyncDelegate = s => Task.FromResult(new Address());
checkoutDataRepository.GetPaymentMethodDelegate = s => Task.FromResult(new PaymentMethod { CardNumber = "1234" });
var target = new CheckoutSummaryPageViewModel(new MockNavigationService(), new MockOrderService(), orderRepository, shippingMethodService,
checkoutDataRepository, shoppingCartRepository,
new MockAccountService(), new MockResourceLoader(), null, null);
target.OnNavigatedTo(new NavigatedToEventArgs { Parameter = null, NavigationMode = NavigationMode.New }, null);
Assert.IsFalse(target.IsBottomAppBarOpened);
target.SelectedCheckoutData = target.CheckoutDataViewModels.First();
Assert.IsTrue(target.IsBottomAppBarOpened);
}
[TestMethod]
public void EditCheckoutData_NavigatesToProperPage()
{
string requestedPageName = string.Empty;
var navigationService = new MockNavigationService()
{
NavigateDelegate = (pageName, navParameter) =>
{
Assert.IsTrue(pageName == requestedPageName);
return true;
}
};
var target = new CheckoutSummaryPageViewModel(navigationService, null, null, null, null, null, null, null, null, null);
requestedPageName = "ShippingAddress";
target.SelectedCheckoutData = new CheckoutDataViewModel() { DataType = Constants.ShippingAddress };
target.EditCheckoutDataCommand.Execute();
requestedPageName = "BillingAddress";
target.SelectedCheckoutData = new CheckoutDataViewModel { DataType = Constants.BillingAddress };
target.EditCheckoutDataCommand.Execute();
requestedPageName = "PaymentMethod";
target.SelectedCheckoutData = new CheckoutDataViewModel { DataType = Constants.PaymentMethod };
target.EditCheckoutDataCommand.Execute();
}
[TestMethod]
public void AddCheckoutData_NavigatesToProperPage()
{
string requestedPageName = string.Empty;
var navigationService= new MockNavigationService()
{
NavigateDelegate = (pageName, navParam) =>
{
Assert.IsTrue(pageName == requestedPageName);
return true;
}
};
var target = new CheckoutSummaryPageViewModel(navigationService, null, null, null, null, null, null, null, null, null);
requestedPageName = "ShippingAddress";
target.SelectedCheckoutData = new CheckoutDataViewModel() { DataType = Constants.ShippingAddress };
target.AddCheckoutDataCommand.Execute();
requestedPageName = "BillingAddress";
target.SelectedCheckoutData = new CheckoutDataViewModel() { DataType = Constants.BillingAddress };
target.AddCheckoutDataCommand.Execute();
requestedPageName = "PaymentMethod";
target.SelectedCheckoutData = new CheckoutDataViewModel() { DataType = Constants.PaymentMethod };
target.AddCheckoutDataCommand.Execute();
}
[TestMethod]
public void NavigatingToWhenNoShippingMethodSelected_RecalculatesOrder()
{
var shippingMethods = new List<ShippingMethod> { new ShippingMethod { Id = 1, Cost = 0 } };
var shoppingCartItems = new List<ShoppingCartItem> { new ShoppingCartItem { Quantity = 1, Currency = "USD", Product = new Product() } };
var order = new Order
{
ShoppingCart = new ShoppingCart(shoppingCartItems) { Currency = "USD", TotalPrice = 100 },
ShippingAddress = new Address { Id = "1"},
BillingAddress = new Address { Id = "1" },
PaymentMethod = new PaymentMethod() { CardNumber = "1234" },
ShippingMethod = null
};
var shippingMethodService = new MockShippingMethodService
{
GetShippingMethodsAsyncDelegate = () => Task.FromResult<IEnumerable<ShippingMethod>>(shippingMethods)
};
var orderRepository = new MockOrderRepository { CurrentOrder = order };
var shoppingCartRepository = new MockShoppingCartRepository
{
GetShoppingCartAsyncDelegate = () => Task.FromResult(order.ShoppingCart)
};
var checkoutDataRepository = new MockCheckoutDataRepository();
checkoutDataRepository.GetShippingAddressAsyncDelegate = s => Task.FromResult(new Address());
checkoutDataRepository.GetBillingAddressAsyncDelegate = s => Task.FromResult(new Address());
checkoutDataRepository.GetPaymentMethodDelegate = s => Task.FromResult(new PaymentMethod { CardNumber = "1234" });
var target = new CheckoutSummaryPageViewModel(new MockNavigationService(), new MockOrderService(), orderRepository, shippingMethodService,
checkoutDataRepository, shoppingCartRepository,
new MockAccountService(), new MockResourceLoader(), null, null);
target.OnNavigatedTo(new NavigatedToEventArgs { Parameter = null, NavigationMode = NavigationMode.New }, null);
Assert.AreEqual("$0.00", target.ShippingCost);
Assert.AreEqual("$100.00", target.OrderSubtotal);
Assert.AreEqual("$100.00", target.GrandTotal);
}
}
}
| |
// 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 RoundToPositiveInfinityScalarDouble()
{
var test = new SimpleBinaryOpTest__RoundToPositiveInfinityScalarDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__RoundToPositiveInfinityScalarDouble
{
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(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
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<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, 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 Vector128<Double> _fld1;
public Vector128<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__RoundToPositiveInfinityScalarDouble testClass)
{
var result = Sse41.RoundToPositiveInfinityScalar(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__RoundToPositiveInfinityScalarDouble testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse41.RoundToPositiveInfinityScalar(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__RoundToPositiveInfinityScalarDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public SimpleBinaryOpTest__RoundToPositiveInfinityScalarDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.RoundToPositiveInfinityScalar(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_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 = Sse41.RoundToPositiveInfinityScalar(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_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 = Sse41.RoundToPositiveInfinityScalar(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_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(Sse41).GetMethod(nameof(Sse41.RoundToPositiveInfinityScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToPositiveInfinityScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToPositiveInfinityScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.RoundToPositiveInfinityScalar(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Double>* pClsVar1 = &_clsVar1)
fixed (Vector128<Double>* pClsVar2 = &_clsVar2)
{
var result = Sse41.RoundToPositiveInfinityScalar(
Sse2.LoadVector128((Double*)(pClsVar1)),
Sse2.LoadVector128((Double*)(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<Vector128<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse41.RoundToPositiveInfinityScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse41.RoundToPositiveInfinityScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse41.RoundToPositiveInfinityScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__RoundToPositiveInfinityScalarDouble();
var result = Sse41.RoundToPositiveInfinityScalar(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__RoundToPositiveInfinityScalarDouble();
fixed (Vector128<Double>* pFld1 = &test._fld1)
fixed (Vector128<Double>* pFld2 = &test._fld2)
{
var result = Sse41.RoundToPositiveInfinityScalar(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.RoundToPositiveInfinityScalar(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse41.RoundToPositiveInfinityScalar(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(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 = Sse41.RoundToPositiveInfinityScalar(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 = Sse41.RoundToPositiveInfinityScalar(
Sse2.LoadVector128((Double*)(&test._fld1)),
Sse2.LoadVector128((Double*)(&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(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits(Math.Ceiling(right[0])))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits(left[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.RoundToPositiveInfinityScalar)}<Double>(Vector128<Double>, Vector128<Double>): {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 System;
namespace Alchemy4Tridion.Plugins.Clients.CoreService
{
public class CoreServiceFaultConstants
{
public class Exceptions
{
public const string AccessTokenExpiredExceptionName = "ExpiredAccessTokenException";
public const string InvalidAccessTokenExceptionName = "InvalidAccessTokenException";
public const string ValidationExceptionName = "ValidationException";
}
public class TcmErrorCodes
{
public const string InvalidURL = "InvalidURL";
public const string ItemIsCheckedOutByOtherUser = "ItemIsCheckedOutByOtherUser";
public const string PermissionDenied = "PermissionDenied";
public const string UniquenessConflict = "UniquenessConflict";
public const string FeatureNotSupported = "FeatureNotSupported";
public const string InvalidPropertyChange = "InvalidPropertyChange";
public const string AccessDenied = "AccessDenied";
public const string AssertFailed = "AssertFailed";
public const string CannotPasteHere = "CannotPasteHere";
public const string CircularLinkDetected = "CircularLinkDetected";
public const string Conversion = "Conversion";
public const string DirectoryCannotBeEmpty = "DirectoryCannotBeEmpty";
public const string DuplicateFieldNames = "DuplicateFieldNames";
public const string ElementNotFound = "ElementNotFound";
public const string EventFailed = "EventFailed";
public const string FieldDoesNotExist = "FieldDoesNotExist";
public const string FileNotFound = "FileNotFound";
public const string InvalidAction = "InvalidAction";
public const string InvalidAssignment = "InvalidAssignment";
public const string InvalidBlueprint = "InvalidBlueprint";
public const string InvalidCharacters = "InvalidCharacters";
public const string InvalidCodePage = "InvalidCodePage";
public const string InvalidComponentPresentation = "InvalidComponentPresentation";
public const string InvalidDateFormat = "InvalidDateFormat";
public const string InvalidDestination = "InvalidDestination";
public const string InvalidFtpRequest = "InvalidFtpRequest";
public const string InvalidGroupMembership = "InvalidGroupMembership";
public const string InvalidInclude = "InvalidInclude";
public const string InvalidIndex = "InvalidIndex";
public const string InvalidInheritanceRoot = "InvalidInheritanceRoot";
public const string InvalidNamespace = "InvalidNamespace";
public const string InvalidNumberFormat = "InvalidNumberFormat";
public const string InvalidParameter = "InvalidParameter";
public const string InvalidPath = "InvalidPath";
public const string InvalidPermissions = "InvalidPermissions";
public const string InvalidProtocol = "InvalidProtocol";
public const string InvalidSchema = "InvalidSchema";
public const string InvalidSchemaPurpose = "InvalidSchemaPurpose";
public const string InvalidSearchFolderConfiguration = "InvalidSearchFolderConfiguration";
public const string InvalidTargetGroupLink = "InvalidTargetGroupLink";
public const string InvalidTrusteeScope = "InvalidTrusteeScope";
public const string InvalidURI = "InvalidURI";
public const string InvalidVersion = "InvalidVersion";
public const string InvalidXML = "InvalidXML";
public const string InvalidXSD = "InvalidXSD";
public const string ItemAlreadyExists = "ItemAlreadyExists";
public const string ItemDoesNotExist = "ItemDoesNotExist";
public const string ItemIsBlueprintParent = "ItemIsBlueprintParent";
public const string ItemIsCheckedOut = "ItemIsCheckedOut";
public const string ItemIsInUse = "ItemIsInUse";
public const string ItemIsInWorkflow = "ItemIsInWorkflow";
public const string ItemIsLocalized = "ItemIsLocalized";
public const string ItemIsNotCheckedOut = "ItemIsNotCheckedOut";
public const string ItemIsNotLocalized = "ItemIsNotLocalized";
public const string ItemIsPublished = "ItemIsPublished";
public const string ItemIsShared = "ItemIsShared";
public const string MissingAttribute = "MissingAttribute";
public const string MissingElementOrType = "MissingElementOrType";
public const string MixedLanguages = "MixedLanguages";
public const string NoMultimedia = "NoMultimedia";
public const string NoPrivileges = "NoPrivileges";
public const string NoScriptEndMarker = "NoScriptEndMarker";
public const string NumericalOperandRequired = "NumericalOperandRequired";
public const string RecursiveCallDetected = "RecursiveCallDetected";
public const string ReservedFileExtension = "ReservedFileExtension";
public const string RootOrgItemAlreadyExists = "RootOrgItemAlreadyExists";
public const string SchemaDoesNotExist = "SchemaDoesNotExist";
public const string SQLException = "SQLException";
public const string TrusteeIsPredefined = "TrusteeIsPredefined";
public const string TypeMismatch = "TypeMismatch";
public const string UnableToDownload = "UnableToDownload";
public const string UnableToOpenInternetConnection = "UnableToOpenInternetConnection";
public const string UnableToTransform = "UnableToTransform";
public const string UnexpectedElement = "UnexpectedElement";
public const string UnexpectedFieldType = "UnexpectedFieldType";
public const string UnexpectedFileExtension = "UnexpectedFileExtension";
public const string UnexpectedItemType = "UnexpectedItemType";
public const string UnexpectedListType = "UnexpectedListType";
public const string UnexpectedMultimediaType = "UnexpectedMultimediaType";
public const string UnexpectedRootElement = "UnexpectedRootElement";
public const string UnsupportedTargetLanguage = "UnsupportedTargetLanguage";
public const string VersionDoesNotExist = "VersionDoesNotExist";
public const string WrongApprovalStatus = "WrongApprovalStatus";
public const string IncorrectConfiguration = "IncorrectConfiguration";
public const string CachingNotActive = "CachingNotActive";
public const string InvalidActivityState = "InvalidActivityState";
public const string InvalidActivityType = "InvalidActivityType";
public const string InvalidNextActivity = "InvalidNextActivity";
public const string ADOConnectionError = "ADOConnectionError";
public const string FeatureNotImplemented = "FeatureNotImplemented";
public const string GeneralError = "GeneralError";
public const string UnsupportedFileSize = "UnsupportedFileSize";
public const string PublishInProgress = "PublishInProgress";
public const string LicenseViolation = "LicenseViolation";
public const string InvalidLicense = "InvalidLicense";
public const string LicensedProductNotFound = "LicensedProductNotFound";
public const string UnableToRenderPage = "UnableToRenderPage";
public const string UnableToRenderComponent = "UnableToRenderComponent";
public const string ItemIsInUseNoWhereUsed = "ItemIsInUseNoWhereUsed";
public const string UnableToExecuteEvent = "UnableToExecuteEvent";
public const string UnableToDeleteRootSgOfParent = "UnableToDeleteRootSgOfParent";
public const string SearchError = "SearchError";
public const string UnknownCacheLevel = "UnknownCacheLevel";
public const string UnknownCacheLifetime = "UnknownCacheLifetime";
public const string TooManyResults = "TooManyResults";
public const string GeneralTypeRegistrationError = "GeneralTypeRegistrationError";
public const string UnknownPublicationTypeId = "UnknownPublicationTypeId";
public const string UnknownPublicationTypeName = "UnknownPublicationTypeName";
public const string MissingTypeRegistryConfigurationError = "MissingTypeRegistryConfigurationError";
public const string InvalidSchemaFieldValue = "InvalidSchemaFieldValue";
public const string InvalidPropertyValue = "InvalidPropertyValue";
public const string InvalidContextRepository = "InvalidContextRepository";
public const string ItemIsLockedByOtherUser = "ItemIsLockedByOtherUser";
public const string ItemIsNotLocked = "ItemIsNotLocked";
public const string ItemIsLocked = "ItemIsLocked";
public const string NotImplemented = "NotImplemented";
public const string DeleteFailed = "DeleteFailed";
public const string PublicationParentsChangeDenied = "PublicationParentsChangeDenied";
public const string ItemCanBeCheckedInByWorkflow = "ItemCanBeCheckedInByWorkflow";
public const string WorkflowNotSupported = "WorkflowNotSupported";
public const string InvalidState = "InvalidState";
public const string InvalidWorkflowType = "InvalidWorkflowType";
public const string InvalidOwner = "InvalidOwner";
public const string ItemIsReserved = "ItemIsReserved";
public const string ClassificationConstraintViolation = "ClassificationConstraintViolation";
public const string LocationConstraintViolation = "LocationConstraintViolation";
public const string OccurenceConstraintViolation = "OccurenceConstraintViolation";
public const string TypeConstraintViolation = "TypeConstraintViolation";
public const string UnexpectedRegion = "UnexpectedRegion";
public const string MissingRegion = "MissingRegion";
public const string InvalidRegion = "InvalidRegion";
public const string FileInUse = "FileInUse";
public const string InvalidMapping = "InvalidMapping";
public const string ItemModificationDetected = "ItemModificationDetected";
public const string MissingDependency = "MissingDependency";
public const string ProcessAborted = "ProcessAborted";
public const string ImportExportException = "ImportExportException";
public const string Timeout = "Timeout";
public const string ProblemDiscovered = "ProblemDiscovered";
public const string TopologyManagerException = "TopologyManagerException";
public const string CdEnvironmentDoesNotHaveDeployerCapability = "CdEnvironmentDoesNotHaveDeployerCapability";
public const string CdEnvironmentDoesNotHavePreviewWebServiceCapability = "CdEnvironmentDoesNotHavePreviewWebServiceCapability";
public const string AuthenticationFailureInCdDiscoveryService = "AuthenticationFailureInCdDiscoveryService";
public const string CommunicationErrorWithCdDiscoveryService = "CommunicationErrorWithCdDiscoveryService";
public const string AuthenticationFailureInTopologyManager = "AuthenticationFailureInTopologyManager";
public const string CommunicationErrorWithTopologyManager = "CommunicationErrorWithTopologyManager";
public const string NoMappingFoundInTopologyManager = "NoMappingFoundInTopologyManager";
public const string ItemHasPublishedItems = "ItemHasPublishedItems";
public const string AccessTokenExpired = "AccessTokenExpired";
public const string AccessTokenEmptySignature = "AccessTokenEmptySignature";
public const string AccessTokenInvalidSignature = "AccessTokenInvalidSignature";
public const string CdEnvironmentIsOffline = "CdEnvironmentIsOffline";
public const string ItemIsNotLocalInPublication = "ItemIsNotLocalInPublication";
public const string OrgItemIsNotLocalInPublication = "OrgItemIsNotLocalInPublication";
public const string PromoteDestinationIsInvalid = "PromoteDestinationIsInvalid";
public const string PromoteValidationFailed = "PromoteValidationFailed";
public const string DemoteDestinationIsInvalid = "DemoteDestinationIsInvalid";
public const string DemoteValidationFailed = "DemoteValidationFailed";
public const string ValidationWarning = "ValidationWarning";
public const string ValidationError = "ValidationError";
public const string MismatchExpectedValueInDb = "MismatchExpectedValueInDb";
public const string LocalizeValidationFailed = "LocalizeValidationFailed";
public const string UnLocalizeValidationFailed = "UnLocalizeValidationFailed";
public const string MoveValidationFailed = "MoveValidationFailed";
public const string UnknownVFType = "UnknownVFType";
public const string ClassNotRegistered = "ClassNotRegistered";
public const string InvalidFilterCondition = "InvalidFilterCondition";
public const string InvalidConditionType = "InvalidConditionType";
public const string InvalidConditionOperator = "InvalidConditionOperator";
public const string GeneralTemplateTypeError = "GeneralTemplateTypeError";
public const string UnknownTemplateTypeName = "UnknownTemplateTypeName";
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Reflection.Metadata.Ecma335;
namespace System.Reflection.Metadata
{
public struct MethodDefinition
{
private readonly MetadataReader reader;
// Workaround: JIT doesn't generate good code for nested structures, so use RowId.
private readonly uint treatmentAndRowId;
internal MethodDefinition(MetadataReader reader, uint treatmentAndRowId)
{
Debug.Assert(reader != null);
Debug.Assert(treatmentAndRowId != 0);
this.reader = reader;
this.treatmentAndRowId = treatmentAndRowId;
}
private uint RowId
{
get { return treatmentAndRowId & TokenTypeIds.RIDMask; }
}
private MethodDefTreatment Treatment
{
get { return (MethodDefTreatment)(treatmentAndRowId >> TokenTypeIds.RowIdBitCount); }
}
private MethodDefinitionHandle Handle
{
get { return MethodDefinitionHandle.FromRowId(RowId); }
}
public StringHandle Name
{
get
{
if (Treatment == 0)
{
return reader.MethodDefTable.GetName(Handle);
}
return GetProjectedName();
}
}
public BlobHandle Signature
{
get
{
if (Treatment == 0)
{
return reader.MethodDefTable.GetSignature(Handle);
}
return GetProjectedSignature();
}
}
public int RelativeVirtualAddress
{
get
{
if (Treatment == 0)
{
return reader.MethodDefTable.GetRva(Handle);
}
return GetProjectedRelativeVirtualAddress();
}
}
public MethodAttributes Attributes
{
get
{
if (Treatment == 0)
{
return reader.MethodDefTable.GetFlags(Handle);
}
return GetProjectedFlags();
}
}
public MethodImplAttributes ImplAttributes
{
get
{
if (Treatment == 0)
{
return reader.MethodDefTable.GetImplFlags(Handle);
}
return GetProjectedImplFlags();
}
}
public TypeDefinitionHandle GetDeclaringType()
{
return reader.GetDeclaringType(Handle);
}
public ParameterHandleCollection GetParameters()
{
return new ParameterHandleCollection(reader, Handle);
}
public GenericParameterHandleCollection GetGenericParameters()
{
return reader.GenericParamTable.FindGenericParametersForMethod(Handle);
}
public MethodImport GetImport()
{
uint implMapRid = reader.ImplMapTable.FindImplForMethod(Handle);
if (implMapRid == 0)
{
return default(MethodImport);
}
return reader.ImplMapTable[implMapRid];
}
public CustomAttributeHandleCollection GetCustomAttributes()
{
return new CustomAttributeHandleCollection(reader, Handle);
}
public DeclarativeSecurityAttributeHandleCollection GetDeclarativeSecurityAttributes()
{
return new DeclarativeSecurityAttributeHandleCollection(reader, Handle);
}
#region Projections
private StringHandle GetProjectedName()
{
if ((Treatment & MethodDefTreatment.KindMask) == MethodDefTreatment.DisposeMethod)
{
return StringHandle.FromVirtualIndex(StringHandle.VirtualIndex.Dispose);
}
return reader.MethodDefTable.GetName(Handle);
}
private MethodAttributes GetProjectedFlags()
{
MethodAttributes flags = reader.MethodDefTable.GetFlags(Handle);
MethodDefTreatment treatment = Treatment;
if ((treatment & MethodDefTreatment.KindMask) == MethodDefTreatment.HiddenInterfaceImplementation)
{
flags = (flags & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Private;
}
if ((treatment & MethodDefTreatment.MarkAbstractFlag) != 0)
{
flags |= MethodAttributes.Abstract;
}
if ((treatment & MethodDefTreatment.MarkPublicFlag) != 0)
{
flags = (flags & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Public;
}
return flags | MethodAttributes.HideBySig;
}
private MethodImplAttributes GetProjectedImplFlags()
{
MethodImplAttributes flags = reader.MethodDefTable.GetImplFlags(Handle);
switch (Treatment & MethodDefTreatment.KindMask)
{
case MethodDefTreatment.DelegateMethod:
flags |= MethodImplAttributes.Runtime;
break;
case MethodDefTreatment.DisposeMethod:
case MethodDefTreatment.AttributeMethod:
case MethodDefTreatment.InterfaceMethod:
case MethodDefTreatment.HiddenInterfaceImplementation:
case MethodDefTreatment.Other:
flags |= MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall;
break;
}
return flags;
}
private BlobHandle GetProjectedSignature()
{
return reader.MethodDefTable.GetSignature(Handle);
}
private int GetProjectedRelativeVirtualAddress()
{
return 0;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace l2pvp
{
public class ByteBuffer
{
//// Methods
// Fields
private byte[] _data;
private int _index;
private int _length;
private int _maxlength;
private const int MAX_LENGTH = 0x400;
public ByteBuffer()
{
this._maxlength = 0x400;
this._data = new byte[this._maxlength];
this._length = this._maxlength;
this._index = 0;
}
public ByteBuffer(int len)
{
if (len > this._maxlength)
{
this._maxlength = len;
}
this._data = new byte[this._maxlength];
this._length = len;
this._index = 0;
}
public ByteBuffer(byte[] buff)
{
this._length = buff.Length;
if (this._length > this._maxlength)
{
this._maxlength = this._length;
}
this._data = new byte[this._maxlength];
this._index = 0;
buff.CopyTo(this._data, 0);
}
public void ClearData()
{
for (int num1 = 0; num1 < this._maxlength; num1++)
{
this._data[num1] = 0;
}
}
public byte[] Get_ByteArray()
{
byte[] buffer1 = new byte[this._length];
for (int num1 = 0; num1 < this._length; num1++)
{
buffer1[num1] = this._data[num1];
}
return buffer1;
}
public byte GetByte(int ind)
{
if (this._length >= ind)
{
return this._data[ind];
}
return 0;
}
public int GetIndex()
{
return this._index;
}
public byte ReadByte()
{
if (this._length >= (this._index + 1))
{
byte num1 = this._data[this._index];
this._index++;
return num1;
}
return 0;
}
public char ReadChar()
{
if (this._length >= (this._index + 1))
{
char ch1 = BitConverter.ToChar(this._data, this._index);
this._index++;
return ch1;
}
return '\0';
}
public double ReadDouble()
{
if (this._length >= (this._index + 8))
{
double num1 = BitConverter.ToDouble(this._data, this._index);
this._index += 8;
return num1;
}
return 0;
}
public short ReadInt16()
{
if (this._length >= (this._index + 2))
{
short num1 = BitConverter.ToInt16(this._data, this._index);
this._index += 2;
return num1;
}
return 0;
}
public int ReadInt32()
{
if (this._length >= (this._index + 4))
{
int num1 = BitConverter.ToInt32(this._data, this._index);
this._index += 4;
return num1;
}
return 0;
}
public long ReadInt64()
{
if (this._length >= (this._index + 8))
{
long num1 = BitConverter.ToInt64(this._data, this._index);
this._index += 8;
return num1;
}
return (long)0;
}
public string ReadString()
{
try
{
string text1 = "";
for (char ch1 = (char)this._data[this._index]; ch1 != '\0'; ch1 = (char)this._data[this._index])
{
text1 = text1 + ch1;
this._index += 2;
}
this._index += 2;
return text1;
}
catch
{
return "";
}
}
public ushort ReadUInt16()
{
if (this._length >= (this._index + 2))
{
ushort num1 = BitConverter.ToUInt16(this._data, this._index);
this._index += 2;
return num1;
}
return 0;
}
public uint ReadUInt32()
{
if (this._length >= (this._index + 4))
{
uint num1 = BitConverter.ToUInt32(this._data, this._index);
this._index += 4;
return num1;
}
return 0;
}
public ulong ReadUInt64()
{
if (this._length >= (this._index + 8))
{
ulong num1 = BitConverter.ToUInt64(this._data, this._index);
this._index += 8;
return num1;
}
return 0;
}
public void ResetIndex()
{
this._index = 0;
}
public void Resize(int len)
{
if (len <= this._maxlength)
{
this._length = len;
}
if (len > this._maxlength)
{
byte[] buffer1 = new byte[this._length];
this._data.CopyTo(buffer1, this._length);
this._maxlength = len;
this._data = new byte[this._maxlength];
buffer1.CopyTo(this._data, this._length);
this._length = this._maxlength;
}
}
public void SetByte(byte b)
{
if (this._length >= (this._index + 1))
{
this._index++;
this._data[this._index] = b;
}
}
public void SetByte(byte b, int ind)
{
if (this._length >= ind)
{
this._data[ind] = b;
}
}
public void SetIndex(int ind)
{
this._index = ind;
}
public void WriteByte(byte val)
{
if (this._length >= (this._index + 1))
{
this._data[this._index] = val;
this._index++;
}
}
public void WriteDouble(double val)
{
if (this._length >= (this._index + 8))
{
byte[] buffer1 = new byte[8];
buffer1 = BitConverter.GetBytes(val);
this._data[this._index] = buffer1[0];
this._data[this._index + 1] = buffer1[1];
this._data[this._index + 2] = buffer1[2];
this._data[this._index + 3] = buffer1[3];
this._data[this._index + 4] = buffer1[4];
this._data[this._index + 5] = buffer1[5];
this._data[this._index + 6] = buffer1[6];
this._data[this._index + 7] = buffer1[7];
this._index += 8;
}
}
public void WriteInt16(short val)
{
if (this._length >= (this._index + 2))
{
byte[] buffer1 = new byte[2];
buffer1 = BitConverter.GetBytes(val);
this._data[this._index] = buffer1[0];
this._data[this._index + 1] = buffer1[1];
this._index += 2;
}
}
public void WriteInt32(int val)
{
if (this._length >= (this._index + 4))
{
byte[] buffer1 = new byte[4];
buffer1 = BitConverter.GetBytes(val);
this._data[this._index] = buffer1[0];
this._data[this._index + 1] = buffer1[1];
this._data[this._index + 2] = buffer1[2];
this._data[this._index + 3] = buffer1[3];
this._index += 4;
}
}
public void WriteInt64(long val)
{
if (this._length >= (this._index + 8))
{
byte[] buffer1 = new byte[8];
buffer1 = BitConverter.GetBytes(val);
this._data[this._index] = buffer1[0];
this._data[this._index + 1] = buffer1[1];
this._data[this._index + 2] = buffer1[2];
this._data[this._index + 3] = buffer1[3];
this._data[this._index + 4] = buffer1[4];
this._data[this._index + 5] = buffer1[5];
this._data[this._index + 6] = buffer1[6];
this._data[this._index + 7] = buffer1[7];
this._index += 8;
}
}
public void WriteString(string text)
{
if (this._length >= ((this._index + (text.Length * 2)) + 2))
{
for (int num1 = 0; num1 < text.Length; num1++)
{
this.WriteByte(Convert.ToByte(text[num1]));
this.WriteByte(0);
}
this.WriteByte(0);
this.WriteByte(0);
}
}
public void WriteUInt16(ushort val)
{
if (this._length >= (this._index + 2))
{
byte[] buffer1 = new byte[2];
buffer1 = BitConverter.GetBytes(val);
this._data[this._index] = buffer1[0];
this._data[this._index + 1] = buffer1[1];
this._index += 2;
}
}
public void WriteUInt32(uint val)
{
if (this._length >= (this._index + 4))
{
byte[] buffer1 = new byte[4];
buffer1 = BitConverter.GetBytes(val);
this._data[this._index] = buffer1[0];
this._data[this._index + 1] = buffer1[1];
this._data[this._index + 2] = buffer1[2];
this._data[this._index + 3] = buffer1[3];
this._index += 4;
}
}
public void WriteUInt64(ulong val)
{
if (this._length >= (this._index + 8))
{
byte[] buffer1 = new byte[8];
buffer1 = BitConverter.GetBytes(val);
this._data[this._index] = buffer1[0];
this._data[this._index + 1] = buffer1[1];
this._data[this._index + 2] = buffer1[2];
this._data[this._index + 3] = buffer1[3];
this._data[this._index + 4] = buffer1[4];
this._data[this._index + 5] = buffer1[5];
this._data[this._index + 6] = buffer1[6];
this._data[this._index + 7] = buffer1[7];
this._index += 8;
}
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gallio.Common.Reflection;
using Gallio.Runtime.Extensibility;
using MbUnit.Framework;
using Rhino.Mocks;
namespace Gallio.Tests.Runtime.Extensibility
{
[TestsOn(typeof(ComponentHandle))]
[TestsOn(typeof(ComponentHandle<,>))]
public class ComponentHandleTest
{
[Test]
public void CreateInstance_WhenDescriptorIsNull_Throws()
{
Assert.Throws<ArgumentNullException>(() => ComponentHandle.CreateInstance(null));
}
[Test]
public void CreateInstanceGeneric_WhenDescriptorIsNull_Throws()
{
Assert.Throws<ArgumentNullException>(() => ComponentHandle.CreateInstance<DummyService, DummyTraits>(null));
}
[Test]
public void CreateInstance_WhenArgumentsValid_ReturnsTypedComponentHandle()
{
var componentDescriptor = CreateStubComponentDescriptor<DummyService, DummyTraits>();
var componentHandle = ComponentHandle.CreateInstance(componentDescriptor);
Assert.Multiple(() =>
{
Assert.IsInstanceOfType(typeof(ComponentHandle<DummyService, DummyTraits>), componentHandle);
Assert.AreSame(componentDescriptor, componentHandle.Descriptor);
Assert.AreEqual(typeof(DummyService), componentHandle.ServiceType);
Assert.AreEqual(typeof(DummyTraits), componentHandle.TraitsType);
});
}
[Test]
public void CreateInstanceGeneric_WhenServiceTypeDoesNotMatchDescriptor_Throws()
{
var componentDescriptor = CreateStubComponentDescriptor<DummyService, DummyTraits>();
var ex = Assert.Throws<ArgumentException>(() => ComponentHandle.CreateInstance<object, DummyTraits>(componentDescriptor));
Assert.Contains(ex.Message, "The component descriptor is not compatible with the requested component handle type because it has a different service type or traits type.");
}
[Test]
public void CreateInstanceGeneric_WhenTraitsTypeDoesNotMatchDescriptor_Throws()
{
var componentDescriptor = CreateStubComponentDescriptor<DummyService, DummyTraits>();
var ex = Assert.Throws<ArgumentException>(() => ComponentHandle.CreateInstance<ServiceDescriptor, Traits>(componentDescriptor));
Assert.Contains(ex.Message, "The component descriptor is not compatible with the requested component handle type because it has a different service type or traits type.");
}
[Test]
public void CreateInstanceGeneric_WhenArgumentsValid_ReturnsTypedComponentHandle()
{
var componentDescriptor = CreateStubComponentDescriptor<DummyService, DummyTraits>();
var componentHandle = ComponentHandle.CreateInstance<DummyService, DummyTraits>(componentDescriptor);
Assert.Multiple(() =>
{
Assert.AreSame(componentDescriptor, componentHandle.Descriptor);
Assert.AreEqual(typeof(DummyService), componentHandle.ServiceType);
Assert.AreEqual(typeof(DummyTraits), componentHandle.TraitsType);
});
}
[Test]
public void CreateStub_WhenComponentIdIsNull_Throws()
{
var component = MockRepository.GenerateStub<DummyService>();
var traits = new DummyTraits();
Assert.Throws<ArgumentNullException>(() => ComponentHandle.CreateStub<DummyService, DummyTraits>(null, component, traits));
}
[Test]
public void CreateStub_WhenComponentIsNull_Throws()
{
var componentId = "componentId";
var traits = new DummyTraits();
Assert.Throws<ArgumentNullException>(() => ComponentHandle.CreateStub<DummyService, DummyTraits>(componentId, null, traits));
}
[Test]
public void CreateStub_WhenTraitsIsNull_Throws()
{
var component = MockRepository.GenerateStub<DummyService>();
var traits = new DummyTraits();
Assert.Throws<ArgumentNullException>(() => ComponentHandle.CreateStub<DummyService, DummyTraits>(null, component, traits));
}
[Test]
public void CreateStub_WhenArgumentsValid_ReturnsHandleWithStubbedDescriptor()
{
var componentId = "componentId";
var component = MockRepository.GenerateStub<DummyService>();
var traits = new DummyTraits();
var handle = ComponentHandle.CreateStub<DummyService, DummyTraits>(componentId, component, traits);
Assert.Multiple(() =>
{
Assert.AreEqual(componentId, handle.Id);
Assert.AreEqual(typeof(DummyService), handle.ServiceType);
Assert.AreEqual(typeof(DummyTraits), handle.TraitsType);
Assert.AreSame(component, handle.GetComponent());
Assert.AreSame(traits, handle.GetTraits());
object x = null;
Assert.Throws<NotSupportedException>(() => x = handle.Descriptor.Plugin);
Assert.Throws<NotSupportedException>(() => x = handle.Descriptor.Service);
Assert.AreEqual(componentId, handle.Descriptor.ComponentId);
Assert.AreEqual(new TypeName(component.GetType()), handle.Descriptor.ComponentTypeName);
Assert.Throws<NotSupportedException>(() => x = handle.Descriptor.ComponentHandlerFactory);
Assert.Throws<NotSupportedException>(() => x = handle.Descriptor.ComponentProperties);
Assert.Throws<NotSupportedException>(() => x = handle.Descriptor.TraitsProperties);
Assert.IsFalse(handle.Descriptor.IsDisabled);
Assert.Throws<InvalidOperationException>(() => x = handle.Descriptor.DisabledReason);
Assert.AreEqual(component.GetType(), handle.Descriptor.ResolveComponentType());
Assert.Throws<NotSupportedException>(() => handle.Descriptor.ResolveComponentHandler());
Assert.AreSame(component, handle.Descriptor.ResolveComponent());
Assert.Throws<NotSupportedException>(() => handle.Descriptor.ResolveTraitsHandler());
Assert.AreSame(traits, handle.Descriptor.ResolveTraits());
});
}
[Test]
public void IsComponentHandleType_WhenTypeIsNull_Throws()
{
Assert.Throws<ArgumentNullException>(() => ComponentHandle.IsComponentHandleType(null));
}
[Test]
public void IsComponentHandleType_WhenTypeIsNonGenericComponentHandle_ReturnsTrue()
{
Assert.IsTrue(ComponentHandle.IsComponentHandleType(typeof(ComponentHandle)));
}
[Test]
public void IsComponentHandleType_WhenTypeIsGenericComponentHandle_ReturnsTrue()
{
Assert.IsTrue(ComponentHandle.IsComponentHandleType(typeof(ComponentHandle<DummyService, DummyTraits>)));
}
[Test]
public void IsComponentHandleType_WhenTypeIsNotAComponentHandleComponentHandle_ReturnsFalse()
{
Assert.IsFalse(ComponentHandle.IsComponentHandleType(typeof(object)));
}
[Test]
public void GetComponentUntyped_WhenComponentCanBeResolved_ReturnsItAndMemoizesIt()
{
var component = MockRepository.GenerateStub<DummyService>();
var componentDescriptor = CreateStubComponentDescriptor<DummyService, DummyTraits>();
var componentHandle = ComponentHandle.CreateInstance(componentDescriptor);
componentDescriptor.Expect(x => x.ResolveComponent()).Return(component);
// first time
object result = componentHandle.GetComponent();
Assert.AreSame(component, result);
// second time should be same but method only called once
result = componentHandle.GetComponent();
Assert.AreSame(component, result);
componentDescriptor.VerifyAllExpectations();
}
[Test]
public void GetTraitsUntyped_WhenComponentCanBeResolved_ReturnsItAndMemoizesIt()
{
var traits = new DummyTraits();
var componentDescriptor = CreateStubComponentDescriptor<DummyService, DummyTraits>();
var componentHandle = ComponentHandle.CreateInstance(componentDescriptor);
componentDescriptor.Expect(x => x.ResolveTraits()).Return(traits);
// first time
Traits result = componentHandle.GetTraits();
Assert.AreSame(traits, result);
// second time should be same but method only called once
result = componentHandle.GetTraits();
Assert.AreSame(traits, result);
componentDescriptor.VerifyAllExpectations();
}
[Test]
public void GetComponentTyped_WhenComponentCanBeResolved_ReturnsAndMemoizesIt()
{
var component = MockRepository.GenerateStub<DummyService>();
var componentDescriptor = CreateStubComponentDescriptor<DummyService, DummyTraits>();
var componentHandle = ComponentHandle.CreateInstance<DummyService, DummyTraits>(componentDescriptor);
componentDescriptor.Expect(x => x.ResolveComponent()).Return(component);
// first time
DummyService result = componentHandle.GetComponent();
Assert.AreSame(component, result);
// second time should be same but method only called once
result = componentHandle.GetComponent();
Assert.AreSame(component, result);
componentDescriptor.VerifyAllExpectations();
}
[Test]
public void GetTraitsTyped_WhenComponentCanBeResolved_ReturnsAndMemoizesIt()
{
var traits = new DummyTraits();
var componentDescriptor = CreateStubComponentDescriptor<DummyService, DummyTraits>();
var componentHandle = ComponentHandle.CreateInstance<DummyService, DummyTraits>(componentDescriptor);
componentDescriptor.Expect(x => x.ResolveTraits()).Return(traits);
// first time
DummyTraits result = componentHandle.GetTraits();
Assert.AreSame(traits, result);
// second time should be same but method only called once
result = componentHandle.GetTraits();
Assert.AreSame(traits, result);
componentDescriptor.VerifyAllExpectations();
}
[Test]
public void Id_ReturnsComponentId()
{
var componentDescriptor = CreateStubComponentDescriptor<DummyService, DummyTraits>();
componentDescriptor.Stub(x => x.ComponentId).Return("componentId");
var componentHandle = ComponentHandle.CreateInstance<DummyService, DummyTraits>(componentDescriptor);
Assert.AreEqual("componentId", componentHandle.Id);
}
[Test]
public void ToString_ReturnsComponentId()
{
var componentDescriptor = CreateStubComponentDescriptor<DummyService, DummyTraits>();
componentDescriptor.Stub(x => x.ComponentId).Return("componentId");
var componentHandle = ComponentHandle.CreateInstance<DummyService, DummyTraits>(componentDescriptor);
Assert.AreEqual("componentId", componentHandle.ToString());
}
private IComponentDescriptor CreateStubComponentDescriptor<TService, TTraits>()
where TTraits : Traits
{
var serviceDescriptor = MockRepository.GenerateMock<IServiceDescriptor>();
serviceDescriptor.Stub(x => x.ResolveServiceType()).Return(typeof(TService));
serviceDescriptor.Stub(x => x.ResolveTraitsType()).Return(typeof(TTraits));
var componentDescriptor = MockRepository.GenerateMock<IComponentDescriptor>();
componentDescriptor.Stub(x => x.Service).Return(serviceDescriptor);
return componentDescriptor;
}
[Traits(typeof(DummyTraits))]
public interface DummyService
{
}
public class DummyTraits : Traits
{
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.IpMessaging.V2.Service.User
{
/// <summary>
/// ReadUserChannelOptions
/// </summary>
public class ReadUserChannelOptions : ReadOptions<UserChannelResource>
{
/// <summary>
/// The service_sid
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The user_sid
/// </summary>
public string PathUserSid { get; }
/// <summary>
/// Construct a new ReadUserChannelOptions
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathUserSid"> The user_sid </param>
public ReadUserChannelOptions(string pathServiceSid, string pathUserSid)
{
PathServiceSid = pathServiceSid;
PathUserSid = pathUserSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
/// <summary>
/// FetchUserChannelOptions
/// </summary>
public class FetchUserChannelOptions : IOptions<UserChannelResource>
{
/// <summary>
/// The service_sid
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The user_sid
/// </summary>
public string PathUserSid { get; }
/// <summary>
/// The channel_sid
/// </summary>
public string PathChannelSid { get; }
/// <summary>
/// Construct a new FetchUserChannelOptions
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathUserSid"> The user_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
public FetchUserChannelOptions(string pathServiceSid, string pathUserSid, string pathChannelSid)
{
PathServiceSid = pathServiceSid;
PathUserSid = pathUserSid;
PathChannelSid = pathChannelSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// DeleteUserChannelOptions
/// </summary>
public class DeleteUserChannelOptions : IOptions<UserChannelResource>
{
/// <summary>
/// The service_sid
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The user_sid
/// </summary>
public string PathUserSid { get; }
/// <summary>
/// The channel_sid
/// </summary>
public string PathChannelSid { get; }
/// <summary>
/// Construct a new DeleteUserChannelOptions
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathUserSid"> The user_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
public DeleteUserChannelOptions(string pathServiceSid, string pathUserSid, string pathChannelSid)
{
PathServiceSid = pathServiceSid;
PathUserSid = pathUserSid;
PathChannelSid = pathChannelSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// UpdateUserChannelOptions
/// </summary>
public class UpdateUserChannelOptions : IOptions<UserChannelResource>
{
/// <summary>
/// The service_sid
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The user_sid
/// </summary>
public string PathUserSid { get; }
/// <summary>
/// The channel_sid
/// </summary>
public string PathChannelSid { get; }
/// <summary>
/// The notification_level
/// </summary>
public UserChannelResource.NotificationLevelEnum NotificationLevel { get; set; }
/// <summary>
/// The last_consumed_message_index
/// </summary>
public int? LastConsumedMessageIndex { get; set; }
/// <summary>
/// The last_consumption_timestamp
/// </summary>
public DateTime? LastConsumptionTimestamp { get; set; }
/// <summary>
/// Construct a new UpdateUserChannelOptions
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathUserSid"> The user_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
public UpdateUserChannelOptions(string pathServiceSid, string pathUserSid, string pathChannelSid)
{
PathServiceSid = pathServiceSid;
PathUserSid = pathUserSid;
PathChannelSid = pathChannelSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (NotificationLevel != null)
{
p.Add(new KeyValuePair<string, string>("NotificationLevel", NotificationLevel.ToString()));
}
if (LastConsumedMessageIndex != null)
{
p.Add(new KeyValuePair<string, string>("LastConsumedMessageIndex", LastConsumedMessageIndex.ToString()));
}
if (LastConsumptionTimestamp != null)
{
p.Add(new KeyValuePair<string, string>("LastConsumptionTimestamp", Serializers.DateTimeIso8601(LastConsumptionTimestamp)));
}
return p;
}
}
}
| |
// 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.Drawing;
using System.Globalization;
using System.Linq;
using Xunit;
namespace System.ComponentModel.TypeConverterTests
{
public class SizeFConverterTests : StringTypeConverterTestBase<SizeF>
{
protected override TypeConverter Converter { get; } = new SizeFConverter();
protected override bool StandardValuesSupported { get; } = false;
protected override bool StandardValuesExclusive { get; } = false;
protected override SizeF Default => new SizeF(1, 1);
protected override bool CreateInstanceSupported { get; } = true;
protected override bool IsGetPropertiesSupported { get; } = true;
protected override IEnumerable<Tuple<SizeF, Dictionary<string, object>>> CreateInstancePairs
{
get
{
yield return Tuple.Create(new SizeF(10, 20), new Dictionary<string, object>
{
["Width"] = 10f,
["Height"] = 20f,
});
yield return Tuple.Create(new SizeF(-2, 3), new Dictionary<string, object>
{
["Width"] = -2f,
["Height"] = 3f,
});
}
}
[Theory]
[InlineData(typeof(string))]
public void CanConvertFromTrue(Type type)
{
CanConvertFrom(type);
}
[Theory]
[InlineData(typeof(Rectangle))]
[InlineData(typeof(RectangleF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(Color))]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(object))]
[InlineData(typeof(int))]
public void CanConvertFromFalse(Type type)
{
CannotConvertFrom(type);
}
[Theory]
[InlineData(typeof(string))]
public void CanConvertToTrue(Type type)
{
CanConvertTo(type);
}
[Theory]
[InlineData(typeof(Rectangle))]
[InlineData(typeof(RectangleF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(Color))]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(object))]
[InlineData(typeof(int))]
public void CanConvertToFalse(Type type)
{
CannotConvertTo(type);
}
public static IEnumerable<object[]> SizeFData =>
new[]
{
new object[] {0, 0},
new object[] {1, 1},
new object[] {-1, 1},
new object[] {1, -1},
new object[] {-1, -1},
new object[] {float.MaxValue, float.MaxValue},
new object[] {float.MinValue, float.MaxValue},
new object[] {float.MaxValue, float.MinValue},
new object[] {float.MinValue, float.MinValue},
};
[Theory]
[MemberData(nameof(SizeFData))]
public void ConvertFrom(float width, float height)
{
TestConvertFromString(new SizeF(width, height), FormattableString.Invariant($"{width:G9}, {height:G9}"));
}
[Theory]
[InlineData("1")]
[InlineData("1, 1, 1")]
public void ConvertFrom_ArgumentException(string value)
{
ConvertFromThrowsArgumentExceptionForString(value);
}
[Fact]
public void ConvertFrom_Invalid()
{
ConvertFromThrowsFormatInnerExceptionForString("*1, 1");
}
public static IEnumerable<object[]> ConvertFrom_NotSupportedData =>
new[]
{
new object[] {new Point(1, 1)},
new object[] {new PointF(1, 1)},
new object[] {new SizeF(1, 1)},
new object[] {new SizeF(1, 1)},
new object[] {0x10},
};
[Theory]
[MemberData(nameof(ConvertFrom_NotSupportedData))]
public void ConvertFrom_NotSupported(object value)
{
ConvertFromThrowsNotSupportedFor(value);
}
[Theory]
[MemberData(nameof(SizeFData))]
public void ConvertTo(float width, float height)
{
TestConvertToString(new SizeF(width, height), FormattableString.Invariant($"{width:G9}, {height:G9}"));
}
[Theory]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(int))]
public void ConvertTo_NotSupportedException(Type type)
{
ConvertToThrowsNotSupportedForType(type);
}
[Fact]
public void ConvertTo_NullCulture()
{
string listSep = CultureInfo.CurrentCulture.TextInfo.ListSeparator;
Assert.Equal($"1{listSep} 1", Converter.ConvertTo(null, null, new SizeF(1, 1), typeof(string)));
}
[Fact]
public void CreateInstance_CaseSensitive()
{
// NET Framework throws NullReferenceException but we want it to be friendly on Core so it
// correctly throws an ArgumentException
Type expectedExceptionType =
PlatformDetection.IsFullFramework ? typeof(NullReferenceException) : typeof(ArgumentException);
Assert.Throws(expectedExceptionType, () =>
{
Converter.CreateInstance(null, new Dictionary<string, object>
{
["width"] = 1,
["Height"] = 1,
});
});
}
[Fact]
public void GetProperties()
{
var pt = new SizeF(1, 1);
var props = Converter.GetProperties(new SizeF(1, 1));
Assert.Equal(2, props.Count);
Assert.Equal(1f, props["Width"].GetValue(pt));
Assert.Equal(1f, props["Height"].GetValue(pt));
props = Converter.GetProperties(null, new SizeF(1, 1));
Assert.Equal(2, props.Count);
Assert.Equal(1f, props["Width"].GetValue(pt));
Assert.Equal(1f, props["Height"].GetValue(pt));
props = Converter.GetProperties(null, new SizeF(1, 1), null);
Assert.Equal(3, props.Count);
Assert.Equal(1f, props["Width"].GetValue(pt));
Assert.Equal(1f, props["Height"].GetValue(pt));
Assert.Equal(false, props["IsEmpty"].GetValue(pt));
props = Converter.GetProperties(null, new SizeF(1, 1), new Attribute[0]);
Assert.Equal(3, props.Count);
Assert.Equal(1f, props["Width"].GetValue(pt));
Assert.Equal(1f, props["Height"].GetValue(pt));
Assert.Equal(false, props["IsEmpty"].GetValue(pt));
// Pick an attibute that cannot be applied to properties to make sure everything gets filtered
props = Converter.GetProperties(null, new SizeF(1, 1), new Attribute[] { new System.Reflection.AssemblyCopyrightAttribute("")});
Assert.Equal(0, props.Count);
}
[Theory]
[MemberData(nameof(SizeFData))]
public void ConvertFromInvariantString(float width, float height)
{
var point = (SizeF)Converter.ConvertFromInvariantString(FormattableString.Invariant($"{width:G9}, {height:G9}"));
Assert.Equal(width, point.Width);
Assert.Equal(height, point.Height);
}
[Fact]
public void ConvertFromInvariantString_ArgumentException()
{
ConvertFromInvariantStringThrowsArgumentException("1");
}
[Fact]
public void ConvertFromInvariantString_FormatException()
{
ConvertFromInvariantStringThrowsFormatInnerException("hello");
}
[Theory]
[MemberData(nameof(SizeFData))]
public void ConvertFromString(float width, float height)
{
var point =
(SizeF)Converter.ConvertFromString(string.Format(CultureInfo.CurrentCulture, "{0:g9}{2} {1:g9}", width, height,
CultureInfo.CurrentCulture.TextInfo.ListSeparator));
Assert.Equal(width, point.Width);
Assert.Equal(height, point.Height);
}
[Fact]
public void ConvertFromString_ArgumentException()
{
ConvertFromStringThrowsArgumentException("1");
}
[Fact]
public void ConvertFromString_FormatException()
{
ConvertFromStringThrowsFormatInnerException("hello");
}
[Theory]
[MemberData(nameof(SizeFData))]
public void ConvertToInvariantString(float width, float height)
{
var str = Converter.ConvertToInvariantString(new SizeF(width, height));
Assert.Equal(FormattableString.Invariant($"{width:G9}, {height:G9}"), str);
}
[Theory]
[MemberData(nameof(SizeFData))]
public void ConvertToString(float width, float height)
{
var str = Converter.ConvertToString(new SizeF(width, height));
Assert.Equal(string.Format(CultureInfo.CurrentCulture, "{0:G9}{2} {1:G9}", width, height, CultureInfo.CurrentCulture.TextInfo.ListSeparator), str);
}
}
}
| |
//
// Copyright (c) 2004-2018 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !SILVERLIGHT && !__ANDROID__ && !__IOS__ && !NETSTANDARD1_3
// Unfortunately, Xamarin Android and Xamarin iOS don't support mutexes (see https://github.com/mono/mono/blob/3a9e18e5405b5772be88bfc45739d6a350560111/mcs/class/corlib/System.Threading/Mutex.cs#L167) so the BaseFileAppender class now throws an exception in the constructor.
#define SupportsMutex
#endif
#if SupportsMutex
namespace NLog.Internal.FileAppenders
{
using System;
using System.IO;
using System.Security;
using System.Threading;
using NLog.Common;
/// <summary>
/// Provides a multiprocess-safe atomic file appends while
/// keeping the files open.
/// </summary>
/// <remarks>
/// On Unix you can get all the appends to be atomic, even when multiple
/// processes are trying to write to the same file, because setting the file
/// pointer to the end of the file and appending can be made one operation.
/// On Win32 we need to maintain some synchronization between processes
/// (global named mutex is used for this)
/// </remarks>
[SecuritySafeCritical]
internal class MutexMultiProcessFileAppender : BaseMutexFileAppender
{
public static readonly IFileAppenderFactory TheFactory = new Factory();
private FileStream _fileStream;
private readonly FileCharacteristicsHelper _fileCharacteristicsHelper;
private Mutex _mutex;
/// <summary>
/// Initializes a new instance of the <see cref="MutexMultiProcessFileAppender" /> class.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="parameters">The parameters.</param>
public MutexMultiProcessFileAppender(string fileName, ICreateFileParameters parameters) : base(fileName, parameters)
{
try
{
_mutex = CreateSharableMutex("FileLock");
_fileStream = CreateFileStream(true);
_fileCharacteristicsHelper = FileCharacteristicsHelper.CreateHelper(parameters.ForceManaged);
}
catch
{
if (_mutex != null)
{
_mutex.Close();
_mutex = null;
}
if (_fileStream != null)
{
_fileStream.Close();
_fileStream = null;
}
throw;
}
}
/// <summary>
/// Writes the specified bytes.
/// </summary>
/// <param name="bytes">The bytes array.</param>
/// <param name="offset">The bytes array offset.</param>
/// <param name="count">The number of bytes.</param>
public override void Write(byte[] bytes, int offset, int count)
{
if (_mutex == null || _fileStream == null)
{
return;
}
try
{
_mutex.WaitOne();
}
catch (AbandonedMutexException)
{
// ignore the exception, another process was killed without properly releasing the mutex
// the mutex has been acquired, so proceed to writing
// See: http://msdn.microsoft.com/en-us/library/system.threading.abandonedmutexexception.aspx
}
try
{
_fileStream.Seek(0, SeekOrigin.End);
_fileStream.Write(bytes, offset, count);
_fileStream.Flush();
if (CaptureLastWriteTime)
{
FileTouched();
}
}
finally
{
_mutex.ReleaseMutex();
}
}
/// <summary>
/// Closes this instance.
/// </summary>
public override void Close()
{
if (_mutex == null && _fileStream == null)
{
return;
}
InternalLogger.Trace("Closing '{0}'", FileName);
try
{
_mutex?.Close();
}
catch (Exception ex)
{
// Swallow exception as the mutex now is in final state (abandoned instead of closed)
InternalLogger.Warn(ex, "Failed to close mutex: '{0}'", FileName);
}
finally
{
_mutex = null;
}
try
{
_fileStream?.Close();
}
catch (Exception ex)
{
// Swallow exception as the file-stream now is in final state (broken instead of closed)
InternalLogger.Warn(ex, "Failed to close file: '{0}'", FileName);
AsyncHelpers.WaitForDelay(TimeSpan.FromMilliseconds(1)); // Artificial delay to avoid hammering a bad file location
}
finally
{
_fileStream = null;
}
FileTouched();
}
/// <summary>
/// Flushes this instance.
/// </summary>
public override void Flush()
{
// do nothing, the stream is always flushed
}
/// <summary>
/// Gets the creation time for a file associated with the appender. The time returned is in Coordinated Universal
/// Time [UTC] standard.
/// </summary>
/// <returns>The file creation time.</returns>
public override DateTime? GetFileCreationTimeUtc()
{
return CreationTimeUtc; // File is kept open, so creation time is static
}
/// <summary>
/// Gets the last time the file associated with the appeander is written. The time returned is in Coordinated
/// Universal Time [UTC] standard.
/// </summary>
/// <returns>The time the file was last written to.</returns>
public override DateTime? GetFileLastWriteTimeUtc()
{
var fileChars = GetFileCharacteristics();
return fileChars.LastWriteTimeUtc;
}
/// <summary>
/// Gets the length in bytes of the file associated with the appeander.
/// </summary>
/// <returns>A long value representing the length of the file in bytes.</returns>
public override long? GetFileLength()
{
var fileChars = GetFileCharacteristics();
return fileChars.FileLength;
}
private FileCharacteristics GetFileCharacteristics()
{
// TODO: It is not efficient to read all the whole FileCharacteristics and then using one property.
return _fileCharacteristicsHelper.GetFileCharacteristics(FileName, _fileStream);
}
/// <summary>
/// Factory class.
/// </summary>
private class Factory : IFileAppenderFactory
{
/// <summary>
/// Opens the appender for given file name and parameters.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="parameters">Creation parameters.</param>
/// <returns>
/// Instance of <see cref="BaseFileAppender"/> which can be used to write to the file.
/// </returns>
BaseFileAppender IFileAppenderFactory.Open(string fileName, ICreateFileParameters parameters)
{
return new MutexMultiProcessFileAppender(fileName, parameters);
}
}
}
}
#endif
| |
// 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!
namespace Google.Cloud.RecommendationEngine.V1Beta1.Snippets
{
using Google.Api.Gax;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedCatalogServiceClientSnippets
{
/// <summary>Snippet for CreateCatalogItem</summary>
public void CreateCatalogItemRequestObject()
{
// Snippet: CreateCatalogItem(CreateCatalogItemRequest, CallSettings)
// Create client
CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create();
// Initialize request argument(s)
CreateCatalogItemRequest request = new CreateCatalogItemRequest
{
ParentAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"),
CatalogItem = new CatalogItem(),
};
// Make the request
CatalogItem response = catalogServiceClient.CreateCatalogItem(request);
// End snippet
}
/// <summary>Snippet for CreateCatalogItemAsync</summary>
public async Task CreateCatalogItemRequestObjectAsync()
{
// Snippet: CreateCatalogItemAsync(CreateCatalogItemRequest, CallSettings)
// Additional: CreateCatalogItemAsync(CreateCatalogItemRequest, CancellationToken)
// Create client
CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync();
// Initialize request argument(s)
CreateCatalogItemRequest request = new CreateCatalogItemRequest
{
ParentAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"),
CatalogItem = new CatalogItem(),
};
// Make the request
CatalogItem response = await catalogServiceClient.CreateCatalogItemAsync(request);
// End snippet
}
/// <summary>Snippet for CreateCatalogItem</summary>
public void CreateCatalogItem()
{
// Snippet: CreateCatalogItem(string, CatalogItem, CallSettings)
// Create client
CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]";
CatalogItem catalogItem = new CatalogItem();
// Make the request
CatalogItem response = catalogServiceClient.CreateCatalogItem(parent, catalogItem);
// End snippet
}
/// <summary>Snippet for CreateCatalogItemAsync</summary>
public async Task CreateCatalogItemAsync()
{
// Snippet: CreateCatalogItemAsync(string, CatalogItem, CallSettings)
// Additional: CreateCatalogItemAsync(string, CatalogItem, CancellationToken)
// Create client
CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]";
CatalogItem catalogItem = new CatalogItem();
// Make the request
CatalogItem response = await catalogServiceClient.CreateCatalogItemAsync(parent, catalogItem);
// End snippet
}
/// <summary>Snippet for CreateCatalogItem</summary>
public void CreateCatalogItemResourceNames()
{
// Snippet: CreateCatalogItem(CatalogName, CatalogItem, CallSettings)
// Create client
CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create();
// Initialize request argument(s)
CatalogName parent = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]");
CatalogItem catalogItem = new CatalogItem();
// Make the request
CatalogItem response = catalogServiceClient.CreateCatalogItem(parent, catalogItem);
// End snippet
}
/// <summary>Snippet for CreateCatalogItemAsync</summary>
public async Task CreateCatalogItemResourceNamesAsync()
{
// Snippet: CreateCatalogItemAsync(CatalogName, CatalogItem, CallSettings)
// Additional: CreateCatalogItemAsync(CatalogName, CatalogItem, CancellationToken)
// Create client
CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync();
// Initialize request argument(s)
CatalogName parent = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]");
CatalogItem catalogItem = new CatalogItem();
// Make the request
CatalogItem response = await catalogServiceClient.CreateCatalogItemAsync(parent, catalogItem);
// End snippet
}
/// <summary>Snippet for GetCatalogItem</summary>
public void GetCatalogItemRequestObject()
{
// Snippet: GetCatalogItem(GetCatalogItemRequest, CallSettings)
// Create client
CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create();
// Initialize request argument(s)
GetCatalogItemRequest request = new GetCatalogItemRequest
{
CatalogItemPathName = CatalogItemPathName.FromProjectLocationCatalogCatalogItemPath("[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]"),
};
// Make the request
CatalogItem response = catalogServiceClient.GetCatalogItem(request);
// End snippet
}
/// <summary>Snippet for GetCatalogItemAsync</summary>
public async Task GetCatalogItemRequestObjectAsync()
{
// Snippet: GetCatalogItemAsync(GetCatalogItemRequest, CallSettings)
// Additional: GetCatalogItemAsync(GetCatalogItemRequest, CancellationToken)
// Create client
CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync();
// Initialize request argument(s)
GetCatalogItemRequest request = new GetCatalogItemRequest
{
CatalogItemPathName = CatalogItemPathName.FromProjectLocationCatalogCatalogItemPath("[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]"),
};
// Make the request
CatalogItem response = await catalogServiceClient.GetCatalogItemAsync(request);
// End snippet
}
/// <summary>Snippet for GetCatalogItem</summary>
public void GetCatalogItem()
{
// Snippet: GetCatalogItem(string, CallSettings)
// Create client
CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/catalogItems/[CATALOG_ITEM_PATH]";
// Make the request
CatalogItem response = catalogServiceClient.GetCatalogItem(name);
// End snippet
}
/// <summary>Snippet for GetCatalogItemAsync</summary>
public async Task GetCatalogItemAsync()
{
// Snippet: GetCatalogItemAsync(string, CallSettings)
// Additional: GetCatalogItemAsync(string, CancellationToken)
// Create client
CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/catalogItems/[CATALOG_ITEM_PATH]";
// Make the request
CatalogItem response = await catalogServiceClient.GetCatalogItemAsync(name);
// End snippet
}
/// <summary>Snippet for GetCatalogItem</summary>
public void GetCatalogItemResourceNames()
{
// Snippet: GetCatalogItem(CatalogItemPathName, CallSettings)
// Create client
CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create();
// Initialize request argument(s)
CatalogItemPathName name = CatalogItemPathName.FromProjectLocationCatalogCatalogItemPath("[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]");
// Make the request
CatalogItem response = catalogServiceClient.GetCatalogItem(name);
// End snippet
}
/// <summary>Snippet for GetCatalogItemAsync</summary>
public async Task GetCatalogItemResourceNamesAsync()
{
// Snippet: GetCatalogItemAsync(CatalogItemPathName, CallSettings)
// Additional: GetCatalogItemAsync(CatalogItemPathName, CancellationToken)
// Create client
CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync();
// Initialize request argument(s)
CatalogItemPathName name = CatalogItemPathName.FromProjectLocationCatalogCatalogItemPath("[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]");
// Make the request
CatalogItem response = await catalogServiceClient.GetCatalogItemAsync(name);
// End snippet
}
/// <summary>Snippet for ListCatalogItems</summary>
public void ListCatalogItemsRequestObject()
{
// Snippet: ListCatalogItems(ListCatalogItemsRequest, CallSettings)
// Create client
CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create();
// Initialize request argument(s)
ListCatalogItemsRequest request = new ListCatalogItemsRequest
{
ParentAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"),
Filter = "",
};
// Make the request
PagedEnumerable<ListCatalogItemsResponse, CatalogItem> response = catalogServiceClient.ListCatalogItems(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (CatalogItem item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListCatalogItemsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (CatalogItem item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<CatalogItem> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (CatalogItem item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListCatalogItemsAsync</summary>
public async Task ListCatalogItemsRequestObjectAsync()
{
// Snippet: ListCatalogItemsAsync(ListCatalogItemsRequest, CallSettings)
// Create client
CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync();
// Initialize request argument(s)
ListCatalogItemsRequest request = new ListCatalogItemsRequest
{
ParentAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"),
Filter = "",
};
// Make the request
PagedAsyncEnumerable<ListCatalogItemsResponse, CatalogItem> response = catalogServiceClient.ListCatalogItemsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((CatalogItem item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListCatalogItemsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (CatalogItem item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<CatalogItem> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (CatalogItem item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListCatalogItems</summary>
public void ListCatalogItems()
{
// Snippet: ListCatalogItems(string, string, string, int?, CallSettings)
// Create client
CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]";
string filter = "";
// Make the request
PagedEnumerable<ListCatalogItemsResponse, CatalogItem> response = catalogServiceClient.ListCatalogItems(parent, filter);
// Iterate over all response items, lazily performing RPCs as required
foreach (CatalogItem item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListCatalogItemsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (CatalogItem item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<CatalogItem> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (CatalogItem item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListCatalogItemsAsync</summary>
public async Task ListCatalogItemsAsync()
{
// Snippet: ListCatalogItemsAsync(string, string, string, int?, CallSettings)
// Create client
CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]";
string filter = "";
// Make the request
PagedAsyncEnumerable<ListCatalogItemsResponse, CatalogItem> response = catalogServiceClient.ListCatalogItemsAsync(parent, filter);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((CatalogItem item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListCatalogItemsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (CatalogItem item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<CatalogItem> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (CatalogItem item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListCatalogItems</summary>
public void ListCatalogItemsResourceNames()
{
// Snippet: ListCatalogItems(CatalogName, string, string, int?, CallSettings)
// Create client
CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create();
// Initialize request argument(s)
CatalogName parent = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]");
string filter = "";
// Make the request
PagedEnumerable<ListCatalogItemsResponse, CatalogItem> response = catalogServiceClient.ListCatalogItems(parent, filter);
// Iterate over all response items, lazily performing RPCs as required
foreach (CatalogItem item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListCatalogItemsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (CatalogItem item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<CatalogItem> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (CatalogItem item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListCatalogItemsAsync</summary>
public async Task ListCatalogItemsResourceNamesAsync()
{
// Snippet: ListCatalogItemsAsync(CatalogName, string, string, int?, CallSettings)
// Create client
CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync();
// Initialize request argument(s)
CatalogName parent = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]");
string filter = "";
// Make the request
PagedAsyncEnumerable<ListCatalogItemsResponse, CatalogItem> response = catalogServiceClient.ListCatalogItemsAsync(parent, filter);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((CatalogItem item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListCatalogItemsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (CatalogItem item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<CatalogItem> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (CatalogItem item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for UpdateCatalogItem</summary>
public void UpdateCatalogItemRequestObject()
{
// Snippet: UpdateCatalogItem(UpdateCatalogItemRequest, CallSettings)
// Create client
CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create();
// Initialize request argument(s)
UpdateCatalogItemRequest request = new UpdateCatalogItemRequest
{
CatalogItemPathName = CatalogItemPathName.FromProjectLocationCatalogCatalogItemPath("[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]"),
CatalogItem = new CatalogItem(),
UpdateMask = new FieldMask(),
};
// Make the request
CatalogItem response = catalogServiceClient.UpdateCatalogItem(request);
// End snippet
}
/// <summary>Snippet for UpdateCatalogItemAsync</summary>
public async Task UpdateCatalogItemRequestObjectAsync()
{
// Snippet: UpdateCatalogItemAsync(UpdateCatalogItemRequest, CallSettings)
// Additional: UpdateCatalogItemAsync(UpdateCatalogItemRequest, CancellationToken)
// Create client
CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync();
// Initialize request argument(s)
UpdateCatalogItemRequest request = new UpdateCatalogItemRequest
{
CatalogItemPathName = CatalogItemPathName.FromProjectLocationCatalogCatalogItemPath("[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]"),
CatalogItem = new CatalogItem(),
UpdateMask = new FieldMask(),
};
// Make the request
CatalogItem response = await catalogServiceClient.UpdateCatalogItemAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateCatalogItem</summary>
public void UpdateCatalogItem()
{
// Snippet: UpdateCatalogItem(string, CatalogItem, FieldMask, CallSettings)
// Create client
CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/catalogItems/[CATALOG_ITEM_PATH]";
CatalogItem catalogItem = new CatalogItem();
FieldMask updateMask = new FieldMask();
// Make the request
CatalogItem response = catalogServiceClient.UpdateCatalogItem(name, catalogItem, updateMask);
// End snippet
}
/// <summary>Snippet for UpdateCatalogItemAsync</summary>
public async Task UpdateCatalogItemAsync()
{
// Snippet: UpdateCatalogItemAsync(string, CatalogItem, FieldMask, CallSettings)
// Additional: UpdateCatalogItemAsync(string, CatalogItem, FieldMask, CancellationToken)
// Create client
CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/catalogItems/[CATALOG_ITEM_PATH]";
CatalogItem catalogItem = new CatalogItem();
FieldMask updateMask = new FieldMask();
// Make the request
CatalogItem response = await catalogServiceClient.UpdateCatalogItemAsync(name, catalogItem, updateMask);
// End snippet
}
/// <summary>Snippet for UpdateCatalogItem</summary>
public void UpdateCatalogItemResourceNames()
{
// Snippet: UpdateCatalogItem(CatalogItemPathName, CatalogItem, FieldMask, CallSettings)
// Create client
CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create();
// Initialize request argument(s)
CatalogItemPathName name = CatalogItemPathName.FromProjectLocationCatalogCatalogItemPath("[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]");
CatalogItem catalogItem = new CatalogItem();
FieldMask updateMask = new FieldMask();
// Make the request
CatalogItem response = catalogServiceClient.UpdateCatalogItem(name, catalogItem, updateMask);
// End snippet
}
/// <summary>Snippet for UpdateCatalogItemAsync</summary>
public async Task UpdateCatalogItemResourceNamesAsync()
{
// Snippet: UpdateCatalogItemAsync(CatalogItemPathName, CatalogItem, FieldMask, CallSettings)
// Additional: UpdateCatalogItemAsync(CatalogItemPathName, CatalogItem, FieldMask, CancellationToken)
// Create client
CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync();
// Initialize request argument(s)
CatalogItemPathName name = CatalogItemPathName.FromProjectLocationCatalogCatalogItemPath("[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]");
CatalogItem catalogItem = new CatalogItem();
FieldMask updateMask = new FieldMask();
// Make the request
CatalogItem response = await catalogServiceClient.UpdateCatalogItemAsync(name, catalogItem, updateMask);
// End snippet
}
/// <summary>Snippet for DeleteCatalogItem</summary>
public void DeleteCatalogItemRequestObject()
{
// Snippet: DeleteCatalogItem(DeleteCatalogItemRequest, CallSettings)
// Create client
CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create();
// Initialize request argument(s)
DeleteCatalogItemRequest request = new DeleteCatalogItemRequest
{
CatalogItemPathName = CatalogItemPathName.FromProjectLocationCatalogCatalogItemPath("[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]"),
};
// Make the request
catalogServiceClient.DeleteCatalogItem(request);
// End snippet
}
/// <summary>Snippet for DeleteCatalogItemAsync</summary>
public async Task DeleteCatalogItemRequestObjectAsync()
{
// Snippet: DeleteCatalogItemAsync(DeleteCatalogItemRequest, CallSettings)
// Additional: DeleteCatalogItemAsync(DeleteCatalogItemRequest, CancellationToken)
// Create client
CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteCatalogItemRequest request = new DeleteCatalogItemRequest
{
CatalogItemPathName = CatalogItemPathName.FromProjectLocationCatalogCatalogItemPath("[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]"),
};
// Make the request
await catalogServiceClient.DeleteCatalogItemAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteCatalogItem</summary>
public void DeleteCatalogItem()
{
// Snippet: DeleteCatalogItem(string, CallSettings)
// Create client
CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/catalogItems/[CATALOG_ITEM_PATH]";
// Make the request
catalogServiceClient.DeleteCatalogItem(name);
// End snippet
}
/// <summary>Snippet for DeleteCatalogItemAsync</summary>
public async Task DeleteCatalogItemAsync()
{
// Snippet: DeleteCatalogItemAsync(string, CallSettings)
// Additional: DeleteCatalogItemAsync(string, CancellationToken)
// Create client
CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/catalogItems/[CATALOG_ITEM_PATH]";
// Make the request
await catalogServiceClient.DeleteCatalogItemAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteCatalogItem</summary>
public void DeleteCatalogItemResourceNames()
{
// Snippet: DeleteCatalogItem(CatalogItemPathName, CallSettings)
// Create client
CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create();
// Initialize request argument(s)
CatalogItemPathName name = CatalogItemPathName.FromProjectLocationCatalogCatalogItemPath("[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]");
// Make the request
catalogServiceClient.DeleteCatalogItem(name);
// End snippet
}
/// <summary>Snippet for DeleteCatalogItemAsync</summary>
public async Task DeleteCatalogItemResourceNamesAsync()
{
// Snippet: DeleteCatalogItemAsync(CatalogItemPathName, CallSettings)
// Additional: DeleteCatalogItemAsync(CatalogItemPathName, CancellationToken)
// Create client
CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync();
// Initialize request argument(s)
CatalogItemPathName name = CatalogItemPathName.FromProjectLocationCatalogCatalogItemPath("[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]");
// Make the request
await catalogServiceClient.DeleteCatalogItemAsync(name);
// End snippet
}
/// <summary>Snippet for ImportCatalogItems</summary>
public void ImportCatalogItemsRequestObject()
{
// Snippet: ImportCatalogItems(ImportCatalogItemsRequest, CallSettings)
// Create client
CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create();
// Initialize request argument(s)
ImportCatalogItemsRequest request = new ImportCatalogItemsRequest
{
ParentAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"),
RequestId = "",
InputConfig = new InputConfig(),
ErrorsConfig = new ImportErrorsConfig(),
};
// Make the request
Operation<ImportCatalogItemsResponse, ImportMetadata> response = catalogServiceClient.ImportCatalogItems(request);
// Poll until the returned long-running operation is complete
Operation<ImportCatalogItemsResponse, ImportMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
ImportCatalogItemsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ImportCatalogItemsResponse, ImportMetadata> retrievedResponse = catalogServiceClient.PollOnceImportCatalogItems(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ImportCatalogItemsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ImportCatalogItemsAsync</summary>
public async Task ImportCatalogItemsRequestObjectAsync()
{
// Snippet: ImportCatalogItemsAsync(ImportCatalogItemsRequest, CallSettings)
// Additional: ImportCatalogItemsAsync(ImportCatalogItemsRequest, CancellationToken)
// Create client
CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync();
// Initialize request argument(s)
ImportCatalogItemsRequest request = new ImportCatalogItemsRequest
{
ParentAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"),
RequestId = "",
InputConfig = new InputConfig(),
ErrorsConfig = new ImportErrorsConfig(),
};
// Make the request
Operation<ImportCatalogItemsResponse, ImportMetadata> response = await catalogServiceClient.ImportCatalogItemsAsync(request);
// Poll until the returned long-running operation is complete
Operation<ImportCatalogItemsResponse, ImportMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
ImportCatalogItemsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ImportCatalogItemsResponse, ImportMetadata> retrievedResponse = await catalogServiceClient.PollOnceImportCatalogItemsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ImportCatalogItemsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ImportCatalogItems</summary>
public void ImportCatalogItems()
{
// Snippet: ImportCatalogItems(string, string, InputConfig, ImportErrorsConfig, CallSettings)
// Create client
CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]";
string requestId = "";
InputConfig inputConfig = new InputConfig();
ImportErrorsConfig errorsConfig = new ImportErrorsConfig();
// Make the request
Operation<ImportCatalogItemsResponse, ImportMetadata> response = catalogServiceClient.ImportCatalogItems(parent, requestId, inputConfig, errorsConfig);
// Poll until the returned long-running operation is complete
Operation<ImportCatalogItemsResponse, ImportMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
ImportCatalogItemsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ImportCatalogItemsResponse, ImportMetadata> retrievedResponse = catalogServiceClient.PollOnceImportCatalogItems(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ImportCatalogItemsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ImportCatalogItemsAsync</summary>
public async Task ImportCatalogItemsAsync()
{
// Snippet: ImportCatalogItemsAsync(string, string, InputConfig, ImportErrorsConfig, CallSettings)
// Additional: ImportCatalogItemsAsync(string, string, InputConfig, ImportErrorsConfig, CancellationToken)
// Create client
CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]";
string requestId = "";
InputConfig inputConfig = new InputConfig();
ImportErrorsConfig errorsConfig = new ImportErrorsConfig();
// Make the request
Operation<ImportCatalogItemsResponse, ImportMetadata> response = await catalogServiceClient.ImportCatalogItemsAsync(parent, requestId, inputConfig, errorsConfig);
// Poll until the returned long-running operation is complete
Operation<ImportCatalogItemsResponse, ImportMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
ImportCatalogItemsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ImportCatalogItemsResponse, ImportMetadata> retrievedResponse = await catalogServiceClient.PollOnceImportCatalogItemsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ImportCatalogItemsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ImportCatalogItems</summary>
public void ImportCatalogItemsResourceNames()
{
// Snippet: ImportCatalogItems(CatalogName, string, InputConfig, ImportErrorsConfig, CallSettings)
// Create client
CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create();
// Initialize request argument(s)
CatalogName parent = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]");
string requestId = "";
InputConfig inputConfig = new InputConfig();
ImportErrorsConfig errorsConfig = new ImportErrorsConfig();
// Make the request
Operation<ImportCatalogItemsResponse, ImportMetadata> response = catalogServiceClient.ImportCatalogItems(parent, requestId, inputConfig, errorsConfig);
// Poll until the returned long-running operation is complete
Operation<ImportCatalogItemsResponse, ImportMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
ImportCatalogItemsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ImportCatalogItemsResponse, ImportMetadata> retrievedResponse = catalogServiceClient.PollOnceImportCatalogItems(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ImportCatalogItemsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ImportCatalogItemsAsync</summary>
public async Task ImportCatalogItemsResourceNamesAsync()
{
// Snippet: ImportCatalogItemsAsync(CatalogName, string, InputConfig, ImportErrorsConfig, CallSettings)
// Additional: ImportCatalogItemsAsync(CatalogName, string, InputConfig, ImportErrorsConfig, CancellationToken)
// Create client
CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync();
// Initialize request argument(s)
CatalogName parent = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]");
string requestId = "";
InputConfig inputConfig = new InputConfig();
ImportErrorsConfig errorsConfig = new ImportErrorsConfig();
// Make the request
Operation<ImportCatalogItemsResponse, ImportMetadata> response = await catalogServiceClient.ImportCatalogItemsAsync(parent, requestId, inputConfig, errorsConfig);
// Poll until the returned long-running operation is complete
Operation<ImportCatalogItemsResponse, ImportMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
ImportCatalogItemsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ImportCatalogItemsResponse, ImportMetadata> retrievedResponse = await catalogServiceClient.PollOnceImportCatalogItemsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ImportCatalogItemsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
}
}
| |
using System;
using System.Linq;
using System.Text;
using CppSharp.AST;
using CppSharp.AST.Extensions;
using CppSharp.Types;
using Type = CppSharp.AST.Type;
namespace CppSharp.Generators.CSharp
{
public class CSharpMarshalContext : MarshalContext
{
public CSharpMarshalContext(BindingContext context)
: base(context)
{
ArgumentPrefix = new TextGenerator();
Cleanup = new TextGenerator();
}
public TextGenerator ArgumentPrefix { get; private set; }
public TextGenerator Cleanup { get; private set; }
public bool HasCodeBlock { get; set; }
}
public abstract class CSharpMarshalPrinter : MarshalPrinter<CSharpMarshalContext>
{
protected CSharpMarshalPrinter(CSharpMarshalContext context)
: base(context)
{
VisitOptions.VisitFunctionParameters = false;
VisitOptions.VisitTemplateArguments = false;
}
public override bool VisitMemberPointerType(MemberPointerType member,
TypeQualifiers quals)
{
return false;
}
}
public class CSharpMarshalNativeToManagedPrinter : CSharpMarshalPrinter
{
public CSharpMarshalNativeToManagedPrinter(CSharpMarshalContext context)
: base(context)
{
typePrinter = new CSharpTypePrinter(context.Context);
}
public bool MarshalsParameter { get; set; }
public override bool VisitType(Type type, TypeQualifiers quals)
{
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling)
{
typeMap.Type = type;
typeMap.CSharpMarshalToManaged(Context);
return false;
}
return true;
}
public override bool VisitDeclaration(Declaration decl)
{
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(decl, out typeMap) && typeMap.DoesMarshalling)
{
typeMap.Declaration = decl;
typeMap.CSharpMarshalToManaged(Context);
return false;
}
return true;
}
public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
{
if (!VisitType(array, quals))
return false;
switch (array.SizeType)
{
case ArrayType.ArraySize.Constant:
if (Context.MarshalKind == MarshalKind.NativeField ||
Context.MarshalKind == MarshalKind.ReturnVariableArray)
{
var supportBefore = Context.Before;
string value = Generator.GeneratedIdentifier("value");
supportBefore.WriteLine("{0}[] {1} = null;", array.Type, value, array.Size);
supportBefore.WriteLine("if ({0} != null)", Context.ReturnVarName);
supportBefore.WriteStartBraceIndent();
supportBefore.WriteLine("{0} = new {1}[{2}];", value, array.Type, array.Size);
supportBefore.WriteLine("for (int i = 0; i < {0}; i++)", array.Size);
if (array.Type.IsPointerToPrimitiveType(PrimitiveType.Void))
supportBefore.WriteLineIndent("{0}[i] = new global::System.IntPtr({1}[i]);",
value, Context.ReturnVarName);
else
{
var arrayType = array.Type.Desugar();
Class @class;
if (arrayType.TryGetClass(out @class) && @class.IsRefType)
supportBefore.WriteLineIndent(
"{0}[i] = {1}.{2}(*(({1}.{3}*)&({4}[i * sizeof({1}.{3})])));",
value, array.Type, Helpers.CreateInstanceIdentifier,
Helpers.InternalStruct, Context.ReturnVarName);
else
{
if (arrayType.IsPrimitiveType(PrimitiveType.Char) &&
Context.Context.Options.MarshalCharAsManagedChar)
{
supportBefore.WriteLineIndent(
"{0}[i] = global::System.Convert.ToChar({1}[i]);",
value, Context.ReturnVarName);
}
else
{
supportBefore.WriteLineIndent("{0}[i] = {1}[i];",
value, Context.ReturnVarName);
}
}
}
supportBefore.WriteCloseBraceIndent();
Context.Return.Write(value);
}
else
{
goto case ArrayType.ArraySize.Incomplete;
}
break;
case ArrayType.ArraySize.Incomplete:
// const char* and const char[] are the same so we can use a string
if (array.Type.Desugar().IsPrimitiveType(PrimitiveType.Char) &&
array.QualifiedType.Qualifiers.IsConst)
return VisitPointerType(new PointerType
{
QualifiedPointee = array.QualifiedType
}, quals);
MarshalArray(array);
break;
case ArrayType.ArraySize.Variable:
Context.Return.Write(Context.ReturnVarName);
break;
}
return true;
}
public override bool VisitPointerType(PointerType pointer, TypeQualifiers quals)
{
if (!VisitType(pointer, quals))
return false;
var param = Context.Parameter;
var isRefParam = param != null && (param.IsInOut || param.IsOut);
var pointee = pointer.Pointee.Desugar();
bool marshalPointeeAsString = CSharpTypePrinter.IsConstCharString(pointee) && isRefParam;
if ((CSharpTypePrinter.IsConstCharString(pointer) && !MarshalsParameter) ||
marshalPointeeAsString)
{
Context.Return.Write(MarshalStringToManaged(Context.ReturnVarName,
pointer.GetFinalPointee().Desugar() as BuiltinType));
return true;
}
var finalPointee = pointer.GetFinalPointee();
PrimitiveType primitive;
if (finalPointee.IsPrimitiveType(out primitive) || finalPointee.IsEnumType())
{
if (isRefParam)
{
Context.Return.Write("_{0}", param.Name);
return true;
}
if (Context.Context.Options.MarshalCharAsManagedChar &&
primitive == PrimitiveType.Char)
Context.Return.Write($"({pointer}) ");
var type = Context.ReturnType.Type.Desugar(
resolveTemplateSubstitution: false);
if (Context.Function != null &&
Context.Function.OperatorKind == CXXOperatorKind.Subscript)
{
if (type.IsPrimitiveType(primitive))
{
Context.Return.Write("*");
}
else
{
var templateParameter = type as TemplateParameterType;
if (templateParameter != null)
Context.Return.Write($@"({templateParameter.Parameter.Name}) (object) *");
}
}
Context.Return.Write(Context.ReturnVarName);
return true;
}
return pointer.QualifiedPointee.Visit(this);
}
private string MarshalStringToManaged(string varName, BuiltinType type)
{
var isChar = type.Type == PrimitiveType.Char;
var encoding = isChar ? Encoding.ASCII : Encoding.Unicode;
if (Equals(encoding, Encoding.ASCII))
encoding = Context.Context.Options.Encoding;
if (Equals(encoding, Encoding.ASCII))
return string.Format("Marshal.PtrToStringAnsi({0})", varName);
// If we reach this, we know the string is Unicode.
if (type.Type == PrimitiveType.Char ||
Context.Context.TargetInfo.WCharWidth == 16)
return string.Format("Marshal.PtrToStringUni({0})", varName);
// If we reach this, we should have an UTF-32 wide string.
const string encodingName = "System.Text.Encoding.UTF32";
return string.Format(
"CppSharp.Runtime.Helpers.MarshalEncodedString({0}, {1})",
varName, encodingName);
}
public override bool VisitPrimitiveType(PrimitiveType primitive, TypeQualifiers quals)
{
switch (primitive)
{
case PrimitiveType.Void:
return true;
case PrimitiveType.Char:
// returned structs must be blittable and char isn't
if (Context.Context.Options.MarshalCharAsManagedChar)
{
Context.Return.Write("global::System.Convert.ToChar({0})",
Context.ReturnVarName);
return true;
}
goto default;
case PrimitiveType.Char16:
return false;
case PrimitiveType.Bool:
if (Context.MarshalKind == MarshalKind.NativeField)
{
// returned structs must be blittable and bool isn't
Context.Return.Write("{0} != 0", Context.ReturnVarName);
return true;
}
goto default;
default:
Context.Return.Write(Context.ReturnVarName);
return true;
}
}
public override bool VisitTypedefType(TypedefType typedef, TypeQualifiers quals)
{
if (!VisitType(typedef, quals))
return false;
var decl = typedef.Declaration;
var functionType = decl.Type as FunctionType;
if (functionType != null || decl.Type.IsPointerTo(out functionType))
{
var ptrName = Generator.GeneratedIdentifier("ptr") +
Context.ParameterIndex;
Context.Before.WriteLine("var {0} = {1};", ptrName,
Context.ReturnVarName);
var res = $"{ptrName} == IntPtr.Zero? null : ({typedef})Marshal.GetDelegateForFunctionPointer({ptrName}, typeof({typedef}))";
Context.Return.Write(res);
return true;
}
return decl.Type.Visit(this);
}
public override bool VisitFunctionType(FunctionType function, TypeQualifiers quals)
{
var ptrName = Generator.GeneratedIdentifier("ptr") + Context.ParameterIndex;
Context.Before.WriteLine("var {0} = {1};", ptrName,
Context.ReturnVarName);
Context.Return.Write("({1})Marshal.GetDelegateForFunctionPointer({0}, typeof({1}))",
ptrName, function.ToString());
return true;
}
public override bool VisitClassDecl(Class @class)
{
var originalClass = @class.OriginalClass ?? @class;
Type returnType = Context.ReturnType.Type.Desugar();
// if the class is an abstract impl, use the original for the object map
var qualifiedClass = originalClass.Visit(typePrinter);
if (returnType.IsAddress())
Context.Return.Write(HandleReturnedPointer(@class, qualifiedClass.Type));
else
Context.Return.Write($"{qualifiedClass}.{Helpers.CreateInstanceIdentifier}({Context.ReturnVarName})");
var finalType = (returnType.GetFinalPointee() ?? returnType).Desugar();
Class returnedClass;
if (finalType.TryGetClass(out returnedClass) && returnedClass.IsDependent)
Context.Return.Write($" as {returnType.Visit(typePrinter)}");
return true;
}
public override bool VisitEnumDecl(Enumeration @enum)
{
Context.Return.Write("{0}", Context.ReturnVarName);
return true;
}
public override bool VisitParameterDecl(Parameter parameter)
{
if (parameter.Usage == ParameterUsage.Unknown || parameter.IsIn)
return base.VisitParameterDecl(parameter);
var ctx = new CSharpMarshalContext(Context.Context)
{
ReturnType = Context.ReturnType,
ReturnVarName = Context.ReturnVarName
};
var marshal = new CSharpMarshalNativeToManagedPrinter(ctx);
parameter.Type.Visit(marshal);
if (!string.IsNullOrWhiteSpace(ctx.Before))
Context.Before.WriteLine(ctx.Before);
if (!string.IsNullOrWhiteSpace(ctx.Return) &&
!parameter.Type.IsPrimitiveTypeConvertibleToRef())
{
Context.Before.WriteLine("var _{0} = {1};", parameter.Name,
ctx.Return);
}
Context.Return.Write("{0}{1}",
parameter.Type.IsPrimitiveTypeConvertibleToRef() ? "ref *" : "_", parameter.Name);
return true;
}
public override bool VisitTemplateParameterSubstitutionType(TemplateParameterSubstitutionType param, TypeQualifiers quals)
{
Context.Return.Write("({0}) (object) ", param.ReplacedParameter.Parameter.Name);
return base.VisitTemplateParameterSubstitutionType(param, quals);
}
private string HandleReturnedPointer(Class @class, string qualifiedClass)
{
var originalClass = @class.OriginalClass ?? @class;
var ret = Generator.GeneratedIdentifier("result") + Context.ParameterIndex;
var qualifiedIdentifier = @class.Visit(typePrinter);
Context.Before.WriteLine("{0} {1};", qualifiedIdentifier, ret);
Context.Before.WriteLine("if ({0} == IntPtr.Zero) {1} = {2};", Context.ReturnVarName, ret,
originalClass.IsRefType ? "null" : string.Format("new {0}()", qualifiedClass));
if (originalClass.IsRefType)
{
Context.Before.WriteLine(
"else if ({0}.NativeToManagedMap.ContainsKey({1}))", qualifiedClass, Context.ReturnVarName);
Context.Before.WriteLineIndent("{0} = ({1}) {2}.NativeToManagedMap[{3}];",
ret, qualifiedIdentifier, qualifiedClass, Context.ReturnVarName);
var dtor = originalClass.Destructors.FirstOrDefault();
if (dtor != null && dtor.IsVirtual)
{
Context.Before.WriteLine("else {0}{1} = ({2}) {3}.{4}({5}{6});",
MarshalsParameter
? string.Empty
: string.Format("{0}.NativeToManagedMap[{1}] = ", qualifiedClass, Context.ReturnVarName),
ret, qualifiedIdentifier, qualifiedClass, Helpers.CreateInstanceIdentifier, Context.ReturnVarName,
MarshalsParameter ? ", skipVTables: true" : string.Empty);
}
else
{
Context.Before.WriteLine("else {0} = {1}.{2}({3});", ret, qualifiedClass,
Helpers.CreateInstanceIdentifier, Context.ReturnVarName);
}
}
else
{
Context.Before.WriteLine("else {0} = {1}.{2}({3});", ret, qualifiedClass,
Helpers.CreateInstanceIdentifier, Context.ReturnVarName);
}
return ret;
}
private void MarshalArray(ArrayType array)
{
Type arrayType = array.Type.Desugar();
if (arrayType.IsPrimitiveType() ||
arrayType.IsPointerToPrimitiveType() ||
Context.MarshalKind != MarshalKind.GenericDelegate)
{
Context.Return.Write(Context.ReturnVarName);
return;
}
var intermediateArray = Generator.GeneratedIdentifier(Context.ReturnVarName);
var intermediateArrayType = arrayType.Visit(typePrinter);
Context.Before.WriteLine($"{intermediateArrayType}[] {intermediateArray};");
Context.Before.WriteLine($"if (ReferenceEquals({Context.ReturnVarName}, null))");
Context.Before.WriteLineIndent($"{intermediateArray} = null;");
Context.Before.WriteLine("else");
Context.Before.WriteStartBraceIndent();
Context.Before.WriteLine($@"{intermediateArray} = new {
intermediateArrayType}[{Context.ReturnVarName}.Length];");
Context.Before.WriteLine($"for (int i = 0; i < {intermediateArray}.Length; i++)");
if (arrayType.IsAddress())
{
Context.Before.WriteStartBraceIndent();
string element = Generator.GeneratedIdentifier("element");
Context.Before.WriteLine($"var {element} = {Context.ReturnVarName}[i];");
var intPtrZero = $"{CSharpTypePrinter.IntPtrType}.Zero";
Context.Before.WriteLine($@"{intermediateArray}[i] = {element} == {
intPtrZero} ? null : {intermediateArrayType}.{
Helpers.CreateInstanceIdentifier}({element});");
Context.Before.WriteCloseBraceIndent();
}
else
Context.Before.WriteLineIndent($@"{intermediateArray}[i] = {
intermediateArrayType}.{Helpers.CreateInstanceIdentifier}({
Context.ReturnVarName}[i]);");
Context.Before.WriteCloseBraceIndent();
Context.Return.Write(intermediateArray);
}
private readonly CSharpTypePrinter typePrinter;
}
public class CSharpMarshalManagedToNativePrinter : CSharpMarshalPrinter
{
public CSharpMarshalManagedToNativePrinter(CSharpMarshalContext context)
: base(context)
{
typePrinter = new CSharpTypePrinter(context.Context);
}
public override bool VisitType(Type type, TypeQualifiers quals)
{
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling)
{
typeMap.Type = type;
typeMap.CSharpMarshalToNative(Context);
return false;
}
return true;
}
public override bool VisitDeclaration(Declaration decl)
{
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(decl, out typeMap) && typeMap.DoesMarshalling)
{
typeMap.Declaration = decl;
typeMap.CSharpMarshalToNative(Context);
return false;
}
return true;
}
public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
{
if (!VisitType(array, quals))
return false;
var arrayType = array.Type.Desugar();
switch (array.SizeType)
{
case ArrayType.ArraySize.Constant:
if (string.IsNullOrEmpty(Context.ReturnVarName))
{
goto case ArrayType.ArraySize.Incomplete;
}
else
{
var supportBefore = Context.Before;
supportBefore.WriteLine("if ({0} != null)", Context.ArgName);
supportBefore.WriteStartBraceIndent();
Class @class;
if (arrayType.TryGetClass(out @class) && @class.IsRefType)
{
supportBefore.WriteLine("if (value.Length != {0})", array.Size);
ThrowArgumentOutOfRangeException();
}
supportBefore.WriteLine("for (int i = 0; i < {0}; i++)", array.Size);
if (@class != null && @class.IsRefType)
{
supportBefore.WriteLineIndent(
"*({1}.{2}*) &{0}[i * sizeof({1}.{2})] = *({1}.{2}*){3}[i].{4};",
Context.ReturnVarName, arrayType, Helpers.InternalStruct,
Context.ArgName, Helpers.InstanceIdentifier);
}
else
{
if (arrayType.IsPrimitiveType(PrimitiveType.Char) &&
Context.Context.Options.MarshalCharAsManagedChar)
{
supportBefore.WriteLineIndent(
"{0}[i] = global::System.Convert.ToSByte({1}[i]);",
Context.ReturnVarName, Context.ArgName);
}
else
{
supportBefore.WriteLineIndent("{0}[i] = {1}[i]{2};",
Context.ReturnVarName,
Context.ArgName,
arrayType.IsPointerToPrimitiveType(PrimitiveType.Void)
? ".ToPointer()"
: string.Empty);
}
}
supportBefore.WriteCloseBraceIndent();
}
break;
case ArrayType.ArraySize.Incomplete:
MarshalArray(array);
break;
default:
Context.Return.Write("null");
break;
}
return true;
}
public override bool VisitPointerType(PointerType pointer, TypeQualifiers quals)
{
if (!VisitType(pointer, quals))
return false;
var pointee = pointer.Pointee.Desugar();
if (Context.Function != null && pointer.IsPrimitiveTypeConvertibleToRef() &&
Context.MarshalKind != MarshalKind.VTableReturnValue &&
Context.Function.OperatorKind != CXXOperatorKind.Subscript)
{
var refParamPtr = string.Format("__refParamPtr{0}", Context.ParameterIndex);
var templateSubstitution = pointer.Pointee as TemplateParameterSubstitutionType;
if (templateSubstitution != null)
{
var castParam = $"__{Context.Parameter.Name}{Context.ParameterIndex}";
Context.Before.WriteLine(
$"var {castParam} = ({templateSubstitution}) (object) {Context.Parameter.Name};");
Context.Before.WriteLine($"{pointer} {refParamPtr} = &{castParam};");
Context.Return.Write(refParamPtr);
}
else
{
if (Context.Parameter.Kind == ParameterKind.PropertyValue)
{
Context.Return.Write($"&{Context.Parameter.Name}");
}
else
{
Context.Before.WriteLine(
$"fixed ({pointer} {refParamPtr} = &{Context.Parameter.Name})");
Context.HasCodeBlock = true;
Context.Before.WriteStartBraceIndent();
Context.Return.Write(refParamPtr);
}
}
return true;
}
var param = Context.Parameter;
var isRefParam = param != null && (param.IsInOut || param.IsOut);
if (CSharpTypePrinter.IsConstCharString(pointee) && isRefParam)
{
if (param.IsOut)
{
Context.Return.Write("IntPtr.Zero");
Context.ArgumentPrefix.Write("&");
}
else if (param.IsInOut)
{
Context.Return.Write(MarshalStringToUnmanaged(Context.Parameter.Name));
Context.ArgumentPrefix.Write("&");
}
else
{
Context.Return.Write(MarshalStringToUnmanaged(Context.Parameter.Name));
Context.Cleanup.WriteLine("Marshal.FreeHGlobal({0});", Context.ArgName);
}
return true;
}
if (pointee is FunctionType)
return VisitDelegateType();
Class @class;
if (pointee.TryGetClass(out @class) && @class.IsValueType)
{
if (Context.Parameter.Usage == ParameterUsage.Out)
{
var qualifiedIdentifier = (@class.OriginalClass ?? @class).Visit(typePrinter);
Context.Before.WriteLine("var {0} = new {1}.{2}();",
Generator.GeneratedIdentifier(Context.ArgName), qualifiedIdentifier,
Helpers.InternalStruct);
}
else
{
Context.Before.WriteLine("var {0} = {1}.{2};",
Generator.GeneratedIdentifier(Context.ArgName),
Context.Parameter.Name,
Helpers.InstanceIdentifier);
}
Context.Return.Write("new global::System.IntPtr(&{0})",
Generator.GeneratedIdentifier(Context.ArgName));
return true;
}
var marshalAsString = CSharpTypePrinter.IsConstCharString(pointer);
var finalPointee = pointer.GetFinalPointee();
PrimitiveType primitive;
if (finalPointee.IsPrimitiveType(out primitive) || finalPointee.IsEnumType() ||
marshalAsString)
{
// From MSDN: "note that a ref or out parameter is classified as a moveable
// variable". This means we must create a local variable to hold the result
// and then assign this value to the parameter.
if (isRefParam)
{
var typeName = Type.TypePrinterDelegate(finalPointee);
if (Context.Function.OperatorKind == CXXOperatorKind.Subscript)
Context.Return.Write(param.Name);
else
{
if (param.IsInOut)
Context.Before.WriteLine($"{typeName} _{param.Name} = {param.Name};");
else
Context.Before.WriteLine($"{typeName} _{param.Name};");
Context.Return.Write($"&_{param.Name}");
}
}
else
{
if (!marshalAsString &&
Context.Context.Options.MarshalCharAsManagedChar &&
primitive == PrimitiveType.Char)
Context.Return.Write($"({typePrinter.PrintNative(pointer)}) ");
if (marshalAsString && (Context.MarshalKind == MarshalKind.NativeField ||
Context.MarshalKind == MarshalKind.VTableReturnValue ||
Context.MarshalKind == MarshalKind.Variable))
Context.Return.Write(MarshalStringToUnmanaged(Context.Parameter.Name));
else
Context.Return.Write(Context.Parameter.Name);
}
return true;
}
return pointer.QualifiedPointee.Visit(this);
}
private string MarshalStringToUnmanaged(string varName)
{
if (Equals(Context.Context.Options.Encoding, Encoding.ASCII))
{
return string.Format("Marshal.StringToHGlobalAnsi({0})", varName);
}
if (Equals(Context.Context.Options.Encoding, Encoding.Unicode) ||
Equals(Context.Context.Options.Encoding, Encoding.BigEndianUnicode))
{
return string.Format("Marshal.StringToHGlobalUni({0})", varName);
}
throw new NotSupportedException(string.Format("{0} is not supported yet.",
Context.Context.Options.Encoding.EncodingName));
}
public override bool VisitPrimitiveType(PrimitiveType primitive, TypeQualifiers quals)
{
switch (primitive)
{
case PrimitiveType.Void:
return true;
case PrimitiveType.Char:
// returned structs must be blittable and char isn't
if (Context.Context.Options.MarshalCharAsManagedChar)
{
Context.Return.Write("global::System.Convert.ToSByte({0})",
Context.Parameter.Name);
return true;
}
goto default;
case PrimitiveType.Char16:
return false;
case PrimitiveType.Bool:
if (Context.MarshalKind == MarshalKind.NativeField)
{
// returned structs must be blittable and bool isn't
Context.Return.Write("(byte) ({0} ? 1 : 0)", Context.Parameter.Name);
return true;
}
goto default;
default:
Context.Return.Write(Context.Parameter.Name);
return true;
}
}
public override bool VisitTypedefType(TypedefType typedef, TypeQualifiers quals)
{
if (!VisitType(typedef, quals))
return false;
var decl = typedef.Declaration;
FunctionType func;
if (decl.Type.IsPointerTo(out func))
{
VisitDelegateType();
return true;
}
return decl.Type.Visit(this);
}
public override bool VisitTemplateParameterSubstitutionType(TemplateParameterSubstitutionType param, TypeQualifiers quals)
{
var replacement = param.Replacement.Type.Desugar();
Class @class;
if (!replacement.IsAddress() && !replacement.TryGetClass(out @class))
Context.Return.Write($"({replacement}) (object) ");
return base.VisitTemplateParameterSubstitutionType(param, quals);
}
public override bool VisitTemplateParameterType(TemplateParameterType param, TypeQualifiers quals)
{
Context.Return.Write(param.Parameter.Name);
return true;
}
public override bool VisitClassDecl(Class @class)
{
if (!VisitDeclaration(@class))
return false;
if (@class.IsValueType)
{
MarshalValueClass();
}
else
{
MarshalRefClass(@class);
}
return true;
}
private void MarshalRefClass(Class @class)
{
var method = Context.Function as Method;
if (method != null
&& method.Conversion == MethodConversionKind.FunctionToInstanceMethod
&& Context.ParameterIndex == 0)
{
Context.Return.Write("{0}", Helpers.InstanceIdentifier);
return;
}
string param = Context.Parameter.Name;
Type type = Context.Parameter.Type.Desugar(resolveTemplateSubstitution: false);
string paramInstance;
Class @interface;
var finalType = type.GetFinalPointee() ?? type;
var templateType = finalType as TemplateParameterSubstitutionType;
type = Context.Parameter.Type.Desugar();
if (finalType.TryGetClass(out @interface) &&
@interface.IsInterface)
paramInstance = $"{param}.__PointerTo{@interface.OriginalClass.Name}";
else
paramInstance = $@"{
(templateType != null ? $"(({@class.Visit(typePrinter)}) (object) " : string.Empty)}{
param}{(templateType != null ? ")" : string.Empty)
}.{Helpers.InstanceIdentifier}";
if (type.IsAddress())
{
Class decl;
if (type.TryGetClass(out decl) && decl.IsValueType)
Context.Return.Write(paramInstance);
else
{
if (type.IsPointer())
{
Context.Return.Write("{0}{1}",
method != null && method.OperatorKind == CXXOperatorKind.EqualEqual
? string.Empty
: $"ReferenceEquals({param}, null) ? global::System.IntPtr.Zero : ",
paramInstance);
}
else
{
if (method == null ||
// redundant for comparison operators, they are handled in a special way
(method.OperatorKind != CXXOperatorKind.EqualEqual &&
method.OperatorKind != CXXOperatorKind.ExclaimEqual))
{
Context.Before.WriteLine("if (ReferenceEquals({0}, null))", param);
Context.Before.WriteLineIndent(
"throw new global::System.ArgumentNullException(\"{0}\", " +
"\"Cannot be null because it is a C++ reference (&).\");",
param);
}
Context.Return.Write(paramInstance);
}
}
return;
}
var realClass = @class.OriginalClass ?? @class;
var qualifiedIdentifier = typePrinter.PrintNative(realClass);
Context.Return.Write(
"ReferenceEquals({0}, null) ? new {1}() : *({1}*) {2}",
param, qualifiedIdentifier, paramInstance);
}
private void MarshalValueClass()
{
Context.Return.Write("{0}.{1}", Context.Parameter.Name, Helpers.InstanceIdentifier);
}
public override bool VisitFieldDecl(Field field)
{
if (!VisitDeclaration(field))
return false;
Context.Parameter = new Parameter
{
Name = Context.ArgName,
QualifiedType = field.QualifiedType
};
return field.Type.Visit(this, field.QualifiedType.Qualifiers);
}
public override bool VisitProperty(Property property)
{
if (!VisitDeclaration(property))
return false;
Context.Parameter = new Parameter
{
Name = Context.ArgName,
QualifiedType = property.QualifiedType
};
return base.VisitProperty(property);
}
public override bool VisitEnumDecl(Enumeration @enum)
{
Context.Return.Write(Context.Parameter.Name);
return true;
}
public override bool VisitClassTemplateDecl(ClassTemplate template)
{
return VisitClassDecl(template.TemplatedClass);
}
public override bool VisitFunctionTemplateDecl(FunctionTemplate template)
{
return template.TemplatedFunction.Visit(this);
}
private bool VisitDelegateType()
{
Context.Return.Write("{0} == null ? global::System.IntPtr.Zero : Marshal.GetFunctionPointerForDelegate({0})",
Context.Parameter.Name);
return true;
}
private void ThrowArgumentOutOfRangeException()
{
Context.Before.WriteLineIndent(
"throw new ArgumentOutOfRangeException(\"{0}\", " +
"\"The dimensions of the provided array don't match the required size.\");",
Context.Parameter.Name);
}
private void MarshalArray(ArrayType arrayType)
{
if (arrayType.SizeType == ArrayType.ArraySize.Constant)
{
Context.Before.WriteLine("if ({0} == null || {0}.Length != {1})",
Context.Parameter.Name, arrayType.Size);
ThrowArgumentOutOfRangeException();
}
var elementType = arrayType.Type.Desugar();
if (elementType.IsPrimitiveType() ||
elementType.IsPointerToPrimitiveType())
{
Context.Return.Write(Context.Parameter.Name);
return;
}
var intermediateArray = Generator.GeneratedIdentifier(Context.Parameter.Name);
var intermediateArrayType = typePrinter.PrintNative(elementType);
Context.Before.WriteLine($"{intermediateArrayType}[] {intermediateArray};");
Context.Before.WriteLine($"if (ReferenceEquals({Context.Parameter.Name}, null))");
Context.Before.WriteLineIndent($"{intermediateArray} = null;");
Context.Before.WriteLine("else");
Context.Before.WriteStartBraceIndent();
Context.Before.WriteLine($@"{intermediateArray} = new {
intermediateArrayType}[{Context.Parameter.Name}.Length];");
Context.Before.WriteLine($"for (int i = 0; i < {intermediateArray}.Length; i++)");
Context.Before.WriteStartBraceIndent();
string element = Generator.GeneratedIdentifier("element");
Context.Before.WriteLine($"var {element} = {Context.Parameter.Name}[i];");
if (elementType.IsAddress())
{
var intPtrZero = $"{CSharpTypePrinter.IntPtrType}.Zero";
Context.Before.WriteLine($@"{intermediateArray}[i] = ReferenceEquals({
element}, null) ? {intPtrZero} : {element}.{Helpers.InstanceIdentifier};");
}
else
Context.Before.WriteLine($@"{intermediateArray}[i] = ReferenceEquals({
element}, null) ? new {intermediateArrayType}() : *({
intermediateArrayType}*) {element}.{Helpers.InstanceIdentifier};");
Context.Before.WriteCloseBraceIndent();
Context.Before.WriteCloseBraceIndent();
Context.Return.Write(intermediateArray);
}
private readonly CSharpTypePrinter typePrinter;
}
}
| |
// 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 System.Collections.Generic;
using DaydreamElements.Common;
using DaydreamElements.Common.IconMenu;
namespace DaydreamElements.ConstellationMenu {
/// A network of icons laid out in concentric circles.
//
// Initialize() must be called on the top icon
// ShowMenu() creates each deeper layer of icons.
//
// Icons can be in the following states:
// * Shown - Fully shown
// * Hidden - The icon is still displayed, but is more transparent. The collision size is reduced
// from the Shown state.
// * Hovering - The hovering icon changes the behavior, appearance, and position of other icons.
// * Closed - In the process of being removed.
//
// Icon appearance will depend on relationship with the hover icon. Relationships may be:
// * AncestorOfRhs - Has a background a tooltip and a line to its parent,
// * DescendantOfRhs - Same but the background is faded out a little bit
// * UnkownRelationship - No background or tooltip and is harder to select.
[RequireComponent(typeof(LineRenderer))]
[RequireComponent(typeof(SpriteRenderer))]
[RequireComponent(typeof(BoxCollider))]
public class ConstellationMenuIcon : MonoBehaviour,
IPointerEnterHandler,
IPointerExitHandler {
/// Distance between the background and foreground icons in meters.
private const float BACKGROUND_ICON_ZOFFSET = -0.005f;
private const float CHILD_LINE_ZOFFSET = -0.01f;
private const float PARENT_LINE_ZOFFSET = -0.04f;
/// Radius from center to menu item in units of scale.
private const float ITEM_SPACING = 0.15f;
/// Size of collision box used to detect selection
private const float COLLIDER_SIZE = 1.0f;
/// Size of collision box when the icon is "hidden"
private const float HIDDEN_COLLIDER_SIZE = 0.7f;
/// Moves items closer together when there are not many of them in the menu layer
private const float MAX_DISTANCE_BETWEEN_ITEMS = 0.1f;
/// The spacing for this many items is the minimum spacing.
private const int MIN_ITEM_SPACE = 5;
/// Time for the fading animations in seconds.
private const float ANIMATION_DURATION_SECONDS = 0.24f;
/// Scaling factor for the tooltip text.
private const float TOOLTIP_TEXT_SCALE = 0.1f;
/// Distance between center of icon and the tooltip
private float TOOLTIP_TEXT_OFFSET = -0.7f;
/// Scaling factor for tooltip sprites.
private float TOOLTIP_SPRITE_SCALE = 1.0f;
/// Distance between center of icon and the tooltip sprite
private float TOOLTIP_SPRITE_OFFSET = -0.5f;
/// Shifts each layer of icons away from selection layer progressively.
private const float ICON_SELECTION_OFFSET_FACTOR = -0.10f;
/// Shifts the entire menu further away as the visible graph gets deeper.
private const float MENU_SELECTION_OFFSET_FACTOR = -0.025f;
/// Sets both size and position of icon based on state
private const float DEFAULT_ICON_SCALE = 0.0f;
private const float SHOWN_ICON_SCALE = 1.0f;
/// Sets transparency of icon based on state
private const float DEFAULT_ICON_ALPHA = 0.0f;
private const float HIDDEN_ICON_ALPHA = 0.6f;
private const float SHOWN_ICON_ALPHA = 1.0f;
/// Set icon's background alpha depending on state and relationship to the hover icon.
private const float DEFAULT_ICON_BG_ALPHA = 0.0f;
private const float CLOSED_ICON_BG_ALPHA = 0.0f;
private const float ANCESTOR_ICON_BG_ALPHA = 0.9f;
private const float DESCENDANT_ICON_BG_ALPHA = 0.6f;
// Sets icon decoration label alpha based on state, children, and relationship to hover icon.
private const float DESCENDANT_DECORATION_LABEL_ALPHA = .6f;
private const float DEFAULT_DECORATION_LABEL_ALPHA = 0.0f;
private const float DEFAULT_TOOLTIP_ALPHA = 0.0f;
private const float SELECTED_PATH_TOOLTIP_ALPHA = 1.0f;
private static Color CLEAR_WHITE = new Color(1.0f, 1.0f, 1.0f, 0.0f);
/// Cached storage for line points.
private Vector3[] lineToParentPositions = new Vector3[2];
private LineRenderer lineToParent;
private Vector3 startPosition;
private Vector3 startScale;
private Vector3 menuCenter;
private Quaternion menuOrientation;
private float menuScale;
private ConstellationMenuIcon parentMenu;
private List<ConstellationMenuIcon> childMenus;
private GameObject background;
private ConstellationMenuItem menuItem;
private AssetTree.Node menuNode;
/// Manages events for all icons in the menu.
public ConstellationMenuRoot menuRoot { private get; set; }
private GameObject tooltip;
private BoxCollider boxCollider;
private MaterialPropertyBlock propertyBlock;
private SpriteRenderer spriteRenderer;
private SpriteRenderer backgroundSpriteRenderer;
private Renderer tooltipRenderer;
// Each icon is shifted in Z based on what other icons are showing.
private IconValue selectionOffset;
// The background is shown or hidden based on which icon is hovering.
private IconValue iconBgAlpha = new IconValue(DEFAULT_ICON_BG_ALPHA);
// The icon fades in/out when Shown/Closed
private IconValue iconAlpha = new IconValue(DEFAULT_ICON_ALPHA);
private IconValue iconScale = new IconValue(DEFAULT_ICON_SCALE);
private IconValue tooltipAlpha = new IconValue(DEFAULT_TOOLTIP_ALPHA);
/// Each icon's orientation is based on the camera transform when the first icon was created.
private Vector3 savedCameraPosition;
private Quaternion savedCameraRotation;
// set when this icon starts a hover.
private float hoverStartTime;
// current sensitivity to the laser pointer.
private float hoverDelaySeconds;
private float angleToRoot;
public int MenuLayer {
get {
int depth = 0;
var next = this;
while (next.parentMenu != null) {
++depth;
next = next.parentMenu;
}
return depth;
}
}
/// returns true if behavior or visual parameters are changing.
private bool IsFadeInProgress {
get {
return (parentMenu != null) && fadeInProgress;
}
}
/// True while the laser is pointing at this icon
private bool selected;
/// Set when the laser starts pointing at this icon
private float selectionStartTime;
/// True if the button can be "selected"
private bool buttonActive;
/// True after state change while visual parameters are changing.
private bool fadeInProgress;
/// State determines visual parameters and logical behavior of the icon
private IconState state = IconState.Closed;
/// Visual parameters to use for the icon's next state.
private FadeParameters fadeParameters;
[SerializeField]
private GameObject tooltipPrefab;
/// If the icon can be expanded, this prefab will be instantiated as a decoration label.
[SerializeField]
private GameObject decorationLabelPrefab = null;
private SpriteRenderer decorationLabelRenderer;
private GameObject decorationLabel;
private IconValue decorationLabelAlpha = new IconValue(DEFAULT_DECORATION_LABEL_ALPHA);
/// Describes how a button should behave in a particular state.
public class FadeParameters {
public FadeParameters(IconState nextState) {
state = nextState;
switch (state) {
case IconState.Shown:
alpha = SHOWN_ICON_ALPHA;
buttonActive = true;
colliderSize = COLLIDER_SIZE;
break;
case IconState.Hovering:
alpha = SHOWN_ICON_ALPHA;
buttonActive = true;
colliderSize = COLLIDER_SIZE;
break;
case IconState.Hidden:
alpha = HIDDEN_ICON_ALPHA;
buttonActive = true;
colliderSize = HIDDEN_COLLIDER_SIZE;
break;
case IconState.Closed:
alpha = DEFAULT_ICON_ALPHA;
buttonActive = false;
colliderSize = 0.0f;
break;
}
}
public IconState state;
public float colliderSize;
public float duration;
public float alpha;
public bool buttonActive = false;
};
/// Get visual parameters and logical behavior of the icon.
public IconState State {
get { return state; }
}
void Awake() {
boxCollider = GetComponent<BoxCollider>();
propertyBlock = new MaterialPropertyBlock();
spriteRenderer = GetComponent<SpriteRenderer>();
childMenus = new List<ConstellationMenuIcon>();
buttonActive = false;
selected = false;
}
/// A "dummy" icon will be invisible and non-interactable
/// The top icon in the hierarchy will be a dummy icon
public void SetDummy() {
buttonActive = false;
}
/// The minimal preparation for use. If these are not set ShowChildLayer() can't work.
public void Initialize(ConstellationMenuRoot root, AssetTree.Node asset, float scale) {
menuRoot = root;
menuRoot.MarkGraphDirty();
menuNode = asset;
menuScale = scale;
menuOrientation = transform.rotation;
menuCenter = transform.position;
startPosition = transform.position;
savedCameraPosition = Camera.main.transform.position;
savedCameraRotation = Camera.main.transform.rotation;
state = IconState.Shown;
}
/// Called to make this icon visible and interactable
public void Initialize(ConstellationMenuRoot root, ConstellationMenuIcon _parentMenu, AssetTree.Node node,
Vector3 _menuCenter, float scale, IconState initialState) {
parentMenu = _parentMenu;
startPosition = transform.position;
startScale = transform.localScale;
menuRoot = root;
menuNode = node;
menuCenter = _menuCenter;
savedCameraPosition = _parentMenu.savedCameraPosition;
savedCameraRotation = _parentMenu.savedCameraRotation;
menuOrientation = transform.rotation;
// Icons are oriented up in world space.
Vector3 iconToCamera = savedCameraPosition - transform.position;
Quaternion rotationToCamera = Quaternion.FromToRotation(-transform.forward, iconToCamera.normalized);
transform.localRotation = rotationToCamera * transform.localRotation;
menuScale = scale;
background = null;
state = IconState.Closed;
if (node != null) {
// Set foreground icon
menuItem = (ConstellationMenuItem)node.value;
spriteRenderer.sprite = menuItem.icon;
gameObject.name = menuItem.name;
// Set background icon
background = new GameObject(name + " Item Background");
background.transform.parent = transform.parent;
background.transform.localPosition = transform.localPosition + transform.forward * BACKGROUND_ICON_ZOFFSET;
background.transform.localRotation = transform.localRotation;
background.transform.localScale = transform.localScale;
backgroundSpriteRenderer = background.AddComponent<SpriteRenderer>();
backgroundSpriteRenderer.sprite = menuRoot.iconBackground;
if (menuNode.children.Count != 0 &&
decorationLabelPrefab != null &&
menuRoot.expandableIconDecoration) {
decorationLabel = Instantiate(decorationLabelPrefab, background.transform);
decorationLabelRenderer = decorationLabel.GetComponent<SpriteRenderer>();
decorationLabelRenderer.sprite = menuRoot.expandableIconDecoration;
decorationLabel.SetActive(false);
}
menuRoot.MarkGraphDirty();
float tooltipOffset;
if (menuItem.tooltipSprite) {
tooltip = new GameObject(name + " Tooltip Sprite");
SpriteRenderer tooltipSpriteRenderer = tooltip.AddComponent<SpriteRenderer>();
tooltipSpriteRenderer.sprite = menuItem.tooltipSprite;
tooltipRenderer = tooltipSpriteRenderer;
tooltip.transform.localScale *= TOOLTIP_SPRITE_SCALE;
tooltipOffset = TOOLTIP_SPRITE_OFFSET;
} else {
tooltip = Instantiate(tooltipPrefab);
tooltip.name = name + " Tooltip Text";
tooltip.GetComponent<TextMesh>().text = menuItem.toolTip.Replace('\\', '\n');
tooltipRenderer = tooltip.GetComponent<MeshRenderer>();
tooltip.transform.localScale = Vector3.one * TOOLTIP_TEXT_SCALE;
tooltipOffset = TOOLTIP_TEXT_OFFSET;
}
tooltip.transform.SetParent(transform, false);
tooltip.transform.localPosition = Vector3.up * tooltipOffset;
tooltip.transform.rotation = transform.rotation;
SetRendererAlpha(tooltipRenderer, DEFAULT_TOOLTIP_ALPHA);
}
parentMenu.childMenus.Add(this);
lineToParent = GetComponent<LineRenderer>();
lineToParent.startColor = Color.clear;
lineToParent.endColor = Color.clear;
UpdateLines();
SetDecorationLabelAlpha(decorationLabelAlpha.ValueAtTime(Time.time));
SetBackgroundTransparency(iconBgAlpha.ValueAtTime(Time.time));
SetRendererAlpha(spriteRenderer, iconAlpha.ValueAtTime(Time.time));
StartFade(initialState);
SetColliderSize(0.0f);
}
private void UpdateSelectionOffset() {
if (state == IconState.Closed) {
// Closing icons changes the menu depth.
// Prevent Closing icons from moving as they fade out.
return;
}
float deepestMenuLayer = menuRoot.MenuDepth();
// Calculates distance from camera based on the deepestIcon
float offset = Mathf.Max(0.0f, (deepestMenuLayer - MenuLayer)) * ICON_SELECTION_OFFSET_FACTOR
+ deepestMenuLayer * MENU_SELECTION_OFFSET_FACTOR;
selectionOffset.FadeTo(offset, ANIMATION_DURATION_SECONDS, Time.time);
}
private void UpdateLines() {
if (!parentMenu) {
return;
}
Vector3 parentEndpoint = parentMenu.transform.position - transform.forward * PARENT_LINE_ZOFFSET;
Vector3 childEndpoint = transform.position - transform.forward * CHILD_LINE_ZOFFSET;
Vector3 delta = childEndpoint - parentEndpoint;
float shortenedLength = delta.magnitude - menuRoot.lineShorteningDistance;
if (shortenedLength < 0) {
lineToParent.enabled = false;
return;
}
lineToParent.enabled = true;
delta.Normalize();
Vector3 halfLine = delta.normalized * shortenedLength * 0.5f;
Vector3 midpoint = (childEndpoint + parentEndpoint) * 0.5f;
lineToParentPositions[0] = midpoint - halfLine;
lineToParentPositions[1] = midpoint + halfLine;
lineToParent.SetPositions(lineToParentPositions);
}
/// Creates and shows a layer of icons below this one.
/// Returns true if a fade needs to occur.
public static bool ShowMenu(ConstellationMenuRoot root, AssetTree.Node treeNode, ConstellationMenuIcon parent,
Quaternion orientation, float scale,
IconState initialState = IconState.Shown) {
// Determine how many children are in the sub-menu
List<AssetTree.Node> childItems = treeNode.children;
// If this is the end of a menu, invoke the action and return early
if (childItems.Count == 0) {
root.MakeSelection(parent.menuItem);
root.CloseAll();
return false;
}
if (parent.childMenus.Count == childItems.Count) {
// children already exist. just fade them in.
bool stateChanged = false;
foreach (ConstellationMenuIcon child in parent.childMenus) {
if (child.StartFade(initialState)) {
stateChanged = true;
}
// Close any children.
child.FadeChildren(IconState.Closed);
}
return stateChanged;
}
List<Vector3> childPositions;
float radius;
if (parent.parentMenu != null) {
radius = (parent.menuCenter - parent.startPosition).magnitude + ITEM_SPACING;
childPositions = ArrangeInCircle(childItems.Count, radius,
parent.angleToRoot - Mathf.PI * .5f,
parent.angleToRoot + Mathf.PI * .5f,
ITEM_SPACING);
} else {
// Radius needs to expand when there are more icons
radius = ITEM_SPACING * Mathf.Max(childItems.Count, MIN_ITEM_SPACE) / (2.0f * Mathf.PI);
// add one unused position to item positions
childPositions = ArrangeInCircle(childItems.Count + 1, radius);
}
for (int i = 0; i < childItems.Count; ++i) {
Vector3 posOffset = childPositions[i];
ConstellationMenuIcon childMenu = (ConstellationMenuIcon)Instantiate(root.menuIconPrefab, root.transform);
childMenu.transform.position = parent.menuCenter + (orientation * posOffset);
childMenu.transform.rotation = orientation;
childMenu.transform.localScale = Vector3.one * scale;
childMenu.Initialize(root, parent, childItems[i], parent.menuCenter, scale, initialState);
childMenu.angleToRoot = Mathf.Atan2(posOffset[1], posOffset[0]);
}
return true;
}
/// Create and arrange the icons in a circle
private static List<Vector3> ArrangeInCircle(int numItems,
float radius,
float startingAngle = 0,
float stoppingAngle = 2.0f * Mathf.PI,
float maximumDistanceBetweenIcons = -1) {
var results = new List<Vector3>();
if (numItems == 1) {
float angle = startingAngle + (stoppingAngle - startingAngle) / 2;
results.Add(new Vector3(Mathf.Cos(angle), Mathf.Sin(angle), 0.0f) * radius);
} else {
float maxAngleBetweenIcons = 2.0f * Mathf.Asin(maximumDistanceBetweenIcons / (2.0f * radius));
float angleBetweenIcons = (stoppingAngle - startingAngle) / (numItems - 1);
if (maximumDistanceBetweenIcons > 0 && angleBetweenIcons > maxAngleBetweenIcons) {
// Shrink the range between start_angle and end_angle so that items are closer together.
angleBetweenIcons = maxAngleBetweenIcons;
startingAngle = startingAngle + (stoppingAngle - startingAngle
- maxAngleBetweenIcons * (numItems - 1)) / 2;
stoppingAngle = startingAngle + maxAngleBetweenIcons * (numItems - 1);
}
for (int i = 0; i < numItems; ++i) {
float angle = startingAngle + (i) * angleBetweenIcons;
results.Add(new Vector3(Mathf.Cos(angle), Mathf.Sin(angle), 0.0f) * radius);
}
}
return results;
}
/// Creates and shows a layer of icons below this one.
/// Returns true if a fade starts.
private bool ShowChildLayer(IconState state = IconState.Shown) {
return ShowMenu(menuRoot, menuNode, this, menuOrientation, menuScale, state);
}
/// Closes layers deeper than this. Shows sibling icons in the same layer.
public void ShowThisLayer(IconState initialState) {
if (parentMenu == null) {
// The root icon has no siblings. Close everything.
menuRoot.CloseAll();
} else {
FadeChildren(IconState.Closed);
parentMenu.ShowChildLayer(initialState);
}
}
/// Fades out and closes all ConstellationMenuIcon's icons except those between the root and
/// this node. Ignores children nodes.
public void HideAllExceptParentsAndChildren() {
ConstellationMenuIcon menu = this;
ConstellationMenuIcon parent = menu.parentMenu;
while (parent != null) {
foreach (var sibling in parent.childMenus) {
if (sibling != menu) {
sibling.FadeChildren(IconState.Closed);
sibling.StartFade(IconState.Hidden);
}
}
menu = parent;
parent = parent.parentMenu;
}
}
void Update() {
if (state == IconState.Closed) {
// If we are closing make sure children close first.
FadeChildren(IconState.Closed);
if (!IsFadeInProgress && childMenus.Count == 0) {
// After fade finishes and children close, destroy this object
Destroy(gameObject);
}
}
// The top menu can not be selected and has no visuals attached.
if (parentMenu == null) {
return;
}
HoverIfNeeded();
ContinueFade();
SetDecorationLabelAlpha(decorationLabelAlpha.ValueAtTime(Time.time));
SetBackgroundTransparency(iconBgAlpha.ValueAtTime(Time.time));
SetRendererAlpha(tooltipRenderer, tooltipAlpha.ValueAtTime(Time.time));
if (buttonActive) {
if (selected && (GvrControllerInput.ClickButtonDown)) {
menuRoot.MakeSelection(menuItem);
if (childMenus.Count == 0) {
menuRoot.CloseAll();
}
}
}
}
void LateUpdate() {
if (!parentMenu) {
return;
}
// selectionOffset depends on the state of other nodes, so we change it in LateUpdate
UpdateSelectionOffset();
SetScaleAndPosition(iconScale.ValueAtTime(Time.time), selectionOffset.ValueAtTime(Time.time));
}
/// Shrink / Grow button
// scaleAndOffset is the scale of the button and the offset from the parent
// depth adjusts the buttons z position to move a button toward or away from viewer
private void SetScaleAndPosition(float scaleAndOffset, float depth) {
float scaleMult = Mathf.Max(scaleAndOffset, 0.01f);
Vector3 scaledPosition = parentMenu.transform.position * (1.0f - scaleMult) + startPosition *
scaleMult;
transform.position = scaledPosition - transform.forward * (depth);
transform.localScale = startScale * scaleMult;
UpdateLines();
if (background) {
background.transform.position = scaledPosition - transform.forward *
(depth + BACKGROUND_ICON_ZOFFSET);
background.transform.localScale = startScale * scaleMult;
background.transform.rotation = transform.rotation;
}
}
void SetRendererAlpha(Renderer target, float alpha) {
if (target == null) {
return;
}
var alphaColor = new Color(1.0f, 1.0f, 1.0f, alpha);
target.GetPropertyBlock(propertyBlock);
propertyBlock.SetColor("_Color", alphaColor);
target.SetPropertyBlock(propertyBlock);
}
void SetDecorationLabelAlpha(float alpha) {
if (decorationLabel == null) {
return;
}
if (Mathf.Approximately(0.0f, alpha) ){
if (decorationLabel.activeSelf) {
decorationLabel.SetActive(false);
}
return;
}
if (!decorationLabel.activeSelf) {
decorationLabel.SetActive(true);
}
SetRendererAlpha(decorationLabelRenderer, alpha);
}
void SetBackgroundTransparency(float backgroundAlpha) {
if (!background) {
return;
}
SetRendererAlpha(backgroundSpriteRenderer, backgroundAlpha);
if (lineToParent != null && MenuLayer > 1) {
lineToParent.startColor = CLEAR_WHITE;
lineToParent.endColor = new Color(1.0f, 1.0f, 1.0f, backgroundAlpha);;
}
}
private void SetColliderSize(float size) {
boxCollider.enabled = !Mathf.Approximately(0.0f, size);
boxCollider.size = new Vector3(size, size, Mathf.Min(size,BACKGROUND_ICON_ZOFFSET));
}
void OnDestroy() {
if (background) {
Destroy(background);
}
if (tooltip) {
Destroy(tooltip);
}
if (parentMenu) {
parentMenu.childMenus.Remove(this);
}
}
private bool FadeChildren(IconState nextState) {
bool stateChanged = false;
foreach (ConstellationMenuIcon child in childMenus) {
if (child.StartFade(nextState)) {
stateChanged = true;
}
}
return stateChanged;
}
private bool StartFade(IconState nextState) {
if(state == nextState) {
return false;
}
if (nextState == IconState.Closed && childMenus.Count > 0) {
FadeChildren(IconState.Closed);
}
state = nextState;
fadeInProgress = true;
if (nextState == IconState.Closed) {
menuRoot.MarkGraphDirty();
}
fadeParameters = new FadeParameters(nextState);
buttonActive = fadeParameters.buttonActive;
SetColliderSize(Mathf.Min(boxCollider.size.x, fadeParameters.colliderSize));
menuRoot.StartFadeOnIcon(this, nextState);
ConstellationMenuIcon hoverIcon = (menuRoot == null) ? null : menuRoot.GetHoverIcon();
// Change the background based on the relationship between this icon and the hoverIcon
var relationship = GetRelationship(hoverIcon);
tooltipAlpha.FadeTo(GetTooltipAlpha(relationship),
ANIMATION_DURATION_SECONDS, Time.time);
iconBgAlpha.FadeTo(GetBackgroundAlpha(relationship),
ANIMATION_DURATION_SECONDS,
Time.time);
decorationLabelAlpha.FadeTo(GetDecorationLabelAlpha(relationship),
ANIMATION_DURATION_SECONDS, Time.time);
iconScale.FadeTo(SHOWN_ICON_SCALE,
ANIMATION_DURATION_SECONDS,
Time.time);
iconAlpha.FadeTo(fadeParameters.alpha,
ANIMATION_DURATION_SECONDS,
Time.time);
return true;
}
/// It is easy or difficult to hover based on the relationship to the most recent hover icon
float GetHoverDelay(IconRelationship relationship) {
switch (relationship) {
case IconRelationship.DescendantOfRhs:
case IconRelationship.AncestorOfRhs:
return 0.0f;
default:
return menuRoot.hoverDelay;
}
}
/// The decoration label is only shown if the icon has children and is a descendant of the hover
/// icon. DescendantOfRhs is also used if hover icon is null.
float GetDecorationLabelAlpha(IconRelationship relationship) {
if (state == IconState.Hovering ||
state == IconState.Closed ||
relationship != IconRelationship.DescendantOfRhs ||
menuNode.children.Count == 0) {
return DEFAULT_DECORATION_LABEL_ALPHA;
}
return DESCENDANT_DECORATION_LABEL_ALPHA;
}
/// Background is determined by the relationship to the most recent hover Icon
private float GetBackgroundAlpha(IconRelationship relationship) {
if (state == IconState.Closed) {
return CLOSED_ICON_BG_ALPHA;
}
float newAlpha;
switch (relationship) {
case IconRelationship.DescendantOfRhs:
newAlpha = DESCENDANT_ICON_BG_ALPHA;
break;
case IconRelationship.AncestorOfRhs:
newAlpha = ANCESTOR_ICON_BG_ALPHA;
break;
default:
newAlpha = DEFAULT_ICON_BG_ALPHA;
break;
}
return newAlpha;
}
private float GetTooltipAlpha(IconRelationship relationship) {
if (state == IconState.Closed) {
return DEFAULT_TOOLTIP_ALPHA;
}
float newAlpha;
switch (relationship) {
case IconRelationship.DescendantOfRhs:
case IconRelationship.AncestorOfRhs:
newAlpha = SELECTED_PATH_TOOLTIP_ALPHA;
break;
default:
newAlpha = DEFAULT_TOOLTIP_ALPHA;
break;
}
return newAlpha;
}
/// Start hovering if the icon has been selected long enough
void HoverIfNeeded() {
if (!selected) {
return;
}
if (!(hoverStartTime < selectionStartTime)) {
return;
}
if ((Time.time - selectionStartTime) < hoverDelaySeconds) {
return;
}
hoverStartTime = Time.time;
menuRoot.MakeHover(menuItem);
if (state == IconState.Hidden) {
parentMenu.ShowChildLayer(IconState.Hidden);
StartFade(IconState.Hovering);
} else {
FadeIfNeeded(IconState.Shown, IconState.Hovering);
}
if (menuNode.children.Count > 0) {
ShowChildLayer(IconState.Hidden);
}
// If we just displayed children
// then hide everything that isn't needed.
// always do hideall on hover.
HideAllExceptParentsAndChildren();
}
/// Called recursively when any icon starts to hover.
public void OnHoverChange(ConstellationMenuIcon hoverIcon) {
foreach (var child in childMenus) {
child.OnHoverChange(hoverIcon);
}
var relationship = GetRelationship(hoverIcon);
decorationLabelAlpha.FadeTo(GetDecorationLabelAlpha(relationship),
ANIMATION_DURATION_SECONDS, Time.time);
// Change the background based on the relationship between this icon and the hoverIcon
iconBgAlpha.FadeTo(GetBackgroundAlpha(relationship),
ANIMATION_DURATION_SECONDS, Time.time);
// Change the tooltip based on the relationship between this icon and the hoverIcon
tooltipAlpha.FadeTo(GetTooltipAlpha(relationship),
ANIMATION_DURATION_SECONDS, Time.time);
// Set how easy/difficult it is to hover based on this relationship
hoverDelaySeconds = GetHoverDelay(relationship);
}
/// Returns IconRelationship.
/// AncestorOfRhs if this class is a descendant of relative (or they are the same)
/// DescendantOfRhs if the opposite is true (or rhsIcon is null)
/// or UnkownRelationship if neither is true.
public IconRelationship GetRelationship(ConstellationMenuIcon rhsIcon) {
if (rhsIcon == null || IsDescendentOf(rhsIcon)) {
return IconRelationship.DescendantOfRhs;
} else if (rhsIcon.IsDescendentOf(this)) {
return IconRelationship.AncestorOfRhs;
} else {
return IconRelationship.UnkownRelationship;
}
}
/// Recursive call to find the child at the deepest MenuLayer
public ConstellationMenuIcon GetDeepestIcon() {
ConstellationMenuIcon returnValue = this;
foreach (var child in childMenus) {
if (child.state == IconState.Closed) {
continue;
}
ConstellationMenuIcon otherIcon = child.GetDeepestIcon();
if (otherIcon.MenuLayer > returnValue.MenuLayer) {
returnValue = otherIcon;
}
}
return returnValue;
}
public bool IsDescendentOf(ConstellationMenuIcon parent) {
ConstellationMenuIcon child = this;
while (child != null) {
if (child == parent) {
return true;
}
child = child.parentMenu;
}
return false;
}
// Apply any logic attached to the end of changing the icon's alpha.
private void FinishFade() {
fadeInProgress = false;
SetColliderSize(fadeParameters.colliderSize);
}
/// Updates icon with interpolated fade values.
private void ContinueFade() {
if (!IsFadeInProgress) {
// no fade in progress. Do nothing.
return;
}
SetRendererAlpha(spriteRenderer, iconAlpha.ValueAtTime(Time.time));
if (state == IconState.Closed) {
selected = false;
} else if (state == IconState.Hidden) {
selected = false;
}
if (!(iconAlpha.GetProgress(Time.time) < 1.0f) &&
!(iconBgAlpha.GetProgress(Time.time) < 1.0f) &&
!(decorationLabelAlpha.GetProgress(Time.time) < 1.0f)) {
FinishFade();
return;
}
}
/// Starts a fade if the there is a match for fromState
public void FadeIfNeeded(IconState fromState,
IconState toState) {
if (state != fromState) {
return;
}
StartFade(toState);
}
/// Recursively closes this menu and its children
public void CloseRecursive() {
foreach (ConstellationMenuIcon child in childMenus) {
child.CloseRecursive();
}
StartFade(IconState.Closed);
}
public void OnPointerEnter(PointerEventData eventData) {
if (parentMenu == null) {
return;
}
if (!buttonActive) {
return;
}
if (!selected) {
selected = true;
selectionStartTime = Time.time;
}
}
public void OnPointerExit(PointerEventData eventData) {
if (parentMenu == null) {
return;
}
selected = false;
}
/// Recursively calculates the angle between a ray and the icons.
public float GetClosestAngle(Vector3 originPosition,
Vector3 normalizedRayFromOrigin) {
Vector3 iconToOrigin = transform.position - originPosition;
float bestAngle = Vector3.Angle(normalizedRayFromOrigin, iconToOrigin.normalized);
foreach (var child in childMenus) {
float childAngle = child.GetClosestAngle(originPosition, normalizedRayFromOrigin);
bestAngle = Mathf.Min(childAngle, bestAngle);
}
return bestAngle;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/firestore/v1beta1/common.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Cloud.Firestore.V1Beta1 {
/// <summary>Holder for reflection information generated from google/firestore/v1beta1/common.proto</summary>
public static partial class CommonReflection {
#region Descriptor
/// <summary>File descriptor for google/firestore/v1beta1/common.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static CommonReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiVnb29nbGUvZmlyZXN0b3JlL3YxYmV0YTEvY29tbW9uLnByb3RvEhhnb29n",
"bGUuZmlyZXN0b3JlLnYxYmV0YTEaHGdvb2dsZS9hcGkvYW5ub3RhdGlvbnMu",
"cHJvdG8aH2dvb2dsZS9wcm90b2J1Zi90aW1lc3RhbXAucHJvdG8iIwoMRG9j",
"dW1lbnRNYXNrEhMKC2ZpZWxkX3BhdGhzGAEgAygJImUKDFByZWNvbmRpdGlv",
"bhIQCgZleGlzdHMYASABKAhIABIxCgt1cGRhdGVfdGltZRgCIAEoCzIaLmdv",
"b2dsZS5wcm90b2J1Zi5UaW1lc3RhbXBIAEIQCg5jb25kaXRpb25fdHlwZSKz",
"AgoSVHJhbnNhY3Rpb25PcHRpb25zEkoKCXJlYWRfb25seRgCIAEoCzI1Lmdv",
"b2dsZS5maXJlc3RvcmUudjFiZXRhMS5UcmFuc2FjdGlvbk9wdGlvbnMuUmVh",
"ZE9ubHlIABJMCgpyZWFkX3dyaXRlGAMgASgLMjYuZ29vZ2xlLmZpcmVzdG9y",
"ZS52MWJldGExLlRyYW5zYWN0aW9uT3B0aW9ucy5SZWFkV3JpdGVIABomCglS",
"ZWFkV3JpdGUSGQoRcmV0cnlfdHJhbnNhY3Rpb24YASABKAwaUwoIUmVhZE9u",
"bHkSLwoJcmVhZF90aW1lGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVz",
"dGFtcEgAQhYKFGNvbnNpc3RlbmN5X3NlbGVjdG9yQgYKBG1vZGVCuQEKHGNv",
"bS5nb29nbGUuZmlyZXN0b3JlLnYxYmV0YTFCC0NvbW1vblByb3RvUAFaQWdv",
"b2dsZS5nb2xhbmcub3JnL2dlbnByb3RvL2dvb2dsZWFwaXMvZmlyZXN0b3Jl",
"L3YxYmV0YTE7ZmlyZXN0b3JlogIER0NGU6oCHkdvb2dsZS5DbG91ZC5GaXJl",
"c3RvcmUuVjFCZXRhMcoCHkdvb2dsZVxDbG91ZFxGaXJlc3RvcmVcVjFiZXRh",
"MWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Firestore.V1Beta1.DocumentMask), global::Google.Cloud.Firestore.V1Beta1.DocumentMask.Parser, new[]{ "FieldPaths" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Firestore.V1Beta1.Precondition), global::Google.Cloud.Firestore.V1Beta1.Precondition.Parser, new[]{ "Exists", "UpdateTime" }, new[]{ "ConditionType" }, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Firestore.V1Beta1.TransactionOptions), global::Google.Cloud.Firestore.V1Beta1.TransactionOptions.Parser, new[]{ "ReadOnly", "ReadWrite" }, new[]{ "Mode" }, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Firestore.V1Beta1.TransactionOptions.Types.ReadWrite), global::Google.Cloud.Firestore.V1Beta1.TransactionOptions.Types.ReadWrite.Parser, new[]{ "RetryTransaction" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Firestore.V1Beta1.TransactionOptions.Types.ReadOnly), global::Google.Cloud.Firestore.V1Beta1.TransactionOptions.Types.ReadOnly.Parser, new[]{ "ReadTime" }, new[]{ "ConsistencySelector" }, null, null)})
}));
}
#endregion
}
#region Messages
/// <summary>
/// A set of field paths on a document.
/// Used to restrict a get or update operation on a document to a subset of its
/// fields.
/// This is different from standard field masks, as this is always scoped to a
/// [Document][google.firestore.v1beta1.Document], and takes in account the dynamic nature of [Value][google.firestore.v1beta1.Value].
/// </summary>
public sealed partial class DocumentMask : pb::IMessage<DocumentMask> {
private static readonly pb::MessageParser<DocumentMask> _parser = new pb::MessageParser<DocumentMask>(() => new DocumentMask());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<DocumentMask> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Firestore.V1Beta1.CommonReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DocumentMask() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DocumentMask(DocumentMask other) : this() {
fieldPaths_ = other.fieldPaths_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DocumentMask Clone() {
return new DocumentMask(this);
}
/// <summary>Field number for the "field_paths" field.</summary>
public const int FieldPathsFieldNumber = 1;
private static readonly pb::FieldCodec<string> _repeated_fieldPaths_codec
= pb::FieldCodec.ForString(10);
private readonly pbc::RepeatedField<string> fieldPaths_ = new pbc::RepeatedField<string>();
/// <summary>
/// The list of field paths in the mask. See [Document.fields][google.firestore.v1beta1.Document.fields] for a field
/// path syntax reference.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<string> FieldPaths {
get { return fieldPaths_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as DocumentMask);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(DocumentMask other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!fieldPaths_.Equals(other.fieldPaths_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= fieldPaths_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
fieldPaths_.WriteTo(output, _repeated_fieldPaths_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += fieldPaths_.CalculateSize(_repeated_fieldPaths_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(DocumentMask other) {
if (other == null) {
return;
}
fieldPaths_.Add(other.fieldPaths_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
fieldPaths_.AddEntriesFrom(input, _repeated_fieldPaths_codec);
break;
}
}
}
}
}
/// <summary>
/// A precondition on a document, used for conditional operations.
/// </summary>
public sealed partial class Precondition : pb::IMessage<Precondition> {
private static readonly pb::MessageParser<Precondition> _parser = new pb::MessageParser<Precondition>(() => new Precondition());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Precondition> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Firestore.V1Beta1.CommonReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Precondition() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Precondition(Precondition other) : this() {
switch (other.ConditionTypeCase) {
case ConditionTypeOneofCase.Exists:
Exists = other.Exists;
break;
case ConditionTypeOneofCase.UpdateTime:
UpdateTime = other.UpdateTime.Clone();
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Precondition Clone() {
return new Precondition(this);
}
/// <summary>Field number for the "exists" field.</summary>
public const int ExistsFieldNumber = 1;
/// <summary>
/// When set to `true`, the target document must exist.
/// When set to `false`, the target document must not exist.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Exists {
get { return conditionTypeCase_ == ConditionTypeOneofCase.Exists ? (bool) conditionType_ : false; }
set {
conditionType_ = value;
conditionTypeCase_ = ConditionTypeOneofCase.Exists;
}
}
/// <summary>Field number for the "update_time" field.</summary>
public const int UpdateTimeFieldNumber = 2;
/// <summary>
/// When set, the target document must exist and have been last updated at
/// that time.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp UpdateTime {
get { return conditionTypeCase_ == ConditionTypeOneofCase.UpdateTime ? (global::Google.Protobuf.WellKnownTypes.Timestamp) conditionType_ : null; }
set {
conditionType_ = value;
conditionTypeCase_ = value == null ? ConditionTypeOneofCase.None : ConditionTypeOneofCase.UpdateTime;
}
}
private object conditionType_;
/// <summary>Enum of possible cases for the "condition_type" oneof.</summary>
public enum ConditionTypeOneofCase {
None = 0,
Exists = 1,
UpdateTime = 2,
}
private ConditionTypeOneofCase conditionTypeCase_ = ConditionTypeOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ConditionTypeOneofCase ConditionTypeCase {
get { return conditionTypeCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearConditionType() {
conditionTypeCase_ = ConditionTypeOneofCase.None;
conditionType_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Precondition);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Precondition other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Exists != other.Exists) return false;
if (!object.Equals(UpdateTime, other.UpdateTime)) return false;
if (ConditionTypeCase != other.ConditionTypeCase) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (conditionTypeCase_ == ConditionTypeOneofCase.Exists) hash ^= Exists.GetHashCode();
if (conditionTypeCase_ == ConditionTypeOneofCase.UpdateTime) hash ^= UpdateTime.GetHashCode();
hash ^= (int) conditionTypeCase_;
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (conditionTypeCase_ == ConditionTypeOneofCase.Exists) {
output.WriteRawTag(8);
output.WriteBool(Exists);
}
if (conditionTypeCase_ == ConditionTypeOneofCase.UpdateTime) {
output.WriteRawTag(18);
output.WriteMessage(UpdateTime);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (conditionTypeCase_ == ConditionTypeOneofCase.Exists) {
size += 1 + 1;
}
if (conditionTypeCase_ == ConditionTypeOneofCase.UpdateTime) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(UpdateTime);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Precondition other) {
if (other == null) {
return;
}
switch (other.ConditionTypeCase) {
case ConditionTypeOneofCase.Exists:
Exists = other.Exists;
break;
case ConditionTypeOneofCase.UpdateTime:
UpdateTime = other.UpdateTime;
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Exists = input.ReadBool();
break;
}
case 18: {
global::Google.Protobuf.WellKnownTypes.Timestamp subBuilder = new global::Google.Protobuf.WellKnownTypes.Timestamp();
if (conditionTypeCase_ == ConditionTypeOneofCase.UpdateTime) {
subBuilder.MergeFrom(UpdateTime);
}
input.ReadMessage(subBuilder);
UpdateTime = subBuilder;
break;
}
}
}
}
}
/// <summary>
/// Options for creating a new transaction.
/// </summary>
public sealed partial class TransactionOptions : pb::IMessage<TransactionOptions> {
private static readonly pb::MessageParser<TransactionOptions> _parser = new pb::MessageParser<TransactionOptions>(() => new TransactionOptions());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<TransactionOptions> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Firestore.V1Beta1.CommonReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TransactionOptions() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TransactionOptions(TransactionOptions other) : this() {
switch (other.ModeCase) {
case ModeOneofCase.ReadOnly:
ReadOnly = other.ReadOnly.Clone();
break;
case ModeOneofCase.ReadWrite:
ReadWrite = other.ReadWrite.Clone();
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TransactionOptions Clone() {
return new TransactionOptions(this);
}
/// <summary>Field number for the "read_only" field.</summary>
public const int ReadOnlyFieldNumber = 2;
/// <summary>
/// The transaction can only be used for read operations.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Firestore.V1Beta1.TransactionOptions.Types.ReadOnly ReadOnly {
get { return modeCase_ == ModeOneofCase.ReadOnly ? (global::Google.Cloud.Firestore.V1Beta1.TransactionOptions.Types.ReadOnly) mode_ : null; }
set {
mode_ = value;
modeCase_ = value == null ? ModeOneofCase.None : ModeOneofCase.ReadOnly;
}
}
/// <summary>Field number for the "read_write" field.</summary>
public const int ReadWriteFieldNumber = 3;
/// <summary>
/// The transaction can be used for both read and write operations.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Firestore.V1Beta1.TransactionOptions.Types.ReadWrite ReadWrite {
get { return modeCase_ == ModeOneofCase.ReadWrite ? (global::Google.Cloud.Firestore.V1Beta1.TransactionOptions.Types.ReadWrite) mode_ : null; }
set {
mode_ = value;
modeCase_ = value == null ? ModeOneofCase.None : ModeOneofCase.ReadWrite;
}
}
private object mode_;
/// <summary>Enum of possible cases for the "mode" oneof.</summary>
public enum ModeOneofCase {
None = 0,
ReadOnly = 2,
ReadWrite = 3,
}
private ModeOneofCase modeCase_ = ModeOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ModeOneofCase ModeCase {
get { return modeCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearMode() {
modeCase_ = ModeOneofCase.None;
mode_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as TransactionOptions);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(TransactionOptions other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(ReadOnly, other.ReadOnly)) return false;
if (!object.Equals(ReadWrite, other.ReadWrite)) return false;
if (ModeCase != other.ModeCase) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (modeCase_ == ModeOneofCase.ReadOnly) hash ^= ReadOnly.GetHashCode();
if (modeCase_ == ModeOneofCase.ReadWrite) hash ^= ReadWrite.GetHashCode();
hash ^= (int) modeCase_;
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (modeCase_ == ModeOneofCase.ReadOnly) {
output.WriteRawTag(18);
output.WriteMessage(ReadOnly);
}
if (modeCase_ == ModeOneofCase.ReadWrite) {
output.WriteRawTag(26);
output.WriteMessage(ReadWrite);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (modeCase_ == ModeOneofCase.ReadOnly) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ReadOnly);
}
if (modeCase_ == ModeOneofCase.ReadWrite) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ReadWrite);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(TransactionOptions other) {
if (other == null) {
return;
}
switch (other.ModeCase) {
case ModeOneofCase.ReadOnly:
ReadOnly = other.ReadOnly;
break;
case ModeOneofCase.ReadWrite:
ReadWrite = other.ReadWrite;
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 18: {
global::Google.Cloud.Firestore.V1Beta1.TransactionOptions.Types.ReadOnly subBuilder = new global::Google.Cloud.Firestore.V1Beta1.TransactionOptions.Types.ReadOnly();
if (modeCase_ == ModeOneofCase.ReadOnly) {
subBuilder.MergeFrom(ReadOnly);
}
input.ReadMessage(subBuilder);
ReadOnly = subBuilder;
break;
}
case 26: {
global::Google.Cloud.Firestore.V1Beta1.TransactionOptions.Types.ReadWrite subBuilder = new global::Google.Cloud.Firestore.V1Beta1.TransactionOptions.Types.ReadWrite();
if (modeCase_ == ModeOneofCase.ReadWrite) {
subBuilder.MergeFrom(ReadWrite);
}
input.ReadMessage(subBuilder);
ReadWrite = subBuilder;
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the TransactionOptions message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// Options for a transaction that can be used to read and write documents.
/// </summary>
public sealed partial class ReadWrite : pb::IMessage<ReadWrite> {
private static readonly pb::MessageParser<ReadWrite> _parser = new pb::MessageParser<ReadWrite>(() => new ReadWrite());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ReadWrite> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Firestore.V1Beta1.TransactionOptions.Descriptor.NestedTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReadWrite() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReadWrite(ReadWrite other) : this() {
retryTransaction_ = other.retryTransaction_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReadWrite Clone() {
return new ReadWrite(this);
}
/// <summary>Field number for the "retry_transaction" field.</summary>
public const int RetryTransactionFieldNumber = 1;
private pb::ByteString retryTransaction_ = pb::ByteString.Empty;
/// <summary>
/// An optional transaction to retry.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString RetryTransaction {
get { return retryTransaction_; }
set {
retryTransaction_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ReadWrite);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ReadWrite other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (RetryTransaction != other.RetryTransaction) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (RetryTransaction.Length != 0) hash ^= RetryTransaction.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (RetryTransaction.Length != 0) {
output.WriteRawTag(10);
output.WriteBytes(RetryTransaction);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (RetryTransaction.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(RetryTransaction);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ReadWrite other) {
if (other == null) {
return;
}
if (other.RetryTransaction.Length != 0) {
RetryTransaction = other.RetryTransaction;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
RetryTransaction = input.ReadBytes();
break;
}
}
}
}
}
/// <summary>
/// Options for a transaction that can only be used to read documents.
/// </summary>
public sealed partial class ReadOnly : pb::IMessage<ReadOnly> {
private static readonly pb::MessageParser<ReadOnly> _parser = new pb::MessageParser<ReadOnly>(() => new ReadOnly());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ReadOnly> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Firestore.V1Beta1.TransactionOptions.Descriptor.NestedTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReadOnly() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReadOnly(ReadOnly other) : this() {
switch (other.ConsistencySelectorCase) {
case ConsistencySelectorOneofCase.ReadTime:
ReadTime = other.ReadTime.Clone();
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReadOnly Clone() {
return new ReadOnly(this);
}
/// <summary>Field number for the "read_time" field.</summary>
public const int ReadTimeFieldNumber = 2;
/// <summary>
/// Reads documents at the given time.
/// This may not be older than 60 seconds.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp ReadTime {
get { return consistencySelectorCase_ == ConsistencySelectorOneofCase.ReadTime ? (global::Google.Protobuf.WellKnownTypes.Timestamp) consistencySelector_ : null; }
set {
consistencySelector_ = value;
consistencySelectorCase_ = value == null ? ConsistencySelectorOneofCase.None : ConsistencySelectorOneofCase.ReadTime;
}
}
private object consistencySelector_;
/// <summary>Enum of possible cases for the "consistency_selector" oneof.</summary>
public enum ConsistencySelectorOneofCase {
None = 0,
ReadTime = 2,
}
private ConsistencySelectorOneofCase consistencySelectorCase_ = ConsistencySelectorOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ConsistencySelectorOneofCase ConsistencySelectorCase {
get { return consistencySelectorCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearConsistencySelector() {
consistencySelectorCase_ = ConsistencySelectorOneofCase.None;
consistencySelector_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ReadOnly);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ReadOnly other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(ReadTime, other.ReadTime)) return false;
if (ConsistencySelectorCase != other.ConsistencySelectorCase) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (consistencySelectorCase_ == ConsistencySelectorOneofCase.ReadTime) hash ^= ReadTime.GetHashCode();
hash ^= (int) consistencySelectorCase_;
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (consistencySelectorCase_ == ConsistencySelectorOneofCase.ReadTime) {
output.WriteRawTag(18);
output.WriteMessage(ReadTime);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (consistencySelectorCase_ == ConsistencySelectorOneofCase.ReadTime) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ReadTime);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ReadOnly other) {
if (other == null) {
return;
}
switch (other.ConsistencySelectorCase) {
case ConsistencySelectorOneofCase.ReadTime:
ReadTime = other.ReadTime;
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 18: {
global::Google.Protobuf.WellKnownTypes.Timestamp subBuilder = new global::Google.Protobuf.WellKnownTypes.Timestamp();
if (consistencySelectorCase_ == ConsistencySelectorOneofCase.ReadTime) {
subBuilder.MergeFrom(ReadTime);
}
input.ReadMessage(subBuilder);
ReadTime = subBuilder;
break;
}
}
}
}
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NBitcoin;
using Stratis.Bitcoin.Base.AsyncWork;
using Stratis.Bitcoin.Base.Deployments;
using Stratis.Bitcoin.BlockPulling;
using Stratis.Bitcoin.Builder;
using Stratis.Bitcoin.Builder.Feature;
using Stratis.Bitcoin.Configuration;
using Stratis.Bitcoin.Configuration.Settings;
using Stratis.Bitcoin.Connection;
using Stratis.Bitcoin.Consensus;
using Stratis.Bitcoin.Consensus.Validators;
using Stratis.Bitcoin.EventBus;
using Stratis.Bitcoin.Interfaces;
using Stratis.Bitcoin.P2P;
using Stratis.Bitcoin.P2P.Peer;
using Stratis.Bitcoin.P2P.Protocol.Behaviors;
using Stratis.Bitcoin.P2P.Protocol.Payloads;
using Stratis.Bitcoin.Signals;
using Stratis.Bitcoin.Utilities;
[assembly: InternalsVisibleTo("Stratis.Bitcoin.Tests")]
[assembly: InternalsVisibleTo("Stratis.Bitcoin.Tests.Common")]
[assembly: InternalsVisibleTo("Stratis.Bitcoin.IntegrationTests.Common")]
[assembly: InternalsVisibleTo("Stratis.Bitcoin.Features.Consensus.Tests")]
[assembly: InternalsVisibleTo("Stratis.Bitcoin.IntegrationTests")]
namespace Stratis.Bitcoin.Base
{
/// <summary>
/// Base node services, these are the services a node has to have.
/// The ConnectionManager feature is also part of the base but may go in a feature of its own.
/// The base features are the minimal components required to connect to peers and maintain the best chain.
/// <para>
/// The base node services for a node are:
/// <list type="bullet">
/// <item>the ConcurrentChain to keep track of the best chain,</item>
/// <item>the ConnectionManager to connect with the network,</item>
/// <item>DatetimeProvider and Cancellation,</item>
/// <item>CancellationProvider and Cancellation,</item>
/// <item>DataFolder,</item>
/// <item>ChainState.</item>
/// </list>
/// </para>
/// </summary>
public sealed class BaseFeature : FullNodeFeature
{
/// <summary>Global application life cycle control - triggers when application shuts down.</summary>
private readonly INodeLifetime nodeLifetime;
/// <summary>Information about node's chain.</summary>
private readonly IChainState chainState;
/// <summary>Access to the database of blocks.</summary>
private readonly IChainRepository chainRepository;
/// <summary>User defined node settings.</summary>
private readonly NodeSettings nodeSettings;
/// <summary>Locations of important folders and files on disk.</summary>
private readonly DataFolder dataFolder;
/// <summary>Thread safe chain of block headers from genesis.</summary>
private readonly ChainIndexer chainIndexer;
/// <summary>Manager of node's network connections.</summary>
private readonly IConnectionManager connectionManager;
/// <summary>Provider of time functions.</summary>
private readonly IDateTimeProvider dateTimeProvider;
/// <summary>Factory for creating background async loop tasks.</summary>
private readonly IAsyncLoopFactory asyncLoopFactory;
/// <summary>Logger for the node.</summary>
private readonly ILogger logger;
/// <summary>Factory for creating loggers.</summary>
private readonly ILoggerFactory loggerFactory;
/// <summary>State of time synchronization feature that stores collected data samples.</summary>
private readonly ITimeSyncBehaviorState timeSyncBehaviorState;
/// <summary>Manager of node's network peers.</summary>
private IPeerAddressManager peerAddressManager;
/// <summary>Periodic task to save list of peers to disk.</summary>
private IAsyncLoop flushAddressManagerLoop;
/// <summary>Periodic task to save the chain to the database.</summary>
private IAsyncLoop flushChainLoop;
/// <summary>A handler that can manage the lifetime of network peers.</summary>
private readonly IPeerBanning peerBanning;
/// <summary>Provider of IBD state.</summary>
private readonly IInitialBlockDownloadState initialBlockDownloadState;
/// <inheritdoc cref="Network"/>
private readonly Network network;
private readonly IProvenBlockHeaderStore provenBlockHeaderStore;
private readonly IConsensusManager consensusManager;
private readonly IConsensusRuleEngine consensusRules;
private readonly IBlockPuller blockPuller;
private readonly IBlockStore blockStore;
private readonly ITipsManager tipsManager;
private readonly IKeyValueRepository keyValueRepo;
/// <inheritdoc cref="IFinalizedBlockInfoRepository"/>
private readonly IFinalizedBlockInfoRepository finalizedBlockInfoRepository;
/// <inheritdoc cref="IPartialValidator"/>
private readonly IPartialValidator partialValidator;
public BaseFeature(NodeSettings nodeSettings,
DataFolder dataFolder,
INodeLifetime nodeLifetime,
ChainIndexer chainIndexer,
IChainState chainState,
IConnectionManager connectionManager,
IChainRepository chainRepository,
IFinalizedBlockInfoRepository finalizedBlockInfo,
IDateTimeProvider dateTimeProvider,
IAsyncLoopFactory asyncLoopFactory,
ITimeSyncBehaviorState timeSyncBehaviorState,
ILoggerFactory loggerFactory,
IInitialBlockDownloadState initialBlockDownloadState,
IPeerBanning peerBanning,
IPeerAddressManager peerAddressManager,
IConsensusManager consensusManager,
IConsensusRuleEngine consensusRules,
IPartialValidator partialValidator,
IBlockPuller blockPuller,
IBlockStore blockStore,
Network network,
ITipsManager tipsManager,
IKeyValueRepository keyValueRepo,
IProvenBlockHeaderStore provenBlockHeaderStore = null)
{
this.chainState = Guard.NotNull(chainState, nameof(chainState));
this.chainRepository = Guard.NotNull(chainRepository, nameof(chainRepository));
this.finalizedBlockInfoRepository = Guard.NotNull(finalizedBlockInfo, nameof(finalizedBlockInfo));
this.nodeSettings = Guard.NotNull(nodeSettings, nameof(nodeSettings));
this.dataFolder = Guard.NotNull(dataFolder, nameof(dataFolder));
this.nodeLifetime = Guard.NotNull(nodeLifetime, nameof(nodeLifetime));
this.chainIndexer = Guard.NotNull(chainIndexer, nameof(chainIndexer));
this.connectionManager = Guard.NotNull(connectionManager, nameof(connectionManager));
this.consensusManager = consensusManager;
this.consensusRules = consensusRules;
this.blockPuller = blockPuller;
this.blockStore = blockStore;
this.network = network;
this.provenBlockHeaderStore = provenBlockHeaderStore;
this.partialValidator = partialValidator;
this.peerBanning = Guard.NotNull(peerBanning, nameof(peerBanning));
this.tipsManager = Guard.NotNull(tipsManager, nameof(tipsManager));
this.keyValueRepo = Guard.NotNull(keyValueRepo, nameof(keyValueRepo));
this.peerAddressManager = Guard.NotNull(peerAddressManager, nameof(peerAddressManager));
this.peerAddressManager.PeerFilePath = this.dataFolder;
this.initialBlockDownloadState = initialBlockDownloadState;
this.dateTimeProvider = dateTimeProvider;
this.asyncLoopFactory = asyncLoopFactory;
this.timeSyncBehaviorState = timeSyncBehaviorState;
this.loggerFactory = loggerFactory;
this.logger = loggerFactory.CreateLogger(this.GetType().FullName);
}
/// <inheritdoc />
public override async Task InitializeAsync()
{
// TODO rewrite chain starting logic. Tips manager should be used.
await this.StartChainAsync().ConfigureAwait(false);
if (this.provenBlockHeaderStore != null)
{
// If we find at this point that proven header store is behind chain we can rewind chain (this will cause a ripple effect and rewind block store and consensus)
// This problem should go away once we implement a component to keep all tips up to date
// https://github.com/stratisproject/StratisBitcoinFullNode/issues/2503
ChainedHeader initializedAt = await this.provenBlockHeaderStore.InitializeAsync(this.chainIndexer.Tip);
this.chainIndexer.Initialize(initializedAt);
}
NetworkPeerConnectionParameters connectionParameters = this.connectionManager.Parameters;
connectionParameters.IsRelay = this.connectionManager.ConnectionSettings.RelayTxes;
connectionParameters.TemplateBehaviors.Add(new PingPongBehavior());
connectionParameters.TemplateBehaviors.Add(new ConsensusManagerBehavior(this.chainIndexer, this.initialBlockDownloadState, this.consensusManager, this.peerBanning, this.loggerFactory));
// TODO: Once a proper rate limiting strategy has been implemented, this check will be removed.
if (!this.network.IsRegTest())
connectionParameters.TemplateBehaviors.Add(new RateLimitingBehavior(this.dateTimeProvider, this.loggerFactory, this.peerBanning));
connectionParameters.TemplateBehaviors.Add(new PeerBanningBehavior(this.loggerFactory, this.peerBanning, this.nodeSettings));
connectionParameters.TemplateBehaviors.Add(new BlockPullerBehavior(this.blockPuller, this.initialBlockDownloadState, this.dateTimeProvider, this.loggerFactory));
connectionParameters.TemplateBehaviors.Add(new ConnectionManagerBehavior(this.connectionManager, this.loggerFactory));
this.StartAddressManager(connectionParameters);
if (this.connectionManager.ConnectionSettings.SyncTimeEnabled)
{
connectionParameters.TemplateBehaviors.Add(new TimeSyncBehavior(this.timeSyncBehaviorState, this.dateTimeProvider, this.loggerFactory));
}
else
{
this.logger.LogDebug("Time synchronization with peers is disabled.");
}
// Block store must be initialized before consensus manager.
// This may be a temporary solution until a better way is found to solve this dependency.
this.blockStore.Initialize();
this.consensusRules.Initialize(this.chainIndexer.Tip);
this.consensusRules.Register();
await this.consensusManager.InitializeAsync(this.chainIndexer.Tip).ConfigureAwait(false);
this.chainState.ConsensusTip = this.consensusManager.Tip;
}
/// <summary>
/// Initializes node's chain repository.
/// Creates periodic task to persist changes to the database.
/// </summary>
private async Task StartChainAsync()
{
if (!Directory.Exists(this.dataFolder.ChainPath))
{
this.logger.LogInformation("Creating {0}.", this.dataFolder.ChainPath);
Directory.CreateDirectory(this.dataFolder.ChainPath);
}
if (!Directory.Exists(this.dataFolder.KeyValueRepositoryPath))
{
this.logger.LogInformation("Creating {0}.", this.dataFolder.KeyValueRepositoryPath);
Directory.CreateDirectory(this.dataFolder.KeyValueRepositoryPath);
}
this.logger.LogInformation("Loading finalized block height.");
await this.finalizedBlockInfoRepository.LoadFinalizedBlockInfoAsync(this.network).ConfigureAwait(false);
this.logger.LogInformation("Loading chain.");
ChainedHeader chainTip = await this.chainRepository.LoadAsync(this.chainIndexer.Genesis).ConfigureAwait(false);
this.chainIndexer.Initialize(chainTip);
this.logger.LogInformation("Chain loaded at height {0}.", this.chainIndexer.Height);
this.flushChainLoop = this.asyncLoopFactory.Run("FlushChain", async token =>
{
await this.chainRepository.SaveAsync(this.chainIndexer).ConfigureAwait(false);
if (this.provenBlockHeaderStore != null)
await this.provenBlockHeaderStore.SaveAsync().ConfigureAwait(false);
},
this.nodeLifetime.ApplicationStopping,
repeatEvery: TimeSpan.FromMinutes(1.0),
startAfter: TimeSpan.FromMinutes(1.0));
}
/// <summary>
/// Initializes node's address manager. Loads previously known peers from the file
/// or creates new peer file if it does not exist. Creates periodic task to persist changes
/// in peers to disk.
/// </summary>
private void StartAddressManager(NetworkPeerConnectionParameters connectionParameters)
{
var addressManagerBehaviour = new PeerAddressManagerBehaviour(this.dateTimeProvider, this.peerAddressManager, this.peerBanning, this.loggerFactory);
connectionParameters.TemplateBehaviors.Add(addressManagerBehaviour);
if (File.Exists(Path.Combine(this.dataFolder.AddressManagerFilePath, PeerAddressManager.PeerFileName)))
{
this.logger.LogInformation($"Loading peers from : {this.dataFolder.AddressManagerFilePath}.");
this.peerAddressManager.LoadPeers();
}
this.flushAddressManagerLoop = this.asyncLoopFactory.Run("Periodic peer flush", token =>
{
this.peerAddressManager.SavePeers();
return Task.CompletedTask;
},
this.nodeLifetime.ApplicationStopping,
repeatEvery: TimeSpan.FromMinutes(5.0),
startAfter: TimeSpan.FromMinutes(5.0));
}
/// <inheritdoc />
public override void Dispose()
{
this.logger.LogInformation("Flushing peers.");
this.flushAddressManagerLoop.Dispose();
this.logger.LogInformation("Disposing peer address manager.");
this.peerAddressManager.Dispose();
if (this.flushChainLoop != null)
{
this.logger.LogInformation("Flushing headers chain.");
this.flushChainLoop.Dispose();
}
this.logger.LogInformation("Disposing time sync behavior.");
this.timeSyncBehaviorState.Dispose();
this.logger.LogInformation("Disposing block puller.");
this.blockPuller.Dispose();
this.logger.LogInformation("Disposing partial validator.");
this.partialValidator.Dispose();
this.logger.LogInformation("Disposing consensus manager.");
this.consensusManager.Dispose();
this.logger.LogInformation("Disposing consensus rules.");
this.consensusRules.Dispose();
this.logger.LogInformation("Saving chain repository.");
this.chainRepository.SaveAsync(this.chainIndexer).GetAwaiter().GetResult();
this.chainRepository.Dispose();
if (this.provenBlockHeaderStore != null)
{
this.logger.LogInformation("Saving proven header store.");
this.provenBlockHeaderStore.SaveAsync().GetAwaiter().GetResult();
this.provenBlockHeaderStore.Dispose();
}
this.logger.LogInformation("Disposing finalized block info repository.");
this.finalizedBlockInfoRepository.Dispose();
this.logger.LogInformation("Disposing address indexer.");
this.logger.LogInformation("Disposing block store.");
this.blockStore.Dispose();
this.keyValueRepo.Dispose();
}
}
/// <summary>
/// A class providing extension methods for <see cref="IFullNodeBuilder"/>.
/// </summary>
public static class FullNodeBuilderBaseFeatureExtension
{
/// <summary>
/// Makes the full node use all the required features - <see cref="BaseFeature"/>.
/// </summary>
/// <param name="fullNodeBuilder">Builder responsible for creating the node.</param>
/// <returns>Full node builder's interface to allow fluent code.</returns>
public static IFullNodeBuilder UseBaseFeature(this IFullNodeBuilder fullNodeBuilder)
{
fullNodeBuilder.ConfigureFeature(features =>
{
features
.AddFeature<BaseFeature>()
.FeatureServices(services =>
{
services.AddSingleton(fullNodeBuilder.Network.Consensus.ConsensusFactory);
services.AddSingleton<DBreezeSerializer>();
services.AddSingleton(fullNodeBuilder.NodeSettings.LoggerFactory);
services.AddSingleton(fullNodeBuilder.NodeSettings.DataFolder);
services.AddSingleton<INodeLifetime, NodeLifetime>();
services.AddSingleton<IPeerBanning, PeerBanning>();
services.AddSingleton<FullNodeFeatureExecutor>();
services.AddSingleton<ISignals, Signals.Signals>();
services.AddSingleton<ISubscriptionErrorHandler, DefaultSubscriptionErrorHandler>();
services.AddSingleton<FullNode>().AddSingleton((provider) => { return provider.GetService<FullNode>() as IFullNode; });
services.AddSingleton<ChainIndexer>(new ChainIndexer(fullNodeBuilder.Network));
services.AddSingleton<IDateTimeProvider>(DateTimeProvider.Default);
services.AddSingleton<IInvalidBlockHashStore, InvalidBlockHashStore>();
services.AddSingleton<IChainState, ChainState>();
services.AddSingleton<IChainRepository, ChainRepository>();
services.AddSingleton<IFinalizedBlockInfoRepository, FinalizedBlockInfoRepository>();
services.AddSingleton<ITimeSyncBehaviorState, TimeSyncBehaviorState>();
services.AddSingleton<IAsyncLoopFactory, AsyncLoopFactory>();
services.AddSingleton<NodeDeployments>();
services.AddSingleton<IInitialBlockDownloadState, InitialBlockDownloadState>();
services.AddSingleton<IKeyValueRepository, KeyValueRepository>();
services.AddSingleton<ITipsManager, TipsManager>();
services.AddSingleton<IAsyncProvider, AsyncWork.AsyncProvider>();
// Consensus
services.AddSingleton<ConsensusSettings>();
services.AddSingleton<ICheckpoints, Checkpoints>();
// Connection
services.AddSingleton<INetworkPeerFactory, NetworkPeerFactory>();
services.AddSingleton<NetworkPeerConnectionParameters>();
services.AddSingleton<IConnectionManager, ConnectionManager>();
services.AddSingleton<ConnectionManagerSettings>();
services.AddSingleton<PayloadProvider>(new PayloadProvider().DiscoverPayloads());
services.AddSingleton<IVersionProvider, VersionProvider>();
services.AddSingleton<IBlockPuller, BlockPuller>();
// Peer address manager
services.AddSingleton<IPeerAddressManager, PeerAddressManager>();
services.AddSingleton<IPeerConnector, PeerConnectorAddNode>();
services.AddSingleton<IPeerConnector, PeerConnectorConnectNode>();
services.AddSingleton<IPeerConnector, PeerConnectorDiscovery>();
services.AddSingleton<IPeerDiscovery, PeerDiscovery>();
services.AddSingleton<ISelfEndpointTracker, SelfEndpointTracker>();
// Consensus
// Consensus manager is created like that due to CM's constructor being internal. This is done
// in order to prevent access to CM creation and CHT usage from another features. CHT is supposed
// to be used only by CM and no other component.
services.AddSingleton<IConsensusManager>(provider => new ConsensusManager(
chainedHeaderTree: provider.GetService<IChainedHeaderTree>(),
network: provider.GetService<Network>(),
loggerFactory: provider.GetService<ILoggerFactory>(),
chainState: provider.GetService<IChainState>(),
integrityValidator: provider.GetService<IIntegrityValidator>(),
partialValidator: provider.GetService<IPartialValidator>(),
fullValidator: provider.GetService<IFullValidator>(),
consensusRules: provider.GetService<IConsensusRuleEngine>(),
finalizedBlockInfo: provider.GetService<IFinalizedBlockInfoRepository>(),
signals: provider.GetService<ISignals>(),
peerBanning: provider.GetService<IPeerBanning>(),
ibdState: provider.GetService<IInitialBlockDownloadState>(),
chainIndexer: provider.GetService<ChainIndexer>(),
blockPuller: provider.GetService<IBlockPuller>(),
blockStore: provider.GetService<IBlockStore>(),
connectionManager: provider.GetService<IConnectionManager>(),
nodeStats: provider.GetService<INodeStats>(),
nodeLifetime: provider.GetService<INodeLifetime>(),
consensusSettings: provider.GetService<ConsensusSettings>()
));
services.AddSingleton<IChainedHeaderTree, ChainedHeaderTree>();
services.AddSingleton<IHeaderValidator, HeaderValidator>();
services.AddSingleton<IIntegrityValidator, IntegrityValidator>();
services.AddSingleton<IPartialValidator, PartialValidator>();
services.AddSingleton<IFullValidator, FullValidator>();
// Console
services.AddSingleton<INodeStats, NodeStats>();
});
});
return fullNodeBuilder;
}
}
}
| |
// 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 TestZInt32()
{
var test = new BooleanBinaryOpTest__TestZInt32();
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 BooleanBinaryOpTest__TestZInt32
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Int32);
private const int Op2ElementCount = VectorSize / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector128<Int32> _clsVar1;
private static Vector128<Int32> _clsVar2;
private Vector128<Int32> _fld1;
private Vector128<Int32> _fld2;
private BooleanBinaryOpTest__DataTable<Int32, Int32> _dataTable;
static BooleanBinaryOpTest__TestZInt32()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize);
}
public BooleanBinaryOpTest__TestZInt32()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
_dataTable = new BooleanBinaryOpTest__DataTable<Int32, Int32>(_data1, _data2, VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.TestZ(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
var result = Sse41.TestZ(
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.TestZ(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestZ), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_Load()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestZ), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_LoadAligned()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestZ), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunClsVarScenario()
{
var result = Sse41.TestZ(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var result = Sse41.TestZ(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse41.TestZ(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse41.TestZ(left, right);
ValidateResult(left, right, result);
}
public void RunLclFldScenario()
{
var test = new BooleanBinaryOpTest__TestZInt32();
var result = Sse41.TestZ(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunFldScenario()
{
var result = Sse41.TestZ(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int32> left, Vector128<Int32> right, bool result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Int32[] left, Int32[] right, bool result, [CallerMemberName] string method = "")
{
var expectedResult = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult &= ((left[i] & right[i]) == 0);
}
if (expectedResult != result)
{
Succeeded = false;
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.TestZ)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
//---------------------------------------------------------------------
// This file is part of the CLR Managed Debugger (mdbg) Sample.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//---------------------------------------------------------------------
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Samples.Debugging.CorDebug;
using Microsoft.Samples.Debugging.CorMetadata;
using Microsoft.Samples.Debugging.CorDebug.NativeApi;
namespace Microsoft.Samples.Debugging.MdbgEngine
{
/// <summary>
/// MDbg Thread class.
/// </summary>
public sealed class MDbgThread : MarshalByRefObject, IComparable
{
internal MDbgThread(MDbgThreadCollection threadCollection, CorThread thread, int threadNumber)
{
m_corThread = thread;
m_threadNumber = threadNumber;
m_threadMgr = threadCollection;
}
/// <summary>
/// Gets or Sets if the Thread is Suspended.
/// </summary>
/// <value>NotImplementedException.</value>
public bool Suspended
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
/// <summary>
/// Gets the Thread Number.
/// </summary>
/// <value>The Thread Number.</value>
public int Number
{
get
{
return m_threadNumber;
}
}
/// <summary>
/// Gets the Thread Id.
/// </summary>
/// <value>Gets the Thread Id.</value>
public int Id
{
get
{
return m_corThread.Id;
}
}
/// <summary>
/// Gets the CorThread.
/// </summary>
/// <value>The CorThread.</value>
public CorThread CorThread
{
get
{
return m_corThread;
}
}
/// <summary>
/// Returns current exception on the thread or MDbgValue representing N/A if there is no exception on the thread.
/// </summary>
/// <value>The current Exception.</value>
public MDbgValue CurrentException
{
get
{
CorValue cv;
try
{
cv = CorThread.CurrentException;
}
catch (COMException e)
{
if (e.ErrorCode == (int)HResult.E_FAIL)
cv = null;
else
throw;
}
return new MDbgValue(m_threadMgr.m_process, cv);
}
}
/// <summary>
/// Returns current notification on the thread or MDbgValue representing N/A if there is no exception on the thread.
/// </summary>
/// <value>The current notification.</value>
public MDbgValue CurrentNotification
{
get
{
CorValue cv;
try
{
cv = CorThread.CurrentNotification;
}
catch (COMException e)
{
if (e.ErrorCode == (int)HResult.E_FAIL)
cv = null;
else
throw;
}
return new MDbgValue(m_threadMgr.m_process, cv);
}
}
/// <summary>
/// The Bottom Frame in the stack for this Thread.
/// </summary>
/// <value>The Bottom Frame.</value>
public MDbgFrame BottomFrame
{
get
{
lock (m_stackLock)
{
EnsureCurrentStackWalker();
return m_stackWalker.GetFrame(0);
}
}
}
/// <summary>
/// Returns all the frames for the thread.
/// </summary>
/// <value>The frames.</value>
public System.Collections.Generic.IEnumerable<MDbgFrame> Frames
{
get
{
lock (m_stackLock)
{
// Explicitly return an enumeration from the cached frames so that we're using the same instances
// as the other enumerators. This lets callers use MDbgFrame operator ==.
EnsureCurrentStackWalker();
return m_stackWalker.EnumerateCachedFrames();
}
}
}
/// <summary>
/// Gets or Sets the Current Logical Frame
/// </summary>
/// <value>The Current Frame.</value>
public MDbgFrame CurrentFrame
{
get
{
lock (m_stackLock)
{
try
{
EnsureCurrentStackWalker();
}
catch (COMException e)
{
throw new MDbgNoCurrentFrameException(e);
}
if (m_currentFrameIndex == -1)
{
throw new MDbgNoCurrentFrameException();
}
MDbgFrame frame = m_stackWalker.GetFrame(m_currentFrameIndex);
if (frame == null)
{
throw new MDbgNoCurrentFrameException();
}
Debug.Assert(!frame.IsInfoOnly);
return frame;
}
}
set
{
lock (m_stackLock)
{
EnsureCurrentStackWalker();
if (value == null ||
value.Thread != this)
throw new ArgumentException();
if (value.IsInfoOnly)
throw new InvalidOperationException("virtual frames cannot be set as current frames");
int frameIndex = m_stackWalker.GetFrameIndex(value);
if (frameIndex < 0)
throw new InvalidOperationException("Cannot set a foreign frame to the thread as a current frame");
m_currentFrameIndex = frameIndex;
}
}
}
/// <summary>
/// Gets if the Thread has a Current Logical Frame.
/// </summary>
/// <value>true if it has, else false.</value>
public bool HaveCurrentFrame
{
get
{
lock (m_stackLock)
{
EnsureCurrentStackWalker();
return m_currentFrameIndex != -1;
}
}
}
/// <summary>
/// Gets the current Source Position.
/// </summary>
/// <value>The Source Ponition.</value>
public MDbgSourcePosition CurrentSourcePosition
{
get
{
return CurrentFrame.SourcePosition;
}
}
/// <summary>
/// Moves the Current Frame up or down.
/// </summary>
/// <param name="down">Moves frame down if true, else up.</param>
public void MoveCurrentFrame(bool down)
{
lock (m_stackLock)
{
MDbgFrame f = CurrentFrame;
Debug.Assert(!f.IsInfoOnly);
bool frameCanBeMoved;
int idx = m_currentFrameIndex;
if (down)
{
do
{
--idx;
}
while (idx >= 0 && m_stackWalker.GetFrame(idx).IsInfoOnly);
frameCanBeMoved = (idx >= 0);
}
else
{
do
{
++idx;
f = m_stackWalker.GetFrame(idx);
} while (f != null && f.IsInfoOnly);
frameCanBeMoved = f != null;
}
if (!frameCanBeMoved)
{
throw new MDbgException("Operation hit " + (down ? "bottom" : "top") + " of the stack.");
}
m_currentFrameIndex = idx;
}
}
/// <summary>
/// This will return an MDbgFrame for the corresponding CorFrame.
/// Note (the frame needs to correspond to this thread!!!!)
/// </summary>
/// <param name="f">The CorFrame to look up.</param>
/// <returns>The coresponding MDbgFrame.</returns>
public MDbgFrame LookupFrame(CorFrame f)
{
Debug.Assert(f != null);
return new MDbgILFrame(this, f);
}
int IComparable.CompareTo(object obj)
{
return this.Number - (obj as MDbgThread).Number;
}
/// <summary>
/// Clears the stack walker's frame cache, which will force the stack
/// to be walked again with the next call that depends on the stack.
/// </summary>
public void InvalidateStackWalker()
{
lock (m_stackLock)
{
if (m_stackWalker != null)
{
m_stackWalker.Invalidate();
}
m_stackWalker = null;
}
}
/// <summary>
/// Runs some heuristics to determine whether the OS thread for this thread is
/// present in the dump. Since the EE notifies us of EE Threads which may still
/// exist, but for which the OS thread has exited, it is quite possible
/// to encounter dumps with an EE Thread, but no corresponding OS thread.
/// </summary>
/// <returns>Boolean indicating whether the OS thread for this thread is
/// present in the dump</returns>
private bool IsOSThreadPresentInDump()
{
// Don't call if we're not dump debugging
Debug.Assert(m_threadMgr.m_process.DumpReader != null);
try
{
// Since we're debugging a dump, the CLR must be new enough
// to support ICorDebugThread2 (and then some).
ICorDebugThread2 th2 = m_corThread.Raw as ICorDebugThread2;
Debug.Assert(th2 != null);
uint osThreadID;
th2.GetVolatileOSThreadID(out osThreadID);
if (osThreadID == 0)
return false;
if (m_threadMgr.m_process.DumpReader.GetThread((int)osThreadID) == null)
return false;
}
catch
{
// It's reasonable for the above to throw exceptions simply
// because the OS thread is not present in the dump. For example, some
// of the above calls go through mscordbi, and then back into our
// DumpReader, which returns errors if it can't find the requested data.
return false;
}
return true;
}
// The function verifies that the stackwalker for this thread is "current". The stack-walker will become
// invalid when a debugger performs an operation that invalidats active stackwalkers. Examples of such
// operations are:
// - calling Continue(), calling SetIP() or calling RefreshStack() methods.
//
// If the current stack-walker is not current, a new stack-walker is created for the thread. The function
// also sets the current frame if the stack walker is refreshed.
//
private void EnsureCurrentStackWalker()
{
lock (m_stackLock)
{
if (m_stackWalker != null)
{
return;
}
m_stackWalker = new FrameCache(m_threadMgr.FrameFactory.EnumerateFrames(this), this);
// initialize the frame index to be the invalid index. -1 is a special value here.
m_currentFrameIndex = -1;
int idx = 0;
try
{
while (true)
{
MDbgFrame f = null;
try
{
// set m_currentFrame to first non-Internal frame
f = m_stackWalker.GetFrame(idx);
}
catch
{
// It is acceptable that the above might throw an exception, if the
// reason is that the OS thread is not in the dump. This
// can happen because the CLR debugging API can notify us of managed
// threads whose OS counterpart has already been destroyed, and is thus
// no longer in the dump. In such a case, just fall through and return
// without having found a current frame for this thread's stack walk.
// Otherwise, propagate the exception.
if (m_threadMgr.m_process.DumpReader == null)
{
// Not debugging a dump, so we wouldn't expect an exception here.
// Don't swallow
throw;
}
if (IsOSThreadPresentInDump())
{
// Looks like we're trying to get a stackwalk of a valid thread in the dump,
// meaning the exception that was thrown was a bad one. Rethrow it.
throw;
}
}
if (f == null)
{
// Hit the end of the stack without finding a frame that we can set as the
// current frame. Should still be set to "no current frame"
Debug.Assert(m_currentFrameIndex == -1);
return;
}
// Skip InfoOnly frames.
if (!f.IsInfoOnly)
{
m_currentFrameIndex = idx;
return;
}
idx++;
}
}
catch (NotImplementedException)
{
// If any of the stackwalking APIs are not implemented, then we have no
// stackwalker, and act like there's no current frame.
}
}
}
//////////////////////////////////////////////////////////////////////////////////
//
// Local variables
//
//////////////////////////////////////////////////////////////////////////////////
internal MDbgThreadCollection m_threadMgr;
private CorThread m_corThread;
private int m_threadNumber;
private int m_currentFrameIndex; // 0-based index of the current frame counted from the leafmost frame
// have value -1, when there is no current frame.
// Stackwalker builds on ICorDebug stackwalking APIs to produce a MDbgFrame collection.
// This abstracts:
// - which APIs to use
// - and which policy to use (eg, what to do about unmanaged frames + native stackwalking, funclets, etc)
// - any other filtering (eg, special language-specific stack massaging)
// Create a new instance each time we want to walk the stack. A given stackWalker instance
// caches the frames of the current stack.
internal FrameCache m_stackWalker;
// Synchronizes all access to the thread stack
object m_stackLock = new object();
}
/// <summary>
/// MDbg Thread Collection class.
/// </summary>
public sealed class MDbgThreadCollection : MarshalByRefObject, IEnumerable
{
internal MDbgThreadCollection(MDbgProcess process)
{
m_process = process;
m_freeThreadNumber = 0;
}
IEnumerator IEnumerable.GetEnumerator()
{
MDbgThread[] ret = new MDbgThread[m_items.Count];
m_items.Values.CopyTo(ret, 0);
Array.Sort(ret);
return ret.GetEnumerator();
}
/// <summary>
/// How many threads are in the collection.
/// </summary>
/// <value>How many threads.</value>
public int Count
{
get
{
return m_items.Count;
}
}
/// <summary>
/// Allows for indexing of the collection by thread number.
/// </summary>
/// <param name="threadNumber">Which thread number to access.</param>
/// <returns>The MDbgThread at that number.</returns>
public MDbgThread this[int threadNumber]
{
get
{
return GetThreadFromThreadNumber(threadNumber);
}
}
/// <summary>
/// Lookup a MDbgThread using a CorThread.
/// </summary>
/// <param name="thread">The CorThread to use.</param>
/// <returns>The rusulting MDbgThread with the same ID.</returns>
public MDbgThread Lookup(CorThread thread)
{
return GetThreadFromThreadId(thread.Id);
}
/// <summary>
/// Gets on sets the Active Thread.
/// </summary>
/// <value>The Active Thread.</value>
public MDbgThread Active
{
get
{
if (m_active == null)
throw new MDbgNoActiveInstanceException("No active thread");
return m_active;
}
set
{
Debug.Assert(value != null &&
m_items.Contains(value.CorThread.Id));
if (value == null || !m_items.Contains(value.CorThread.Id))
throw new ArgumentException();
m_active = value;
}
}
/// <summary>
/// Gets if the collection has an Active Thread.
/// </summary>
/// <value>true if it has an Active Thread, else false.</value>
public bool HaveActive
{
get
{
return m_active != null;
}
}
/// <summary>
/// Gets or sets the current FrameFactory object for MDbgEngine stackwalking implementation.
/// </summary>
public IMDbgFrameFactory FrameFactory
{
get
{
if (m_frameFactory == null)
{
// we need to get a default frame factory
if (m_process.m_engine.m_defaultStackWalkingFrameFactoryProvider != null)
{
m_frameFactory = m_process.m_engine.m_defaultStackWalkingFrameFactoryProvider();
}
// default fallback mechanism if we do not have frameFactory provider or
// the provider returns null
if (m_frameFactory == null)
{
m_frameFactory = new MDbgLatestFrameFactory();
}
}
return m_frameFactory;
}
set
{
InvalidateAllStacks();
m_frameFactory = value;
}
}
/// <summary>
/// This function needs to be called when we do "setip" so that callstack will get refreshed.
/// </summary>
[Obsolete("Use InvalidateAllStacks() which has identical functionality and is more accurately named")]
public void RefreshStack()
{
InvalidateAllStacks();
}
internal void Register(CorThread t)
{
// Prevent double-registration. This may happen if we pick up a CorThread
// via enumeration before the CreateThread callback.
if (!m_items.Contains(t.Id))
{
m_items.Add(t.Id, new MDbgThread(this, t, m_freeThreadNumber++));
}
}
internal void UnRegister(CorThread t)
{
m_items.Remove(t.Id);
if (m_active != null &&
m_active.CorThread.Id == t.Id)
{
m_active = null;
}
}
internal void Clear()
{
m_items.Clear();
m_active = null;
m_freeThreadNumber = 0;
}
internal void SetActiveThread(CorThread thread)
{
if (thread == null)
{
m_active = null;
}
else
{
m_active = GetThreadFromThreadId(thread.Id);
}
InvalidateAllStacks();
}
/// <summary>
/// Invalidates all stackwalkers
/// </summary>
public void InvalidateAllStacks()
{
foreach (MDbgThread thread in m_items.Values)
{
thread.InvalidateStackWalker();
}
}
/// <summary>
/// Gets the MDbgThread with the given ThreadId.
/// </summary>
/// <param name="threadId">The ThreadId to look up.</param>
/// <returns>The MDbgThread.</returns>
public MDbgThread GetThreadFromThreadId(int threadId)
{
// This sometimes fails because we're looking for a thread don't recognize.
// Need to offer lazy create semantics here.
MDbgThread te = (MDbgThread)m_items[threadId];
if (te == null)
{
CorThread t = m_process.CorProcess.GetThread(threadId);
if (t != null)
{
Register(t);
te = (MDbgThread)m_items[threadId];
}
}
return te;
}
private MDbgThread GetThreadFromThreadNumber(int threadNumber)
{
foreach (MDbgThread te in m_items.Values)
{
if (te.Number == threadNumber)
{
return te;
}
}
return null;
}
private Hashtable m_items = new Hashtable();
private int m_freeThreadNumber;
private MDbgThread m_active;
internal MDbgProcess m_process;
private IMDbgFrameFactory m_frameFactory;
}
/// <summary>
/// MDbg Frame class
/// MDbgFrame is defined as abstract so that we can have
/// different kind of frames. There could be e.g. ManagedFrames
/// (IL code) and NativeFrames (native) corresponding to native
/// code.
/// </summary>
public abstract class MDbgFrame
{
/// <summary>
/// Returns cor-wrapper for frame or throws an exception if N/A.
/// </summary>
/// <value>The cor-wrapper for the frame.</value>
public abstract CorFrame CorFrame
{
get;
}
/// <summary>
/// Returns thread owning this frame.
/// </summary>
/// <value>The Thread.</value>
public abstract MDbgThread Thread
{
get;
}
/// <summary>
/// Return true if frame has a managed IL code behind it.
/// </summary>
/// <value>true if frame is managed, else false.</value>
public abstract bool IsManaged
{
get;
}
/// <summary>
/// Returns true if the frame is informational (i.e. informative/internal).
/// </summary>
/// <value>true if frame is informational, else false.</value>
public abstract bool IsInfoOnly
{
get;
}
/// <summary>
/// Returns source position for the frame or null if not available.
/// </summary>
/// <value>The Source Position.</value>
public abstract MDbgSourcePosition SourcePosition
{
get;
}
/// <summary>
/// Returns function whose code is executed in this frame.
/// </summary>
/// <value>The Function.</value>
public abstract MDbgFunction Function
{
get;
}
/// <summary>
/// Returns next frame up the stack or null if topmost frame.
/// </summary>
/// <value>The next frame up.</value>
public abstract MDbgFrame NextUp
{
get;
}
/// <summary>
/// Returns next frame down the stack or null if bottom frame.
/// </summary>
/// <value>The next frame up.</value>
public abstract MDbgFrame NextDown
{
get;
}
/// <summary>
/// Returns a string that represents current frame
/// Currently supported formats:
/// null or empty string: returns short frame format (just frame name)
/// "v" : returns long frame format (including module & arguments)
/// </summary>
/// <param name="format">Which format to use.</param>
/// <returns>The formatted string that represtents the current frame.</returns>
public abstract string ToString(string format);
/// <summary>
/// Equality testing. Allows for things like "if(thing1 == thing2)" to work properly.
/// </summary>
/// <param name="operand">First Operand.</param>
/// <param name="operand2">Second Operand.</param>
/// <returns>true if equal, else false.</returns>
public static bool operator ==(MDbgFrame operand, MDbgFrame operand2)
{
if (Object.ReferenceEquals(operand, operand2))
return true;
// If both are null, then ReferenceEqual would return true.
// We still need to check if one is null and the other is non-null.
if (((object)operand == null) || ((object)operand2 == null))
return false;
return operand.Equals(operand2);
}
/// <summary>
/// Inequality testing. Allows for things like "if(thing1 != thing2)" to work properly.
/// </summary>
/// <param name="operand">First Operand.</param>
/// <param name="operand2">Second Operand.</param>
/// <returns>true if not equal, else false.</returns>
public static bool operator !=(MDbgFrame operand, MDbgFrame operand2)
{
return !(operand == operand2);
}
/// <summary>
/// Determines whether the specified object is equal to the other object.
/// </summary>
/// <param name="value">The object to compare with the current frame.</param>
public abstract override bool Equals(Object value);
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public abstract override int GetHashCode();
}
/// <summary>
/// The MDbgILFrame class is a frame with Intermediate Language code behind it.
/// </summary>
public abstract class MDbgFrameBase : MDbgFrame
{
/// <summary>
/// Creates an instance of class MDbgFramebase.
/// </summary>
/// <param name="thread"></param>
protected MDbgFrameBase(MDbgThread thread)
{
Debug.Assert(thread != null);
m_thread = thread;
}
/// <summary>
/// Returns thread owning this frame.
/// </summary>
/// <value>The Thread.</value>
public override MDbgThread Thread
{
get
{
return m_thread;
}
}
/// <summary>
/// Returns next frame up the stack or null if topmost frame.
/// </summary>
/// <value>The next frame up.</value>
public override MDbgFrame NextUp
{
get
{
return m_thread.m_stackWalker.GetFrame(m_thread.m_stackWalker.GetFrameIndex(this) + 1);
}
}
/// <summary>
/// Returns next frame down the stack or null if bottom frame.
/// </summary>
/// <value>The next frame up.</value>
public override MDbgFrame NextDown
{
get
{
return m_thread.m_stackWalker.GetFrame(m_thread.m_stackWalker.GetFrameIndex(this) - 1);
}
}
/// <summary>
/// Returns a string that represents current frame using default formatting.
/// </summary>
/// <returns>The default formatted string that represtents the current frame.</returns>
public override string ToString()
{
return ToString(null);
}
// Type parameter information.
private MDbgThread m_thread;
}
/// <summary>
/// The MDbgILFrame class is a frame with Intermediate Language code behind it.
/// </summary>
public sealed class MDbgILFrame : MDbgFrameBase
{
internal MDbgILFrame(MDbgThread thread, CorFrame frame)
: base(thread)
{
Debug.Assert(frame != null);
m_frame = frame;
}
/// <summary>
/// Determines if the wrapped object is equal to another.
/// </summary>
/// <param name="value">The object to compare to.</param>
/// <returns>true if equal, else false.</returns>
public override bool Equals(Object value)
{
if (!(value is MDbgILFrame))
return false;
return ((value as MDbgILFrame).m_frame == this.m_frame);
}
/// <summary>
/// Required to implement MarshalByRefObject.
/// </summary>
/// <returns>Hash Code.</returns>
public override int GetHashCode()
{
return m_frame.GetHashCode();
}
/// <summary>
/// Returns cor-wrapper for frame or throws an exception if N/A.
/// </summary>
/// <value>The cor-wrapper for the frame.</value>
public override CorFrame CorFrame
{
get
{
return m_frame;
}
}
/// <summary>
/// Return true if frame has a managed IL code behind it.
/// </summary>
/// <value>true if frame is managed, else false.</value>
public override bool IsManaged
{
get
{
return (m_frame.FrameType == CorFrameType.ILFrame);
}
}
/// <summary>
/// Returns true if the frame is informational (i.e. informative/internal).
/// MDbg does not allow users to set an informational frame as the current frame.
/// </summary>
/// <value>true if frame is informational, else false.</value>
public override bool IsInfoOnly
{
get
{
// Currently we are marking NativeFrames as informational as well.
// Since they don't have corresponding ILFrames, users can't do much with them anyways.
// However, once we implement debugging support for dynamic languages,
// we should definitely consider unmarking them.
return ((m_frame.FrameType == CorFrameType.InternalFrame) ||
(m_frame.FrameType == CorFrameType.NativeFrame));
}
}
/// <summary>
/// Returns source position for the frame or null if not available.
/// </summary>
/// <value>The Source Position.</value>
public override MDbgSourcePosition SourcePosition
{
get
{
MDbgFunction f = null;
// we can return source position only for ILFrames.
if (IsManaged)
f = Function;
return (f == null) ? null : f.GetSourcePositionFromFrame(m_frame);
}
}
/// <summary>
/// Returns function whose code is executed in this frame.
/// </summary>
/// <value>The Function.</value>
public override MDbgFunction Function
{
get
{
return Thread.m_threadMgr.m_process.Modules.LookupFunction(m_frame.Function);
}
}
/// <summary>
/// Get a CorType that function for this frame is declared in.
/// </summary>
//
// If the frame is Class<int>::Func<string>,
// get a CorType representing 'Class<int>'.
// The CorClass would only give us 'Class<T>', and the
// Function only gives Func<U>
// Returns 'null' for global methods.
//
public CorType FunctionType
{
get
{
MDbgFunction f = this.Function;
CorClass c = f.CorFunction.Class;
Debug.Assert(TokenUtils.TypeFromToken(c.Token) == CorTokenType.mdtTypeDef);
// Check if we're the "global" class, in which case this is a global method, so return null.
if (TokenUtils.RidFromToken(c.Token) == 1
|| TokenUtils.RidFromToken(c.Token) == 0)
return null;
// ICorDebug API lets us always pass ET_Class
CorElementType et = CorElementType.ELEMENT_TYPE_CLASS;
// Get type parameters.
IEnumerable typars = m_frame.TypeParameters;
MDbgModule module = this.Function.Module;
int cNumTyParamsOnClass = module.Importer.CountGenericParams(c.Token);
CorType[] args = new CorType[cNumTyParamsOnClass];
int i = 0;
foreach (CorType arg in typars)
{
if (i == cNumTyParamsOnClass)
{
break;
}
args[i] = arg;
i++;
}
CorType t = c.GetParameterizedType(et, args);
return t;
}
}
/// <summary> Return an enumerator that enumerates through just the generic args on this frame's method </summary>
/// <remarks>Enumerating generic args on the frame gives a single collection including both
/// class and function args. This is a helper to skip past the class and use just the funciton args.</remarks>
public IEnumerable FunctionTypeParameters
{
get
{
MDbgModule module = this.Function.Module;
CorClass c = this.Function.CorFunction.Class;
int cNumTyParamsOnClass = module.Importer.CountGenericParams(c.Token);
return m_frame.GetTypeParamEnumWithSkip(cNumTyParamsOnClass);
}
}
/// <summary>
/// Returns a string that represents current frame
/// Currently supported formats:
/// null or empty string: returns short frame format (just frame name)
/// "v" : returns long frame format (including module & arguments)
/// </summary>
/// <param name="format">Which format to use.</param>
/// <returns>The formatted string that represtents the current frame.</returns>
public override string ToString(string format)
{
string fn;
switch (m_frame.FrameType)
{
case CorFrameType.ILFrame:
MDbgSourcePosition sl = SourcePosition;
string sp;
if (sl != null)
{
string filePath = sl.Path;
if (!Thread.m_threadMgr.m_process.m_engine.Options.ShowFullPaths)
filePath = Path.GetFileName(sl.Path);
sp = " (" + filePath + ":" + sl.Line.ToString(System.Globalization.CultureInfo.CurrentUICulture) + ")";
}
else
sp = " (source line information unavailable)";
StringBuilder sbFuncName = new StringBuilder();
MDbgModule module = this.Function.Module;
MDbgProcess proc = Thread.m_threadMgr.m_process;
// Get class name w/ generic args.
CorType tClass = this.FunctionType;
if (tClass != null)
InternalUtil.PrintCorType(sbFuncName, proc, tClass);
sbFuncName.Append('.');
// Get method name w/ generic args.
MethodInfo mi = this.Function.MethodInfo;
sbFuncName.Append(mi.Name);
InternalUtil.AddGenericArgs(sbFuncName, proc, this.FunctionTypeParameters);
string stFuncName = sbFuncName.ToString();
if (format == "v")
{
CorModule m = module.CorModule;
// verbose frame output
// in verbose output we'll print module name + arguments to the functions
StringBuilder sb = new StringBuilder();
bool bFirst = true;
foreach (MDbgValue v in this.Function.GetArguments(this))
{
if (sb.Length != 0)
sb.Append(", ");
// skip this references
if (!(bFirst && v.Name == "this"))
sb.Append(v.Name).Append("=").Append(v.GetStringValue(0));
bFirst = false;
}
if (m.IsDynamic || m.IsInMemory)
{
fn = m.Name;
}
else
{
fn = System.IO.Path.GetFileName(m.Name);
}
MDbgAppDomain ad = this.Thread.m_threadMgr.m_process.AppDomains.Lookup(m.Assembly.AppDomain);
fn += "#" + ad.Number
+ "!" + stFuncName + "(" + sb.ToString() + ") " + sp;
}
else
{
fn = stFuncName + sp;
}
break;
case CorFrameType.NativeFrame:
fn = "[IL Method without Metadata]";
break;
case CorFrameType.InternalFrame:
switch (m_frame.InternalFrameType)
{
case CorDebugInternalFrameType.STUBFRAME_NONE:
fn = "None";
break;
case CorDebugInternalFrameType.STUBFRAME_M2U:
fn = "M-->U";
break;
case CorDebugInternalFrameType.STUBFRAME_U2M:
fn = "U-->M";
break;
case CorDebugInternalFrameType.STUBFRAME_APPDOMAIN_TRANSITION:
fn = "AD Switch";
break;
case CorDebugInternalFrameType.STUBFRAME_LIGHTWEIGHT_FUNCTION:
fn = "LightWeight";
break;
case CorDebugInternalFrameType.STUBFRAME_FUNC_EVAL:
fn = "FuncEval";
break;
case CorDebugInternalFrameType.STUBFRAME_INTERNALCALL:
fn = "InternalCall";
break;
case CorDebugInternalFrameType.STUBFRAME_CLASS_INIT:
fn = "ClassInit";
break;
case CorDebugInternalFrameType.STUBFRAME_EXCEPTION:
fn = "Exception";
break;
case CorDebugInternalFrameType.STUBFRAME_SECURITY:
fn = "Security";
break;
case CorDebugInternalFrameType.STUBFRAME_JIT_COMPILATION:
fn = "JitCompilation";
break;
default:
fn = "UNKNOWN";
break;
}
fn = "[Internal Frame, '" + fn + "']";
break;
default:
fn = "UNKNOWN Frame Type";
break;
}
return fn;
}
// Type parameter information.
private CorFrame m_frame;
}
}
| |
//
// CharsetUtils.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2012 Jeffrey Stedfast
//
// 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.Text;
using System.Collections.Generic;
namespace MimeKit.Utils {
static class CharsetUtils
{
static readonly StringComparer icase = StringComparer.InvariantCultureIgnoreCase;
static readonly Dictionary<string, int> aliases;
static CharsetUtils ()
{
aliases = new Dictionary<string, int> (icase);
aliases.Add ("utf-8", 65001);
aliases.Add ("utf8", 65001);
// ANSI_X3.4-1968 is used on some systems and should be
// treated the same as US-ASCII.
aliases.Add ("ansi_x3.4-1968", 20127);
// Korean charsets (aliases for euc-kr)
// 'upgrade' ks_c_5601-1987 to euc-kr since it is a superset
aliases.Add ("ks_c_5601-1987", 51949);
aliases.Add ("5601", 51949);
aliases.Add ("ksc-5601", 51949);
aliases.Add ("ksc-5601-1987", 51949);
aliases.Add ("ksc-5601_1987", 51949);
aliases.Add ("ks_c_5861-1992", 51949);
aliases.Add ("euckr-0", 51949);
aliases.Add ("euc-kr", 51949);
// Chinese charsets (aliases for big5)
aliases.Add ("big5", 950);
aliases.Add ("big5-0", 950);
aliases.Add ("big5.eten-0", 950);
aliases.Add ("big5hkscs-0", 950);
// Chinese charsets (aliases for gbk / euc-cn)
// 'upgrade' gb2312 to GBK (aka euc-cn) since it is a superset
aliases.Add ("gb2312", 51936);
aliases.Add ("gb-2312", 51936);
aliases.Add ("gb2312-0", 51936);
aliases.Add ("gb2312-80", 51936);
aliases.Add ("gb2312.1980-0", 51936);
aliases.Add ("euc-cn", 51936);
aliases.Add ("gbk-0", 51936);
aliases.Add ("gbk", 51936);
// Chinese charsets (aliases for gb18030)
aliases.Add ("gb18030-0", 54936);
aliases.Add ("gb18030", 54936);
// Japanese charsets (aliases for euc-jp)
aliases.Add ("eucjp-0", 51932);
aliases.Add ("euc-jp", 51932);
aliases.Add ("ujis-0", 51932);
aliases.Add ("ujis", 51932);
// Japanese charsets (aliases for Shift_JIS)
aliases.Add ("jisx0208.1983-0", 932);
aliases.Add ("jisx0212.1990-0", 932);
aliases.Add ("pck", 932);
// Note from http://msdn.microsoft.com/en-us/library/system.text.encoding.getencodings.aspx
// Encodings 50220 and 50222 are both associated with the name "iso-2022-jp", but they
// are not identical. Encoding 50220 converts half-width Katakana characters to
// full-width Katakana characters, whereas encoding 50222 uses a shift-in/shift-out
// sequence to encode half-width Katakana characters. The display name for encoding
// 50222 is "Japanese (JIS-Allow 1 byte Kana - SO/SI)" to distinguish it from encoding
// 50220, which has the display name "Japanese (JIS)".
//
// If your application requests the encoding name "iso-2022-jp", the .NET Framework
// returns encoding 50220. However, the encoding that is appropriate for your application
// will depend on the preferred treatment of the half-width Katakana characters.
}
public static string GetMimeCharset (Encoding encoding)
{
if (encoding == null)
throw new ArgumentNullException ("encoding");
switch (encoding.CodePage) {
case 949: // ks_c_5601-1987
return "euc-kr";
default:
return encoding.HeaderName.ToLowerInvariant ();
}
}
public static string GetMimeCharset (string charset)
{
try {
var encoding = GetEncoding (charset);
return GetMimeCharset (encoding);
} catch (NotSupportedException) {
return charset;
}
}
static int ParseIsoCodePage (string charset)
{
if (charset.Length < 6)
return -1;
int dash = charset.IndexOfAny (new char[] { '-', '_' });
if (dash == -1)
dash = charset.Length;
int iso;
if (!int.TryParse (charset.Substring (0, dash), out iso))
return -1;
if (iso == 10646)
return 1201;
if (dash + 2 > charset.Length)
return -1;
string suffix = charset.Substring (dash + 1);
int codepage;
switch (iso) {
case 8859:
if (!int.TryParse (suffix, out codepage))
return -1;
if (codepage <= 0 || (codepage > 9 && codepage < 13) || codepage > 15)
return -1;
codepage += 28590;
break;
case 2022:
switch (suffix.ToLowerInvariant ()) {
case "jp":
codepage = 50220;
break;
case "kr":
codepage = 50225;
break;
default:
return -1;
}
break;
default:
return -1;
}
return codepage;
}
static int ParseCodePage (string charset)
{
int codepage;
int i;
if (charset.StartsWith ("windows", StringComparison.OrdinalIgnoreCase)) {
i = 7;
if (i == charset.Length)
return -1;
if (charset[i] == '-' || charset[i] == '_') {
if (i + 1 == charset.Length)
return -1;
i++;
}
if (i + 2 < charset.Length && charset[i] == 'c' && charset[i + 1] == 'p')
i += 2;
if (int.TryParse (charset.Substring (i), out codepage))
return codepage;
} else if (charset.StartsWith ("iso", StringComparison.OrdinalIgnoreCase)) {
i = 3;
if (i == charset.Length)
return -1;
if (charset[i] == '-' || charset[i] == '_')
i++;
if ((codepage = ParseIsoCodePage (charset.Substring (i))) != -1)
return codepage;
} else if (charset.StartsWith ("cp", StringComparison.OrdinalIgnoreCase)) {
i = 2;
if (i == charset.Length)
return -1;
if (charset[i] == '-' || charset[i] == '_')
i++;
if (int.TryParse (charset.Substring (i), out codepage))
return codepage;
} else if (charset == "latin1") {
return 28591;
} else {
foreach (var info in Encoding.GetEncodings ()) {
if (icase.Compare (info.Name, charset) == 0)
return info.CodePage;
}
}
return -1;
}
public static int GetCodePage (string charset)
{
if (charset == null)
throw new ArgumentNullException ("charset");
int codepage;
lock (aliases) {
if (!aliases.TryGetValue (charset, out codepage)) {
codepage = ParseCodePage (charset);
if (codepage == -1)
return -1;
try {
var encoding = Encoding.GetEncoding (codepage);
aliases[encoding.HeaderName] = codepage;
} catch (NotSupportedException) {
codepage = -1;
}
aliases[charset] = codepage;
}
}
return codepage;
}
public static Encoding GetEncoding (string charset, string fallback)
{
int codepage;
if (charset == null)
throw new ArgumentNullException ("charset");
if (fallback == null)
throw new ArgumentNullException ("fallback");
if ((codepage = GetCodePage (charset)) == -1)
throw new NotSupportedException ();
var encoderFallback = new EncoderReplacementFallback (fallback);
var decoderFallback = new DecoderReplacementFallback (fallback);
return Encoding.GetEncoding (codepage, encoderFallback, decoderFallback);
}
public static Encoding GetEncoding (string charset)
{
int codepage = GetCodePage (charset);
if (codepage == -1)
throw new NotSupportedException ();
return Encoding.GetEncoding (codepage);
}
public static Encoding GetEncoding (int codepage, string fallback)
{
if (fallback == null)
throw new ArgumentNullException ("fallback");
var encoderFallback = new EncoderReplacementFallback (fallback);
var decoderFallback = new DecoderReplacementFallback (fallback);
return Encoding.GetEncoding (codepage, encoderFallback, decoderFallback);
}
public static Encoding GetEncoding (int codepage)
{
return Encoding.GetEncoding (codepage);
}
class InvalidByteCountFallback : DecoderFallback
{
class InvalidByteCountFallbackBuffer : DecoderFallbackBuffer
{
readonly InvalidByteCountFallback fallback;
const string replacement = "?";
int current = 0;
bool invalid;
public InvalidByteCountFallbackBuffer (InvalidByteCountFallback fallback)
{
this.fallback = fallback;
}
public override bool Fallback (byte[] bytesUnknown, int index)
{
fallback.InvalidByteCount++;
invalid = true;
current = 0;
return true;
}
public override char GetNextChar ()
{
if (!invalid)
return '\0';
if (current == replacement.Length)
return '\0';
return replacement[current++];
}
public override bool MovePrevious ()
{
if (current == 0)
return false;
current--;
return true;
}
public override int Remaining {
get { return invalid ? replacement.Length - current : 0; }
}
public override void Reset ()
{
invalid = false;
current = 0;
base.Reset ();
}
}
public InvalidByteCountFallback ()
{
Reset ();
}
public int InvalidByteCount {
get; private set;
}
public void Reset ()
{
InvalidByteCount = 0;
}
public override DecoderFallbackBuffer CreateFallbackBuffer ()
{
return new InvalidByteCountFallbackBuffer (this);
}
public override int MaxCharCount {
get { return 1; }
}
}
internal static char[] ConvertToUnicode (ParserOptions options, byte[] input, int startIndex, int length, out int charCount)
{
var invalid = new InvalidByteCountFallback ();
var userCharset = options.CharsetEncoding;
int min = Int32.MaxValue;
int bestCharCount = 0;
char[] output = null;
Encoding encoding;
Decoder decoder;
int[] codepages;
int best = -1;
int count;
// Note: 65001 is UTF-8 and 28591 is iso-8859-1
if (userCharset != null && userCharset.CodePage != 65001 && userCharset.CodePage != 28591) {
codepages = new int[] { 65001, userCharset.CodePage, 28591 };
} else {
codepages = new int[] { 65001, 28591 };
}
for (int i = 0; i < codepages.Length; i++) {
encoding = Encoding.GetEncoding (codepages[i], new EncoderReplacementFallback ("?"), invalid);
decoder = encoding.GetDecoder ();
count = decoder.GetCharCount (input, startIndex, length, true);
if (invalid.InvalidByteCount < min) {
min = invalid.InvalidByteCount;
bestCharCount = count;
best = codepages[i];
if (min == 0)
break;
}
invalid.Reset ();
}
encoding = CharsetUtils.GetEncoding (best, "?");
decoder = encoding.GetDecoder ();
output = new char[bestCharCount];
charCount = decoder.GetChars (input, startIndex, length, output, 0, true);
return output;
}
public static string ConvertToUnicode (ParserOptions options, byte[] buffer, int startIndex, int length)
{
if (options == null)
throw new ArgumentNullException ("options");
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (startIndex < 0 || startIndex > buffer.Length)
throw new ArgumentOutOfRangeException ("startIndex");
if (length < 0 || startIndex + length > buffer.Length)
throw new ArgumentOutOfRangeException ("length");
int count;
return new string (ConvertToUnicode (options, buffer, startIndex, length, out count), 0, count);
}
internal static char[] ConvertToUnicode (Encoding encoding, byte[] input, int startIndex, int length, out int charCount)
{
var decoder = encoding.GetDecoder ();
int count = decoder.GetCharCount (input, startIndex, length, true);
char[] output = new char[count];
charCount = decoder.GetChars (input, startIndex, length, output, 0, true);
return output;
}
internal static char[] ConvertToUnicode (ParserOptions options, int codepage, byte[] input, int startIndex, int length, out int charCount)
{
Encoding encoding = null;
if (codepage != -1) {
try {
encoding = CharsetUtils.GetEncoding (codepage);
} catch (NotSupportedException) {
}
}
if (encoding == null)
return ConvertToUnicode (options, input, startIndex, length, out charCount);
return ConvertToUnicode (encoding, input, startIndex, length, out charCount);
}
public static string ConvertToUnicode (Encoding encoding, byte[] buffer, int startIndex, int length)
{
if (encoding == null)
throw new ArgumentNullException ("encoding");
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (startIndex < 0 || startIndex > buffer.Length)
throw new ArgumentOutOfRangeException ("startIndex");
if (length < 0 || startIndex + length > buffer.Length)
throw new ArgumentOutOfRangeException ("length");
int count;
return new string (ConvertToUnicode (encoding, buffer, startIndex, length, out count), 0, count);
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Text;
namespace Microsoft.PythonTools.Debugger {
static class Extensions {
/// <summary>
/// Reads a string from the socket which is encoded as:
/// U, byte count, bytes
/// A, byte count, ASCII
///
/// Which supports either UTF-8 or ASCII strings.
/// </summary>
internal static string ReadString(this Stream stream) {
int type = stream.ReadByte();
if (type < 0) {
Debug.Assert(false, "Socket.ReadString failed to read string type");
throw new IOException();
}
bool isUnicode;
switch ((char)type) {
case 'N': // null string
return null;
case 'U':
isUnicode = true;
break;
case 'A':
isUnicode = false;
break;
default:
Debug.Assert(false, "Socket.ReadString failed to parse unknown string type " + (char)type);
throw new IOException();
}
int len = stream.ReadInt32();
byte[] buffer = new byte[len];
stream.ReadToFill(buffer);
if (isUnicode) {
return Encoding.UTF8.GetString(buffer);
} else {
char[] chars = new char[buffer.Length];
for (int i = 0; i < buffer.Length; i++) {
chars[i] = (char)buffer[i];
}
return new string(chars);
}
}
internal static int ReadInt32(this Stream stream) {
return (int)stream.ReadInt64();
}
internal static long ReadInt64(this Stream stream) {
byte[] buf = new byte[8];
stream.ReadToFill(buf);
// Can't use BitConverter because we need to convert big-endian to little-endian here,
// and BitConverter.IsLittleEndian is platform-dependent (and usually true).
ulong hi = (ulong)(uint)((buf[0] << 0x18) | (buf[1] << 0x10) | (buf[2] << 0x08) | (buf[3] << 0x00));
ulong lo = (ulong)(uint)((buf[4] << 0x18) | (buf[5] << 0x10) | (buf[6] << 0x08) | (buf[7] << 0x00));
return (long)((hi << 0x20) | lo);
}
internal static string ReadAsciiString(this Stream stream, int length) {
var buf = new byte[length];
stream.ReadToFill(buf);
return Encoding.ASCII.GetString(buf, 0, buf.Length);
}
internal static void ReadToFill(this Stream stream, byte[] b) {
int count = stream.ReadBytes(b, b.Length);
if (count != b.Length) {
throw new EndOfStreamException();
}
}
internal static int ReadBytes(this Stream stream, byte[] b, int count) {
int i = 0;
while (i < count) {
int read = stream.Read(b, i, count - i);
if (read == 0) {
break;
}
i += read;
}
return i;
}
internal static void WriteInt32(this Stream stream, int x) {
stream.WriteInt64(x);
}
internal static void WriteInt64(this Stream stream, long x) {
// Can't use BitConverter because we need to convert big-endian to little-endian here,
// and BitConverter.IsLittleEndian is platform-dependent (and usually true).
uint hi = (uint)((ulong)x >> 0x20);
uint lo = (uint)((ulong)x & 0xFFFFFFFFu);
byte[] buf = {
(byte)((hi >> 0x18) & 0xFFu),
(byte)((hi >> 0x10) & 0xFFu),
(byte)((hi >> 0x08) & 0xFFu),
(byte)((hi >> 0x00) & 0xFFu),
(byte)((lo >> 0x18) & 0xFFu),
(byte)((lo >> 0x10) & 0xFFu),
(byte)((lo >> 0x08) & 0xFFu),
(byte)((lo >> 0x00) & 0xFFu)
};
stream.Write(buf, 0, buf.Length);
}
internal static void WriteString(this Stream stream, string str) {
byte[] bytes = Encoding.UTF8.GetBytes(str);
stream.WriteInt32(bytes.Length);
if (bytes.Length > 0) {
stream.Write(bytes);
}
}
internal static void Write(this Stream stream, byte[] b) {
stream.Write(b, 0, b.Length);
}
/// <summary>
/// Replaces \uxxxx with the actual unicode char for a prettier display in local variables.
/// </summary>
public static string FixupEscapedUnicodeChars(this string text) {
StringBuilder buf = null;
int i = 0;
int l = text.Length;
int val;
while (i < l) {
char ch = text[i++];
if (ch == '\\') {
if (buf == null) {
buf = new StringBuilder(text.Length);
buf.Append(text, 0, i - 1);
}
if (i >= l) {
return text;
}
ch = text[i++];
if (ch == 'u' || ch == 'U') {
int len = (ch == 'u') ? 4 : 8;
int max = 16;
if (TryParseInt(text, i, len, max, out val)) {
buf.Append((char)val);
i += len;
} else {
return text;
}
} else {
buf.Append("\\");
buf.Append(ch);
}
} else if (buf != null) {
buf.Append(ch);
}
}
if (buf != null) {
return buf.ToString();
}
return text;
}
private static bool TryParseInt(string text, int start, int length, int b, out int value) {
value = 0;
if (start + length > text.Length) {
return false;
}
for (int i = start, end = start + length; i < end; i++) {
int onechar;
if (HexValue(text[i], out onechar) && onechar < b) {
value = value * b + onechar;
} else {
return false;
}
}
return true;
}
private static int HexValue(char ch) {
int value;
if (!HexValue(ch, out value)) {
throw new ArgumentException("bad char for integer value: " + ch);
}
return value;
}
private static bool HexValue(char ch, out int value) {
switch (ch) {
case '0':
case '\x660': value = 0; break;
case '1':
case '\x661': value = 1; break;
case '2':
case '\x662': value = 2; break;
case '3':
case '\x663': value = 3; break;
case '4':
case '\x664': value = 4; break;
case '5':
case '\x665': value = 5; break;
case '6':
case '\x666': value = 6; break;
case '7':
case '\x667': value = 7; break;
case '8':
case '\x668': value = 8; break;
case '9':
case '\x669': value = 9; break;
default:
if (ch >= 'a' && ch <= 'z') {
value = ch - 'a' + 10;
} else if (ch >= 'A' && ch <= 'Z') {
value = ch - 'A' + 10;
} else {
value = -1;
return false;
}
break;
}
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using System.Collections;
using System.IO;
using zlib;
namespace ARZExplorer
{
public class ARZFile
{
// The different data-types a variable can be.
public enum VariableDataType
{
Integer = 0, // values will be Int32
Float = 1, // values will be Single
StringVar = 2, // Values will be string
Boolean = 3, // Values will be Int32
Unknown = 4 // values will be Int32
};
// A variable within a DB Record
public class Variable
{
private string m_variableName;
private VariableDataType m_dataType;
private object[] m_value; // the values
public Variable(string variableName, VariableDataType dataType, int numValues)
{
m_variableName = variableName;
m_dataType = dataType;
m_value = new object[numValues];
}
public string Name
{
get
{
return m_variableName;
}
}
public VariableDataType DataType
{
get
{
return m_dataType;
}
}
public int NumValues
{
get
{
return m_value.Length;
}
}
public object this [int index]
{
get
{
return m_value[index];
}
set
{
m_value[index] = value;
}
}
// throws exception if value is not the correct type
public int GetInt32(int i)
{
return Convert.ToInt32(m_value[i]);
}
public float GetFloat(int i)
{
return Convert.ToSingle(m_value[i]);
}
public string GetString(int i)
{
return Convert.ToString(m_value[i]);
}
public override string ToString()
{
// Format is name,val1;val2;val3;val4;...;valn,
// First set our val format string based on the data type
string formatSpec = "{0}";
if(DataType == VariableDataType.Float) formatSpec = "{0:f6}";
StringBuilder ans = new StringBuilder(64);
ans.Append(Name);
ans.Append(",");
for (int i = 0; i < NumValues; ++i)
{
if (i > 0) ans.Append (";");
ans.AppendFormat(CultureInfo.InvariantCulture, formatSpec, m_value[i]);
}
ans.Append(",");
return ans.ToString();
}
public string ToStringValue()
{
// Format is name,val1;val2;val3;val4;...;valn,
// First set our val format string based on the data type
string formatSpec = "{0}";
if(DataType == VariableDataType.Float) formatSpec = "{0:f6}";
StringBuilder ans = new StringBuilder(64);
for(int i = 0; i < NumValues; ++i)
{
if(i > 0) ans.Append(", ");
//ans.Append(m_value[i]);
ans.AppendFormat(CultureInfo.InvariantCulture, formatSpec, m_value[i]);
}
return ans.ToString();
}
/*public string ToStringNice()
{
StringBuilder ans = new StringBuilder(64);
ans.Append(Database.sDb.GetItemAttributeFriendlyText(Name));
ans.Append(": ");
ans.Append(ToStringValue());
return ans.ToString();
}*/
};
public class DBRecord
{
private string m_id;
private string m_recordType;
private Hashtable m_variables;
public DBRecord(string id, string recordType)
{
m_id = id;
m_recordType = recordType;
m_variables = new Hashtable();
}
public string ID
{
get
{
return m_id;
}
}
public string RecordType
{
get
{
return m_recordType;
}
}
public Variable this[string variableName]
{
get
{
return (Variable)m_variables[variableName];
}
}
public int Count
{
get
{
return m_variables.Count;
}
}
public void Set(Variable v) { m_variables.Add(v.Name, v); }
// Returns the variables collection
public ICollection GetVariableEnumerable() { return m_variables.Values; }
// Returns a short descriptive string: recordID,recordType,numVariables
public string ToShortString()
{
return string.Format("{0},{1},{2}", m_id, m_recordType, Count);
}
// Returns the value for the variable, or 0 if the variable does not exist.
// throws exception of the variable is not integer type
public int GetInt32(string variableName, int i)
{
Variable v = (Variable) m_variables[variableName];
if(v == null) return 0;
return v.GetInt32(i);
}
public float GetFloat(string variableName, int i)
{
Variable v = (Variable) m_variables[variableName];
if(v == null) return 0;
return v.GetFloat(i);
}
// returns "" if the variable does not exist
public string GetString(string variableName, int i)
{
Variable v = (Variable) m_variables[variableName];
if(v == null) return "";
string ans = v.GetString(i);
if (ans == null) return "";
return ans;
}
// Added by VillageIdiot
// Gets all of the string values for a particular variable entry
public string[] GetAllStrings (string variableName)
{
Variable v = (Variable) m_variables[variableName];
if(v == null) return null;
string[] ansArray = new string[v.NumValues];
for(int i = 0; i < v.NumValues ; ++i)
{
ansArray[i] = v.GetString(i);
}
return ansArray;
}
public void Write(string baseFolder)
{
Write(baseFolder, null);
}
public void Write(string baseFolder, string fileName)
{
// construct the full path
string fullPath;
string destFolder;
if (fileName == null)
{
fullPath = Path.Combine(baseFolder, ID);
destFolder = Path.GetDirectoryName(fullPath);
}
else
{
fullPath = Path.Combine(baseFolder, fileName);
destFolder = baseFolder;
}
// Create the folder path if necessary
if(!Directory.Exists(destFolder))
{
Directory.CreateDirectory(destFolder);
}
// Open the file
StreamWriter outStream = new StreamWriter(fullPath, false);
try
{
// Write all the variables
foreach ( Variable v in GetVariableEnumerable() )
{
outStream.WriteLine(v.ToString());
}
}
finally
{
outStream.Close();
}
}
};
private
class RecordInfo
{
private int m_offset;
private int m_compressedSize;
private int m_idstringIndex;
private string m_id;
private string m_recordType;
private int m_crap1; // some sort of timestamp?
private int m_crap2; // some sort of timestamp?
public RecordInfo ()
{
m_offset = 0;
m_compressedSize = 0;
m_idstringIndex = -1;
m_id = null;
m_recordType = "";
m_crap1 = 0;
m_crap2 = 0;
}
public string ID
{
get
{
return m_id;
}
}
public string RecordType
{
get
{
return m_recordType;
}
}
public void Decode(BinaryReader inReader, int baseOffset, ARZFile arzFile)
{
// Record Entry Format
// 0x0000 int32 stringEntryID (dbr filename)
// 0x0004 int32 string length
// 0x0008 string (record type)
// 0x00?? int32 offset
// 0x00?? int32 length in bytes
// 0x00?? int32 timestamp?
// 0x00?? int32 timestamp?
m_idstringIndex = inReader.ReadInt32();
m_recordType = ReadCString(inReader);
m_offset = inReader.ReadInt32() + baseOffset;
m_compressedSize = inReader.ReadInt32();
m_crap1 = inReader.ReadInt32();
m_crap2 = inReader.ReadInt32();
// Get the ID string
m_id = arzFile.Getstring(m_idstringIndex);
}
public DBRecord Decompress(ARZFile arzFile)
{
// record variables have this format:
// 0x00 int16 specifies data type:
// 0x0000 = int - data will be an int32
// 0x0001 = float - data will be a Single
// 0x0002 = string - data will be an int32 that is index into string table
// 0x0003 = bool - data will be an int32
// 0x02 int16 specifies number of values (usually 1, but sometimes more (for arrays)
// 0x04 int32 key string ID (the id into the string table for this variable name
// 0x08 data value
byte[] data = DecompressBytes(arzFile);
// Lets dump the file to disk
//System.IO.FileStream dump = new System.IO.FileStream("recdump.dat", System.IO.FileMode.Create, System.IO.FileAccess.Write);
//try
//{
// dump.Write(data, 0, data.Length);
//}
//finally
//{
// dump.Close();
//}
int numDWords = data.Length / 4;
int numVariables = numDWords / 3;
if(data.Length % 4 != 0)
{
throw new ApplicationException(string.Format("Error while parsing arz record {0}, data Length = {1} which is not a multiple of 4", ID, (int)data.Length));
}
DBRecord record = new DBRecord(ID, RecordType);
// Create a memory stream to read the binary data
MemoryStream inStream = new MemoryStream(data, false);
BinaryReader inReader = new BinaryReader(inStream);
try
{
int i = 0;
while (i < numDWords)
{
int pos = (int) inReader.BaseStream.Position;
short dataType = inReader.ReadInt16();
short valCount = inReader.ReadInt16();
int variableID = inReader.ReadInt32();
string variableName = arzFile.Getstring(variableID);
if(variableName == null)
{
throw new ApplicationException(string.Format("Error while parsing arz record {0}, variable is NULL", ID));
}
if(dataType < 0 || dataType > 3)
{
throw new ApplicationException(string.Format("Error while parsing arz record {0}, variable {2}, bad dataType {3}", ID, variableName, dataType));
}
Variable v = new Variable(variableName, (VariableDataType) dataType, valCount);
if(valCount < 1)
{
throw new ApplicationException (string.Format ("Error while parsing arz record {0}, variable {1}, bad valCount {2}", ID, variableName, valCount));
}
i += 2 + valCount; // increment our dword count
for(int j = 0; j < valCount; ++j)
{
switch (v.DataType) {
case VariableDataType.Integer:
case VariableDataType.Boolean:
{
int val = inReader.ReadInt32();
v[j] = val;
break;
}
case VariableDataType.Float:
{
float val = inReader.ReadSingle();
v[j] = val;
break;
}
case VariableDataType.StringVar:
{
int id = inReader.ReadInt32();
string val = arzFile.Getstring(id);
if (val == null) val = "";
else val = val.Trim();
v[j] = val;
break;
}
default:
{
int val = inReader.ReadInt32();
v[j] = val;
break;
}
}
}
record.Set(v);
}
}
finally {
inReader.Close();
}
return record;
}
private byte[] DecompressBytes(ARZFile arzFile)
{
// Read in the compressed data and decompress it, storing the results in a memorystream
FileStream arzStream = new FileStream(arzFile.m_filename, FileMode.Open, FileAccess.Read, FileShare.Read);
try
{
arzStream.Seek(m_offset, SeekOrigin.Begin);
// Create a decompression stream
ZInputStream zinput = new ZInputStream(arzStream);
// Create a memorystream to hold the decompressed data
MemoryStream outStream = new MemoryStream();
try
{
// Now decompress
byte[] buffer = new byte[1024];
int len;
while((len = zinput.read(buffer, 0, 1024)) > 0)
{
outStream.Write(buffer, 0, len);
}
// Now create a final Byte array to hold the answer
byte[] ans = new byte[(int)zinput.TotalOut];
// Copy the data into it
Array.Copy(outStream.GetBuffer(), ans, (int) zinput.TotalOut);
// Return the decompressed data
return ans;
}
finally
{
outStream.Close();
}
}
finally
{
arzStream.Close();
}
}
};
private string m_filename;
private string[] m_strings;
private Hashtable m_recordInfo; // keyed by their id
private Hashtable m_cache; // DBRecords cached as they get requested
private string[] m_keys;
public static ARZFile arzFile = null;
public ARZFile(string filename)
{
m_filename = filename;
m_cache = new Hashtable();
m_recordInfo = null;
m_keys = null;
}
public bool Read()
{
StreamWriter outStream = null; // new System.IO.StreamWriter("arzOut.txt", false);
try
{
// ARZ header file format
//
// 0x000000 int32
// 0x000004 int32 start of dbRecord table
// 0x000008 int32 size in bytes of dbRecord table
// 0x00000c int32 numEntries in dbRecord table
// 0x000010 int32 start of string table
// 0x000014 int32 size in bytes of string table
FileStream instream = new FileStream(m_filename, FileMode.Open, FileAccess.Read, FileShare.Read);
BinaryReader reader = new BinaryReader(instream);
try
{
int[] header = new int[6];
for (int i = 0; i < 6; ++i)
{
header[i] = reader.ReadInt32();
if (outStream != null) outStream.WriteLine("Header[{0}] = {1:n0} (0x{1:X})", i, header[i]);
}
int firstTableStart = header[1];
int firstTableSize = header[2];
int firstTableCount = header[3];
int secondTableStart = header[4];
int secondTableSize = header[5];
if (!ReadstringTable(secondTableStart, secondTableSize, reader, outStream))
throw new Exception("Error Reading String Table");
if (!ReadRecordTable(firstTableStart, firstTableCount, reader, outStream))
throw new Exception("Error Reading Record Table");
// 4 final int32's from file
// first int32 is numstrings in the stringtable
// second int32 is something ;)
// 3rd and 4th are crap (timestamps maybe?)
for (int i = 0; i < 4; ++i)
{
int val = reader.ReadInt32();
if (outStream != null) outStream.WriteLine("{0:n0} 0x{0:X}", val);
}
}
catch (Exception e)
{
throw e;
}
finally
{
reader.Close();
}
// Let's examine *all* the records
//IEnumerator recs = this.GetRecordIDEnumerator();
//while(recs.MoveNext())
//{
// DBRecord r = GetRecordUnCached((string) (recs.Current));
// out.WriteLine(r.ToShortstring());
//}
}
catch (Exception)
{
return false;
}
finally
{
if (outStream != null) outStream.Close();
}
BuildKeyTable();
return true;
}
private void BuildKeyTable()
{
int index = 0;
m_keys = new string[m_recordInfo.Count];
foreach ( string recordID in m_recordInfo.Keys)
{
m_keys[index] = recordID;
index++;
}
Array.Sort(m_keys);
}
public string[] KeyTable
{
get
{
return m_keys;
}
}
public DBRecord Get_Item(string recordID)
{
recordID = NormalizeRecordPath(recordID);
DBRecord ans = (DBRecord) (m_cache[recordID]);
if (ans == null)
{
RecordInfo rawRecord = (RecordInfo) m_recordInfo[recordID];
if (rawRecord == null) return null; // record not found
ans = rawRecord.Decompress(this);
m_cache.Add(recordID, ans);
}
return ans;
}
// the number of DBRecords
public int Count
{
get
{
return m_recordInfo.Count;
}
}
// The Item property caches the DBRecords, which is great when you
// are only using a few 100 (1000?) records and are requesting
// them many times. Not great if you are looping through all the
// records as it eats alot of memory. This method will create
// the record on the fly if it is not in the cache so when you are
// done with it, it can be reclaimed by the garbage collector.
// Great for when you want to loop through all the records for
// some reason. It will take longer, but use less memory.
public DBRecord GetRecordUnCached(string recordID)
{
recordID = NormalizeRecordPath(recordID);
// If it is already in the cache no need not to use it
DBRecord ans = (DBRecord) (m_cache[recordID]);
if(ans != null) return ans;
RecordInfo rawRecord = (RecordInfo) (m_recordInfo[recordID]);
if(rawRecord == null) return null; // record not found
return rawRecord.Decompress(this);
}
// Returns an enumerator that will cycle through all the recordID's stored in the DB.
// you can then get each DBRecord you are interested in
public IEnumerator GetRecordIDEnumerator() { return m_recordInfo.Keys.GetEnumerator(); }
public ICollection GetRecordIDEnumerable() { return m_recordInfo.Keys; }
// Retrieves a string from the string table.
private string Getstring (int i)
{
return m_strings[i];
}
private bool ReadstringTable(int pos, int size, BinaryReader reader, StreamWriter outStream)
{
try
{
// string Table Format
// first 4 bytes is the number of entries
// then
// one string followed by another...
reader.BaseStream.Seek(pos, SeekOrigin.Begin);
int numstrings = reader.ReadInt32();
m_strings = new string[numstrings];
int finalPos = pos + size;
if (outStream != null) outStream.WriteLine("stringTable located at 0x{1:X} numstrings= {0:n0}", numstrings, pos);
for (int i = 0; i < numstrings; ++i)
{
m_strings[i] = ReadCString(reader);
if (outStream != null) outStream.WriteLine("{0},{1}", i, m_strings[i]);
}
return true;
}
catch (Exception)
{
return false;
}
}
private bool ReadRecordTable(int pos, int numEntries, BinaryReader reader, StreamWriter outStream)
{
try
{
m_recordInfo = new Hashtable((int)Math.Round(numEntries * 1.2), (float)1.0);
reader.BaseStream.Seek(pos, SeekOrigin.Begin);
if (outStream != null) outStream.WriteLine("RecordTable located at 0x{0:X}", pos);
for (int i = 0; i < numEntries; ++i)
{
RecordInfo r = new RecordInfo();
r.Decode(reader, 24, this); // 24 is the offset of where all record data begins
m_recordInfo.Add(NormalizeRecordPath(r.ID), r);
// output this record
if (outStream != null) outStream.WriteLine("{0},{1},{2}", i, r.ID, r.RecordType);
}
return true;
}
catch (Exception)
{
return false;
}
}
// Reads a string from the binary stream
public static string ReadCString(BinaryReader reader)
{
// first 4 bytes is the string length, followed by the string.
int len = reader.ReadInt32();
// Convert the next len bytes into a string
Encoding ascii = Encoding.GetEncoding(1252);
byte[] rawData = reader.ReadBytes(len);
char[] chars = new char[ascii.GetCharCount(rawData, 0, len)];
ascii.GetChars(rawData, 0, len, chars, 0);
string ans = new string(chars);
return ans;
}
public static string NormalizeRecordPath(string recordID)
{
// lowercase it
string ans = recordID.ToLower(System.Globalization.CultureInfo.InvariantCulture);
// replace any '/' with '\\'
ans = ans.Replace('/', '\\');
return ans;
}
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* 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.
* http://www.gnu.org/copyleft/gpl.html
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using MindTouch.Collections;
using MindTouch.Dream.Test;
using MindTouch.IO;
using MindTouch.LuceneService;
using MindTouch.Tasking;
using MindTouch.Xml;
using NUnit.Framework;
namespace MindTouch.Lucene.Tests {
using Yield = IEnumerator<IYield>;
[TestFixture]
public class UpdateDelayQueueTests {
private static readonly log4net.ILog _log = LogUtils.CreateLog();
private TransactionalQueue<XDoc> _peekQueue;
private MockUpdateRecordDispatcher _dispatcher;
private UpdateDelayQueue _queue;
public class MockUpdateRecordDispatcher : IUpdateRecordDispatcher {
public List<Tuplet<DateTime, UpdateRecord>> Dispatches = new List<Tuplet<DateTime, UpdateRecord>>();
public ManualResetEvent ResetEvent = new ManualResetEvent(false);
public Result Dispatch(UpdateRecord updateRecord, Result result) {
_log.DebugFormat("got dispatch");
Dispatches.Add(new Tuplet<DateTime, UpdateRecord>(DateTime.Now, updateRecord));
result.Return();
ResetEvent.Set();
return result;
}
}
[SetUp]
public void Setup() {
_peekQueue = new TransactionalQueue<XDoc>(new SingleFileQueueStream(new MemoryStream()), new XDocQueueItemSerializer());
_dispatcher = new MockUpdateRecordDispatcher();
_queue = new UpdateDelayQueue(TimeSpan.FromSeconds(3), _dispatcher, _peekQueue);
}
[Test]
public void Mods_followed_by_delete_result_in_delete() {
ActionStack actionStack = new ActionStack();
//mod
actionStack.PushDelete();
actionStack.PushAdd();
//mod
actionStack.PushDelete();
actionStack.PushAdd();
//delete
actionStack.PushDelete();
Assert.IsFalse(actionStack.IsAdd);
Assert.IsTrue(actionStack.IsDelete);
}
[Test]
public void Create_mod_delete_results_in_no_op() {
ActionStack actionStack = new ActionStack();
//create
actionStack.PushAdd();
//mod
actionStack.PushDelete();
actionStack.PushAdd();
//delete
actionStack.PushDelete();
Assert.IsFalse(actionStack.IsAdd);
Assert.IsFalse(actionStack.IsDelete);
}
[Test]
public void Delete_create_mod_results_in_add_and_delete() {
ActionStack actionStack = new ActionStack();
//delete
actionStack.PushDelete();
//create
actionStack.PushAdd();
//mod
actionStack.PushDelete();
actionStack.PushAdd();
Assert.IsTrue(actionStack.IsAdd);
Assert.IsTrue(actionStack.IsDelete);
}
[Test]
public void Delete_create_delete_results_in_delete() {
ActionStack actionStack = new ActionStack();
//delete
actionStack.PushDelete();
//create
actionStack.PushAdd();
//delete
actionStack.PushDelete();
Assert.IsFalse(actionStack.IsAdd);
Assert.IsTrue(actionStack.IsDelete);
}
[Test]
public void Callback_in_delay_time() {
XDoc queued = new XDoc("deki-event")
.Attr("wikiid", "abc")
.Elem("channel", "event://abc/deki/pages/update")
.Elem("uri", "http://foo/bar")
.Elem("content.uri", "")
.Elem("revision.uri", "")
.Elem("path", "bar")
.Elem("previous-path", "bar");
_log.DebugFormat("queueing item");
_queue.Enqueue(queued);
Assert.AreEqual(1, _peekQueue.Count);
Assert.AreEqual(0, _dispatcher.Dispatches.Count);
if(!_dispatcher.ResetEvent.WaitOne(5000, true)) {
_log.Debug("reset event never fired");
Assert.AreEqual(0, _peekQueue.Count, "item still in the queue");
Assert.Fail("callback didn't happen");
}
Assert.IsTrue(_dispatcher.ResetEvent.WaitOne(5000));
Assert.AreEqual(1, _dispatcher.Dispatches.Count);
Assert.AreEqual(queued.ToString(), _dispatcher.Dispatches[0].Item2.Meta.ToString());
Assert.IsNotNull(_dispatcher.Dispatches[0].Item2.Id);
Assert.IsTrue(_dispatcher.Dispatches[0].Item2.ActionStack.IsAdd);
Assert.IsTrue(_dispatcher.Dispatches[0].Item2.ActionStack.IsDelete);
}
[Test]
public void Same_item_in_queue_updates_item_not_time() {
XDoc m1 = new XDoc("deki-event")
.Attr("wikiid", "abc")
.Elem("channel", "event://abc/deki/pages/update")
.Elem("uri", "http://foo/bar")
.Elem("content.uri", "")
.Elem("revision.uri", "")
.Elem("path", "bar")
.Elem("previous-path", "bar");
_queue.Enqueue(m1);
Thread.Sleep(500);
XDoc m2 = new XDoc("deki-event")
.Attr("wikiid", "abc")
.Elem("channel", "event://abc/deki/pages/update")
.Elem("uri", "http://foo/bar")
.Elem("content.uri", "")
.Elem("revision.uri", "")
.Elem("path", "bar")
.Elem("previous-path", "bar");
_queue.Enqueue(m2);
Assert.AreEqual(0, _dispatcher.Dispatches.Count);
if(!_dispatcher.ResetEvent.WaitOne(5000, true)) {
Assert.Fail("callback didn't happen");
}
Assert.AreEqual(1, _dispatcher.Dispatches.Count);
Assert.AreEqual(m2.ToString(), _dispatcher.Dispatches[0].Item2.Meta.ToString());
Assert.IsNotNull(_dispatcher.Dispatches[0].Item2.Id);
Assert.IsTrue(_dispatcher.Dispatches[0].Item2.ActionStack.IsAdd);
Assert.IsTrue(_dispatcher.Dispatches[0].Item2.ActionStack.IsDelete);
Thread.Sleep(1500);
Assert.AreEqual(1, _dispatcher.Dispatches.Count);
Assert.AreEqual(0, _peekQueue.Count);
}
[Test]
public void Different_items_in_queue_fire_separately() {
XDoc m1 = new XDoc("deki-event")
.Attr("wikiid", "abc")
.Elem("channel", "event://abc/deki/pages/update")
.Elem("uri", "http://foo/bar")
.Elem("content.uri", "")
.Elem("revision.uri", "")
.Elem("path", "bar")
.Elem("previous-path", "bar");
DateTime queueTime1 = DateTime.Now;
_queue.Enqueue(m1);
Thread.Sleep(1000);
XDoc m2 = new XDoc("deki-event")
.Attr("wikiid", "abc")
.Elem("channel", "event://abc/deki/pages/update")
.Elem("uri", "http://foo/baz")
.Elem("content.uri", "")
.Elem("revision.uri", "")
.Elem("path", "baz")
.Elem("previous-path", "baz");
DateTime queueTime2 = DateTime.Now;
_queue.Enqueue(m2);
Assert.AreEqual(0, _dispatcher.Dispatches.Count);
Assert.IsTrue(_dispatcher.ResetEvent.WaitOne(5000, true), "first callback didn't happen");
_dispatcher.ResetEvent.Reset();
Assert.IsTrue(_dispatcher.ResetEvent.WaitOne(2000, true), "second callback didn't happen");
Assert.AreEqual(2, _dispatcher.Dispatches.Count);
Assert.AreEqual(m1.ToString(), _dispatcher.Dispatches[0].Item2.Meta.ToString());
Assert.AreEqual(m2.ToString(), _dispatcher.Dispatches[1].Item2.Meta.ToString());
Assert.AreEqual(0, _peekQueue.Count);
}
[Test]
public void Adding_same_document_after_first_dispatch_fires_after_normal_delay() {
XDoc m1 = new XDoc("deki-event")
.Attr("wikiid", "abc")
.Elem("channel", "event://abc/deki/pages/create")
.Elem("uri", "http://foo/baz")
.Elem("content.uri", "")
.Elem("revision.uri", "")
.Elem("path", "baz")
.Elem("previous-path", "bar");
DateTime queueTime1 = DateTime.Now;
_queue.Enqueue(m1);
Assert.AreEqual(0, _dispatcher.Dispatches.Count);
Assert.IsTrue(_dispatcher.ResetEvent.WaitOne(5000, true), "first callback didn't happen");
_dispatcher.ResetEvent.Reset();
Assert.AreEqual(1, _dispatcher.Dispatches.Count);
_queue.Enqueue(m1.Clone());
Assert.AreEqual(1, _dispatcher.Dispatches.Count);
Assert.IsTrue(_dispatcher.ResetEvent.WaitOne(5000, true), "second callback didn't happen");
Assert.AreEqual(2, _dispatcher.Dispatches.Count);
Assert.AreEqual(0, _peekQueue.Count);
}
}
}
| |
using Assets.PostProcessing.Runtime.Utils;
using UnityEditorInternal;
using UnityEngine;
namespace UnityEditor.PostProcessing
{
public class WaveformMonitor : PostProcessingMonitor
{
static GUIContent s_MonitorTitle = new GUIContent("Waveform");
ComputeShader m_ComputeShader;
ComputeBuffer m_Buffer;
Material m_Material;
RenderTexture m_WaveformTexture;
Rect m_MonitorAreaRect;
public WaveformMonitor()
{
m_ComputeShader = EditorResources.Load<ComputeShader>("Monitors/WaveformCompute.compute");
}
public override void Dispose()
{
GraphicsUtils.Destroy(m_Material);
GraphicsUtils.Destroy(m_WaveformTexture);
if (m_Buffer != null)
m_Buffer.Release();
m_Material = null;
m_WaveformTexture = null;
m_Buffer = null;
}
public override bool IsSupported()
{
return m_ComputeShader != null && GraphicsUtils.supportsDX11;
}
public override GUIContent GetMonitorTitle()
{
return s_MonitorTitle;
}
public override void OnMonitorSettings()
{
EditorGUI.BeginChangeCheck();
bool refreshOnPlay = m_MonitorSettings.refreshOnPlay;
float exposure = m_MonitorSettings.waveformExposure;
bool Y = m_MonitorSettings.waveformY;
bool R = m_MonitorSettings.waveformR;
bool G = m_MonitorSettings.waveformG;
bool B = m_MonitorSettings.waveformB;
refreshOnPlay = GUILayout.Toggle(refreshOnPlay, new GUIContent(FxStyles.playIcon, "Keep refreshing the waveform in play mode; this may impact performances."), FxStyles.preButton);
exposure = GUILayout.HorizontalSlider(exposure, 0.05f, 0.3f, FxStyles.preSlider, FxStyles.preSliderThumb, GUILayout.Width(40f));
Y = GUILayout.Toggle(Y, new GUIContent("Y", "Show the luminance waveform only."), FxStyles.preButton);
if (Y)
{
R = false;
G = false;
B = false;
}
R = GUILayout.Toggle(R, new GUIContent("R", "Show the red waveform."), FxStyles.preButton);
G = GUILayout.Toggle(G, new GUIContent("G", "Show the green waveform."), FxStyles.preButton);
B = GUILayout.Toggle(B, new GUIContent("B", "Show the blue waveform."), FxStyles.preButton);
if (R || G || B)
Y = false;
if (!Y && !R && !G && !B)
{
R = true;
G = true;
B = true;
}
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(m_BaseEditor.serializedObject.targetObject, "Waveforme Settings Changed");
m_MonitorSettings.refreshOnPlay = refreshOnPlay;
m_MonitorSettings.waveformExposure = exposure;
m_MonitorSettings.waveformY = Y;
m_MonitorSettings.waveformR = R;
m_MonitorSettings.waveformG = G;
m_MonitorSettings.waveformB = B;
InternalEditorUtility.RepaintAllViews();
}
}
public override void OnMonitorGUI(Rect r)
{
if (Event.current.type == EventType.Repaint)
{
// If m_MonitorAreaRect isn't set the preview was just opened so refresh the render to get the waveform data
if (Mathf.Approximately(m_MonitorAreaRect.width, 0) && Mathf.Approximately(m_MonitorAreaRect.height, 0))
InternalEditorUtility.RepaintAllViews();
// Sizing
float width = m_WaveformTexture != null
? Mathf.Min(m_WaveformTexture.width, r.width - 65f)
: r.width;
float height = m_WaveformTexture != null
? Mathf.Min(m_WaveformTexture.height, r.height - 45f)
: r.height;
m_MonitorAreaRect = new Rect(
Mathf.Floor(r.x + r.width / 2f - width / 2f),
Mathf.Floor(r.y + r.height / 2f - height / 2f - 5f),
width, height
);
if (m_WaveformTexture != null)
{
m_Material.SetFloat("_Exposure", m_MonitorSettings.waveformExposure);
var oldActive = RenderTexture.active;
Graphics.Blit(null, m_WaveformTexture, m_Material, 0);
RenderTexture.active = oldActive;
Graphics.DrawTexture(m_MonitorAreaRect, m_WaveformTexture);
var color = Color.white;
const float kTickSize = 5f;
// Rect, lines & ticks points
// A B C D E
// P F
// O G
// N H
// M L K J I
var A = new Vector3(m_MonitorAreaRect.x, m_MonitorAreaRect.y);
var E = new Vector3(A.x + m_MonitorAreaRect.width + 1f, m_MonitorAreaRect.y);
var I = new Vector3(E.x, E.y + m_MonitorAreaRect.height + 1f);
var M = new Vector3(A.x, I.y);
var C = new Vector3(A.x + (E.x - A.x) / 2f, A.y);
var G = new Vector3(E.x, E.y + (I.y - E.y) / 2f);
var K = new Vector3(M.x + (I.x - M.x) / 2f, M.y);
var O = new Vector3(A.x, A.y + (M.y - A.y) / 2f);
var P = new Vector3(A.x, A.y + (O.y - A.y) / 2f);
var F = new Vector3(E.x, E.y + (G.y - E.y) / 2f);
var N = new Vector3(A.x, O.y + (M.y - O.y) / 2f);
var H = new Vector3(E.x, G.y + (I.y - G.y) / 2f);
var B = new Vector3(A.x + (C.x - A.x) / 2f, A.y);
var L = new Vector3(M.x + (K.x - M.x) / 2f, M.y);
var D = new Vector3(C.x + (E.x - C.x) / 2f, A.y);
var J = new Vector3(K.x + (I.x - K.x) / 2f, M.y);
// Borders
Handles.color = color;
Handles.DrawLine(A, E);
Handles.DrawLine(E, I);
Handles.DrawLine(I, M);
Handles.DrawLine(M, new Vector3(A.x, A.y - 1f));
// Vertical ticks
Handles.DrawLine(A, new Vector3(A.x - kTickSize, A.y));
Handles.DrawLine(P, new Vector3(P.x - kTickSize, P.y));
Handles.DrawLine(O, new Vector3(O.x - kTickSize, O.y));
Handles.DrawLine(N, new Vector3(N.x - kTickSize, N.y));
Handles.DrawLine(M, new Vector3(M.x - kTickSize, M.y));
Handles.DrawLine(E, new Vector3(E.x + kTickSize, E.y));
Handles.DrawLine(F, new Vector3(F.x + kTickSize, F.y));
Handles.DrawLine(G, new Vector3(G.x + kTickSize, G.y));
Handles.DrawLine(H, new Vector3(H.x + kTickSize, H.y));
Handles.DrawLine(I, new Vector3(I.x + kTickSize, I.y));
// Horizontal ticks
Handles.DrawLine(A, new Vector3(A.x, A.y - kTickSize));
Handles.DrawLine(B, new Vector3(B.x, B.y - kTickSize));
Handles.DrawLine(C, new Vector3(C.x, C.y - kTickSize));
Handles.DrawLine(D, new Vector3(D.x, D.y - kTickSize));
Handles.DrawLine(E, new Vector3(E.x, E.y - kTickSize));
Handles.DrawLine(M, new Vector3(M.x, M.y + kTickSize));
Handles.DrawLine(L, new Vector3(L.x, L.y + kTickSize));
Handles.DrawLine(K, new Vector3(K.x, K.y + kTickSize));
Handles.DrawLine(J, new Vector3(J.x, J.y + kTickSize));
Handles.DrawLine(I, new Vector3(I.x, I.y + kTickSize));
// Labels
GUI.color = color;
GUI.Label(new Rect(A.x - kTickSize - 34f, A.y - 15f, 30f, 30f), "1.0", FxStyles.tickStyleRight);
GUI.Label(new Rect(O.x - kTickSize - 34f, O.y - 15f, 30f, 30f), "0.5", FxStyles.tickStyleRight);
GUI.Label(new Rect(M.x - kTickSize - 34f, M.y - 15f, 30f, 30f), "0.0", FxStyles.tickStyleRight);
GUI.Label(new Rect(E.x + kTickSize + 4f, E.y - 15f, 30f, 30f), "1.0", FxStyles.tickStyleLeft);
GUI.Label(new Rect(G.x + kTickSize + 4f, G.y - 15f, 30f, 30f), "0.5", FxStyles.tickStyleLeft);
GUI.Label(new Rect(I.x + kTickSize + 4f, I.y - 15f, 30f, 30f), "0.0", FxStyles.tickStyleLeft);
GUI.Label(new Rect(M.x - 15f, M.y + kTickSize - 4f, 30f, 30f), "0.0", FxStyles.tickStyleCenter);
GUI.Label(new Rect(K.x - 15f, K.y + kTickSize - 4f, 30f, 30f), "0.5", FxStyles.tickStyleCenter);
GUI.Label(new Rect(I.x - 15f, I.y + kTickSize - 4f, 30f, 30f), "1.0", FxStyles.tickStyleCenter);
}
}
}
public override void OnFrameData(RenderTexture source)
{
if (Application.isPlaying && !m_MonitorSettings.refreshOnPlay)
return;
if (Mathf.Approximately(m_MonitorAreaRect.width, 0) || Mathf.Approximately(m_MonitorAreaRect.height, 0))
return;
float ratio = (float)source.width / (float)source.height;
int h = 384;
int w = Mathf.FloorToInt(h * ratio);
var rt = RenderTexture.GetTemporary(w, h, 0, source.format);
Graphics.Blit(source, rt);
ComputeWaveform(rt);
m_BaseEditor.Repaint();
RenderTexture.ReleaseTemporary(rt);
}
void CreateBuffer(int width, int height)
{
m_Buffer = new ComputeBuffer(width * height, sizeof(uint) << 2);
}
void ComputeWaveform(RenderTexture source)
{
if (m_Buffer == null)
{
CreateBuffer(source.width, source.height);
}
else if (m_Buffer.count != (source.width * source.height))
{
m_Buffer.Release();
CreateBuffer(source.width, source.height);
}
var channels = m_MonitorSettings.waveformY
? new Vector4(0f, 0f, 0f, 1f)
: new Vector4(m_MonitorSettings.waveformR ? 1f : 0f, m_MonitorSettings.waveformG ? 1f : 0f, m_MonitorSettings.waveformB ? 1f : 0f, 0f);
var cs = m_ComputeShader;
int kernel = cs.FindKernel("KWaveformClear");
cs.SetBuffer(kernel, "_Waveform", m_Buffer);
cs.Dispatch(kernel, source.width, 1, 1);
kernel = cs.FindKernel("KWaveform");
cs.SetBuffer(kernel, "_Waveform", m_Buffer);
cs.SetTexture(kernel, "_Source", source);
cs.SetInt("_IsLinear", GraphicsUtils.isLinearColorSpace ? 1 : 0);
cs.SetVector("_Channels", channels);
cs.Dispatch(kernel, source.width, 1, 1);
if (m_WaveformTexture == null || m_WaveformTexture.width != source.width || m_WaveformTexture.height != source.height)
{
GraphicsUtils.Destroy(m_WaveformTexture);
m_WaveformTexture = new RenderTexture(source.width, source.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear)
{
hideFlags = HideFlags.DontSave,
wrapMode = TextureWrapMode.Clamp,
filterMode = FilterMode.Bilinear
};
}
if (m_Material == null)
m_Material = new Material(Shader.Find("Hidden/Post FX/Monitors/Waveform Render")) { hideFlags = HideFlags.DontSave };
m_Material.SetBuffer("_Waveform", m_Buffer);
m_Material.SetVector("_Size", new Vector2(m_WaveformTexture.width, m_WaveformTexture.height));
m_Material.SetVector("_Channels", channels);
}
}
}
| |
using System;
using System.Collections.Specialized;
using gov.va.medora.mdws.dto;
using gov.va.medora.mdo.api;
using gov.va.medora.mdo;
using System.Collections.Generic;
namespace gov.va.medora.mdws
{
public class ClinicalLib
{
MySession mySession;
public ClinicalLib(MySession mySession)
{
this.mySession = mySession;
}
public TaggedTextArray getAdHocHealthSummaryByDisplayName(string displayName)
{
TaggedTextArray result = new TaggedTextArray();
string msg = MdwsUtils.isAuthorizedConnection(mySession);
if (msg != "OK")
{
result.fault = new FaultTO(msg);
}
else if (displayName == "")
{
result.fault = new FaultTO("Missing displayName");
}
if (result.fault != null)
{
return result;
}
try
{
IndexedHashtable t = ClinicalApi.getAdHocHealthSummaryByDisplayName(mySession.ConnectionSet, displayName);
return new TaggedTextArray(t);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
return result;
}
}
public TextTO getAdHocHealthSummaryByDisplayName(string sitecode, string displayName)
{
TextTO result = new TextTO();
if (displayName == "")
{
result.fault = new FaultTO("Missing display name");
}
if (result.fault != null)
{
return result;
}
try
{
result.text = ClinicalApi.getAdHocHealthSummaryByDisplayName(mySession.ConnectionSet.getConnection(sitecode), displayName);
if (result.text == null)
{
result.fault = new FaultTO("Site " + sitecode + " does not have " + displayName + " enabled! Please contact the site for remediation.");
}
}
catch (Exception e)
{
result.fault = new FaultTO(e.Message);
}
return result;
}
#if false
public HealthSummaryTO getHealthSummary(string healthSummaryId, string healthSummaryName)
{
HealthSummaryTO result = new HealthSummaryTO();
if (string.IsNullOrEmpty(healthSummaryId) && string.IsNullOrEmpty(healthSummaryName))
{
result.fault = new FaultTO("Missing health summary Id OR health summary name. Please provide one of the parameters.");
return result;
}
try
{
HealthSummary hs = ClinicalApi.getHealthSummary(mySession.ConnectionSet.BaseConnection, new MdoDocument(healthSummaryId, healthSummaryName));
result.Init(hs);
}
catch (Exception e)
{
result.fault = new FaultTO(e.Message);
}
return result;
}
#endif
public TaggedHealthSummaryArray getHealthSummary(string healthSummaryId, string healthSummaryName)
{
TaggedHealthSummaryArray result = new TaggedHealthSummaryArray();
string msg = MdwsUtils.isAuthorizedConnection(mySession);
if (msg != "OK")
{
result.fault = new FaultTO(msg);
return result;
}
if ((mySession.Patient == null) || (string.IsNullOrEmpty(mySession.Patient.LocalPid)))
{
result.fault = new FaultTO("Need to select a patient before calling this method.");
return result;
}
if (string.IsNullOrEmpty(healthSummaryId) && string.IsNullOrEmpty(healthSummaryName))
{
result.fault = new FaultTO("Missing health summary Id OR health summary name. Please provide one of the parameters.");
return result;
}
try
{
IndexedHashtable hs = ClinicalApi.getHealthSummary(mySession.ConnectionSet, new MdoDocument(healthSummaryId, healthSummaryName));
result.Init(hs);
}
catch (Exception e)
{
result.fault = new FaultTO(e.Message);
}
return result;
}
public TaggedAllergyArrays getAllergies()
{
TaggedAllergyArrays result = new TaggedAllergyArrays();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
if (result.fault != null)
{
return result;
}
try
{
IndexedHashtable t = ClinicalApi.getAllergies(mySession.ConnectionSet);
result = new TaggedAllergyArrays(t);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public TaggedAllergyArrays getAllergiesBySite(string siteCode)
{
TaggedAllergyArrays result = new TaggedAllergyArrays();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
if (result.fault != null)
{
return result;
}
try
{
IndexedHashtable t = ClinicalApi.getAllergiesBySite(mySession.ConnectionSet, siteCode);
result = new TaggedAllergyArrays(t);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public TaggedRadiologyReportArrays getRadiologyReportsBySite(string fromDate, string toDate, string siteCode)
{
TaggedRadiologyReportArrays results = new TaggedRadiologyReportArrays();
if (!mySession.ConnectionSet.IsAuthorized)
{
results.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
else if (String.IsNullOrEmpty(fromDate))
{
results.fault = new FaultTO("Missing fromDate");
}
else if (String.IsNullOrEmpty(toDate))
{
results.fault = new FaultTO("Missing toDate");
}
else if (String.IsNullOrEmpty(siteCode))
{
results.fault = new FaultTO("missing siteCode");
}
if (results.fault != null)
{
return results;
}
try
{
IndexedHashtable t = ClinicalApi.getRadiologyReportsBySite(mySession.ConnectionSet, fromDate, toDate, siteCode);
results = new TaggedRadiologyReportArrays(t);
}
catch (Exception e)
{
results.fault = new FaultTO(e);
}
return results;
}
public TaggedRadiologyReportArrays getRadiologyReports(string fromDate, string toDate, int nrpts)
{
TaggedRadiologyReportArrays result = new TaggedRadiologyReportArrays();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
else if (String.IsNullOrEmpty(fromDate))
{
result.fault = new FaultTO("Missing fromDate");
}
else if (String.IsNullOrEmpty(toDate))
{
result.fault = new FaultTO("Missing toDate");
}
if (result.fault != null)
{
return result;
}
try
{
IndexedHashtable t = ClinicalApi.getRadiologyReports(mySession.ConnectionSet, fromDate, toDate, nrpts);
result = new TaggedRadiologyReportArrays(t);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public TaggedSurgeryReportArrays getSurgeryReports()
{
return getSurgeryReports(false);
}
public TaggedSurgeryReportArrays getSurgeryReports(bool fWithText)
{
TaggedSurgeryReportArrays result = new TaggedSurgeryReportArrays();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
if (result.fault != null)
{
return result;
}
try
{
IndexedHashtable t = ClinicalApi.getSurgeryReports(mySession.ConnectionSet, fWithText);
result = new TaggedSurgeryReportArrays(t);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public TaggedSurgeryReportArrays getSurgeryReportsBySite(string siteCode)
{
TaggedSurgeryReportArrays result = new TaggedSurgeryReportArrays();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
if (result.fault != null)
{
return result;
}
try
{
IndexedHashtable t = ClinicalApi.getSurgeryReportsBySite(mySession.ConnectionSet, siteCode);
result = new TaggedSurgeryReportArrays(t);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public TextTO getSurgeryReportText(string siteId, string rptId)
{
TextTO result = new TextTO();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
else if (siteId == "")
{
result.fault = new FaultTO("Missing siteId");
}
else if (rptId == "")
{
result.fault = new FaultTO("Missing rptId");
}
if (result.fault != null)
{
return result;
}
try
{
ClinicalApi api = new ClinicalApi();
string s = api.getSurgeryReportText(mySession.ConnectionSet.getConnection(siteId), rptId);
result = new TextTO(s);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public TaggedProblemArrays getProblemList(string type)
{
TaggedProblemArrays result = new TaggedProblemArrays();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
else if (type == "")
{
result.fault = new FaultTO("Missing type");
}
if (result.fault != null)
{
return result;
}
try
{
IndexedHashtable t = ClinicalApi.getProblemList(mySession.ConnectionSet, type.ToUpper());
result = new TaggedProblemArrays(t);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public TaggedProblemArrays getFluRelatedProblemList()
{
TaggedProblemArrays result = new TaggedProblemArrays();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
if (result.fault != null)
{
return result;
}
try
{
IndexedHashtable t = ClinicalApi.getFluRelatedProblemList(mySession.ConnectionSet);
result = new TaggedProblemArrays(t);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public RadiologyReportTO getImagingReport(string ssn, string accessionNumber)
{
RadiologyReportTO result = new RadiologyReportTO();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
else if (String.IsNullOrEmpty(ssn))
{
result.fault = new FaultTO("Missing SSN");
}
else if (String.IsNullOrEmpty(accessionNumber))
{
result.fault = new FaultTO("Missing Accession Number");
}
if (result.fault != null)
{
return result;
}
try
{
PatientApi patientApi = new PatientApi();
Patient[] matches = patientApi.match(mySession.ConnectionSet.BaseConnection, ssn);
if (matches == null || matches.Length != 1)
{
result.fault = new FaultTO("More than one patient has that SSN in this site (" +
mySession.ConnectionSet.BaseConnection.DataSource.SiteId.Id + ")");
return result;
}
RadiologyReport report = ImagingExam.getReportText(mySession.ConnectionSet.BaseConnection, matches[0].LocalPid, accessionNumber);
result = new RadiologyReportTO(report);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public TextTO getConsultNote(string consultId)
{
return getConsultNote(mySession.ConnectionSet.BaseConnection.DataSource.SiteId.Id, consultId);
}
public TextTO getConsultNote(string siteId, string consultId)
{
TextTO result = new TextTO();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
else if (String.IsNullOrEmpty(siteId))
{
result.fault = new FaultTO("Missing siteId");
}
else if (String.IsNullOrEmpty(consultId))
{
result.fault = new FaultTO("Missing consultId");
}
if (result.fault != null)
{
return result;
}
try
{
string s = Consult.getConsultNote(mySession.ConnectionSet.getConnection(siteId), consultId);
result = new TextTO(s);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public TaggedTextArray getNhinData(string types)
{
TaggedTextArray result = new TaggedTextArray();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
if (result.fault != null)
{
return result;
}
try
{
IndexedHashtable t = ClinicalApi.getNhinData(mySession.ConnectionSet, types,
mySession.MdwsConfiguration.AllConfigs[conf.MdwsConfigConstants.MDWS_CONFIG_SECTION][conf.MdwsConfigConstants.NHIN_TYPES]);
result = new TaggedTextArray(t);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public TaggedMentalHealthInstrumentAdministrationArrays getMentalHealthInstrumentsForPatient()
{
TaggedMentalHealthInstrumentAdministrationArrays result = new TaggedMentalHealthInstrumentAdministrationArrays();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
if (result.fault != null)
{
return result;
}
try
{
IndexedHashtable t = MentalHealthInstrumentAdministration.getMentalHealthInstrumentsForPatient(mySession.ConnectionSet);
result = new TaggedMentalHealthInstrumentAdministrationArrays(t);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public TaggedMentalHealthInstrumentAdministrationArrays getMentalHealthInstrumentsForPatientBySurvey(string surveyName)
{
TaggedMentalHealthInstrumentAdministrationArrays result = new TaggedMentalHealthInstrumentAdministrationArrays();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
if (result.fault != null)
{
return result;
}
try
{
IndexedHashtable t = MentalHealthInstrumentAdministration.getMentalHealthInstrumentsForPatientBySurvey(mySession.ConnectionSet, surveyName);
result = new TaggedMentalHealthInstrumentAdministrationArrays(t);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public MentalHealthInstrumentResultSetTO getMentalHealthInstrumentResultSet(string siteId, string administrationId)
{
MentalHealthInstrumentResultSetTO result = new MentalHealthInstrumentResultSetTO();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
else if (String.IsNullOrEmpty(siteId))
{
result.fault = new FaultTO("Missing siteId");
}
else if (String.IsNullOrEmpty(administrationId))
{
result.fault = new FaultTO("Missing administrationId");
}
if (result.fault != null)
{
return result;
}
try
{
MentalHealthInstrumentResultSet rs = MentalHealthInstrumentAdministration.getMentalHealthInstrumentResultSet(mySession.ConnectionSet.getConnection(siteId), administrationId);
result = new MentalHealthInstrumentResultSetTO(rs);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public TaggedMentalHealthResultSetArray getMentalHealthInstrumentResultSetsBySurvey(string siteId, string surveyName)
{
TaggedMentalHealthResultSetArray result = new TaggedMentalHealthResultSetArray();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
else if (String.IsNullOrEmpty(surveyName))
{
result.fault = new FaultTO("Missing siteId");
}
if (result.fault != null)
{
return result;
}
try
{
List<MentalHealthInstrumentResultSet> rs = MentalHealthInstrumentAdministration.getMentalHealthInstrumentResultSetsBySurvey(mySession.ConnectionSet.getConnection(siteId), surveyName);
result = new TaggedMentalHealthResultSetArray(siteId, rs);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
#region Clinic Directory
public TaggedUserArrays getStaffByCriteria(string siteCode, string searchTerm, string firstName, string lastName, string type)
{
TaggedUserArrays result = new TaggedUserArrays();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connection not established or authorized");
}
else if (String.IsNullOrEmpty(type))
{
result.fault = new FaultTO("Missing type of search {email, phone, firstAndLast, firstOrLast}");
}
else if (String.IsNullOrEmpty(siteCode))
{
result.fault = new FaultTO("Missing siteCode");
}
if (result.fault != null)
{
return result;
}
try
{
IndexedHashtable ht = ClinicalApi.getStaffByCriteria(mySession.ConnectionSet, siteCode, searchTerm, firstName, lastName, type);
result = new TaggedUserArrays(ht);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
#endregion
}
}
| |
using System;
using CoreGraphics;
using UIKit;
namespace Xamarin.iOS.FileExplorer.CustomViews
{
public sealed class ItemCell : UICollectionViewCell, IEditable, IUIGestureRecognizerDelegate
{
public enum AccessoryType
{
DetailButton,
DisclousoureIndicator
}
private UIImageView accessoryImageView;
private UITapGestureRecognizer accessoryImageViewTapRecognizer;
private CheckmarkButton checkmarkButton;
private UIView containerView;
private NSLayoutConstraint containerViewLeadingConstraint;
private NSLayoutConstraint containerViewTrailingConstraint;
private AccessoryType customAccessoryType = AccessoryType.DetailButton;
private UIImageView iconImageView;
private bool isEditing;
private SeparatorView separatorView;
private UILabel subtitleTextLabel;
private UILabel textLabel;
protected internal ItemCell(IntPtr handle) : base(handle)
{
Initialize(Frame);
}
public ItemCell(CGRect frame) : base(frame)
{
Initialize(frame);
}
public string Title
{
get { return textLabel.Text; }
set { textLabel.Text = value; }
}
public string Subtitle
{
get { return subtitleTextLabel.Text; }
set { subtitleTextLabel.Text = value; }
}
public UIImage IconImage
{
get { return iconImageView.Image; }
set { iconImageView.Image = value; }
}
public override bool Selected
{
get { return base.Selected; }
set
{
base.Selected = value;
checkmarkButton.Selected = value;
SetNeedsLayout();
}
}
public bool IsEditing
{
get { return isEditing; }
set
{
isEditing = value;
containerViewLeadingConstraint.Constant = isEditing ? 38 : 0;
containerViewTrailingConstraint.Constant = isEditing ? 38 : 0;
SetNeedsLayout();
}
}
public AccessoryType Accessory
{
get { return customAccessoryType; }
set
{
customAccessoryType = value;
switch (value)
{
case AccessoryType.DetailButton:
accessoryImageView.Image = UIImage.FromBundle("DetailButtonImage");
accessoryImageViewTapRecognizer.Enabled = true;
break;
case AccessoryType.DisclousoureIndicator:
accessoryImageView.Image = UIImage.FromBundle("DisclosureButtonImage");
accessoryImageViewTapRecognizer.Enabled = false;
break;
}
}
}
public CGSize MaximumIconSize
{
get
{
var max = Math.Max(Math.Max(iconImageView.Frame.Width, iconImageView.Frame.Height), LayoutConstants.IconWidth);
return new CGSize(max, max);
}
}
public Action TapAction { get; set; } = () => { };
public void SetEditing(bool editing, bool animated)
{
if (animated)
{
Animate(0.2f, () =>
{
IsEditing = editing;
LayoutIfNeeded();
});
}
else
IsEditing = editing;
}
private void Initialize(CGRect frame)
{
containerView = new UIView
{
BackgroundColor = UIColor.White
};
separatorView = new SeparatorView
{
BackgroundColor = ColorPallete.Gray
};
containerView.Add(separatorView);
iconImageView = new UIImageView
{
ContentMode = UIViewContentMode.ScaleAspectFit
};
containerView.Add(iconImageView);
textLabel = new UILabel
{
Lines = 1,
LineBreakMode = UILineBreakMode.MiddleTruncation,
Font = UIFont.SystemFontOfSize(17)
};
containerView.Add(textLabel);
subtitleTextLabel = new UILabel
{
Lines = 1,
LineBreakMode = UILineBreakMode.MiddleTruncation,
Font = UIFont.SystemFontOfSize(12),
TextColor = UIColor.Gray
};
containerView.Add(subtitleTextLabel);
accessoryImageView = new UIImageView
{
ContentMode = UIViewContentMode.Center
};
containerView.Add(accessoryImageView);
checkmarkButton = new CheckmarkButton(new CGRect());
BackgroundColor = UIColor.White;
accessoryImageViewTapRecognizer = new UITapGestureRecognizer(HandleAccessoryImageTap);
accessoryImageViewTapRecognizer.Delegate = this;
accessoryImageView.AddGestureRecognizer(accessoryImageViewTapRecognizer);
accessoryImageView.UserInteractionEnabled = true;
Add(checkmarkButton);
Add(containerView);
containerView.TranslatesAutoresizingMaskIntoConstraints = false;
separatorView.TranslatesAutoresizingMaskIntoConstraints = false;
textLabel.TranslatesAutoresizingMaskIntoConstraints = false;
subtitleTextLabel.TranslatesAutoresizingMaskIntoConstraints = false;
iconImageView.TranslatesAutoresizingMaskIntoConstraints = false;
checkmarkButton.TranslatesAutoresizingMaskIntoConstraints = false;
accessoryImageView.TranslatesAutoresizingMaskIntoConstraints = false;
SetupContainerViewConstraint();
SetupSeparatorViewConstraints();
SetupIconImageViewConstraints();
SetupAccessoryImageViewConstraints();
SetupTitleLabelConstraints();
SetupSubtitleLabelConstraints();
SetupCheckmarkButtonConstraints();
}
private void SetupContainerViewConstraint()
{
containerViewLeadingConstraint = containerView.LeadingAnchor.ConstraintEqualTo(LeadingAnchor);
containerViewLeadingConstraint.Active = true;
containerViewTrailingConstraint = containerView.TrailingAnchor.ConstraintEqualTo(TrailingAnchor);
containerViewTrailingConstraint.Active = true;
containerView.TopAnchor.ConstraintEqualTo(TopAnchor).Active = true;
containerView.BottomAnchor.ConstraintEqualTo(BottomAnchor).Active = true;
}
private void SetupSeparatorViewConstraints()
{
separatorView.LeadingAnchor.ConstraintEqualTo(LeadingAnchor, LayoutConstants.SeparatorLeftInset).Active = true;
separatorView.TrailingAnchor.ConstraintEqualTo(containerView.TrailingAnchor).Active = true;
separatorView.BottomAnchor.ConstraintEqualTo(containerView.BottomAnchor).Active = true;
}
private void SetupIconImageViewConstraints()
{
iconImageView.LeadingAnchor.ConstraintEqualTo(containerView.LeadingAnchor, 24).Active = true;
iconImageView.WidthAnchor.ConstraintEqualTo(LayoutConstants.IconWidth).Active = true;
iconImageView.TopAnchor.ConstraintEqualTo(containerView.TopAnchor, 10).Active = true;
iconImageView.BottomAnchor.ConstraintEqualTo(containerView.BottomAnchor, -10).Active = true;
}
private void SetupAccessoryImageViewConstraints()
{
accessoryImageView.TrailingAnchor.ConstraintEqualTo(containerView.TrailingAnchor, -15).Active = true;
accessoryImageView.CenterYAnchor.ConstraintEqualTo(containerView.CenterYAnchor).Active = true;
accessoryImageView.SetContentCompressionResistancePriority(1000, UILayoutConstraintAxis.Horizontal);
accessoryImageView.SetContentCompressionResistancePriority(750, UILayoutConstraintAxis.Vertical);
accessoryImageView.SetContentHuggingPriority(750, UILayoutConstraintAxis.Horizontal);
}
private void SetupTitleLabelConstraints()
{
textLabel.LeadingAnchor.ConstraintEqualTo(iconImageView.TrailingAnchor, 12).Active = true;
textLabel.TrailingAnchor.ConstraintEqualTo(accessoryImageView.LeadingAnchor, -10).Active = true;
textLabel.TopAnchor.ConstraintEqualTo(containerView.TopAnchor, 12).Active = true;
textLabel.SetContentCompressionResistancePriority(750, UILayoutConstraintAxis.Horizontal);
textLabel.SetContentHuggingPriority(750, UILayoutConstraintAxis.Vertical);
}
private void SetupSubtitleLabelConstraints()
{
subtitleTextLabel.LeadingAnchor.ConstraintEqualTo(textLabel.LeadingAnchor).Active = true;
subtitleTextLabel.TrailingAnchor.ConstraintEqualTo(textLabel.TrailingAnchor).Active = true;
subtitleTextLabel.TopAnchor.ConstraintEqualTo(textLabel.BottomAnchor, 3).Active = true;
subtitleTextLabel.SetContentCompressionResistancePriority(750, UILayoutConstraintAxis.Horizontal);
subtitleTextLabel.SetContentHuggingPriority(750, UILayoutConstraintAxis.Vertical);
}
private void SetupCheckmarkButtonConstraints()
{
checkmarkButton.TrailingAnchor.ConstraintEqualTo(containerView.LeadingAnchor, -4).Active = true;
checkmarkButton.CenterYAnchor.ConstraintEqualTo(CenterYAnchor, 1).Active = true;
}
public override bool GestureRecognizerShouldBegin(UIGestureRecognizer gestureRecognizer)
{
return true;
}
private void HandleAccessoryImageTap()
{
}
}
}
| |
using System;
using System.IO;
namespace CatLib._3rd.ICSharpCode.SharpZipLib.Core
{
/// <summary>
/// PathFilter filters directories and files using a form of <see cref="System.Text.RegularExpressions.Regex">regular expressions</see>
/// by full path name.
/// See <see cref="NameFilter">NameFilter</see> for more detail on filtering.
/// </summary>
public class PathFilter : IScanFilter
{
#region Constructors
/// <summary>
/// Initialise a new instance of <see cref="PathFilter"></see>.
/// </summary>
/// <param name="filter">The <see cref="NameFilter">filter</see> expression to apply.</param>
public PathFilter(string filter)
{
nameFilter_ = new NameFilter(filter);
}
#endregion
#region IScanFilter Members
/// <summary>
/// Test a name to see if it matches the filter.
/// </summary>
/// <param name="name">The name to test.</param>
/// <returns>True if the name matches, false otherwise.</returns>
/// <remarks><see cref="Path.GetFullPath(string)"/> is used to get the full path before matching.</remarks>
public virtual bool IsMatch(string name)
{
bool result = false;
if (name != null) {
string cooked = (name.Length > 0) ? Path.GetFullPath(name) : "";
result = nameFilter_.IsMatch(cooked);
}
return result;
}
readonly
#endregion
#region Instance Fields
NameFilter nameFilter_;
#endregion
}
/// <summary>
/// ExtendedPathFilter filters based on name, file size, and the last write time of the file.
/// </summary>
/// <remarks>Provides an example of how to customise filtering.</remarks>
public class ExtendedPathFilter : PathFilter
{
#region Constructors
/// <summary>
/// Initialise a new instance of ExtendedPathFilter.
/// </summary>
/// <param name="filter">The filter to apply.</param>
/// <param name="minSize">The minimum file size to include.</param>
/// <param name="maxSize">The maximum file size to include.</param>
public ExtendedPathFilter(string filter,
long minSize, long maxSize)
: base(filter)
{
MinSize = minSize;
MaxSize = maxSize;
}
/// <summary>
/// Initialise a new instance of ExtendedPathFilter.
/// </summary>
/// <param name="filter">The filter to apply.</param>
/// <param name="minDate">The minimum <see cref="DateTime"/> to include.</param>
/// <param name="maxDate">The maximum <see cref="DateTime"/> to include.</param>
public ExtendedPathFilter(string filter,
DateTime minDate, DateTime maxDate)
: base(filter)
{
MinDate = minDate;
MaxDate = maxDate;
}
/// <summary>
/// Initialise a new instance of ExtendedPathFilter.
/// </summary>
/// <param name="filter">The filter to apply.</param>
/// <param name="minSize">The minimum file size to include.</param>
/// <param name="maxSize">The maximum file size to include.</param>
/// <param name="minDate">The minimum <see cref="DateTime"/> to include.</param>
/// <param name="maxDate">The maximum <see cref="DateTime"/> to include.</param>
public ExtendedPathFilter(string filter,
long minSize, long maxSize,
DateTime minDate, DateTime maxDate)
: base(filter)
{
MinSize = minSize;
MaxSize = maxSize;
MinDate = minDate;
MaxDate = maxDate;
}
#endregion
#region IScanFilter Members
/// <summary>
/// Test a filename to see if it matches the filter.
/// </summary>
/// <param name="name">The filename to test.</param>
/// <returns>True if the filter matches, false otherwise.</returns>
/// <exception cref="System.IO.FileNotFoundException">The <see paramref="fileName"/> doesnt exist</exception>
public override bool IsMatch(string name)
{
bool result = base.IsMatch(name);
if (result) {
var fileInfo = new FileInfo(name);
result =
(MinSize <= fileInfo.Length) &&
(MaxSize >= fileInfo.Length) &&
(MinDate <= fileInfo.LastWriteTime) &&
(MaxDate >= fileInfo.LastWriteTime)
;
}
return result;
}
#endregion
#region Properties
/// <summary>
/// Get/set the minimum size/length for a file that will match this filter.
/// </summary>
/// <remarks>The default value is zero.</remarks>
/// <exception cref="ArgumentOutOfRangeException">value is less than zero; greater than <see cref="MaxSize"/></exception>
public long MinSize {
get { return minSize_; }
set {
if ((value < 0) || (maxSize_ < value)) {
throw new ArgumentOutOfRangeException("value");
}
minSize_ = value;
}
}
/// <summary>
/// Get/set the maximum size/length for a file that will match this filter.
/// </summary>
/// <remarks>The default value is <see cref="System.Int64.MaxValue"/></remarks>
/// <exception cref="ArgumentOutOfRangeException">value is less than zero or less than <see cref="MinSize"/></exception>
public long MaxSize {
get { return maxSize_; }
set {
if ((value < 0) || (minSize_ > value)) {
throw new ArgumentOutOfRangeException("value");
}
maxSize_ = value;
}
}
/// <summary>
/// Get/set the minimum <see cref="DateTime"/> value that will match for this filter.
/// </summary>
/// <remarks>Files with a LastWrite time less than this value are excluded by the filter.</remarks>
public DateTime MinDate {
get {
return minDate_;
}
set {
if (value > maxDate_) {
throw new ArgumentOutOfRangeException("value", "Exceeds MaxDate");
}
minDate_ = value;
}
}
/// <summary>
/// Get/set the maximum <see cref="DateTime"/> value that will match for this filter.
/// </summary>
/// <remarks>Files with a LastWrite time greater than this value are excluded by the filter.</remarks>
public DateTime MaxDate {
get {
return maxDate_;
}
set {
if (minDate_ > value) {
throw new ArgumentOutOfRangeException("value", "Exceeds MinDate");
}
maxDate_ = value;
}
}
#endregion
#region Instance Fields
long minSize_;
long maxSize_ = long.MaxValue;
DateTime minDate_ = DateTime.MinValue;
DateTime maxDate_ = DateTime.MaxValue;
#endregion
}
/// <summary>
/// NameAndSizeFilter filters based on name and file size.
/// </summary>
/// <remarks>A sample showing how filters might be extended.</remarks>
[Obsolete("Use ExtendedPathFilter instead")]
public class NameAndSizeFilter : PathFilter
{
/// <summary>
/// Initialise a new instance of NameAndSizeFilter.
/// </summary>
/// <param name="filter">The filter to apply.</param>
/// <param name="minSize">The minimum file size to include.</param>
/// <param name="maxSize">The maximum file size to include.</param>
public NameAndSizeFilter(string filter, long minSize, long maxSize)
: base(filter)
{
MinSize = minSize;
MaxSize = maxSize;
}
/// <summary>
/// Test a filename to see if it matches the filter.
/// </summary>
/// <param name="name">The filename to test.</param>
/// <returns>True if the filter matches, false otherwise.</returns>
public override bool IsMatch(string name)
{
bool result = base.IsMatch(name);
if (result) {
var fileInfo = new FileInfo(name);
long length = fileInfo.Length;
result =
(MinSize <= length) &&
(MaxSize >= length);
}
return result;
}
/// <summary>
/// Get/set the minimum size for a file that will match this filter.
/// </summary>
public long MinSize {
get { return minSize_; }
set {
if ((value < 0) || (maxSize_ < value)) {
throw new ArgumentOutOfRangeException("value");
}
minSize_ = value;
}
}
/// <summary>
/// Get/set the maximum size for a file that will match this filter.
/// </summary>
public long MaxSize {
get { return maxSize_; }
set {
if ((value < 0) || (minSize_ > value)) {
throw new ArgumentOutOfRangeException("value");
}
maxSize_ = value;
}
}
#region Instance Fields
long minSize_;
long maxSize_ = long.MaxValue;
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime;
using Xunit;
namespace System.Tests
{
public static class GCTests
{
private static bool s_is32Bits = IntPtr.Size == 4; // Skip IntPtr tests on 32-bit platforms
[Fact]
public static void AddMemoryPressure_InvalidBytesAllocated_ThrowsArgumentOutOfRangeException()
{
Assert.Throws<ArgumentOutOfRangeException>("bytesAllocated", () => GC.AddMemoryPressure(-1)); // Bytes allocated < 0
if (s_is32Bits)
{
Assert.Throws<ArgumentOutOfRangeException>("bytesAllocated", () => GC.AddMemoryPressure((long)int.MaxValue + 1)); // Bytes allocated > int.MaxValue on 32 bit platforms
}
}
[Fact]
public static void Collect_Int()
{
for (int i = 0; i < GC.MaxGeneration + 10; i++)
{
GC.Collect(i);
}
}
[Fact]
public static void Collect_Int_NegativeGeneration_ThrowsArgumentOutOfRangeException()
{
Assert.Throws<ArgumentOutOfRangeException>("generation", () => GC.Collect(-1)); // Generation < 0
}
[Theory]
[InlineData(GCCollectionMode.Default)]
[InlineData(GCCollectionMode.Forced)]
public static void Collect_Int_GCCollectionMode(GCCollectionMode mode)
{
for (int gen = 0; gen <= 2; gen++)
{
var b = new byte[1024 * 1024 * 10];
int oldCollectionCount = GC.CollectionCount(gen);
b = null;
GC.Collect(gen, GCCollectionMode.Default);
Assert.True(GC.CollectionCount(gen) > oldCollectionCount);
}
}
[Fact]
public static void Collect_Int_GCCollectionMode_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("generation", () => GC.Collect(-1, GCCollectionMode.Default)); // Generation < 0
Assert.Throws<ArgumentOutOfRangeException>("mode", () => GC.Collect(2, GCCollectionMode.Default - 1)); // Invalid collection mode
Assert.Throws<ArgumentOutOfRangeException>("mode", () => GC.Collect(2, GCCollectionMode.Optimized + 1)); // Invalid collection mode
}
[Fact]
public static void Collect_Int_GCCollectionMode_Bool_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("generation", () => GC.Collect(-1, GCCollectionMode.Default, false)); // Generation < 0
Assert.Throws<ArgumentOutOfRangeException>("mode", () => GC.Collect(2, GCCollectionMode.Default - 1, false)); // Invalid collection mode
Assert.Throws<ArgumentOutOfRangeException>("mode", () => GC.Collect(2, GCCollectionMode.Optimized + 1, false)); // Invalid collection mode
}
[Fact]
public static void Collect_CallsFinalizer()
{
FinalizerTest.Run();
}
private class FinalizerTest
{
public static void Run()
{
var obj = new TestObject();
obj = null;
GC.Collect();
// Make sure Finalize() is called
GC.WaitForPendingFinalizers();
Assert.True(TestObject.Finalized);
}
private class TestObject
{
public static bool Finalized { get; private set; }
~TestObject()
{
Finalized = true;
}
}
}
[Fact]
public static void KeepAlive()
{
KeepAliveTest.Run();
}
private class KeepAliveTest
{
public static void Run()
{
var keepAlive = new KeepAliveObject();
var doNotKeepAlive = new DoNotKeepAliveObject();
doNotKeepAlive = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(DoNotKeepAliveObject.Finalized);
Assert.False(KeepAliveObject.Finalized);
GC.KeepAlive(keepAlive);
}
private class KeepAliveObject
{
public static bool Finalized { get; private set; }
~KeepAliveObject()
{
Finalized = true;
}
}
private class DoNotKeepAliveObject
{
public static bool Finalized { get; private set; }
~DoNotKeepAliveObject()
{
Finalized = true;
}
}
}
[Fact]
public static void KeepAlive_Null()
{
KeepAliveNullTest.Run();
}
private class KeepAliveNullTest
{
public static void Run()
{
var obj = new TestObject();
obj = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.KeepAlive(obj);
Assert.True(TestObject.Finalized);
}
private class TestObject
{
public static bool Finalized { get; private set; }
~TestObject()
{
Finalized = true;
}
}
}
[Fact]
public static void KeepAlive_Recursive()
{
KeepAliveRecursiveTest.Run();
}
private class KeepAliveRecursiveTest
{
public static void Run()
{
int recursionCount = 0;
RunWorker(new TestObject(), ref recursionCount);
}
private static void RunWorker(object obj, ref int recursionCount)
{
if (recursionCount++ == 10)
return;
GC.Collect();
GC.WaitForPendingFinalizers();
RunWorker(obj, ref recursionCount);
Assert.False(TestObject.Finalized);
GC.KeepAlive(obj);
}
private class TestObject
{
public static bool Finalized { get; private set; }
~TestObject()
{
Finalized = true;
}
}
}
[Fact]
public static void SuppressFinalizer()
{
SuppressFinalizerTest.Run();
}
private class SuppressFinalizerTest
{
public static void Run()
{
var obj = new TestObject();
GC.SuppressFinalize(obj);
obj = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.False(TestObject.Finalized);
}
private class TestObject
{
public static bool Finalized { get; private set; }
~TestObject()
{
Finalized = true;
}
}
}
[Fact]
public static void SuppressFinalizer_NullObject_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("obj", () => GC.SuppressFinalize(null)); // Obj is null
}
[Fact]
public static void ReRegisterForFinalize()
{
ReRegisterForFinalizeTest.Run();
}
[Fact]
public static void ReRegisterFoFinalize_NullObject_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("obj", () => GC.ReRegisterForFinalize(null)); // Obj is null
}
private class ReRegisterForFinalizeTest
{
public static void Run()
{
TestObject.Finalized = false;
CreateObject();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(TestObject.Finalized);
}
private static void CreateObject()
{
using (var obj = new TestObject())
{
GC.SuppressFinalize(obj);
}
}
private class TestObject : IDisposable
{
public static bool Finalized { get; set; }
~TestObject()
{
Finalized = true;
}
public void Dispose()
{
GC.ReRegisterForFinalize(this);
}
}
}
[Fact]
public static void CollectionCount_NegativeGeneration_ThrowsArgumentOutOfRangeException()
{
Assert.Throws<ArgumentOutOfRangeException>("generation", () => GC.CollectionCount(-1)); // Generation < 0
}
[Fact]
public static void RemoveMemoryPressure_InvalidBytesAllocated_ThrowsArgumentOutOfRangeException()
{
Assert.Throws<ArgumentOutOfRangeException>("bytesAllocated", () => GC.RemoveMemoryPressure(-1)); // Bytes allocated < 0
if (s_is32Bits)
{
Assert.Throws<ArgumentOutOfRangeException>("bytesAllocated", () => GC.RemoveMemoryPressure((long)int.MaxValue + 1)); // Bytes allocated > int.MaxValue on 32 bit platforms
}
}
[Fact]
public static void GetTotalMemoryTest_ForceCollection()
{
// We don't test GetTotalMemory(false) at all because a collection
// could still occur even if not due to the GetTotalMemory call,
// and as such there's no way to validate the behavior. We also
// don't verify a tighter bound for the result of GetTotalMemory
// because collections could cause significant fluctuations.
GC.Collect();
int gen0 = GC.CollectionCount(0);
int gen1 = GC.CollectionCount(1);
int gen2 = GC.CollectionCount(2);
Assert.InRange(GC.GetTotalMemory(true), 1, long.MaxValue);
Assert.InRange(GC.CollectionCount(0), gen0 + 1, int.MaxValue);
Assert.InRange(GC.CollectionCount(1), gen1 + 1, int.MaxValue);
Assert.InRange(GC.CollectionCount(2), gen2 + 1, int.MaxValue);
}
[Fact]
public static void GetGeneration()
{
// We don't test a tighter bound on GetGeneration as objects
// can actually get demoted or stay in the same generation
// across collections.
GC.Collect();
var obj = new object();
for (int i = 0; i <= GC.MaxGeneration + 1; i++)
{
Assert.InRange(GC.GetGeneration(obj), 0, GC.MaxGeneration);
GC.Collect();
}
}
[Theory]
[InlineData(GCLargeObjectHeapCompactionMode.CompactOnce)]
[InlineData(GCLargeObjectHeapCompactionMode.Default)]
public static void LargeObjectHeapCompactionModeRoundTrips(GCLargeObjectHeapCompactionMode value)
{
GCLargeObjectHeapCompactionMode orig = GCSettings.LargeObjectHeapCompactionMode;
try
{
GCSettings.LargeObjectHeapCompactionMode = value;
Assert.Equal(value, GCSettings.LargeObjectHeapCompactionMode);
}
finally
{
GCSettings.LargeObjectHeapCompactionMode = orig;
Assert.Equal(orig, GCSettings.LargeObjectHeapCompactionMode);
}
}
[Theory]
[InlineData(GCLatencyMode.Batch)]
[InlineData(GCLatencyMode.Interactive)]
public static void LatencyRoundtrips(GCLatencyMode value)
{
GCLatencyMode orig = GCSettings.LatencyMode;
try
{
GCSettings.LatencyMode = value;
Assert.Equal(value, GCSettings.LatencyMode);
}
finally
{
GCSettings.LatencyMode = orig;
Assert.Equal(orig, GCSettings.LatencyMode);
}
}
[Theory]
[PlatformSpecific(PlatformID.Windows)] //Concurent GC is not enabled on Unix. Recombine to TestLatencyRoundTrips once addressed.
[InlineData(GCLatencyMode.LowLatency)]
[InlineData(GCLatencyMode.SustainedLowLatency)]
public static void LatencyRoundtrips_LowLatency(GCLatencyMode value) => LatencyRoundtrips(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.Globalization;
using Xunit;
namespace System.Drawing.PrimitivesTests
{
public class PointTests
{
[Fact]
public void DefaultConstructorTest()
{
Assert.Equal(Point.Empty, new Point());
}
[Theory]
[InlineData(int.MaxValue, int.MinValue)]
[InlineData(int.MinValue, int.MinValue)]
[InlineData(int.MaxValue, int.MaxValue)]
[InlineData(0, 0)]
public void NonDefaultConstructorTest(int x, int y)
{
Point p1 = new Point(x, y);
Point p2 = new Point(new Size(x, y));
Assert.Equal(p1, p2);
}
[Theory]
[InlineData(int.MaxValue)]
[InlineData(int.MinValue)]
[InlineData(0)]
public void SingleIntConstructorTest(int x)
{
Point p1 = new Point(x);
Point p2 = new Point(unchecked((short)(x & 0xFFFF)), unchecked((short)((x >> 16) & 0xFFFF)));
Assert.Equal(p1, p2);
}
[Fact]
public void IsEmptyDefaultsTest()
{
Assert.True(Point.Empty.IsEmpty);
Assert.True(new Point().IsEmpty);
Assert.True(new Point(0, 0).IsEmpty);
}
[Theory]
[InlineData(int.MaxValue, int.MinValue)]
[InlineData(int.MinValue, int.MinValue)]
[InlineData(int.MaxValue, int.MaxValue)]
public void IsEmptyRandomTest(int x, int y)
{
Assert.False(new Point(x, y).IsEmpty);
}
[Theory]
[InlineData(int.MaxValue, int.MinValue)]
[InlineData(int.MinValue, int.MinValue)]
[InlineData(int.MaxValue, int.MaxValue)]
[InlineData(0, 0)]
public void CoordinatesTest(int x, int y)
{
Point p = new Point(x, y);
Assert.Equal(x, p.X);
Assert.Equal(y, p.Y);
}
[Theory]
[InlineData(int.MaxValue, int.MinValue)]
[InlineData(int.MinValue, int.MinValue)]
[InlineData(int.MaxValue, int.MaxValue)]
[InlineData(0, 0)]
public void PointFConversionTest(int x, int y)
{
PointF p = new Point(x, y);
Assert.Equal(new PointF(x, y), p);
}
[Theory]
[InlineData(int.MaxValue, int.MinValue)]
[InlineData(int.MinValue, int.MinValue)]
[InlineData(int.MaxValue, int.MaxValue)]
[InlineData(0, 0)]
public void SizeConversionTest(int x, int y)
{
Size sz = (Size)new Point(x, y);
Assert.Equal(new Size(x, y), sz);
}
[Theory]
[InlineData(int.MaxValue, int.MinValue)]
[InlineData(int.MinValue, int.MinValue)]
[InlineData(int.MaxValue, int.MaxValue)]
[InlineData(0, 0)]
public void ArithmeticTest(int x, int y)
{
Point addExpected, subExpected, p = new Point(x, y);
Size s = new Size(y, x);
unchecked
{
addExpected = new Point(x + y, y + x);
subExpected = new Point(x - y, y - x);
}
Assert.Equal(addExpected, p + s);
Assert.Equal(subExpected, p - s);
Assert.Equal(addExpected, Point.Add(p, s));
Assert.Equal(subExpected, Point.Subtract(p, s));
}
[Theory]
[InlineData(float.MaxValue, float.MinValue)]
[InlineData(float.MinValue, float.MinValue)]
[InlineData(float.MaxValue, float.MaxValue)]
[InlineData(0, 0)]
public void PointFMathematicalTest(float x, float y)
{
PointF pf = new PointF(x, y);
Point pCeiling, pTruncate, pRound;
unchecked
{
pCeiling = new Point((int)Math.Ceiling(x), (int)Math.Ceiling(y));
pTruncate = new Point((int)x, (int)y);
pRound = new Point((int)Math.Round(x), (int)Math.Round(y));
}
Assert.Equal(pCeiling, Point.Ceiling(pf));
Assert.Equal(pRound, Point.Round(pf));
Assert.Equal(pTruncate, Point.Truncate(pf));
}
[Theory]
[InlineData(int.MaxValue, int.MinValue)]
[InlineData(int.MinValue, int.MinValue)]
[InlineData(int.MaxValue, int.MaxValue)]
[InlineData(0, 0)]
public void OffsetTest(int x, int y)
{
Point p1 = new Point(x, y);
Point p2 = new Point(y, x);
p1.Offset(p2);
Assert.Equal(unchecked(p2.X + p2.Y), p1.X);
Assert.Equal(p1.X, p1.Y);
p2.Offset(x, y);
Assert.Equal(p1, p2);
}
[Theory]
[InlineData(int.MaxValue, int.MinValue)]
[InlineData(int.MinValue, int.MinValue)]
[InlineData(int.MaxValue, int.MaxValue)]
[InlineData(0, 0)]
public void EqualityTest(int x, int y)
{
Point p1 = new Point(x, y);
Point p2 = new Point(x / 2 - 1, y / 2 - 1);
Point p3 = new Point(x, y);
Assert.True(p1 == p3);
Assert.True(p1 != p2);
Assert.True(p2 != p3);
Assert.True(p1.Equals(p3));
Assert.False(p1.Equals(p2));
Assert.False(p2.Equals(p3));
Assert.True(p1.Equals((object)p3));
Assert.False(p1.Equals((object)p2));
Assert.False(p2.Equals((object)p3));
Assert.Equal(p1.GetHashCode(), p3.GetHashCode());
}
[Fact]
public static void EqualityTest_NotPoint()
{
var point = new Point(0, 0);
Assert.False(point.Equals(null));
Assert.False(point.Equals(0));
Assert.False(point.Equals(new PointF(0, 0)));
}
[Fact]
public static void GetHashCodeTest()
{
var point = new Point(10, 10);
Assert.Equal(point.GetHashCode(), new Point(10, 10).GetHashCode());
Assert.NotEqual(point.GetHashCode(), new Point(20, 10).GetHashCode());
Assert.NotEqual(point.GetHashCode(), new Point(10, 20).GetHashCode());
}
[Theory]
[InlineData(0, 0, 0, 0)]
[InlineData(1, -2, 3, -4)]
public void ConversionTest(int x, int y, int width, int height)
{
Rectangle rect = new Rectangle(x, y, width, height);
RectangleF rectF = rect;
Assert.Equal(x, rectF.X);
Assert.Equal(y, rectF.Y);
Assert.Equal(width, rectF.Width);
Assert.Equal(height, rectF.Height);
}
[Theory]
[InlineData(0, 0)]
[InlineData(5, -5)]
public void ToStringTest(int x, int y)
{
Point p = new Point(x, y);
Assert.Equal(string.Format(CultureInfo.CurrentCulture, "{{X={0},Y={1}}}", p.X, p.Y), p.ToString());
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if FEATURE_CORE_DLR
using System.Linq.Expressions;
#else
using Microsoft.Scripting.Ast;
#endif
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Dynamic;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
namespace IronPython.Runtime {
[PythonType("instancemethod"), DontMapGetMemberNamesToDir]
public sealed partial class Method : PythonTypeSlot, IWeakReferenceable, IPythonMembersList, IDynamicMetaObjectProvider, ICodeFormattable, Binding.IFastInvokable {
private readonly object _func;
private readonly object _inst;
private readonly object _declaringClass;
private WeakRefTracker _weakref;
public Method(object function, object instance, object @class) {
_func = function;
_inst = instance;
_declaringClass = @class;
}
public Method(object function, object instance) {
if (instance == null) {
throw PythonOps.TypeError("unbound methods must have a class provided");
}
_func = function;
_inst = instance;
}
internal string Name {
get { return (string)PythonOps.GetBoundAttr(DefaultContext.Default, _func, "__name__"); }
}
public string __doc__ {
get {
return PythonOps.GetBoundAttr(DefaultContext.Default, _func, "__doc__") as string;
}
}
public object im_func {
get {
return _func;
}
}
public object __func__ {
get {
return _func;
}
}
public object im_self {
get {
return _inst;
}
}
public object __self__ {
get {
return _inst;
}
}
public object im_class {
get {
// we could have an OldClass (or any other object) here if the user called the ctor directly
return PythonOps.ToPythonType(_declaringClass as PythonType) ?? _declaringClass;
}
}
[SpecialName]
public object Call(CodeContext/*!*/ context, params object[] args) {
return PythonContext.GetContext(context).CallSplat(this, args);
}
[SpecialName]
public object Call(CodeContext/*!*/ context, [ParamDictionary]IDictionary<object, object> kwArgs, params object[] args) {
return PythonContext.GetContext(context).CallWithKeywords(this, args, kwArgs);
}
private Exception BadSelf(object got) {
OldClass dt = im_class as OldClass;
string firstArg;
if (got == null) {
firstArg = "nothing";
} else {
firstArg = PythonOps.GetPythonTypeName(got) + " instance";
}
PythonType pt = im_class as PythonType;
return PythonOps.TypeError("unbound method {0}() must be called with {1} instance as first argument (got {2} instead)",
Name,
(dt != null) ? dt.Name : (pt != null) ? pt.Name : im_class,
firstArg);
}
/// <summary>
/// Validates that the current self object is usable for this method.
/// </summary>
internal object CheckSelf(CodeContext context, object self) {
if (!PythonOps.IsInstance(context, self, im_class)) {
throw BadSelf(self);
}
return self;
}
#region Object Overrides
private string DeclaringClassAsString() {
if (im_class == null) return "?";
PythonType dt = im_class as PythonType;
if (dt != null) return dt.Name;
OldClass oc = im_class as OldClass;
if (oc != null) return oc.Name;
return im_class.ToString();
}
public override bool Equals(object obj) {
Method other = obj as Method;
if (other == null) return false;
return
object.ReferenceEquals(_inst, other._inst) &&
PythonOps.EqualRetBool(_func, other._func);
}
public override int GetHashCode() {
if (_inst == null) return PythonOps.Hash(DefaultContext.Default, _func);
return PythonOps.Hash(DefaultContext.Default, _inst) ^ PythonOps.Hash(DefaultContext.Default, _func);
}
#endregion
#region IWeakReferenceable Members
WeakRefTracker IWeakReferenceable.GetWeakRef() {
return _weakref;
}
bool IWeakReferenceable.SetWeakRef(WeakRefTracker value) {
_weakref = value;
return true;
}
void IWeakReferenceable.SetFinalizer(WeakRefTracker value) {
((IWeakReferenceable)this).SetWeakRef(value);
}
#endregion
#region Custom member access
[SpecialName]
public object GetCustomMember(CodeContext context, string name) {
switch (name) {
// Get the module name from the function and pass that out. Note that CPython's method has
// no __module__ attribute and this value can be gotten via a call to method.__getattribute__
// there as well.
case "__module__":
return PythonOps.GetBoundAttr(context, _func, "__module__");
case "__name__":
return PythonOps.GetBoundAttr(DefaultContext.Default, _func, "__name__");
default:
object value;
string symbol = name;
if (TypeCache.Method.TryGetBoundMember(context, this, symbol, out value) || // look on method
PythonOps.TryGetBoundAttr(context, _func, symbol, out value)) { // Forward to the func
return value;
}
return OperationFailed.Value;
}
}
[SpecialName]
public void SetMemberAfter(CodeContext context, string name, object value) {
TypeCache.Method.SetMember(context, this, name, value);
}
[SpecialName]
public void DeleteMember(CodeContext context, string name) {
TypeCache.Method.DeleteMember(context, this, name);
}
IList<string> IMembersList.GetMemberNames() {
return PythonOps.GetStringMemberList(this);
}
IList<object> IPythonMembersList.GetMemberNames(CodeContext/*!*/ context) {
List ret = TypeCache.Method.GetMemberNames(context);
ret.AddNoLockNoDups("__module__");
PythonFunction pf = _func as PythonFunction;
if (pf != null) {
PythonDictionary dict = pf.func_dict;
// Check the func
foreach (KeyValuePair<object, object> kvp in dict) {
ret.AddNoLockNoDups(kvp.Key);
}
}
return ret;
}
#endregion
#region PythonTypeSlot Overrides
internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) {
if (this.im_self == null) {
if (owner == null || owner == im_class || PythonOps.IsSubClass(context, owner, im_class)) {
value = new Method(_func, instance, owner);
return true;
}
}
value = this;
return true;
}
internal override bool GetAlwaysSucceeds {
get {
return true;
}
}
#endregion
#region ICodeFormattable Members
public string/*!*/ __repr__(CodeContext/*!*/ context) {
object name;
if (!PythonOps.TryGetBoundAttr(context, _func, "__name__", out name)) {
name = "?";
}
if (_inst != null) {
return string.Format("<bound method {0}.{1} of {2}>",
DeclaringClassAsString(),
name,
PythonOps.Repr(context, _inst));
} else {
return string.Format("<unbound method {0}.{1}>", DeclaringClassAsString(), name);
}
}
#endregion
#region IDynamicMetaObjectProvider Members
DynamicMetaObject/*!*/ IDynamicMetaObjectProvider.GetMetaObject(Expression/*!*/ parameter) {
return new Binding.MetaMethod(parameter, BindingRestrictions.Empty, this);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// SmtpClientTest.cs - NUnit Test Cases for System.Net.Mail.SmtpClient
//
// Authors:
// John Luke (john.luke@gmail.com)
//
// (C) 2006 John Luke
//
using System.IO;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Mail.Tests
{
public class SmtpClientTest : FileCleanupTestBase
{
private SmtpClient _smtp;
private SmtpClient Smtp
{
get
{
return _smtp ?? (_smtp = new SmtpClient());
}
}
private string TempFolder
{
get
{
return TestDirectory;
}
}
protected override void Dispose(bool disposing)
{
if (_smtp != null)
{
_smtp.Dispose();
}
base.Dispose(disposing);
}
[Theory]
[InlineData(SmtpDeliveryMethod.SpecifiedPickupDirectory)]
[InlineData(SmtpDeliveryMethod.PickupDirectoryFromIis)]
public void DeliveryMethodTest(SmtpDeliveryMethod method)
{
Smtp.DeliveryMethod = method;
Assert.Equal(method, Smtp.DeliveryMethod);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void EnableSslTest(bool value)
{
Smtp.EnableSsl = value;
Assert.Equal(value, Smtp.EnableSsl);
}
[Theory]
[InlineData("127.0.0.1")]
[InlineData("smtp.ximian.com")]
public void HostTest(string host)
{
Smtp.Host = host;
Assert.Equal(host, Smtp.Host);
}
[Fact]
public void InvalidHostTest()
{
Assert.Throws<ArgumentNullException>(() => Smtp.Host = null);
AssertExtensions.Throws<ArgumentException>("value", () => Smtp.Host = "");
}
[Fact]
public void ServicePoint_GetsCachedInstanceSpecificToHostPort()
{
using (var smtp1 = new SmtpClient("localhost1", 25))
using (var smtp2 = new SmtpClient("localhost1", 25))
using (var smtp3 = new SmtpClient("localhost2", 25))
using (var smtp4 = new SmtpClient("localhost2", 26))
{
ServicePoint s1 = smtp1.ServicePoint;
ServicePoint s2 = smtp2.ServicePoint;
ServicePoint s3 = smtp3.ServicePoint;
ServicePoint s4 = smtp4.ServicePoint;
Assert.NotNull(s1);
Assert.NotNull(s2);
Assert.NotNull(s3);
Assert.NotNull(s4);
Assert.Same(s1, s2);
Assert.NotSame(s2, s3);
Assert.NotSame(s2, s4);
Assert.NotSame(s3, s4);
}
}
[Fact]
public void ServicePoint_NetCoreApp_AddressIsAccessible()
{
using (var smtp = new SmtpClient("localhost", 25))
{
Assert.Equal("mailto", smtp.ServicePoint.Address.Scheme);
Assert.Equal("localhost", smtp.ServicePoint.Address.Host);
Assert.Equal(25, smtp.ServicePoint.Address.Port);
}
}
[Fact]
public void ServicePoint_ReflectsHostAndPortChange()
{
using (var smtp = new SmtpClient("localhost1", 25))
{
ServicePoint s1 = smtp.ServicePoint;
smtp.Host = "localhost2";
ServicePoint s2 = smtp.ServicePoint;
smtp.Host = "localhost2";
ServicePoint s3 = smtp.ServicePoint;
Assert.NotSame(s1, s2);
Assert.Same(s2, s3);
smtp.Port = 26;
ServicePoint s4 = smtp.ServicePoint;
smtp.Port = 26;
ServicePoint s5 = smtp.ServicePoint;
Assert.NotSame(s3, s4);
Assert.Same(s4, s5);
}
}
[Theory]
[InlineData("")]
[InlineData(null)]
[InlineData("shouldnotexist")]
[InlineData("\0")]
[InlineData("C:\\some\\path\\like\\string")]
public void PickupDirectoryLocationTest(string folder)
{
Smtp.PickupDirectoryLocation = folder;
Assert.Equal(folder, Smtp.PickupDirectoryLocation);
}
[Theory]
[InlineData(25)]
[InlineData(1)]
[InlineData(int.MaxValue)]
public void PortTest(int value)
{
Smtp.Port = value;
Assert.Equal(value, Smtp.Port);
}
[Fact]
public void TestDefaultsOnProperties()
{
Assert.Equal(25, Smtp.Port);
Assert.Equal(100000, Smtp.Timeout);
Assert.Null(Smtp.Host);
Assert.Null(Smtp.Credentials);
Assert.False(Smtp.EnableSsl);
Assert.False(Smtp.UseDefaultCredentials);
Assert.Equal(SmtpDeliveryMethod.Network, Smtp.DeliveryMethod);
Assert.Null(Smtp.PickupDirectoryLocation);
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
[InlineData(int.MinValue)]
public void Port_Value_Invalid(int value)
{
Assert.Throws<ArgumentOutOfRangeException>(() => Smtp.Port = value);
}
[Fact]
public void Send_Message_Null()
{
Assert.Throws<ArgumentNullException>(() => Smtp.Send(null));
}
[Fact]
public void Send_Network_Host_Null()
{
Assert.Throws<InvalidOperationException>(() => Smtp.Send("mono@novell.com", "everyone@novell.com", "introduction", "hello"));
}
[Fact]
public void Send_Network_Host_Whitespace()
{
Smtp.Host = " \r\n ";
Assert.Throws<InvalidOperationException>(() => Smtp.Send("mono@novell.com", "everyone@novell.com", "introduction", "hello"));
}
[Fact]
public void Send_SpecifiedPickupDirectory()
{
Smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
Smtp.PickupDirectoryLocation = TempFolder;
Smtp.Send("mono@novell.com", "everyone@novell.com", "introduction", "hello");
string[] files = Directory.GetFiles(TempFolder, "*");
Assert.Equal(1, files.Length);
Assert.Equal(".eml", Path.GetExtension(files[0]));
}
[Fact]
public void Send_SpecifiedPickupDirectory_MessageBodyDoesNotEncodeForTransport()
{
// This test verifies that a line fold which results in a dot appearing as the first character of
// a new line does not get dot-stuffed when the delivery method is pickup. To do so, it relies on
// folding happening at a precise location. If folding implementation details change, this test will
// likely fail and need to be updated accordingly.
string padding = new string('a', 65);
Smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
Smtp.PickupDirectoryLocation = TempFolder;
Smtp.Send("mono@novell.com", "everyone@novell.com", "introduction", padding + ".");
string[] files = Directory.GetFiles(TempFolder, "*");
Assert.Equal(1, files.Length);
Assert.Equal(".eml", Path.GetExtension(files[0]));
string message = File.ReadAllText(files[0]);
Assert.EndsWith($"{padding}=\r\n.\r\n", message);
}
[Theory]
[InlineData("some_path_not_exist")]
[InlineData("")]
[InlineData(null)]
[InlineData("\0abc")]
public void Send_SpecifiedPickupDirectoryInvalid(string location)
{
Smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
Smtp.PickupDirectoryLocation = location;
Assert.Throws<SmtpException>(() => Smtp.Send("mono@novell.com", "everyone@novell.com", "introduction", "hello"));
}
[Theory]
[InlineData(0)]
[InlineData(50)]
[InlineData(int.MaxValue)]
[InlineData(int.MinValue)]
[InlineData(-1)]
public void TestTimeout(int value)
{
if (value < 0)
{
Assert.Throws<ArgumentOutOfRangeException>(() => Smtp.Timeout = value);
return;
}
Smtp.Timeout = value;
Assert.Equal(value, Smtp.Timeout);
}
[Fact]
public void Send_ServerDoesntExist_Throws()
{
using (var smtp = new SmtpClient(Guid.NewGuid().ToString("N")))
{
Assert.Throws<SmtpException>(() => smtp.Send("anyone@anyone.com", "anyone@anyone.com", "subject", "body"));
}
}
[Fact]
public async Task SendAsync_ServerDoesntExist_Throws()
{
using (var smtp = new SmtpClient(Guid.NewGuid().ToString("N")))
{
await Assert.ThrowsAsync<SmtpException>(() => smtp.SendMailAsync("anyone@anyone.com", "anyone@anyone.com", "subject", "body"));
}
}
[Fact]
public void TestMailDelivery()
{
SmtpServer server = new SmtpServer();
SmtpClient client = new SmtpClient("localhost", server.EndPoint.Port);
client.Credentials = new NetworkCredential("user", "password");
MailMessage msg = new MailMessage("foo@example.com", "bar@example.com", "hello", "howdydoo");
string clientDomain = IPGlobalProperties.GetIPGlobalProperties().HostName.Trim().ToLower();
try
{
Thread t = new Thread(server.Run);
t.Start();
client.Send(msg);
t.Join();
Assert.Equal("<foo@example.com>", server.MailFrom);
Assert.Equal("<bar@example.com>", server.MailTo);
Assert.Equal("hello", server.Subject);
Assert.Equal("howdydoo", server.Body);
Assert.Equal(clientDomain, server.ClientDomain);
}
finally
{
server.Stop();
}
}
[Fact]
// [ActiveIssue(40711)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework has a bug and may not time out for low values")]
[PlatformSpecific(~TestPlatforms.OSX)] // on OSX, not all synchronous operations (e.g. connect) can be aborted by closing the socket.
public void TestZeroTimeout()
{
var testTask = Task.Run(() =>
{
using (Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
serverSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
serverSocket.Listen(1);
SmtpClient smtpClient = new SmtpClient("localhost", (serverSocket.LocalEndPoint as IPEndPoint).Port);
smtpClient.Timeout = 0;
MailMessage msg = new MailMessage("foo@example.com", "bar@example.com", "hello", "test");
Assert.Throws<SmtpException>(() => smtpClient.Send(msg));
}
});
// Abort in order to get a coredump if this test takes too long.
if (!testTask.Wait(TimeSpan.FromMinutes(5)))
{
Environment.FailFast(nameof(TestZeroTimeout));
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework has a bug and could hang in case of null or empty body")]
[Theory]
[InlineData("howdydoo")]
[InlineData("")]
[InlineData(null)]
public async Task TestMailDeliveryAsync(string body)
{
SmtpServer server = new SmtpServer();
SmtpClient client = new SmtpClient("localhost", server.EndPoint.Port);
MailMessage msg = new MailMessage("foo@example.com", "bar@example.com", "hello", body);
string clientDomain = IPGlobalProperties.GetIPGlobalProperties().HostName.Trim().ToLower();
try
{
Thread t = new Thread(server.Run);
t.Start();
await client.SendMailAsync(msg).TimeoutAfter((int)TimeSpan.FromSeconds(30).TotalMilliseconds);
t.Join();
Assert.Equal("<foo@example.com>", server.MailFrom);
Assert.Equal("<bar@example.com>", server.MailTo);
Assert.Equal("hello", server.Subject);
Assert.Equal(body ?? "", server.Body);
Assert.Equal(clientDomain, server.ClientDomain);
}
finally
{
server.Stop();
}
}
[Fact]
public async Task TestCredentialsCopyInAsyncContext()
{
SmtpServer server = new SmtpServer();
SmtpClient client = new SmtpClient("localhost", server.EndPoint.Port);
MailMessage msg = new MailMessage("foo@example.com", "bar@example.com", "hello", "howdydoo");
string clientDomain = IPGlobalProperties.GetIPGlobalProperties().HostName.Trim().ToLower();
CredentialCache cache = new CredentialCache();
cache.Add("localhost", server.EndPoint.Port, "NTLM", CredentialCache.DefaultNetworkCredentials);
client.Credentials = cache;
try
{
Thread t = new Thread(server.Run);
t.Start();
await client.SendMailAsync(msg);
t.Join();
Assert.Equal("<foo@example.com>", server.MailFrom);
Assert.Equal("<bar@example.com>", server.MailTo);
Assert.Equal("hello", server.Subject);
Assert.Equal("howdydoo", server.Body);
Assert.Equal(clientDomain, server.ClientDomain);
}
finally
{
server.Stop();
}
}
[Theory]
[InlineData(false, false, false)]
[InlineData(false, false, true)] // Received subjectText.
[InlineData(false, true, false)]
[InlineData(false, true, true)]
[InlineData(true, false, false)]
[InlineData(true, false, true)] // Received subjectText.
[InlineData(true, true, false)]
[InlineData(true, true, true)] // Received subjectBase64. If subjectText is received, the test fails, and the results are inconsistent with those of synchronous methods.
public void SendMail_DeliveryFormat_SubjectEncoded(bool useAsyncSend, bool useSevenBit, bool useSmtpUTF8)
{
// If the server support `SMTPUTF8` and use `SmtpDeliveryFormat.International`, the server should received this subject.
const string subjectText = "Test \u6d4b\u8bd5 Contain \u5305\u542b UTF8";
// If the server does not support `SMTPUTF8` or use `SmtpDeliveryFormat.SevenBit`, the server should received this subject.
const string subjectBase64 = "=?utf-8?B?VGVzdCDmtYvor5UgQ29udGFpbiDljIXlkKsgVVRGOA==?=";
SmtpServer server = new SmtpServer();
// Setting up Server Support for `SMTPUTF8`.
server.SupportSmtpUTF8 = useSmtpUTF8;
SmtpClient client = new SmtpClient("localhost", server.EndPoint.Port);
if (useSevenBit)
{
// Subject will be encoded by Base64.
client.DeliveryFormat = SmtpDeliveryFormat.SevenBit;
}
else
{
// If the server supports `SMTPUTF8`, subject will not be encoded. Otherwise, subject will be encoded by Base64.
client.DeliveryFormat = SmtpDeliveryFormat.International;
}
MailMessage msg = new MailMessage("foo@example.com", "bar@example.com", subjectText, "hello \u9ad8\u575a\u679c");
msg.HeadersEncoding = msg.BodyEncoding = msg.SubjectEncoding = System.Text.Encoding.UTF8;
try
{
Thread t = new Thread(server.Run);
t.Start();
if (useAsyncSend)
{
client.SendMailAsync(msg).Wait();
}
else
{
client.Send(msg);
}
if (useSevenBit || !useSmtpUTF8)
{
Assert.Equal(subjectBase64, server.Subject);
}
else
{
Assert.Equal(subjectText, server.Subject);
}
}
finally
{
server.Stop();
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Build.Framework
{
public delegate void AnyEventHandler(object sender, Microsoft.Build.Framework.BuildEventArgs e);
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct BuildEngineResult
{
public BuildEngineResult(bool result, System.Collections.Generic.List<System.Collections.Generic.IDictionary<string, Microsoft.Build.Framework.ITaskItem[]>> targetOutputsPerProject) { throw null;}
public bool Result { get { throw null; } }
public System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string, Microsoft.Build.Framework.ITaskItem[]>> TargetOutputsPerProject { get { throw null; } }
}
public partial class BuildErrorEventArgs : Microsoft.Build.Framework.LazyFormattedBuildEventArgs
{
protected BuildErrorEventArgs() { }
public BuildErrorEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName) { }
public BuildErrorEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, System.DateTime eventTimestamp) { }
public BuildErrorEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, System.DateTime eventTimestamp, params object[] messageArgs) { }
public string Code { get { throw null; } }
public int ColumnNumber { get { throw null; } }
public int EndColumnNumber { get { throw null; } }
public int EndLineNumber { get { throw null; } }
public string File { get { throw null; } }
public int LineNumber { get { throw null; } }
public string ProjectFile { get { throw null; } set { } }
public string Subcategory { get { throw null; } }
}
public delegate void BuildErrorEventHandler(object sender, Microsoft.Build.Framework.BuildErrorEventArgs e);
public abstract partial class BuildEventArgs : System.EventArgs
{
protected BuildEventArgs() { }
protected BuildEventArgs(string message, string helpKeyword, string senderName) { }
protected BuildEventArgs(string message, string helpKeyword, string senderName, System.DateTime eventTimestamp) { }
public Microsoft.Build.Framework.BuildEventContext BuildEventContext { get { throw null; } set { } }
public string HelpKeyword { get { throw null; } }
public virtual string Message { get { throw null; } protected set { } }
public string SenderName { get { throw null; } }
public int ThreadId { get { throw null; } }
public System.DateTime Timestamp { get { throw null; } }
}
public partial class BuildEventContext
{
public const int InvalidEvaluationId = -1;
public const int InvalidNodeId = -2;
public const int InvalidProjectContextId = -2;
public const int InvalidProjectInstanceId = -1;
public const int InvalidSubmissionId = -1;
public const int InvalidTargetId = -1;
public const int InvalidTaskId = -1;
public BuildEventContext(int nodeId, int targetId, int projectContextId, int taskId) { }
public BuildEventContext(int nodeId, int projectInstanceId, int projectContextId, int targetId, int taskId) { }
public BuildEventContext(int submissionId, int nodeId, int projectInstanceId, int projectContextId, int targetId, int taskId) { }
public BuildEventContext(int submissionId, int nodeId, int evaluationId, int projectInstanceId, int projectContextId, int targetId, int taskId) { }
public long BuildRequestId { get { throw null; } }
public int EvaluationId { get { throw null; } }
public static Microsoft.Build.Framework.BuildEventContext Invalid { get { throw null; } }
public int NodeId { get { throw null; } }
public int ProjectContextId { get { throw null; } }
public int ProjectInstanceId { get { throw null; } }
public int SubmissionId { get { throw null; } }
public int TargetId { get { throw null; } }
public int TaskId { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(Microsoft.Build.Framework.BuildEventContext left, Microsoft.Build.Framework.BuildEventContext right) { throw null; }
public static bool operator !=(Microsoft.Build.Framework.BuildEventContext left, Microsoft.Build.Framework.BuildEventContext right) { throw null; }
}
public partial class BuildFinishedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs
{
protected BuildFinishedEventArgs() { }
public BuildFinishedEventArgs(string message, string helpKeyword, bool succeeded) { }
public BuildFinishedEventArgs(string message, string helpKeyword, bool succeeded, System.DateTime eventTimestamp) { }
public BuildFinishedEventArgs(string message, string helpKeyword, bool succeeded, System.DateTime eventTimestamp, params object[] messageArgs) { }
public bool Succeeded { get { throw null; } }
}
public delegate void BuildFinishedEventHandler(object sender, Microsoft.Build.Framework.BuildFinishedEventArgs e);
public partial class BuildMessageEventArgs : Microsoft.Build.Framework.LazyFormattedBuildEventArgs
{
protected BuildMessageEventArgs() { }
public BuildMessageEventArgs(string message, string helpKeyword, string senderName, Microsoft.Build.Framework.MessageImportance importance) { }
public BuildMessageEventArgs(string message, string helpKeyword, string senderName, Microsoft.Build.Framework.MessageImportance importance, System.DateTime eventTimestamp) { }
public BuildMessageEventArgs(string message, string helpKeyword, string senderName, Microsoft.Build.Framework.MessageImportance importance, System.DateTime eventTimestamp, params object[] messageArgs) { }
public BuildMessageEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, Microsoft.Build.Framework.MessageImportance importance) { }
public BuildMessageEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, Microsoft.Build.Framework.MessageImportance importance, System.DateTime eventTimestamp) { }
public BuildMessageEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, Microsoft.Build.Framework.MessageImportance importance, System.DateTime eventTimestamp, params object[] messageArgs) { }
public string Code { get { throw null; } }
public int ColumnNumber { get { throw null; } }
public int EndColumnNumber { get { throw null; } }
public int EndLineNumber { get { throw null; } }
public string File { get { throw null; } }
public Microsoft.Build.Framework.MessageImportance Importance { get { throw null; } }
public int LineNumber { get { throw null; } }
public string ProjectFile { get { throw null; } set { } }
public string Subcategory { get { throw null; } }
}
public delegate void BuildMessageEventHandler(object sender, Microsoft.Build.Framework.BuildMessageEventArgs e);
public partial class BuildStartedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs
{
protected BuildStartedEventArgs() { }
public BuildStartedEventArgs(string message, string helpKeyword) { }
public BuildStartedEventArgs(string message, string helpKeyword, System.Collections.Generic.IDictionary<string, string> environmentOfBuild) { }
public BuildStartedEventArgs(string message, string helpKeyword, System.DateTime eventTimestamp) { }
public BuildStartedEventArgs(string message, string helpKeyword, System.DateTime eventTimestamp, params object[] messageArgs) { }
public System.Collections.Generic.IDictionary<string, string> BuildEnvironment { get { throw null; } }
}
public delegate void BuildStartedEventHandler(object sender, Microsoft.Build.Framework.BuildStartedEventArgs e);
public abstract partial class BuildStatusEventArgs : Microsoft.Build.Framework.LazyFormattedBuildEventArgs
{
protected BuildStatusEventArgs() { }
protected BuildStatusEventArgs(string message, string helpKeyword, string senderName) { }
protected BuildStatusEventArgs(string message, string helpKeyword, string senderName, System.DateTime eventTimestamp) { }
protected BuildStatusEventArgs(string message, string helpKeyword, string senderName, System.DateTime eventTimestamp, params object[] messageArgs) { }
}
public delegate void BuildStatusEventHandler(object sender, Microsoft.Build.Framework.BuildStatusEventArgs e);
public partial class BuildWarningEventArgs : Microsoft.Build.Framework.LazyFormattedBuildEventArgs
{
protected BuildWarningEventArgs() { }
public BuildWarningEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName) { }
public BuildWarningEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, System.DateTime eventTimestamp) { }
public BuildWarningEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, System.DateTime eventTimestamp, params object[] messageArgs) { }
public string Code { get { throw null; } }
public int ColumnNumber { get { throw null; } }
public int EndColumnNumber { get { throw null; } }
public int EndLineNumber { get { throw null; } }
public string File { get { throw null; } }
public int LineNumber { get { throw null; } }
public string ProjectFile { get { throw null; } set { } }
public string Subcategory { get { throw null; } }
}
public delegate void BuildWarningEventHandler(object sender, Microsoft.Build.Framework.BuildWarningEventArgs e);
public partial class CriticalBuildMessageEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs
{
protected CriticalBuildMessageEventArgs() { }
public CriticalBuildMessageEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName) { }
public CriticalBuildMessageEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, System.DateTime eventTimestamp) { }
public CriticalBuildMessageEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, System.DateTime eventTimestamp, params object[] messageArgs) { }
}
public abstract partial class CustomBuildEventArgs : Microsoft.Build.Framework.LazyFormattedBuildEventArgs
{
protected CustomBuildEventArgs() { }
protected CustomBuildEventArgs(string message, string helpKeyword, string senderName) { }
protected CustomBuildEventArgs(string message, string helpKeyword, string senderName, System.DateTime eventTimestamp) { }
protected CustomBuildEventArgs(string message, string helpKeyword, string senderName, System.DateTime eventTimestamp, params object[] messageArgs) { }
}
public delegate void CustomBuildEventHandler(object sender, Microsoft.Build.Framework.CustomBuildEventArgs e);
public partial class ExternalProjectFinishedEventArgs : Microsoft.Build.Framework.CustomBuildEventArgs
{
protected ExternalProjectFinishedEventArgs() { }
public ExternalProjectFinishedEventArgs(string message, string helpKeyword, string senderName, string projectFile, bool succeeded) { }
public ExternalProjectFinishedEventArgs(string message, string helpKeyword, string senderName, string projectFile, bool succeeded, System.DateTime eventTimestamp) { }
public string ProjectFile { get { throw null; } }
public bool Succeeded { get { throw null; } }
}
public partial class ExternalProjectStartedEventArgs : Microsoft.Build.Framework.CustomBuildEventArgs
{
protected ExternalProjectStartedEventArgs() { }
public ExternalProjectStartedEventArgs(string message, string helpKeyword, string senderName, string projectFile, string targetNames) { }
public ExternalProjectStartedEventArgs(string message, string helpKeyword, string senderName, string projectFile, string targetNames, System.DateTime eventTimestamp) { }
public string ProjectFile { get { throw null; } }
public string TargetNames { get { throw null; } }
}
public partial interface IBuildEngine
{
int ColumnNumberOfTaskNode { get; }
bool ContinueOnError { get; }
int LineNumberOfTaskNode { get; }
string ProjectFileOfTaskNode { get; }
bool BuildProjectFile(string projectFileName, string[] targetNames, System.Collections.IDictionary globalProperties, System.Collections.IDictionary targetOutputs);
void LogCustomEvent(Microsoft.Build.Framework.CustomBuildEventArgs e);
void LogErrorEvent(Microsoft.Build.Framework.BuildErrorEventArgs e);
void LogMessageEvent(Microsoft.Build.Framework.BuildMessageEventArgs e);
void LogWarningEvent(Microsoft.Build.Framework.BuildWarningEventArgs e);
}
public partial interface IBuildEngine2 : Microsoft.Build.Framework.IBuildEngine
{
bool IsRunningMultipleNodes { get; }
bool BuildProjectFile(string projectFileName, string[] targetNames, System.Collections.IDictionary globalProperties, System.Collections.IDictionary targetOutputs, string toolsVersion);
bool BuildProjectFilesInParallel(string[] projectFileNames, string[] targetNames, System.Collections.IDictionary[] globalProperties, System.Collections.IDictionary[] targetOutputsPerProject, string[] toolsVersion, bool useResultsCache, bool unloadProjectsOnCompletion);
}
public partial interface IBuildEngine3 : Microsoft.Build.Framework.IBuildEngine, Microsoft.Build.Framework.IBuildEngine2
{
Microsoft.Build.Framework.BuildEngineResult BuildProjectFilesInParallel(string[] projectFileNames, string[] targetNames, System.Collections.IDictionary[] globalProperties, System.Collections.Generic.IList<string>[] removeGlobalProperties, string[] toolsVersion, bool returnTargetOutputs);
void Reacquire();
void Yield();
}
public partial interface IBuildEngine4 : Microsoft.Build.Framework.IBuildEngine, Microsoft.Build.Framework.IBuildEngine2, Microsoft.Build.Framework.IBuildEngine3
{
object GetRegisteredTaskObject(object key, Microsoft.Build.Framework.RegisteredTaskObjectLifetime lifetime);
void RegisterTaskObject(object key, object obj, Microsoft.Build.Framework.RegisteredTaskObjectLifetime lifetime, bool allowEarlyCollection);
object UnregisterTaskObject(object key, Microsoft.Build.Framework.RegisteredTaskObjectLifetime lifetime);
}
public partial interface IBuildEngine5 : Microsoft.Build.Framework.IBuildEngine, Microsoft.Build.Framework.IBuildEngine2, Microsoft.Build.Framework.IBuildEngine3, Microsoft.Build.Framework.IBuildEngine4
{
void LogTelemetry(string eventName, System.Collections.Generic.IDictionary<string, string> properties);
}
public partial interface IBuildEngine6 : Microsoft.Build.Framework.IBuildEngine, Microsoft.Build.Framework.IBuildEngine2, Microsoft.Build.Framework.IBuildEngine3, Microsoft.Build.Framework.IBuildEngine4, Microsoft.Build.Framework.IBuildEngine5
{
System.Collections.Generic.IReadOnlyDictionary<string, string> GetGlobalProperties();
}
public partial interface ICancelableTask : Microsoft.Build.Framework.ITask
{
void Cancel();
}
public partial interface IEventRedirector
{
void ForwardEvent(Microsoft.Build.Framework.BuildEventArgs buildEvent);
}
public partial interface IEventSource
{
event Microsoft.Build.Framework.AnyEventHandler AnyEventRaised;
event Microsoft.Build.Framework.BuildFinishedEventHandler BuildFinished;
event Microsoft.Build.Framework.BuildStartedEventHandler BuildStarted;
event Microsoft.Build.Framework.CustomBuildEventHandler CustomEventRaised;
event Microsoft.Build.Framework.BuildErrorEventHandler ErrorRaised;
event Microsoft.Build.Framework.BuildMessageEventHandler MessageRaised;
event Microsoft.Build.Framework.ProjectFinishedEventHandler ProjectFinished;
event Microsoft.Build.Framework.ProjectStartedEventHandler ProjectStarted;
event Microsoft.Build.Framework.BuildStatusEventHandler StatusEventRaised;
event Microsoft.Build.Framework.TargetFinishedEventHandler TargetFinished;
event Microsoft.Build.Framework.TargetStartedEventHandler TargetStarted;
event Microsoft.Build.Framework.TaskFinishedEventHandler TaskFinished;
event Microsoft.Build.Framework.TaskStartedEventHandler TaskStarted;
event Microsoft.Build.Framework.BuildWarningEventHandler WarningRaised;
}
public partial interface IEventSource2 : Microsoft.Build.Framework.IEventSource
{
event Microsoft.Build.Framework.TelemetryEventHandler TelemetryLogged;
}
public partial interface IEventSource3 : Microsoft.Build.Framework.IEventSource, Microsoft.Build.Framework.IEventSource2
{
void IncludeEvaluationMetaprojects();
void IncludeEvaluationProfiles();
void IncludeTaskInputs();
}
public partial interface IForwardingLogger : Microsoft.Build.Framework.ILogger, Microsoft.Build.Framework.INodeLogger
{
Microsoft.Build.Framework.IEventRedirector BuildEventRedirector { get; set; }
int NodeId { get; set; }
}
public partial interface IGeneratedTask : Microsoft.Build.Framework.ITask
{
object GetPropertyValue(Microsoft.Build.Framework.TaskPropertyInfo property);
void SetPropertyValue(Microsoft.Build.Framework.TaskPropertyInfo property, object value);
}
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial interface ILogger
{
string Parameters { get; set; }
Microsoft.Build.Framework.LoggerVerbosity Verbosity { get; set; }
void Initialize(Microsoft.Build.Framework.IEventSource eventSource);
void Shutdown();
}
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial interface INodeLogger : Microsoft.Build.Framework.ILogger
{
void Initialize(Microsoft.Build.Framework.IEventSource eventSource, int nodeCount);
}
public partial interface IProjectElement
{
string ElementName { get; }
string OuterElement { get; }
}
public partial interface ITask
{
Microsoft.Build.Framework.IBuildEngine BuildEngine { get; set; }
Microsoft.Build.Framework.ITaskHost HostObject { get; set; }
bool Execute();
}
public partial interface ITaskFactory
{
string FactoryName { get; }
System.Type TaskType { get; }
void CleanupTask(Microsoft.Build.Framework.ITask task);
Microsoft.Build.Framework.ITask CreateTask(Microsoft.Build.Framework.IBuildEngine taskFactoryLoggingHost);
Microsoft.Build.Framework.TaskPropertyInfo[] GetTaskParameters();
bool Initialize(string taskName, System.Collections.Generic.IDictionary<string, Microsoft.Build.Framework.TaskPropertyInfo> parameterGroup, string taskBody, Microsoft.Build.Framework.IBuildEngine taskFactoryLoggingHost);
}
public partial interface ITaskFactory2 : Microsoft.Build.Framework.ITaskFactory
{
Microsoft.Build.Framework.ITask CreateTask(Microsoft.Build.Framework.IBuildEngine taskFactoryLoggingHost, System.Collections.Generic.IDictionary<string, string> taskIdentityParameters);
bool Initialize(string taskName, System.Collections.Generic.IDictionary<string, string> factoryIdentityParameters, System.Collections.Generic.IDictionary<string, Microsoft.Build.Framework.TaskPropertyInfo> parameterGroup, string taskBody, Microsoft.Build.Framework.IBuildEngine taskFactoryLoggingHost);
}
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
[System.Runtime.InteropServices.GuidAttribute("9049A481-D0E9-414f-8F92-D4F67A0359A6")]
[System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)(1))]
public partial interface ITaskHost
{
}
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
[System.Runtime.InteropServices.GuidAttribute("8661674F-2148-4F71-A92A-49875511C528")]
public partial interface ITaskItem
{
string ItemSpec { get; set; }
int MetadataCount { get; }
System.Collections.ICollection MetadataNames { get; }
System.Collections.IDictionary CloneCustomMetadata();
void CopyMetadataTo(Microsoft.Build.Framework.ITaskItem destinationItem);
string GetMetadata(string metadataName);
void RemoveMetadata(string metadataName);
void SetMetadata(string metadataName, string metadataValue);
}
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
[System.Runtime.InteropServices.GuidAttribute("ac6d5a59-f877-461b-88e3-b2f06fce0cb9")]
public partial interface ITaskItem2 : Microsoft.Build.Framework.ITaskItem
{
string EvaluatedIncludeEscaped { get; set; }
System.Collections.IDictionary CloneCustomMetadataEscaped();
string GetMetadataValueEscaped(string metadataName);
void SetMetadataValueLiteral(string metadataName, string metadataValue);
}
public partial class LazyFormattedBuildEventArgs : Microsoft.Build.Framework.BuildEventArgs
{
protected LazyFormattedBuildEventArgs() { }
public LazyFormattedBuildEventArgs(string message, string helpKeyword, string senderName) { }
public LazyFormattedBuildEventArgs(string message, string helpKeyword, string senderName, System.DateTime eventTimestamp, params object[] messageArgs) { }
public override string Message { get { throw null; } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=true)]
public sealed partial class LoadInSeparateAppDomainAttribute : System.Attribute
{
public LoadInSeparateAppDomainAttribute() { }
}
public partial class LoggerException : System.Exception
{
public LoggerException() { }
protected LoggerException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public LoggerException(string message) { }
public LoggerException(string message, System.Exception innerException) { }
public LoggerException(string message, System.Exception innerException, string errorCode, string helpKeyword) { }
public string ErrorCode { get { throw null; } }
public string HelpKeyword { get { throw null; } }
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
}
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public enum LoggerVerbosity
{
Detailed = 3,
Diagnostic = 4,
Minimal = 1,
Normal = 2,
Quiet = 0,
}
public enum MessageImportance
{
High = 0,
Low = 2,
Normal = 1,
}
public partial class MetaprojectGeneratedEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs
{
public string metaprojectXml;
public MetaprojectGeneratedEventArgs(string metaprojectXml, string metaprojectPath, string message) { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(128), AllowMultiple=false, Inherited=false)]
public sealed partial class OutputAttribute : System.Attribute
{
public OutputAttribute() { }
}
public sealed partial class ProjectEvaluationFinishedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs
{
public ProjectEvaluationFinishedEventArgs() { }
public ProjectEvaluationFinishedEventArgs(string message, params object[] messageArgs) { }
public System.Nullable<Microsoft.Build.Framework.Profiler.ProfilerResult> ProfilerResult { get { throw null; } set { } }
public string ProjectFile { get { throw null; } set { } }
}
public partial class ProjectEvaluationStartedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs
{
public ProjectEvaluationStartedEventArgs() { }
public ProjectEvaluationStartedEventArgs(string message, params object[] messageArgs) { }
public string ProjectFile { get { throw null; } set { } }
}
public partial class ProjectFinishedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs
{
protected ProjectFinishedEventArgs() { }
public ProjectFinishedEventArgs(string message, string helpKeyword, string projectFile, bool succeeded) { }
public ProjectFinishedEventArgs(string message, string helpKeyword, string projectFile, bool succeeded, System.DateTime eventTimestamp) { }
public string ProjectFile { get { throw null; } }
public bool Succeeded { get { throw null; } }
}
public delegate void ProjectFinishedEventHandler(object sender, Microsoft.Build.Framework.ProjectFinishedEventArgs e);
public partial class ProjectImportedEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs
{
public ProjectImportedEventArgs() { }
public ProjectImportedEventArgs(int lineNumber, int columnNumber, string message, params object[] messageArgs) { }
public string ImportedProjectFile { get { throw null; } set { } }
public bool ImportIgnored { get { throw null; } set { } }
public string UnexpandedProject { get { throw null; } set { } }
}
public partial class ProjectStartedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs
{
public const int InvalidProjectId = -1;
protected ProjectStartedEventArgs() { }
public ProjectStartedEventArgs(int projectId, string message, string helpKeyword, string projectFile, string targetNames, System.Collections.IEnumerable properties, System.Collections.IEnumerable items, Microsoft.Build.Framework.BuildEventContext parentBuildEventContext) { }
public ProjectStartedEventArgs(int projectId, string message, string helpKeyword, string projectFile, string targetNames, System.Collections.IEnumerable properties, System.Collections.IEnumerable items, Microsoft.Build.Framework.BuildEventContext parentBuildEventContext, System.Collections.Generic.IDictionary<string, string> globalProperties, string toolsVersion) { }
public ProjectStartedEventArgs(int projectId, string message, string helpKeyword, string projectFile, string targetNames, System.Collections.IEnumerable properties, System.Collections.IEnumerable items, Microsoft.Build.Framework.BuildEventContext parentBuildEventContext, System.DateTime eventTimestamp) { }
public ProjectStartedEventArgs(string message, string helpKeyword, string projectFile, string targetNames, System.Collections.IEnumerable properties, System.Collections.IEnumerable items) { }
public ProjectStartedEventArgs(string message, string helpKeyword, string projectFile, string targetNames, System.Collections.IEnumerable properties, System.Collections.IEnumerable items, System.DateTime eventTimestamp) { }
public System.Collections.Generic.IDictionary<string, string> GlobalProperties { get { throw null; } }
public System.Collections.IEnumerable Items { get { throw null; } }
public Microsoft.Build.Framework.BuildEventContext ParentProjectBuildEventContext { get { throw null; } }
public string ProjectFile { get { throw null; } }
public int ProjectId { get { throw null; } }
public System.Collections.IEnumerable Properties { get { throw null; } }
public string TargetNames { get { throw null; } }
public string ToolsVersion { get { throw null; } }
}
public delegate void ProjectStartedEventHandler(object sender, Microsoft.Build.Framework.ProjectStartedEventArgs e);
public enum RegisteredTaskObjectLifetime
{
AppDomain = 1,
Build = 0,
}
[System.AttributeUsageAttribute((System.AttributeTargets)(128), AllowMultiple=false, Inherited=false)]
public sealed partial class RequiredAttribute : System.Attribute
{
public RequiredAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=false)]
public sealed partial class RequiredRuntimeAttribute : System.Attribute
{
public RequiredRuntimeAttribute(string runtimeVersion) { }
public string RuntimeVersion { get { throw null; } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=false)]
public sealed partial class RunInMTAAttribute : System.Attribute
{
public RunInMTAAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=false)]
public sealed partial class RunInSTAAttribute : System.Attribute
{
public RunInSTAAttribute() { }
}
public abstract partial class SdkLogger
{
protected SdkLogger() { }
public abstract void LogMessage(string message, Microsoft.Build.Framework.MessageImportance messageImportance=(Microsoft.Build.Framework.MessageImportance)(2));
}
public sealed partial class SdkReference : System.IEquatable<Microsoft.Build.Framework.SdkReference>
{
public SdkReference(string name, string version, string minimumVersion) { }
public string MinimumVersion { get { throw null; } }
public string Name { get { throw null; } }
public string Version { get { throw null; } }
public bool Equals(Microsoft.Build.Framework.SdkReference other) { throw null; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string sdk, out Microsoft.Build.Framework.SdkReference sdkReference) { sdkReference = default(Microsoft.Build.Framework.SdkReference); throw null; }
}
public abstract partial class SdkResolver
{
protected SdkResolver() { }
public abstract string Name { get; }
public abstract int Priority { get; }
public abstract Microsoft.Build.Framework.SdkResult Resolve(Microsoft.Build.Framework.SdkReference sdkReference, Microsoft.Build.Framework.SdkResolverContext resolverContext, Microsoft.Build.Framework.SdkResultFactory factory);
}
public abstract partial class SdkResolverContext
{
protected SdkResolverContext() { }
public virtual bool Interactive { get { throw null; } protected set { } }
public virtual Microsoft.Build.Framework.SdkLogger Logger { get { throw null; } protected set { } }
public virtual System.Version MSBuildVersion { get { throw null; } protected set { } }
public virtual string ProjectFilePath { get { throw null; } protected set { } }
public virtual string SolutionFilePath { get { throw null; } protected set { } }
public virtual object State { get { throw null; } set { } }
}
public abstract partial class SdkResult
{
protected SdkResult() { }
public virtual string Path { get { throw null; } protected set { } }
public virtual Microsoft.Build.Framework.SdkReference SdkReference { get { throw null; } protected set { } }
public virtual bool Success { get { throw null; } protected set { } }
public virtual string Version { get { throw null; } protected set { } }
}
public abstract partial class SdkResultFactory
{
protected SdkResultFactory() { }
public abstract Microsoft.Build.Framework.SdkResult IndicateFailure(System.Collections.Generic.IEnumerable<string> errors, System.Collections.Generic.IEnumerable<string> warnings=null);
public abstract Microsoft.Build.Framework.SdkResult IndicateSuccess(string path, string version, System.Collections.Generic.IEnumerable<string> warnings=null);
}
public enum TargetBuiltReason
{
AfterTargets = 3,
BeforeTargets = 1,
DependsOn = 2,
None = 0,
}
public partial class TargetFinishedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs
{
protected TargetFinishedEventArgs() { }
public TargetFinishedEventArgs(string message, string helpKeyword, string targetName, string projectFile, string targetFile, bool succeeded) { }
public TargetFinishedEventArgs(string message, string helpKeyword, string targetName, string projectFile, string targetFile, bool succeeded, System.Collections.IEnumerable targetOutputs) { }
public TargetFinishedEventArgs(string message, string helpKeyword, string targetName, string projectFile, string targetFile, bool succeeded, System.DateTime eventTimestamp, System.Collections.IEnumerable targetOutputs) { }
public string ProjectFile { get { throw null; } }
public bool Succeeded { get { throw null; } }
public string TargetFile { get { throw null; } }
public string TargetName { get { throw null; } }
public System.Collections.IEnumerable TargetOutputs { get { throw null; } set { } }
}
public delegate void TargetFinishedEventHandler(object sender, Microsoft.Build.Framework.TargetFinishedEventArgs e);
public partial class TargetSkippedEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs
{
public TargetSkippedEventArgs() { }
public TargetSkippedEventArgs(string message, params object[] messageArgs) { }
public Microsoft.Build.Framework.TargetBuiltReason BuildReason { get { throw null; } set { } }
public string ParentTarget { get { throw null; } set { } }
public string TargetFile { get { throw null; } set { } }
public string TargetName { get { throw null; } set { } }
}
public partial class TargetStartedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs
{
protected TargetStartedEventArgs() { }
public TargetStartedEventArgs(string message, string helpKeyword, string targetName, string projectFile, string targetFile) { }
public TargetStartedEventArgs(string message, string helpKeyword, string targetName, string projectFile, string targetFile, string parentTarget, Microsoft.Build.Framework.TargetBuiltReason buildReason, System.DateTime eventTimestamp) { }
public TargetStartedEventArgs(string message, string helpKeyword, string targetName, string projectFile, string targetFile, string parentTarget, System.DateTime eventTimestamp) { }
public Microsoft.Build.Framework.TargetBuiltReason BuildReason { get { throw null; } }
public string ParentTarget { get { throw null; } }
public string ProjectFile { get { throw null; } }
public string TargetFile { get { throw null; } }
public string TargetName { get { throw null; } }
}
public delegate void TargetStartedEventHandler(object sender, Microsoft.Build.Framework.TargetStartedEventArgs e);
public partial class TaskCommandLineEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs
{
protected TaskCommandLineEventArgs() { }
public TaskCommandLineEventArgs(string commandLine, string taskName, Microsoft.Build.Framework.MessageImportance importance) { }
public TaskCommandLineEventArgs(string commandLine, string taskName, Microsoft.Build.Framework.MessageImportance importance, System.DateTime eventTimestamp) { }
public string CommandLine { get { throw null; } }
public string TaskName { get { throw null; } }
}
public partial class TaskFinishedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs
{
protected TaskFinishedEventArgs() { }
public TaskFinishedEventArgs(string message, string helpKeyword, string projectFile, string taskFile, string taskName, bool succeeded) { }
public TaskFinishedEventArgs(string message, string helpKeyword, string projectFile, string taskFile, string taskName, bool succeeded, System.DateTime eventTimestamp) { }
public string ProjectFile { get { throw null; } }
public bool Succeeded { get { throw null; } }
public string TaskFile { get { throw null; } }
public string TaskName { get { throw null; } }
}
public delegate void TaskFinishedEventHandler(object sender, Microsoft.Build.Framework.TaskFinishedEventArgs e);
public partial class TaskPropertyInfo
{
public TaskPropertyInfo(string name, System.Type typeOfParameter, bool output, bool required) { }
public string Name { get { throw null; } }
public bool Output { get { throw null; } }
public System.Type PropertyType { get { throw null; } }
public bool Required { get { throw null; } }
}
public partial class TaskStartedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs
{
protected TaskStartedEventArgs() { }
public TaskStartedEventArgs(string message, string helpKeyword, string projectFile, string taskFile, string taskName) { }
public TaskStartedEventArgs(string message, string helpKeyword, string projectFile, string taskFile, string taskName, System.DateTime eventTimestamp) { }
public string ProjectFile { get { throw null; } }
public string TaskFile { get { throw null; } }
public string TaskName { get { throw null; } }
}
public delegate void TaskStartedEventHandler(object sender, Microsoft.Build.Framework.TaskStartedEventArgs e);
public sealed partial class TelemetryEventArgs : Microsoft.Build.Framework.BuildEventArgs
{
public TelemetryEventArgs() { }
public string EventName { get { throw null; } set { } }
public System.Collections.Generic.IDictionary<string, string> Properties { get { throw null; } set { } }
}
public delegate void TelemetryEventHandler(object sender, Microsoft.Build.Framework.TelemetryEventArgs e);
}
namespace Microsoft.Build.Framework.Profiler
{
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct EvaluationLocation
{
public EvaluationLocation(Microsoft.Build.Framework.Profiler.EvaluationPass evaluationPass, string evaluationPassDescription, string file, System.Nullable<int> line, string elementName, string elementDescription, Microsoft.Build.Framework.Profiler.EvaluationLocationKind kind) { throw null;}
public EvaluationLocation(long id, System.Nullable<long> parentId, Microsoft.Build.Framework.Profiler.EvaluationPass evaluationPass, string evaluationPassDescription, string file, System.Nullable<int> line, string elementName, string elementDescription, Microsoft.Build.Framework.Profiler.EvaluationLocationKind kind) { throw null;}
public EvaluationLocation(System.Nullable<long> parentId, Microsoft.Build.Framework.Profiler.EvaluationPass evaluationPass, string evaluationPassDescription, string file, System.Nullable<int> line, string elementName, string elementDescription, Microsoft.Build.Framework.Profiler.EvaluationLocationKind kind) { throw null;}
public string ElementDescription { get { throw null; } }
public string ElementName { get { throw null; } }
public static Microsoft.Build.Framework.Profiler.EvaluationLocation EmptyLocation { get { throw null; } }
public Microsoft.Build.Framework.Profiler.EvaluationPass EvaluationPass { get { throw null; } }
public string EvaluationPassDescription { get { throw null; } }
public string File { get { throw null; } }
public long Id { get { throw null; } }
public bool IsEvaluationPass { get { throw null; } }
public Microsoft.Build.Framework.Profiler.EvaluationLocationKind Kind { get { throw null; } }
public System.Nullable<int> Line { get { throw null; } }
public System.Nullable<long> ParentId { get { throw null; } }
public static Microsoft.Build.Framework.Profiler.EvaluationLocation CreateLocationForAggregatedGlob() { throw null; }
public static Microsoft.Build.Framework.Profiler.EvaluationLocation CreateLocationForCondition(System.Nullable<long> parentId, Microsoft.Build.Framework.Profiler.EvaluationPass evaluationPass, string evaluationDescription, string file, System.Nullable<int> line, string condition) { throw null; }
public static Microsoft.Build.Framework.Profiler.EvaluationLocation CreateLocationForGlob(System.Nullable<long> parentId, Microsoft.Build.Framework.Profiler.EvaluationPass evaluationPass, string evaluationDescription, string file, System.Nullable<int> line, string globDescription) { throw null; }
public static Microsoft.Build.Framework.Profiler.EvaluationLocation CreateLocationForProject(System.Nullable<long> parentId, Microsoft.Build.Framework.Profiler.EvaluationPass evaluationPass, string evaluationDescription, string file, System.Nullable<int> line, Microsoft.Build.Framework.IProjectElement element) { throw null; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public override string ToString() { throw null; }
public Microsoft.Build.Framework.Profiler.EvaluationLocation WithEvaluationPass(Microsoft.Build.Framework.Profiler.EvaluationPass evaluationPass, string passDescription=null) { throw null; }
public Microsoft.Build.Framework.Profiler.EvaluationLocation WithFile(string file) { throw null; }
public Microsoft.Build.Framework.Profiler.EvaluationLocation WithFileLineAndCondition(string file, System.Nullable<int> line, string condition) { throw null; }
public Microsoft.Build.Framework.Profiler.EvaluationLocation WithFileLineAndElement(string file, System.Nullable<int> line, Microsoft.Build.Framework.IProjectElement element) { throw null; }
public Microsoft.Build.Framework.Profiler.EvaluationLocation WithGlob(string globDescription) { throw null; }
public Microsoft.Build.Framework.Profiler.EvaluationLocation WithParentId(System.Nullable<long> parentId) { throw null; }
}
public enum EvaluationLocationKind : byte
{
Condition = (byte)1,
Element = (byte)0,
Glob = (byte)2,
}
public enum EvaluationPass : byte
{
InitialProperties = (byte)2,
ItemDefinitionGroups = (byte)4,
Items = (byte)5,
LazyItems = (byte)6,
Properties = (byte)3,
Targets = (byte)8,
TotalEvaluation = (byte)0,
TotalGlobbing = (byte)1,
UsingTasks = (byte)7,
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct ProfiledLocation
{
public ProfiledLocation(System.TimeSpan inclusiveTime, System.TimeSpan exclusiveTime, int numberOfHits) { throw null;}
public System.TimeSpan ExclusiveTime { get { throw null; } }
public System.TimeSpan InclusiveTime { get { throw null; } }
public int NumberOfHits { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public override string ToString() { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct ProfilerResult
{
public ProfilerResult(System.Collections.Generic.IDictionary<Microsoft.Build.Framework.Profiler.EvaluationLocation, Microsoft.Build.Framework.Profiler.ProfiledLocation> profiledLocations) { throw null;}
public System.Collections.Generic.IReadOnlyDictionary<Microsoft.Build.Framework.Profiler.EvaluationLocation, Microsoft.Build.Framework.Profiler.ProfiledLocation> ProfiledLocations { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.CompilerServices;
namespace System.Numerics
{
// This file contains the definitions for all of the JIT intrinsic methods and properties that are recognized by the current x64 JIT compiler.
// The implementation defined here is used in any circumstance where the JIT fails to recognize these members as intrinsic.
// The JIT recognizes these methods and properties by name and signature: if either is changed, the JIT will no longer recognize the member.
// Some methods declared here are not strictly intrinsic, but delegate to an intrinsic method. For example, only one overload of CopyTo()
// is actually recognized by the JIT, but both are here for simplicity.
public partial struct Vector3
{
/// <summary>
/// The X component of the vector.
/// </summary>
public Single X;
/// <summary>
/// The Y component of the vector.
/// </summary>
public Single Y;
/// <summary>
/// The Z component of the vector.
/// </summary>
public Single Z;
#region Constructors
/// <summary>
/// Constructs a vector whose elements are all the single specified value.
/// </summary>
/// <param name="value">The element to fill the vector with.</param>
[JitIntrinsic]
public Vector3(Single value) : this(value, value, value) { }
/// <summary>
/// Constructs a Vector3 from the given Vector2 and a third value.
/// </summary>
/// <param name="value">The Vector to extract X and Y components from.</param>
/// <param name="z">The Z component.</param>
public Vector3(Vector2 value, float z) : this(value.X, value.Y, z) { }
/// <summary>
/// Constructs a vector with the given individual elements.
/// </summary>
/// <param name="x">The X component.</param>
/// <param name="y">The Y component.</param>
/// <param name="z">The Z component.</param>
[JitIntrinsic]
public Vector3(Single x, Single y, Single z)
{
X = x;
Y = y;
Z = z;
}
#endregion Constructors
#region Public Instance Methods
/// <summary>
/// Copies the contents of the vector into the given array.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CopyTo(Single[] array)
{
CopyTo(array, 0);
}
/// <summary>
/// Copies the contents of the vector into the given array, starting from index.
/// </summary>
/// <exception cref="ArgumentNullException">If array is null.</exception>
/// <exception cref="RankException">If array is multidimensional.</exception>
/// <exception cref="ArgumentOutOfRangeException">If index is greater than end of the array or index is less than zero.</exception>
/// <exception cref="ArgumentException">If number of elements in source vector is greater than those available in destination array.</exception>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CopyTo(Single[] array, int index)
{
if (array == null)
throw new ArgumentNullException("values");
if (index < 0 || index >= array.Length)
throw new ArgumentOutOfRangeException(SR.GetString("Arg_ArgumentOutOfRangeException", index));
if ((array.Length - index) < 3)
throw new ArgumentException(SR.GetString("Arg_ElementsInSourceIsGreaterThanDestination", index));
array[index] = X;
array[index + 1] = Y;
array[index + 2] = Z;
}
/// <summary>
/// Returns a boolean indicating whether the given Vector3 is equal to this Vector3 instance.
/// </summary>
/// <param name="other">The Vector3 to compare this instance to.</param>
/// <returns>True if the other Vector3 is equal to this instance; False otherwise.</returns>
[JitIntrinsic]
public bool Equals(Vector3 other)
{
return X == other.X &&
Y == other.Y &&
Z == other.Z;
}
#endregion Public Instance Methods
#region Public Static Methods
/// <summary>
/// Returns the dot product of two vectors.
/// </summary>
/// <param name="vector1">The first vector.</param>
/// <param name="vector2">The second vector.</param>
/// <returns>The dot product.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Dot(Vector3 vector1, Vector3 vector2)
{
return vector1.X * vector2.X +
vector1.Y * vector2.Y +
vector1.Z * vector2.Z;
}
/// <summary>
/// Returns a vector whose elements are the minimum of each of the pairs of elements in the two source vectors.
/// </summary>
/// <param name="value1">The first source vector.</param>
/// <param name="value2">The second source vector.</param>
/// <returns>The minimized vector.</returns>
[JitIntrinsic]
public static Vector3 Min(Vector3 value1, Vector3 value2)
{
return new Vector3(
(value1.X < value2.X) ? value1.X : value2.X,
(value1.Y < value2.Y) ? value1.Y : value2.Y,
(value1.Z < value2.Z) ? value1.Z : value2.Z);
}
/// <summary>
/// Returns a vector whose elements are the maximum of each of the pairs of elements in the two source vectors.
/// </summary>
/// <param name="value1">The first source vector.</param>
/// <param name="value2">The second source vector.</param>
/// <returns>The maximized vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Max(Vector3 value1, Vector3 value2)
{
return new Vector3(
(value1.X > value2.X) ? value1.X : value2.X,
(value1.Y > value2.Y) ? value1.Y : value2.Y,
(value1.Z > value2.Z) ? value1.Z : value2.Z);
}
/// <summary>
/// Returns a vector whose elements are the absolute values of each of the source vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The absolute value vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Abs(Vector3 value)
{
return new Vector3(Math.Abs(value.X), Math.Abs(value.Y), Math.Abs(value.Z));
}
/// <summary>
/// Returns a vector whose elements are the square root of each of hte source vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The square root vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 SquareRoot(Vector3 value)
{
return new Vector3((Single)Math.Sqrt(value.X), (Single)Math.Sqrt(value.Y), (Single)Math.Sqrt(value.Z));
}
#endregion Public Static Methods
#region Public Static Operators
/// <summary>
/// Adds two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The summed vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator +(Vector3 left, Vector3 right)
{
return new Vector3(left.X + right.X, left.Y + right.Y, left.Z + right.Z);
}
/// <summary>
/// Subtracts the second vector from the first.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The difference vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator -(Vector3 left, Vector3 right)
{
return new Vector3(left.X - right.X, left.Y - right.Y, left.Z - right.Z);
}
/// <summary>
/// Multiplies two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The product vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator *(Vector3 left, Vector3 right)
{
return new Vector3(left.X * right.X, left.Y * right.Y, left.Z * right.Z);
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="right">The scalar value.</param>
/// <returns>The scaled vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator *(Vector3 left, Single right)
{
return left * new Vector3(right);
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The scalar value.</param>
/// <param name="right">The source vector.</param>
/// <returns>The scaled vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator *(Single left, Vector3 right)
{
return new Vector3(left) * right;
}
/// <summary>
/// Divides the first vector by the second.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The vector resulting from the division.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator /(Vector3 left, Vector3 right)
{
return new Vector3(left.X / right.X, left.Y / right.Y, left.Z / right.Z);
}
/// <summary>
/// Divides the vector by the given scalar.
/// </summary>
/// <param name="value1">The source vector.</param>
/// <param name="value2">The scalar value.</param>
/// <returns>The result of the division.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator /(Vector3 value1, float value2)
{
float invDiv = 1.0f / value2;
return new Vector3(
value1.X * invDiv,
value1.Y * invDiv,
value1.Z * invDiv);
}
/// <summary>
/// Negates a given vector.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The negated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator -(Vector3 value)
{
return Zero - value;
}
/// <summary>
/// Returns a boolean indicating whether the two given vectors are equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if the vectors are equal; False otherwise.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Vector3 left, Vector3 right)
{
return (left.X == right.X &&
left.Y == right.Y &&
left.Z == right.Z);
}
/// <summary>
/// Returns a boolean indicating whether the two given vectors are not equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if the vectors are not equal; False if they are equal.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Vector3 left, Vector3 right)
{
return (left.X != right.X ||
left.Y != right.Y ||
left.Z != right.Z);
}
#endregion Public Static Operators
}
}
| |
namespace Zayko.Dialogs.UnhandledExceptionDlg
{
partial class UnhandledExDlgForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if(disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.panelTop = new System.Windows.Forms.Panel();
this.labelTitle = new System.Windows.Forms.Label();
this.panelDevider = new System.Windows.Forms.Panel();
this.labelExceptionDate = new System.Windows.Forms.Label();
this.labelCaption = new System.Windows.Forms.Label();
this.labelDescription = new System.Windows.Forms.Label();
this.buttonNotSend = new System.Windows.Forms.Button();
this.buttonSend = new System.Windows.Forms.Button();
this.labelLinkTitle = new System.Windows.Forms.Label();
this.linkLabelData = new System.Windows.Forms.LinkLabel();
this.checkBoxRestart = new System.Windows.Forms.CheckBox();
this.panelTop.SuspendLayout();
this.SuspendLayout();
//
// panelTop
//
this.panelTop.BackColor = System.Drawing.SystemColors.Window;
this.panelTop.Controls.Add(this.labelTitle);
this.panelTop.Dock = System.Windows.Forms.DockStyle.Top;
this.panelTop.Location = new System.Drawing.Point(0, 0);
this.panelTop.Name = "panelTop";
this.panelTop.Size = new System.Drawing.Size(412, 63);
this.panelTop.TabIndex = 0;
//
// labelTitle
//
this.labelTitle.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelTitle.Location = new System.Drawing.Point(13, 13);
this.labelTitle.Name = "labelTitle";
this.labelTitle.Size = new System.Drawing.Size(387, 44);
this.labelTitle.TabIndex = 0;
this.labelTitle.Text = "\"{0}\" encountered a problem and must close";
//
// panelDevider
//
this.panelDevider.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panelDevider.Dock = System.Windows.Forms.DockStyle.Top;
this.panelDevider.Location = new System.Drawing.Point(0, 63);
this.panelDevider.Name = "panelDevider";
this.panelDevider.Size = new System.Drawing.Size(412, 2);
this.panelDevider.TabIndex = 1;
//
// labelExceptionDate
//
this.labelExceptionDate.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelExceptionDate.Location = new System.Drawing.Point(12, 68);
this.labelExceptionDate.Name = "labelExceptionDate";
this.labelExceptionDate.Size = new System.Drawing.Size(384, 23);
this.labelExceptionDate.TabIndex = 2;
this.labelExceptionDate.Text = "This error occured on {0}";
//
// labelCaption
//
this.labelCaption.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelCaption.Location = new System.Drawing.Point(13, 91);
this.labelCaption.Name = "labelCaption";
this.labelCaption.Size = new System.Drawing.Size(387, 23);
this.labelCaption.TabIndex = 3;
this.labelCaption.Text = "Please tell us about this problem";
//
// labelDescription
//
this.labelDescription.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.labelDescription.Location = new System.Drawing.Point(12, 114);
this.labelDescription.Name = "labelDescription";
this.labelDescription.Size = new System.Drawing.Size(387, 29);
this.labelDescription.TabIndex = 4;
this.labelDescription.Text = "We have created an error report that you can send us. We will treat this report a" +
"s confidential and anonymous.";
//
// buttonNotSend
//
this.buttonNotSend.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonNotSend.Location = new System.Drawing.Point(325, 198);
this.buttonNotSend.Name = "buttonNotSend";
this.buttonNotSend.Size = new System.Drawing.Size(75, 23);
this.buttonNotSend.TabIndex = 6;
this.buttonNotSend.Text = "&Don\'t Send";
this.buttonNotSend.UseVisualStyleBackColor = true;
//
// buttonSend
//
this.buttonSend.DialogResult = System.Windows.Forms.DialogResult.Yes;
this.buttonSend.Location = new System.Drawing.Point(212, 198);
this.buttonSend.Name = "buttonSend";
this.buttonSend.Size = new System.Drawing.Size(107, 23);
this.buttonSend.TabIndex = 7;
this.buttonSend.Text = "&Send Error Report";
this.buttonSend.UseVisualStyleBackColor = true;
//
// labelLinkTitle
//
this.labelLinkTitle.AutoSize = true;
this.labelLinkTitle.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.labelLinkTitle.Location = new System.Drawing.Point(13, 143);
this.labelLinkTitle.Name = "labelLinkTitle";
this.labelLinkTitle.Size = new System.Drawing.Size(243, 13);
this.labelLinkTitle.TabIndex = 7;
this.labelLinkTitle.Text = "To see what data this error report contains, please";
//
// linkLabelData
//
this.linkLabelData.AutoSize = true;
this.linkLabelData.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.linkLabelData.Location = new System.Drawing.Point(262, 143);
this.linkLabelData.Name = "linkLabelData";
this.linkLabelData.Size = new System.Drawing.Size(56, 13);
this.linkLabelData.TabIndex = 8;
this.linkLabelData.TabStop = true;
this.linkLabelData.Text = "click here.";
//
// checkBoxRestart
//
this.checkBoxRestart.AutoSize = true;
this.checkBoxRestart.Checked = true;
this.checkBoxRestart.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBoxRestart.Location = new System.Drawing.Point(16, 168);
this.checkBoxRestart.Name = "checkBoxRestart";
this.checkBoxRestart.Size = new System.Drawing.Size(87, 17);
this.checkBoxRestart.TabIndex = 5;
this.checkBoxRestart.Text = "&Restart \"{0}\"";
this.checkBoxRestart.UseVisualStyleBackColor = true;
//
// UnhandledExDlgForm
//
this.AcceptButton = this.buttonNotSend;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.buttonNotSend;
this.ClientSize = new System.Drawing.Size(412, 233);
this.ControlBox = false;
this.Controls.Add(this.checkBoxRestart);
this.Controls.Add(this.linkLabelData);
this.Controls.Add(this.labelLinkTitle);
this.Controls.Add(this.buttonSend);
this.Controls.Add(this.buttonNotSend);
this.Controls.Add(this.labelDescription);
this.Controls.Add(this.labelCaption);
this.Controls.Add(this.labelExceptionDate);
this.Controls.Add(this.panelDevider);
this.Controls.Add(this.panelTop);
this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "UnhandledExDlgForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "UnhandledExDlgForm";
this.TopMost = true;
this.Load += new System.EventHandler(this.UnhandledExDlgForm_Load);
this.panelTop.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Panel panelTop;
private System.Windows.Forms.Panel panelDevider;
private System.Windows.Forms.Label labelExceptionDate;
private System.Windows.Forms.Label labelCaption;
private System.Windows.Forms.Label labelDescription;
private System.Windows.Forms.Button buttonNotSend;
internal System.Windows.Forms.Label labelTitle;
internal System.Windows.Forms.CheckBox checkBoxRestart;
internal System.Windows.Forms.Label labelLinkTitle;
internal System.Windows.Forms.LinkLabel linkLabelData;
internal System.Windows.Forms.Button buttonSend;
}
}
| |
// Copyright (C) 2009-2018 Luca Piccioni
//
// 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.
// Macro utility for logging platform-relared function calls
#undef PLATFORM_LOG_ENABLED
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
namespace Khronos
{
/// <summary>
/// Interface implemented by those classes which are able to get function pointers from dynamically loaded libraries.
/// </summary>
interface IGetProcAddressOS
{
/// <summary>
/// Add a path of a directory as additional path for searching libraries.
/// </summary>
/// <param name="libraryDirPath">
/// A <see cref="String"/> that specify the absolute path of the directory where the libraries are loaded using
/// <see cref="GetProcAddress(string, string)"/> method.
/// </param>
void AddLibraryDirectory(string libraryDirPath);
/// <summary>
/// Get a function pointer from a library, specified by path.
/// </summary>
/// <param name="library">
/// A <see cref="String"/> that specifies the path of the library defining the function.
/// </param>
/// <param name="function">
/// A <see cref="String"/> that specifies the function name.
/// </param>
/// <returns>
/// It returns an <see cref="IntPtr"/> that specifies the address of the function <paramref name="function"/>.
/// </returns>
IntPtr GetProcAddress(string library, string function);
}
/// <summary>
/// Abtract an interface for loading procedures from dynamically loaded libraries.
/// </summary>
internal static class GetProcAddressOS
{
#region Constructors
/// <summary>
/// Static constructor.
/// </summary>
static GetProcAddressOS()
{
#if !NETSTANDARD1_1
string envOsLoader = Environment.GetEnvironmentVariable("OPENGL_NET_OSLOADER");
#else
string envOsLoader = null;
#endif
switch (envOsLoader) {
case "EGL":
// Force using eglGetProcAddress
_GetProcAddressOS = GetProcAddressEGL.Instance;
// Use EGL backend as default
// Egl.IsRequired = true; -.-
break;
default:
_GetProcAddressOS = CreateOS();
break;
}
}
/// <summary>
/// Most appropriate <see cref="IGetProcAddressOS"/> for the current platform.
/// </summary>
private static readonly IGetProcAddressOS _GetProcAddressOS;
/// <summary>
/// Create an <see cref="IGetProcAddressOS"/> for the hosting platform.
/// </summary>
/// <returns>
/// It returns the most appropriate <see cref="IGetProcAddressOS"/> for the current platform.
/// </returns>
private static IGetProcAddressOS CreateOS()
{
switch (Platform.CurrentPlatformId) {
case Platform.Id.WindowsNT:
return new GetProcAddressWindows();
case Platform.Id.Linux:
return new GetProcAddressLinux();
case Platform.Id.MacOS:
return new GetProcAddressOSX();
case Platform.Id.Android:
return new GetProcAddressEGL();
default:
throw new NotSupportedException($"platform {Platform.CurrentPlatformId} not supported");
}
}
#endregion
#region Abstract Interface
/// <summary>
/// Add a path of a directory as additional path for searching libraries.
/// </summary>
/// <param name="libraryDirPath">
/// A <see cref="String"/> that specify the absolute path of the directory where the libraries are loaded using
/// <see cref="GetProcAddress(string, string)"/> method.
/// </param>
public static void AddLibraryDirectory(string libraryDirPath)
{
_GetProcAddressOS.AddLibraryDirectory(libraryDirPath);
}
/// <summary>
/// Get a function pointer from a library, specified by path.
/// </summary>
/// <param name="library">
/// A <see cref="String"/> that specifies the path of the library defining the function.
/// </param>
/// <param name="function">
/// A <see cref="String"/> that specifies the function name.
/// </param>
/// <returns>
/// It returns an <see cref="IntPtr"/> that specifies the address of the function <paramref name="function"/>.
/// </returns>
public static IntPtr GetProcAddress(string library, string function)
{
return _GetProcAddressOS.GetProcAddress(library, function);
}
#endregion
}
/// <summary>
/// Class able to get function pointers on Windows platform.
/// </summary>
internal class GetProcAddressWindows : IGetProcAddressOS
{
#region Singleton
/// <summary>
/// The <see cref="GetGLProcAddressEGL"/> singleton instance.
/// </summary>
public static readonly GetProcAddressWindows Instance = new GetProcAddressWindows();
#endregion
#region Windows Platform Imports
static class UnsafeNativeMethods
{
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("Kernel32.dll", EntryPoint = "GetProcAddress", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
public static extern IntPtr Win32GetProcAddress(IntPtr hModule, string lpProcName);
}
#endregion
#region IGetProcAddress Implementation
/// <summary>
/// Add a path of a directory as additional path for searching libraries.
/// </summary>
/// <param name="libraryDirPath">
/// A <see cref="String"/> that specify the absolute path of the directory where the libraries are loaded using
/// <see cref="GetProcAddress(string, string)"/> method.
/// </param>
public void AddLibraryDirectory(string libraryDirPath)
{
#if NETSTANDARD1_1 || NETSTANDARD1_4 || NETCOREAPP1_1
// Note: no support for library directories for the following targets:
// - .NET Standard 1.4 and below
// - .NET Core App 1.1
#else
string path = Environment.GetEnvironmentVariable("PATH");
Environment.SetEnvironmentVariable("PATH", $"{path};{libraryDirPath}", EnvironmentVariableTarget.Process);
#endif
}
/// <summary>
/// Get a function pointer from a library, specified by path.
/// </summary>
/// <param name="library">
/// A <see cref="String"/> that specifies the path of the library defining the function.
/// </param>
/// <param name="function">
/// A <see cref="String"/> that specifies the function name.
/// </param>
/// <returns>
/// It returns an <see cref="IntPtr"/> that specifies the address of the function <paramref name="function"/>.
/// </returns>
public IntPtr GetProcAddress(string library, string function)
{
IntPtr handle = GetLibraryHandle(library);
return GetProcAddress(handle, function);
}
/// <summary>
/// Get a function pointer from a library, specified by handle.
/// </summary>
/// <param name="library">
/// A <see cref="IntPtr"/> which represents an opaque handle to the library containing the function.
/// </param>
/// <param name="function">
/// A <see cref="String"/> that specifies the function name.
/// </param>
/// <returns>
/// It returns an <see cref="IntPtr"/> that specifies the address of the function <paramref name="function"/>.
/// </returns>
private IntPtr GetProcAddress(IntPtr library, string function)
{
if (library == IntPtr.Zero)
throw new ArgumentNullException(nameof(library));
if (function == null)
throw new ArgumentNullException(nameof(function));
IntPtr procAddress = UnsafeNativeMethods.Win32GetProcAddress(library, function);
#if PLATFORM_LOG_ENABLED
KhronosApi.LogFunction("GetProcAddress(0x{0}, {1}) = 0x{2}", library.ToString("X8"), function, procAddress.ToString("X8"));
#endif
return procAddress;
}
/// <summary>
/// Get the handle relative to the specified library.
/// </summary>
/// <param name="libraryPath">
/// A <see cref="String"/> that specify the path of the library to load.
/// </param>
/// <returns>
/// It returns a <see cref="IntPtr"/> that represents the handle of the library loaded from <paramref name="libraryPath"/>.
/// </returns>
public IntPtr GetLibraryHandle(string libraryPath)
{
IntPtr libraryHandle;
if (_LibraryHandles.TryGetValue(libraryPath, out libraryHandle) == false) {
// Load library
libraryHandle = UnsafeNativeMethods.LoadLibrary(libraryPath);
#if PLATFORM_LOG_ENABLED
KhronosApi.LogFunction("LoadLibrary({0}) = 0x{1}", libraryPath, libraryHandle.ToString("X8"));
#endif
_LibraryHandles.Add(libraryPath, libraryHandle);
}
if (libraryHandle == IntPtr.Zero)
throw new InvalidOperationException($"unable to load library at {libraryPath}", new Win32Exception(Marshal.GetLastWin32Error()));
return libraryHandle;
}
/// <summary>
/// Currently loaded libraries.
/// </summary>
private static readonly Dictionary<string, IntPtr> _LibraryHandles = new Dictionary<string,IntPtr>();
#endregion
}
/// <summary>
/// Class able to get function pointers on X11 platform.
/// </summary>
internal class GetProcAddressLinux : IGetProcAddressOS
{
#region Singleton
/// <summary>
/// The <see cref="GetGLProcAddressEGL"/> singleton instance.
/// </summary>
internal static readonly GetProcAddressLinux Instance = new GetProcAddressLinux();
#endregion
#region Linux Platform Imports
[SuppressMessage("ReSharper", "InconsistentNaming")]
static class UnsafeNativeMethods
{
public const int RTLD_LAZY = 1;
public const int RTLD_NOW = 2;
#if NETCORE
[DllImport("dl")]
public static extern IntPtr dlopen(string filename, int flags);
[DllImport("dl")]
public static extern IntPtr dlsym(IntPtr handle, string symbol);
#else
[DllImport("dl")]
public static extern IntPtr dlopen([MarshalAs(UnmanagedType.LPTStr)] string filename, int flags);
[DllImport("dl")]
public static extern IntPtr dlsym(IntPtr handle, [MarshalAs(UnmanagedType.LPTStr)] string symbol);
#endif
[DllImport("dl")]
public static extern string dlerror();
}
#endregion
#region IGetProcAdress Implementation
/// <summary>
/// Add a path of a directory as additional path for searching libraries.
/// </summary>
/// <param name="libraryDirPath">
/// A <see cref="String"/> that specify the absolute path of the directory where the libraries are loaded using
/// <see cref="GetProcAddress(string, string)"/> method.
/// </param>
public void AddLibraryDirectory(string libraryDirPath)
{
}
/// <summary>
/// Get a function pointer from a library, specified by path.
/// </summary>
/// <param name="library">
/// A <see cref="String"/> that specifies the path of the library defining the function.
/// </param>
/// <param name="function">
/// A <see cref="String"/> that specifies the function name.
/// </param>
/// <returns>
/// It returns an <see cref="IntPtr"/> that specifies the address of the function <paramref name="function"/>.
/// </returns>
public IntPtr GetProcAddress(string library, string function)
{
IntPtr handle = GetLibraryHandle(library);
return GetProcAddress(handle, function);
}
/// <summary>
/// Get a function pointer from a library, specified by handle.
/// </summary>
/// <param name="library">
/// A <see cref="IntPtr"/> which represents an opaque handle to the library containing the function.
/// </param>
/// <param name="function">
/// A <see cref="String"/> that specifies the function name.
/// </param>
/// <returns>
/// It returns an <see cref="IntPtr"/> that specifies the address of the function <paramref name="function"/>.
/// </returns>
private IntPtr GetProcAddress(IntPtr library, string function)
{
if (library == IntPtr.Zero)
throw new ArgumentNullException(nameof(library));
if (function == null)
throw new ArgumentNullException(nameof(function));
return UnsafeNativeMethods.dlsym(library, function);
}
internal static IntPtr GetLibraryHandle(string libraryPath)
{
return GetLibraryHandle(libraryPath, true);
}
internal static IntPtr GetLibraryHandle(string libraryPath, bool throws)
{
IntPtr libraryHandle;
if (_LibraryHandles.TryGetValue(libraryPath, out libraryHandle) == false) {
if ((libraryHandle = UnsafeNativeMethods.dlopen(libraryPath, UnsafeNativeMethods.RTLD_LAZY)) == IntPtr.Zero) {
if (throws)
throw new InvalidOperationException($"unable to load library at {libraryPath}", new InvalidOperationException(UnsafeNativeMethods.dlerror()));
}
_LibraryHandles.Add(libraryPath, libraryHandle);
}
return libraryHandle;
}
/// <summary>
/// Currently loaded libraries.
/// </summary>
private static readonly Dictionary<string, IntPtr> _LibraryHandles = new Dictionary<string,IntPtr>();
#endregion
}
/// <summary>
/// Class able to get function pointers on OSX platform.
/// </summary>
internal class GetProcAddressOSX : IGetProcAddressOS
{
#region Singleton
/// <summary>
/// The <see cref="GetProcAddressOSX"/> singleton instance.
/// </summary>
public static readonly GetProcAddressOSX Instance = new GetProcAddressOSX();
#endregion
#region OSX Platform Imports
static class UnsafeNativeMethods
{
[DllImport(Library, EntryPoint = "NSIsSymbolNameDefined")]
public static extern bool NSIsSymbolNameDefined(string s);
[DllImport(Library, EntryPoint = "NSLookupAndBindSymbol")]
public static extern IntPtr NSLookupAndBindSymbol(string s);
[DllImport(Library, EntryPoint = "NSAddressOfSymbol")]
public static extern IntPtr NSAddressOfSymbol(IntPtr symbol);
}
#endregion
#region IGetProcAddress Implementation
/// <summary>
/// Add a path of a directory as additional path for searching libraries.
/// </summary>
/// <param name="libraryDirPath">
/// A <see cref="String"/> that specify the absolute path of the directory where the libraries are loaded using
/// <see cref="GetProcAddress(string, string)"/> method.
/// </param>
public void AddLibraryDirectory(string libraryDirPath)
{
}
/// <summary>
/// Get a function pointer from a library, specified by path.
/// </summary>
/// <param name="library">
/// A <see cref="String"/> that specifies the path of the library defining the function.
/// </param>
/// <param name="function">
/// A <see cref="String"/> that specifies the function name.
/// </param>
/// <returns>
/// It returns an <see cref="IntPtr"/> that specifies the address of the function <paramref name="function"/>.
/// </returns>
public IntPtr GetProcAddress(string library, string function)
{
return GetProcAddressCore(function);
}
/// <summary>
/// Get a function pointer from the OpenGL driver.
/// </summary>
/// <param name="function">
/// A <see cref="String"/> that specifies the function name.
/// </param>
/// <returns>
/// It returns an <see cref="IntPtr"/> that specifies the address of the function <paramref name="function"/>.
/// </returns>
public IntPtr GetProcAddressCore(string function)
{
string fname = "_" + function;
if (!UnsafeNativeMethods.NSIsSymbolNameDefined(fname))
return IntPtr.Zero;
IntPtr symbol = UnsafeNativeMethods.NSLookupAndBindSymbol(fname);
if (symbol != IntPtr.Zero)
symbol = UnsafeNativeMethods.NSAddressOfSymbol(symbol);
return symbol;
}
/// <summary>
/// The OpenGL library on OSX platform.
/// </summary>
private const string Library = "libdl.dylib";
#endregion
#region IGetGLProcAddress Implementation
/// <summary>
/// Get a function pointer from the OpenGL driver.
/// </summary>
/// <param name="function">
/// A <see cref="String"/> that specifies the function name.
/// </param>
/// <returns>
/// It returns an <see cref="IntPtr"/> that specifies the address of the function <paramref name="function"/>. If not
/// defined, it returns <see cref="IntPtr.Zero"/>.
/// </returns>
public IntPtr GetProcAddress(string function)
{
return GetProcAddressCore(function);
}
#endregion
}
/// <summary>
/// Class able to get function pointers on different platforms supporting EGL.
/// </summary>
internal class GetProcAddressEGL : IGetProcAddressOS
{
#region Singleton
/// <summary>
/// The <see cref="GetProcAddressEGL"/> singleton instance.
/// </summary>
public static readonly GetProcAddressEGL Instance = new GetProcAddressEGL();
#endregion
#region IGetProcAddress Implementation
/// <summary>
/// Add a path of a directory as additional path for searching libraries.
/// </summary>
/// <param name="libraryDirPath">
/// A <see cref="String"/> that specify the absolute path of the directory where the libraries are loaded using
/// <see cref="GetProcAddress(string, string)"/> method.
/// </param>
public void AddLibraryDirectory(string libraryDirPath)
{
}
/// <summary>
/// Get a function pointer from a library, specified by path.
/// </summary>
/// <param name="library">
/// A <see cref="String"/> that specifies the path of the library defining the function.
/// </param>
/// <param name="function">
/// A <see cref="String"/> that specifies the function name.
/// </param>
/// <returns>
/// It returns an <see cref="IntPtr"/> that specifies the address of the function <paramref name="function"/>.
/// </returns>
public IntPtr GetProcAddress(string library, string function)
{
return GetProcAddressCore(function);
}
/// <summary>
/// Static import for eglGetProcAddress.
/// </summary>
/// <param name="funcname"></param>
/// <returns></returns>
[DllImport("libEGL.dll", EntryPoint = "eglGetProcAddress")]
public static extern IntPtr GetProcAddressCore(string funcname);
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DataRelation.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
// <owner current="false" primary="false">[....]</owner>
//------------------------------------------------------------------------------
/*****************************************************************************************************
Rules for Multiple Nested Parent, enforce following constraints
1) At all times, only 1(ONE) FK can be NON-Null in a row.
2) NULL FK values are not associated with PARENT(x), even if if PK is NULL in Parent
3) Enforce <rule 1> when
a) Any FK value is changed
b) A relation created that result in Multiple Nested Child
WriteXml
1) WriteXml will throw if <rule 1> is violated
2) if NON-Null FK has parentRow (boolean check) print as Nested, else it will get written as normal row
additional notes:
We decided to enforce the rule 1 just if Xml being persisted
******************************************************************************************************/
namespace System.Data {
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Data.Common;
using System.Collections.Generic;
/// <devdoc>
/// <para>
/// Represents a parent/child relationship between two tables.
/// </para>
/// </devdoc>
[
DefaultProperty("RelationName"),
Editor("Microsoft.VSDesigner.Data.Design.DataRelationEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing),
TypeConverter(typeof(RelationshipConverter)),
]
public class DataRelation {
// properties
private DataSet dataSet = null;
internal PropertyCollection extendedProperties = null;
internal string relationName = "";
// events
private PropertyChangedEventHandler onPropertyChangingDelegate = null;
// state
private DataKey childKey;
private DataKey parentKey;
private UniqueConstraint parentKeyConstraint = null;
private ForeignKeyConstraint childKeyConstraint = null;
// Design time serialization
internal string[] parentColumnNames = null;
internal string[] childColumnNames = null;
internal string parentTableName = null;
internal string childTableName = null;
internal string parentTableNamespace= null;
internal string childTableNamespace = null;
/// <devdoc>
/// this stores whether the child element appears beneath the parent in the XML persised files.
/// </devdoc>
internal bool nested = false;
/// <devdoc>
/// this stores whether the the relationship should make sure that KeyConstraints and ForeignKeyConstraints
/// exist when added to the ConstraintsCollections of the table.
/// </devdoc>
internal bool createConstraints;
private bool _checkMultipleNested = true;
private static int _objectTypeCount; // Bid counter
private readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Data.DataRelation'/> class using the specified name,
/// parent, and child columns.
/// </para>
/// </devdoc>
public DataRelation(string relationName, DataColumn parentColumn, DataColumn childColumn)
: this(relationName, parentColumn, childColumn, true) {
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Data.DataRelation'/> class using the specified name, parent, and child columns, and
/// value to create constraints.
/// </para>
/// </devdoc>
public DataRelation(string relationName, DataColumn parentColumn, DataColumn childColumn, bool createConstraints) {
Bid.Trace("<ds.DataRelation.DataRelation|API> %d#, relationName='%ls', parentColumn=%d, childColumn=%d, createConstraints=%d{bool}\n",
ObjectID, relationName, (parentColumn != null) ? parentColumn.ObjectID : 0, (childColumn != null) ? childColumn.ObjectID : 0,
createConstraints);
DataColumn[] parentColumns = new DataColumn[1];
parentColumns[0] = parentColumn;
DataColumn[] childColumns = new DataColumn[1];
childColumns[0] = childColumn;
Create(relationName, parentColumns, childColumns, createConstraints);
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Data.DataRelation'/> class using the specified name
/// and matched arrays of parent and child columns.
/// </para>
/// </devdoc>
public DataRelation(string relationName, DataColumn[] parentColumns, DataColumn[] childColumns)
: this(relationName, parentColumns, childColumns, true) {
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Data.DataRelation'/> class using the specified name, matched arrays of parent
/// and child columns, and value to create constraints.
/// </para>
/// </devdoc>
public DataRelation(string relationName, DataColumn[] parentColumns, DataColumn[] childColumns, bool createConstraints) {
Create(relationName, parentColumns, childColumns, createConstraints);
}
// Design time constructor
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[Browsable(false)]
public DataRelation(string relationName, string parentTableName, string childTableName, string[] parentColumnNames, string[] childColumnNames, bool nested) {
this.relationName = relationName;
this.parentColumnNames = parentColumnNames;
this.childColumnNames = childColumnNames;
this.parentTableName = parentTableName;
this.childTableName = childTableName;
this.nested = nested;
// DataRelation(relationName, parentTableName, null, childTableName, null, parentColumnNames, childColumnNames, nested)
}
[Browsable(false)]
// Design time constructor
public DataRelation(string relationName, string parentTableName, string parentTableNamespace, string childTableName, string childTableNamespace, string[] parentColumnNames, string[] childColumnNames, bool nested) {
this.relationName = relationName;
this.parentColumnNames = parentColumnNames;
this.childColumnNames = childColumnNames;
this.parentTableName = parentTableName;
this.childTableName = childTableName;
this.parentTableNamespace = parentTableNamespace;
this.childTableNamespace = childTableNamespace;
this.nested = nested;
}
/// <devdoc>
/// <para>
/// Gets the child columns of this relation.
/// </para>
/// </devdoc>
[
ResCategoryAttribute(Res.DataCategory_Data),
ResDescriptionAttribute(Res.DataRelationChildColumnsDescr)
]
public virtual DataColumn[] ChildColumns {
get {
CheckStateForProperty();
return childKey.ToArray();
}
}
internal DataColumn[] ChildColumnsReference {
get {
CheckStateForProperty();
return childKey.ColumnsReference;
}
}
/// <devdoc>
/// The internal Key object for the child table.
/// </devdoc>
internal DataKey ChildKey {
get {
CheckStateForProperty();
return childKey;
}
}
/// <devdoc>
/// <para>
/// Gets the child table of this relation.
/// </para>
/// </devdoc>
public virtual DataTable ChildTable {
get {
CheckStateForProperty();
return childKey.Table;
}
}
/// <devdoc>
/// <para>
/// Gets the <see cref='System.Data.DataSet'/> to which the relations' collection belongs to.
/// </para>
/// </devdoc>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
public virtual DataSet DataSet {
get {
CheckStateForProperty();
return dataSet;
}
}
internal string[] ParentColumnNames {
get {
return parentKey.GetColumnNames();
}
}
internal string[] ChildColumnNames {
get {
return childKey.GetColumnNames();
}
}
private static bool IsKeyNull(object[] values) {
for (int i = 0; i < values.Length; i++) {
if (!DataStorage.IsObjectNull(values[i]))
return false;
}
return true;
}
/// <devdoc>
/// Gets the child rows for the parent row across the relation using the version given
/// </devdoc>
internal static DataRow[] GetChildRows(DataKey parentKey, DataKey childKey, DataRow parentRow, DataRowVersion version) {
object[] values = parentRow.GetKeyValues(parentKey, version);
if (IsKeyNull(values)) {
return childKey.Table.NewRowArray(0);
}
Index index = childKey.GetSortIndex((version == DataRowVersion.Original) ? DataViewRowState.OriginalRows : DataViewRowState.CurrentRows);
return index.GetRows(values);
}
/// <devdoc>
/// Gets the parent rows for the given child row across the relation using the version given
/// </devdoc>
internal static DataRow[] GetParentRows(DataKey parentKey, DataKey childKey, DataRow childRow, DataRowVersion version) {
object[] values = childRow.GetKeyValues(childKey, version);
if (IsKeyNull(values)) {
return parentKey.Table.NewRowArray(0);
}
Index index = parentKey.GetSortIndex((version == DataRowVersion.Original) ? DataViewRowState.OriginalRows : DataViewRowState.CurrentRows);
return index.GetRows(values);
}
internal static DataRow GetParentRow(DataKey parentKey, DataKey childKey, DataRow childRow, DataRowVersion version) {
if (!childRow.HasVersion((version == DataRowVersion.Original) ? DataRowVersion.Original : DataRowVersion.Current))
if (childRow.tempRecord == -1)
return null;
object[] values = childRow.GetKeyValues(childKey, version);
if (IsKeyNull(values)) {
return null;
}
Index index = parentKey.GetSortIndex((version == DataRowVersion.Original) ? DataViewRowState.OriginalRows : DataViewRowState.CurrentRows);
Range range = index.FindRecords(values);
if (range.IsNull) {
return null;
}
if (range.Count > 1) {
throw ExceptionBuilder.MultipleParents();
}
return parentKey.Table.recordManager[index.GetRecord(range.Min)];
}
/// <devdoc>
/// Internally sets the DataSet pointer.
/// </devdoc>
internal void SetDataSet(DataSet dataSet) {
if (this.dataSet != dataSet) {
this.dataSet = dataSet;
}
}
internal void SetParentRowRecords(DataRow childRow, DataRow parentRow) {
object[] parentKeyValues = parentRow.GetKeyValues(ParentKey);
if (childRow.tempRecord != -1) {
ChildTable.recordManager.SetKeyValues(childRow.tempRecord, ChildKey, parentKeyValues);
}
if (childRow.newRecord != -1) {
ChildTable.recordManager.SetKeyValues(childRow.newRecord, ChildKey, parentKeyValues);
}
if (childRow.oldRecord != -1) {
ChildTable.recordManager.SetKeyValues(childRow.oldRecord, ChildKey, parentKeyValues);
}
}
/// <devdoc>
/// <para>
/// Gets the parent columns of this relation.
/// </para>
/// </devdoc>
[
ResCategoryAttribute(Res.DataCategory_Data),
ResDescriptionAttribute(Res.DataRelationParentColumnsDescr)
]
public virtual DataColumn[] ParentColumns {
get {
CheckStateForProperty();
return parentKey.ToArray();
}
}
internal DataColumn[] ParentColumnsReference {
get {
return parentKey.ColumnsReference;
}
}
/// <devdoc>
/// The internal constraint object for the parent table.
/// </devdoc>
internal DataKey ParentKey {
get {
CheckStateForProperty();
return parentKey;
}
}
/// <devdoc>
/// <para>
/// Gets the parent table of this relation.
/// </para>
/// </devdoc>
public virtual DataTable ParentTable {
get {
CheckStateForProperty();
return parentKey.Table;
}
}
/// <devdoc>
/// <para>
/// Gets or sets
/// the name used to look up this relation in the parent
/// data set's <see cref='System.Data.DataRelationCollection'/>.
/// </para>
/// </devdoc>
[
ResCategoryAttribute(Res.DataCategory_Data),
DefaultValue(""),
ResDescriptionAttribute(Res.DataRelationRelationNameDescr)
]
public virtual string RelationName {
get {
CheckStateForProperty();
return relationName;
}
set {
IntPtr hscp;
Bid.ScopeEnter(out hscp, "<ds.DataRelation.set_RelationName|API> %d#, '%ls'\n", ObjectID, value);
try {
if (value == null)
value = "";
CultureInfo locale = (dataSet != null ? dataSet.Locale : CultureInfo.CurrentCulture);
if (String.Compare(relationName, value, true, locale) != 0) {
if (dataSet != null) {
if (value.Length == 0)
throw ExceptionBuilder.NoRelationName();
dataSet.Relations.RegisterName(value);
if (relationName.Length != 0)
dataSet.Relations.UnregisterName(relationName);
}
this.relationName = value;
((DataRelationCollection.DataTableRelationCollection)(ParentTable.ChildRelations)).OnRelationPropertyChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, this));
((DataRelationCollection.DataTableRelationCollection)(ChildTable.ParentRelations)).OnRelationPropertyChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, this));
}
else if (String.Compare(relationName, value, false, locale) != 0) {
relationName = value;
((DataRelationCollection.DataTableRelationCollection)(ParentTable.ChildRelations)).OnRelationPropertyChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, this));
((DataRelationCollection.DataTableRelationCollection)(ChildTable.ParentRelations)).OnRelationPropertyChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, this));
}
}
finally{
Bid.ScopeLeave(ref hscp);
}
}
}
internal void CheckNamespaceValidityForNestedRelations(string ns) {
foreach(DataRelation rel in ChildTable.ParentRelations) {
if (rel == this || rel.Nested) {
if (rel.ParentTable.Namespace != ns) {
throw ExceptionBuilder.InValidNestedRelation(ChildTable.TableName);
}
}
}
}
internal void CheckNestedRelations() {
Bid.Trace("<ds.DataRelation.CheckNestedRelations|INFO> %d#\n", ObjectID);
Debug.Assert(DataSet == null || ! nested, "this relation supposed to be not in dataset or not nested");
// 1. There is no other relation (R) that has this.ChildTable as R.ChildTable
// This is not valid for Whidbey anymore so the code has been removed
// 2. There is no loop in nested relations
#if DEBUG
int numTables = ParentTable.DataSet.Tables.Count;
#endif
DataTable dt = ParentTable;
if (ChildTable == ParentTable){
if (String.Compare(ChildTable.TableName, ChildTable.DataSet.DataSetName, true, ChildTable.DataSet.Locale) == 0)
throw ExceptionBuilder.SelfnestedDatasetConflictingName(ChildTable.TableName);
return; //allow self join tables.
}
List<DataTable> list = new List<DataTable>();
list.Add(ChildTable);
// We have already checked for nested relaion UP
for(int i = 0; i < list.Count; ++i) {
DataRelation[] relations = list[i].NestedParentRelations;
foreach(DataRelation rel in relations) {
if (rel.ParentTable == ChildTable && rel.ChildTable != ChildTable) {
throw ExceptionBuilder.LoopInNestedRelations(ChildTable.TableName);
}
if (!list.Contains (rel.ParentTable)) { // check for self nested
list.Add(rel.ParentTable);
}
}
}
}
/********************
The Namespace of a table nested inside multiple parents can be
1. Explicitly specified
2. Inherited from Parent Table
3. Empty (Form = unqualified case)
However, Schema does not allow (3) to be a global element and multiple nested child has to be a global element.
Therefore we'll reduce case (3) to (2) if all parents have same namespace else throw.
********************/
/// <devdoc>
/// <para>
/// Gets or sets a value indicating whether relations are nested.
/// </para>
/// </devdoc>
[
ResCategoryAttribute(Res.DataCategory_Data),
DefaultValue(false),
ResDescriptionAttribute(Res.DataRelationNested)
]
public virtual bool Nested {
get {
CheckStateForProperty();
return nested;
}
set {
IntPtr hscp;
Bid.ScopeEnter(out hscp, "<ds.DataRelation.set_Nested|API> %d#, %d{bool}\n", ObjectID, value);
try {
if (nested != value) {
if (dataSet != null) {
if (value) {
if (ChildTable.IsNamespaceInherited()) { // if not added to collection, don't do this check
CheckNamespaceValidityForNestedRelations(ParentTable.Namespace);
}
Debug.Assert(ChildTable != null, "On a DataSet, but not on Table. Bad state");
ForeignKeyConstraint constraint = ChildTable.Constraints.FindForeignKeyConstraint(ChildKey.ColumnsReference, ParentKey.ColumnsReference);
if (constraint != null) {
constraint.CheckConstraint();
}
ValidateMultipleNestedRelations();
}
}
if (!value && (parentKey.ColumnsReference[0].ColumnMapping == MappingType.Hidden))
throw ExceptionBuilder.RelationNestedReadOnly();
if (value) {
this.ParentTable.Columns.RegisterColumnName(this.ChildTable.TableName, null);
} else {
this.ParentTable.Columns.UnregisterName(this.ChildTable.TableName);
}
RaisePropertyChanging("Nested");
if(value) {
CheckNestedRelations();
if (this.DataSet != null)
if (ParentTable == ChildTable) {
foreach(DataRow row in ChildTable.Rows)
row.CheckForLoops(this);
if (ChildTable.DataSet != null && ( String.Compare(ChildTable.TableName, ChildTable.DataSet.DataSetName, true, ChildTable.DataSet.Locale) == 0) )
throw ExceptionBuilder.DatasetConflictingName(dataSet.DataSetName);
ChildTable.fNestedInDataset = false;
}
else {
foreach(DataRow row in ChildTable.Rows)
row.GetParentRow(this);
}
this.ParentTable.ElementColumnCount++;
}
else {
this.ParentTable.ElementColumnCount--;
}
this.nested = value;
ChildTable.CacheNestedParent();
if (value) {
if (ADP.IsEmpty(ChildTable.Namespace) && ((ChildTable.NestedParentsCount > 1) ||
((ChildTable.NestedParentsCount > 0) && ! (ChildTable.DataSet.Relations.Contains(this.RelationName))))) {
string parentNs = null;
foreach(DataRelation rel in ChildTable.ParentRelations) {
if (rel.Nested) {
if (null == parentNs) {
parentNs = rel.ParentTable.Namespace;
}
else {
if (String.Compare(parentNs, rel.ParentTable.Namespace, StringComparison.Ordinal) != 0) {
this.nested = false;
throw ExceptionBuilder.InvalidParentNamespaceinNestedRelation(ChildTable.TableName);
}
}
}
}
// if not already in memory , form == unqualified
if (CheckMultipleNested && ChildTable.tableNamespace != null && ChildTable.tableNamespace.Length == 0) {
throw ExceptionBuilder.TableCantBeNestedInTwoTables(ChildTable.TableName);
}
ChildTable.tableNamespace = null; // if we dont throw, then let it inherit the Namespace
}
}
}
}
finally{
Bid.ScopeLeave(ref hscp);
}
}
}
/// <devdoc>
/// <para>
/// Gets the constraint which ensures values in a column are unique.
/// </para>
/// </devdoc>
public virtual UniqueConstraint ParentKeyConstraint {
get {
CheckStateForProperty();
return parentKeyConstraint;
}
}
internal void SetParentKeyConstraint(UniqueConstraint value) {
Debug.Assert(parentKeyConstraint == null || value == null, "ParentKeyConstraint should not have been set already.");
parentKeyConstraint = value;
}
/// <devdoc>
/// <para>
/// Gets the <see cref='System.Data.ForeignKeyConstraint'/> for the relation.
/// </para>
/// </devdoc>
public virtual ForeignKeyConstraint ChildKeyConstraint {
get {
CheckStateForProperty();
return childKeyConstraint;
}
}
/// <devdoc>
/// <para>Gets the collection of custom user information.</para>
/// </devdoc>
[
ResCategoryAttribute(Res.DataCategory_Data),
Browsable(false),
ResDescriptionAttribute(Res.ExtendedPropertiesDescr)
]
public PropertyCollection ExtendedProperties {
get {
if (extendedProperties == null) {
extendedProperties = new PropertyCollection();
}
return extendedProperties;
}
}
internal bool CheckMultipleNested {
get {
return _checkMultipleNested;
}
set {
_checkMultipleNested = value;
}
}
internal void SetChildKeyConstraint(ForeignKeyConstraint value) {
Debug.Assert(childKeyConstraint == null || value == null, "ChildKeyConstraint should not have been set already.");
childKeyConstraint = value;
}
internal event PropertyChangedEventHandler PropertyChanging {
add {
onPropertyChangingDelegate += value;
}
remove {
onPropertyChangingDelegate -= value;
}
}
// If we're not in a dataSet relations collection, we need to verify on every property get that we're
// still a good relation object.
internal void CheckState() {
if (dataSet == null) {
parentKey.CheckState();
childKey.CheckState();
if (parentKey.Table.DataSet != childKey.Table.DataSet) {
throw ExceptionBuilder.RelationDataSetMismatch();
}
if (childKey.ColumnsEqual(parentKey)) {
throw ExceptionBuilder.KeyColumnsIdentical();
}
for (int i = 0; i < parentKey.ColumnsReference.Length; i++) {
if ((parentKey.ColumnsReference[i].DataType != childKey.ColumnsReference[i].DataType) ||
((parentKey.ColumnsReference[i].DataType == typeof(DateTime)) &&
(parentKey.ColumnsReference[i].DateTimeMode != childKey.ColumnsReference[i].DateTimeMode) &&
((parentKey.ColumnsReference[i].DateTimeMode & childKey.ColumnsReference[i].DateTimeMode) != DataSetDateTime.Unspecified)))
// alow unspecified and unspecifiedlocal
throw ExceptionBuilder.ColumnsTypeMismatch();
}
}
}
/// <devdoc>
/// <para>Checks to ensure the DataRelation is a valid object, even if it doesn't
/// belong to a <see cref='System.Data.DataSet'/>.</para>
/// </devdoc>
protected void CheckStateForProperty() {
try {
CheckState();
}
catch (Exception e) {
//
if (ADP.IsCatchableExceptionType(e)) {
throw ExceptionBuilder.BadObjectPropertyAccess(e.Message);
}
throw;
}
}
private void Create(string relationName, DataColumn[] parentColumns, DataColumn[] childColumns, bool createConstraints) {
IntPtr hscp;
Bid.ScopeEnter(out hscp, "<ds.DataRelation.Create|INFO> %d#, relationName='%ls', createConstraints=%d{bool}\n",
ObjectID, relationName, createConstraints);
try {
this.parentKey = new DataKey(parentColumns, true);
this.childKey = new DataKey(childColumns, true);
if (parentColumns.Length != childColumns.Length)
throw ExceptionBuilder.KeyLengthMismatch();
for(int i = 0; i < parentColumns.Length; i++){
if ((parentColumns[i].Table.DataSet == null) || (childColumns[i].Table.DataSet == null))
throw ExceptionBuilder.ParentOrChildColumnsDoNotHaveDataSet();
}
CheckState();
this.relationName = (relationName == null ? "" : relationName);
this.createConstraints = createConstraints;
}
finally{
Bid.ScopeLeave(ref hscp);
}
}
internal DataRelation Clone(DataSet destination) {
Bid.Trace("<ds.DataRelation.Clone|INFO> %d#, destination=%d\n", ObjectID, (destination != null) ? destination.ObjectID : 0);
DataTable parent = destination.Tables[ParentTable.TableName, ParentTable.Namespace];
DataTable child = destination.Tables[ChildTable.TableName, ChildTable.Namespace];
int keyLength = parentKey.ColumnsReference.Length;
DataColumn[] parentColumns = new DataColumn[keyLength];
DataColumn[] childColumns = new DataColumn[keyLength];
for (int i = 0; i < keyLength; i++) {
parentColumns[i] = parent.Columns[ParentKey.ColumnsReference[i].ColumnName];
childColumns[i] = child.Columns[ChildKey.ColumnsReference[i].ColumnName];
}
DataRelation clone = new DataRelation(relationName, parentColumns, childColumns, false);
clone.CheckMultipleNested = false; // disable the check in clone as it is already created
clone.Nested = this.Nested;
clone.CheckMultipleNested = true; // enable the check
// ...Extended Properties
if (this.extendedProperties != null) {
foreach(Object key in this.extendedProperties.Keys) {
clone.ExtendedProperties[key]=this.extendedProperties[key];
}
}
return clone;
}
protected internal void OnPropertyChanging(PropertyChangedEventArgs pcevent) {
if (onPropertyChangingDelegate != null) {
Bid.Trace("<ds.DataRelation.OnPropertyChanging|INFO> %d#\n", ObjectID);
onPropertyChangingDelegate(this, pcevent);
}
}
protected internal void RaisePropertyChanging(string name) {
OnPropertyChanging(new PropertyChangedEventArgs(name));
}
/// <devdoc>
/// </devdoc>
public override string ToString() {
return RelationName;
}
internal void ValidateMultipleNestedRelations() {
// find all nested relations that this child table has
// if this relation is the only relation it has, then fine,
// otherwise check if all relations are created from XSD, without using Key/KeyRef
// check all keys to see autogenerated
if (!this.Nested || !CheckMultipleNested) // no need for this verification
return;
if (0 < ChildTable.NestedParentRelations.Length) {
DataColumn[] childCols = ChildColumns;
if (childCols.Length != 1 || !IsAutoGenerated(childCols[0])) {
throw ExceptionBuilder.TableCantBeNestedInTwoTables(ChildTable.TableName);
}
if (!XmlTreeGen.AutoGenerated(this)) {
throw ExceptionBuilder.TableCantBeNestedInTwoTables(ChildTable.TableName);
}
foreach (Constraint cs in ChildTable.Constraints) {
if (cs is ForeignKeyConstraint) {
ForeignKeyConstraint fk = (ForeignKeyConstraint) cs;
if (!XmlTreeGen.AutoGenerated(fk, true)) {
throw ExceptionBuilder.TableCantBeNestedInTwoTables(ChildTable.TableName);
}
}
else {
UniqueConstraint unique = (UniqueConstraint) cs;
if (!XmlTreeGen.AutoGenerated(unique)) {
throw ExceptionBuilder.TableCantBeNestedInTwoTables(ChildTable.TableName);
}
}
}
}
}
private bool IsAutoGenerated(DataColumn col) {
if (col.ColumnMapping != MappingType.Hidden)
return false;
if (col.DataType != typeof(int))
return false;
string generatedname = col.Table.TableName+"_Id";
if ((col.ColumnName == generatedname) || (col.ColumnName == generatedname+"_0"))
return true;
generatedname = this.ParentColumnsReference[0].Table.TableName+"_Id";
if ((col.ColumnName == generatedname) || (col.ColumnName == generatedname+"_0"))
return true;
return false;
}
internal int ObjectID {
get {
return _objectID;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using Microsoft.Cci.Extensions;
using Microsoft.Cci.Extensions.CSharp;
using Microsoft.Cci.Filters;
using Microsoft.Cci.Writers.Syntax;
namespace Microsoft.Cci.Writers.CSharp
{
public partial class CSDeclarationWriter : ICciDeclarationWriter
{
private readonly ISyntaxWriter _writer;
private readonly ICciFilter _filter;
private bool _forCompilation;
private bool _forCompilationIncludeGlobalprefix;
private string _platformNotSupportedExceptionMessage;
private bool _includeFakeAttributes;
public CSDeclarationWriter(ISyntaxWriter writer)
: this(writer, new PublicOnlyCciFilter())
{
}
public CSDeclarationWriter(ISyntaxWriter writer, ICciFilter filter)
: this(writer, filter, true)
{
}
public CSDeclarationWriter(ISyntaxWriter writer, ICciFilter filter, bool forCompilation)
{
Contract.Requires(writer != null);
_writer = writer;
_filter = filter;
_forCompilation = forCompilation;
_forCompilationIncludeGlobalprefix = false;
_platformNotSupportedExceptionMessage = null;
_includeFakeAttributes = false;
}
public CSDeclarationWriter(ISyntaxWriter writer, ICciFilter filter, bool forCompilation, bool includePseudoCustomAttributes = false)
: this(writer, filter, forCompilation)
{
_includeFakeAttributes = includePseudoCustomAttributes;
}
public bool ForCompilation
{
get { return _forCompilation; }
set { _forCompilation = value; }
}
public bool ForCompilationIncludeGlobalPrefix
{
get { return _forCompilationIncludeGlobalprefix; }
set { _forCompilationIncludeGlobalprefix = value; }
}
public string PlatformNotSupportedExceptionMessage
{
get { return _platformNotSupportedExceptionMessage; }
set { _platformNotSupportedExceptionMessage = value; }
}
public ISyntaxWriter SyntaxtWriter { get { return _writer; } }
public ICciFilter Filter { get { return _filter; } }
public void WriteDeclaration(IDefinition definition)
{
if (definition == null)
return;
IAssembly assembly = definition as IAssembly;
if (assembly != null)
{
WriteAssemblyDeclaration(assembly);
return;
}
INamespaceDefinition ns = definition as INamespaceDefinition;
if (ns != null)
{
WriteNamespaceDeclaration(ns);
return;
}
ITypeDefinition type = definition as ITypeDefinition;
if (type != null)
{
WriteTypeDeclaration(type);
return;
}
ITypeDefinitionMember member = definition as ITypeDefinitionMember;
if (member != null)
{
WriteMemberDeclaration(member);
return;
}
DummyInternalConstructor ctor = definition as DummyInternalConstructor;
if (ctor != null)
{
WritePrivateConstructor(ctor.ContainingType);
return;
}
INamedEntity named = definition as INamedEntity;
if (named != null)
{
WriteIdentifier(named.Name);
return;
}
_writer.Write("Unknown definition type {0}", definition.ToString());
}
public void WriteAttribute(ICustomAttribute attribute)
{
WriteSymbol("[");
WriteAttribute(attribute, null);
WriteSymbol("]");
}
public void WriteAssemblyDeclaration(IAssembly assembly)
{
WriteAttributes(assembly.Attributes, prefix: "assembly");
WriteAttributes(assembly.SecurityAttributes, prefix: "assembly");
}
public void WriteMemberDeclaration(ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
{
WriteMethodDefinition(method);
return;
}
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
{
WritePropertyDefinition(property);
return;
}
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
{
WriteEventDefinition(evnt);
return;
}
IFieldDefinition field = member as IFieldDefinition;
if (field != null)
{
WriteFieldDefinition(field);
return;
}
_writer.Write("Unknown member definitions type {0}", member.ToString());
}
private void WriteVisibility(TypeMemberVisibility visibility)
{
switch (visibility)
{
case TypeMemberVisibility.Public:
WriteKeyword("public"); break;
case TypeMemberVisibility.Private:
WriteKeyword("private"); break;
case TypeMemberVisibility.Assembly:
WriteKeyword("internal"); break;
case TypeMemberVisibility.Family:
WriteKeyword("protected"); break;
case TypeMemberVisibility.FamilyOrAssembly:
WriteKeyword("protected"); WriteKeyword("internal"); break;
case TypeMemberVisibility.FamilyAndAssembly:
WriteKeyword("internal"); WriteKeyword("protected"); break; // Is this right?
default:
WriteKeyword("<Unknown-Visibility>"); break;
}
}
private void WriteCustomModifiers(IEnumerable<ICustomModifier> modifiers)
{
foreach (ICustomModifier modifier in modifiers)
{
if (modifier.Modifier.FullName() == "System.Runtime.CompilerServices.IsVolatile")
WriteKeyword("volatile");
}
}
// Writer Helpers these are the only methods that should directly acess _writer
private void WriteKeyword(string keyword, bool noSpace = false)
{
_writer.WriteKeyword(keyword);
if (!noSpace) WriteSpace();
}
private void WriteSymbol(string symbol, bool addSpace = false)
{
_writer.WriteSymbol(symbol);
if (addSpace)
WriteSpace();
}
private void Write(string literal)
{
_writer.Write(literal);
}
private void WriteTypeName(ITypeReference type, bool noSpace = false, bool isDynamic = false, bool useTypeKeywords = true, bool omitGenericTypeList = false)
{
if (isDynamic)
{
WriteKeyword("dynamic", noSpace: noSpace);
return;
}
NameFormattingOptions namingOptions = NameFormattingOptions.TypeParameters;
if (useTypeKeywords)
namingOptions |= NameFormattingOptions.UseTypeKeywords;
if (_forCompilationIncludeGlobalprefix)
namingOptions |= NameFormattingOptions.UseGlobalPrefix;
if (!_forCompilation)
namingOptions |= NameFormattingOptions.OmitContainingNamespace;
if (omitGenericTypeList)
namingOptions |= NameFormattingOptions.EmptyTypeParameterList;
string name = TypeHelper.GetTypeName(type, namingOptions);
if (CSharpCciExtensions.IsKeyword(name))
_writer.WriteKeyword(name);
else
_writer.WriteTypeName(name);
if (!noSpace) WriteSpace();
}
public void WriteIdentifier(string id)
{
WriteIdentifier(id, true);
}
public void WriteIdentifier(string id, bool escape)
{
// Escape keywords
if (escape && CSharpCciExtensions.IsKeyword(id))
id = "@" + id;
_writer.WriteIdentifier(id);
}
private void WriteIdentifier(IName name)
{
WriteIdentifier(name.Value);
}
private void WriteSpace()
{
_writer.Write(" ");
}
private void WriteList<T>(IEnumerable<T> list, Action<T> writeItem)
{
_writer.WriteList(list, writeItem);
}
}
}
| |
// 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.Linq;
using NUnit.Framework;
using osu.Framework.Bindables;
using osu.Framework.Extensions.IEnumerableExtensions;
namespace osu.Framework.Tests.Bindables
{
[TestFixture]
public class BindableDictionaryTest
{
private BindableDictionary<string, byte> bindableStringByteDictionary;
[SetUp]
public void SetUp()
{
bindableStringByteDictionary = new BindableDictionary<string, byte>();
}
#region Constructor
[Test]
public void TestConstructorDoesNotAddItemsByDefault()
{
Assert.IsEmpty(bindableStringByteDictionary);
}
[Test]
public void TestConstructorWithItemsAddsItemsInternally()
{
KeyValuePair<string, byte>[] array =
{
new KeyValuePair<string, byte>("ok", 0),
new KeyValuePair<string, byte>("nope", 1),
new KeyValuePair<string, byte>("random", 2),
new KeyValuePair<string, byte>("", 4)
};
var dict = new BindableDictionary<string, byte>(array);
Assert.Multiple(() =>
{
foreach ((string key, byte value) in array)
{
Assert.That(dict.TryGetValue(key, out byte val), Is.True);
Assert.That(val, Is.EqualTo(value));
}
Assert.AreEqual(array.Length, dict.Count);
});
}
#endregion
#region BindTarget
/// <summary>
/// Tests binding via the various <see cref="BindableDictionary{TKey,TValue}"/> methods.
/// </summary>
[Test]
public void TestBindViaBindTarget()
{
BindableDictionary<string, byte> parentBindable = new BindableDictionary<string, byte>();
BindableDictionary<string, byte> bindable1 = new BindableDictionary<string, byte>();
BindableDictionary<string, byte> bindable2 = new BindableDictionary<string, byte>();
bindable1.BindTarget = parentBindable;
bindable2.BindTarget = parentBindable;
parentBindable.Add("5", 1);
Assert.That(bindable1["5"], Is.EqualTo(1));
Assert.That(bindable2["5"], Is.EqualTo(1));
}
#endregion
#region BindCollectionChanged
[Test]
public void TestBindCollectionChangedWithoutRunningImmediately()
{
var dict = new BindableDictionary<string, byte> { { "a", 1 } };
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgs = null;
dict.BindCollectionChanged((_, args) => triggeredArgs = args);
Assert.That(triggeredArgs, Is.Null);
}
[Test]
public void TestBindCollectionChangedWithRunImmediately()
{
var dict = new BindableDictionary<string, byte> { { "a", 1 } };
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgs = null;
dict.BindCollectionChanged((_, args) => triggeredArgs = args, true);
Assert.That(triggeredArgs.Action, Is.EqualTo(NotifyDictionaryChangedAction.Add));
Assert.That(triggeredArgs.NewItems, Is.EquivalentTo(dict));
}
[Test]
public void TestBindCollectionChangedNotRunIfBoundToSequenceEqualDictionary()
{
var dict = new BindableDictionary<string, byte>
{
{ "a", 1 },
{ "b", 3 },
{ "c", 5 },
{ "d", 7 }
};
var otherDict = new BindableDictionary<string, byte>
{
{ "a", 1 },
{ "b", 3 },
{ "c", 5 },
{ "d", 7 }
};
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgs = null;
dict.BindCollectionChanged((_, args) => triggeredArgs = args);
dict.BindTo(otherDict);
Assert.That(triggeredArgs, Is.Null);
}
[Test]
public void TestBindCollectionChangedNotRunIfParsingSequenceEqualEnumerable()
{
var dict = new BindableDictionary<string, byte>
{
{ "a", 1 },
{ "b", 3 },
{ "c", 5 },
{ "d", 7 }
};
var enumerable = new[]
{
new KeyValuePair<string, byte>("a", 1),
new KeyValuePair<string, byte>("b", 3),
new KeyValuePair<string, byte>("c", 5),
new KeyValuePair<string, byte>("d", 7)
};
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgs = null;
dict.BindCollectionChanged((_, args) => triggeredArgs = args);
dict.Parse(enumerable);
Assert.That(triggeredArgs, Is.Null);
}
[Test]
public void TestBindCollectionChangedEventsRanIfBoundToDifferentDictionary()
{
var firstDictContents = new[]
{
new KeyValuePair<string, byte>("a", 1),
new KeyValuePair<string, byte>("b", 3),
new KeyValuePair<string, byte>("c", 5),
new KeyValuePair<string, byte>("d", 7),
};
var otherDictContents = new[]
{
new KeyValuePair<string, byte>("a", 2),
new KeyValuePair<string, byte>("b", 4),
new KeyValuePair<string, byte>("c", 6),
new KeyValuePair<string, byte>("d", 8),
new KeyValuePair<string, byte>("e", 10),
};
var dict = new BindableDictionary<string, byte>(firstDictContents);
var otherDict = new BindableDictionary<string, byte>(otherDictContents);
var triggeredArgs = new List<NotifyDictionaryChangedEventArgs<string, byte>>();
dict.BindCollectionChanged((_, args) => triggeredArgs.Add(args));
dict.BindTo(otherDict);
Assert.That(triggeredArgs, Has.Count.EqualTo(2));
var removeEvent = triggeredArgs.SingleOrDefault(ev => ev.Action == NotifyDictionaryChangedAction.Remove);
Assert.That(removeEvent, Is.Not.Null);
Assert.That(removeEvent.OldItems, Is.EquivalentTo(firstDictContents));
var addEvent = triggeredArgs.SingleOrDefault(ev => ev.Action == NotifyDictionaryChangedAction.Add);
Assert.That(addEvent, Is.Not.Null);
Assert.That(addEvent.NewItems, Is.EquivalentTo(otherDict));
}
#endregion
#region dictionary[index]
[Test]
public void TestGetRetrievesObjectAtIndex()
{
bindableStringByteDictionary.Add("0", 0);
bindableStringByteDictionary.Add("1", 1);
bindableStringByteDictionary.Add("2", 2);
Assert.AreEqual(1, bindableStringByteDictionary["1"]);
}
[Test]
public void TestSetNotifiesSubscribersOfAddWhenItemDoesNotExist()
{
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgs = null;
bindableStringByteDictionary.CollectionChanged += (_, args) => triggeredArgs = args;
bindableStringByteDictionary["0"] = 0;
Assert.That(triggeredArgs.Action, Is.EqualTo(NotifyDictionaryChangedAction.Add));
Assert.That(triggeredArgs.OldItems, Is.Null);
Assert.That(triggeredArgs.NewItems, Is.EquivalentTo(new KeyValuePair<string, byte>("0", 0).Yield()));
}
[Test]
public void TestSetNotifiesSubscribersOfReplacementWhenItemExists()
{
bindableStringByteDictionary["0"] = 0;
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgs = null;
bindableStringByteDictionary.CollectionChanged += (_, args) => triggeredArgs = args;
bindableStringByteDictionary["0"] = 1;
Assert.That(triggeredArgs.Action, Is.EqualTo(NotifyDictionaryChangedAction.Replace));
Assert.That(triggeredArgs.OldItems, Is.EquivalentTo(new KeyValuePair<string, byte>("0", 0).Yield()));
Assert.That(triggeredArgs.NewItems, Is.EquivalentTo(new KeyValuePair<string, byte>("0", 1).Yield()));
}
[Test]
public void TestSetMutatesObjectAtIndex()
{
bindableStringByteDictionary.Add("0", 0);
bindableStringByteDictionary.Add("1", 1);
bindableStringByteDictionary["1"] = 2;
Assert.AreEqual(2, bindableStringByteDictionary["1"]);
}
[Test]
public void TestGetWhileDisabledDoesNotThrowInvalidOperationException()
{
bindableStringByteDictionary.Add("0", 0);
bindableStringByteDictionary.Disabled = true;
Assert.AreEqual(0, bindableStringByteDictionary["0"]);
}
[Test]
public void TestSetWhileDisabledThrowsInvalidOperationException()
{
bindableStringByteDictionary.Add("0", 0);
bindableStringByteDictionary.Disabled = true;
Assert.Throws<InvalidOperationException>(() => bindableStringByteDictionary["0"] = 1);
}
[Test]
public void TestSetNotifiesBoundDictionaries()
{
bindableStringByteDictionary.Add("0", 0);
var dict = new BindableDictionary<string, byte>();
dict.BindTo(bindableStringByteDictionary);
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgs = null;
dict.CollectionChanged += (_, args) => triggeredArgs = args;
bindableStringByteDictionary["0"] = 1;
Assert.That(triggeredArgs.Action, Is.EqualTo(NotifyDictionaryChangedAction.Replace));
Assert.That(triggeredArgs.OldItems, Is.EquivalentTo(new KeyValuePair<string, byte>("0", 0).Yield()));
Assert.That(triggeredArgs.NewItems, Is.EquivalentTo(new KeyValuePair<string, byte>("0", 1).Yield()));
}
#endregion
#region .Add(key, value)
[TestCase("a random string", 0)]
[TestCase("", 1, Description = "Empty string")]
public void TestAddWithStringAddsStringToEnumerator(string key, byte value)
{
bindableStringByteDictionary.Add(key, value);
Assert.Contains(new KeyValuePair<string, byte>(key, value), bindableStringByteDictionary);
}
[TestCase("a random string", 0)]
[TestCase("", 1, Description = "Empty string")]
public void TestAddWithStringNotifiesSubscriber(string key, byte value)
{
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgs = null;
bindableStringByteDictionary.CollectionChanged += (_, args) => triggeredArgs = args;
bindableStringByteDictionary.Add(key, value);
Assert.That(triggeredArgs.Action, Is.EqualTo(NotifyDictionaryChangedAction.Add));
Assert.That(triggeredArgs.NewItems, Is.EquivalentTo(new KeyValuePair<string, byte>(key, value).Yield()));
}
[TestCase("a random string", 0)]
[TestCase("", 1, Description = "Empty string")]
public void TestAddWithStringNotifiesSubscriberOnce(string key, byte value)
{
var triggeredArgs = new List<NotifyDictionaryChangedEventArgs<string, byte>>();
bindableStringByteDictionary.CollectionChanged += (_, args) => triggeredArgs.Add(args);
bindableStringByteDictionary.Add(key, value);
Assert.That(triggeredArgs, Has.Count.EqualTo(1));
}
[TestCase("a random string", 0)]
[TestCase("", 1, Description = "Empty string")]
public void TestAddWithStringNotifiesMultipleSubscribers(string key, byte value)
{
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgsA = null;
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgsB = null;
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgsC = null;
bindableStringByteDictionary.CollectionChanged += (_, args) => triggeredArgsA = args;
bindableStringByteDictionary.CollectionChanged += (_, args) => triggeredArgsB = args;
bindableStringByteDictionary.CollectionChanged += (_, args) => triggeredArgsC = args;
bindableStringByteDictionary.Add(key, value);
Assert.That(triggeredArgsA, Is.Not.Null);
Assert.That(triggeredArgsB, Is.Not.Null);
Assert.That(triggeredArgsC, Is.Not.Null);
}
[TestCase("a random string", 0)]
[TestCase("", 1, Description = "Empty string")]
public void TestAddWithStringNotifiesMultipleSubscribersOnlyAfterTheAdd(string key, byte value)
{
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgsA = null;
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgsB = null;
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgsC = null;
bindableStringByteDictionary.CollectionChanged += (_, args) => triggeredArgsA = args;
bindableStringByteDictionary.CollectionChanged += (_, args) => triggeredArgsB = args;
bindableStringByteDictionary.CollectionChanged += (_, args) => triggeredArgsC = args;
Assert.That(triggeredArgsA, Is.Null);
Assert.That(triggeredArgsB, Is.Null);
Assert.That(triggeredArgsC, Is.Null);
bindableStringByteDictionary.Add(key, value);
}
[TestCase("a random string", 0)]
[TestCase("", 1, Description = "Empty string")]
public void TestAddWithStringNotifiesBoundDictionary(string key, byte value)
{
var dict = new BindableDictionary<string, byte>();
dict.BindTo(bindableStringByteDictionary);
bindableStringByteDictionary.Add(key, value);
Assert.That(dict, Contains.Key(key));
}
[TestCase("a random string", 0)]
[TestCase("", 1, Description = "Empty string")]
public void TestAddWithStringNotifiesBoundDictionaries(string key, byte value)
{
var dictA = new BindableDictionary<string, byte>();
var dictB = new BindableDictionary<string, byte>();
var dictC = new BindableDictionary<string, byte>();
dictA.BindTo(bindableStringByteDictionary);
dictB.BindTo(bindableStringByteDictionary);
dictC.BindTo(bindableStringByteDictionary);
bindableStringByteDictionary.Add(key, value);
Assert.That(dictA, Contains.Key(key));
Assert.That(dictB, Contains.Key(key));
Assert.That(dictC, Contains.Key(key));
}
[TestCase("a random string", 0)]
[TestCase("", 1, Description = "Empty string")]
public void TestAddWithDisabledDictionaryThrowsInvalidOperationException(string key, byte value)
{
bindableStringByteDictionary.Disabled = true;
Assert.Throws<InvalidOperationException>(() => { bindableStringByteDictionary.Add(key, value); });
}
[TestCase("a random string", 0)]
[TestCase("", 1, Description = "Empty string")]
public void TestAddWithDictionaryContainingItemsDoesNotOverrideItems(string key, byte value)
{
const string item = "existing string";
bindableStringByteDictionary.Add(item, 0);
bindableStringByteDictionary.Add(key, value);
Assert.That(bindableStringByteDictionary, Contains.Key(item));
Assert.That(bindableStringByteDictionary[item], Is.EqualTo(0));
}
#endregion
#region .Remove(key)
[Test]
public void TestRemoveWithDisabledDictionaryThrowsInvalidOperationException()
{
const string item = "hi";
bindableStringByteDictionary.Add(item, 0);
bindableStringByteDictionary.Disabled = true;
Assert.Throws(typeof(InvalidOperationException), () => bindableStringByteDictionary.Remove(item));
}
[Test]
public void TestRemoveWithAnItemThatIsNotInTheDictionaryReturnsFalse()
{
bool gotRemoved = bindableStringByteDictionary.Remove("hm");
Assert.IsFalse(gotRemoved);
}
[Test]
public void TestRemoveWhenDictionaryIsDisabledThrowsInvalidOperationException()
{
const string item = "item";
bindableStringByteDictionary.Add(item, 0);
bindableStringByteDictionary.Disabled = true;
Assert.Throws<InvalidOperationException>(() => { bindableStringByteDictionary.Remove(item); });
}
[Test]
public void TestRemoveWithAnItemThatIsInTheDictionaryReturnsTrue()
{
const string item = "item";
bindableStringByteDictionary.Add(item, 0);
bool gotRemoved = bindableStringByteDictionary.Remove(item);
Assert.IsTrue(gotRemoved);
}
[Test]
public void TestRemoveNotifiesSubscriber()
{
const string item = "item";
bindableStringByteDictionary.Add(item, 0);
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgs = null;
bindableStringByteDictionary.CollectionChanged += (_, args) => triggeredArgs = args;
bindableStringByteDictionary.Remove(item);
Assert.That(triggeredArgs.Action, Is.EqualTo(NotifyDictionaryChangedAction.Remove));
Assert.That(triggeredArgs.OldItems, Is.EquivalentTo(new KeyValuePair<string, byte>("item", 0).Yield()));
}
[Test]
public void TestRemoveDoesntNotifySubscribersOnNoOp()
{
const string item = "item";
bindableStringByteDictionary.Add(item, 0);
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgs = null;
bindableStringByteDictionary.Remove(item);
bindableStringByteDictionary.CollectionChanged += (_, args) => triggeredArgs = args;
bindableStringByteDictionary.Remove(item);
Assert.That(triggeredArgs, Is.Null);
}
[Test]
public void TestRemoveNotifiesSubscribers()
{
const string item = "item";
bindableStringByteDictionary.Add(item, 0);
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgsA = null;
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgsB = null;
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgsC = null;
bindableStringByteDictionary.CollectionChanged += (_, args) => triggeredArgsA = args;
bindableStringByteDictionary.CollectionChanged += (_, args) => triggeredArgsB = args;
bindableStringByteDictionary.CollectionChanged += (_, args) => triggeredArgsC = args;
bindableStringByteDictionary.Remove(item);
Assert.That(triggeredArgsA, Is.Not.Null);
Assert.That(triggeredArgsB, Is.Not.Null);
Assert.That(triggeredArgsC, Is.Not.Null);
}
[Test]
public void TestRemoveNotifiesBoundDictionary()
{
const string item = "item";
bindableStringByteDictionary.Add(item, 0);
var dict = new BindableDictionary<string, byte>();
dict.BindTo(bindableStringByteDictionary);
bindableStringByteDictionary.Remove(item);
Assert.IsEmpty(dict);
}
[Test]
public void TestRemoveNotifiesBoundDictionaries()
{
const string item = "item";
bindableStringByteDictionary.Add(item, 0);
var dictA = new BindableDictionary<string, byte>();
dictA.BindTo(bindableStringByteDictionary);
var dictB = new BindableDictionary<string, byte>();
dictB.BindTo(bindableStringByteDictionary);
var dictC = new BindableDictionary<string, byte>();
dictC.BindTo(bindableStringByteDictionary);
bindableStringByteDictionary.Remove(item);
Assert.Multiple(() =>
{
Assert.False(dictA.ContainsKey(item));
Assert.False(dictB.ContainsKey(item));
Assert.False(dictC.ContainsKey(item));
});
}
[Test]
public void TestRemoveNotifiesBoundDictionarySubscription()
{
const string item = "item";
bindableStringByteDictionary.Add(item, 0);
var dict = new BindableDictionary<string, byte>();
dict.BindTo(bindableStringByteDictionary);
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgs = null;
dict.CollectionChanged += (_, args) => triggeredArgs = args;
bindableStringByteDictionary.Remove(item);
Assert.That(triggeredArgs.Action, Is.EqualTo(NotifyDictionaryChangedAction.Remove));
Assert.That(triggeredArgs.OldItems, Is.EquivalentTo(new KeyValuePair<string, byte>(item, 0).Yield()));
}
[Test]
public void TestRemoveNotifiesBoundDictionarySubscriptions()
{
const string item = "item";
bindableStringByteDictionary.Add(item, 0);
var dictA = new BindableDictionary<string, byte>();
dictA.BindTo(bindableStringByteDictionary);
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgsA1 = null;
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgsA2 = null;
dictA.CollectionChanged += (_, args) => triggeredArgsA1 = args;
dictA.CollectionChanged += (_, args) => triggeredArgsA2 = args;
var dictB = new BindableDictionary<string, byte>();
dictB.BindTo(bindableStringByteDictionary);
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgsB1 = null;
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgsB2 = null;
dictB.CollectionChanged += (_, args) => triggeredArgsB1 = args;
dictB.CollectionChanged += (_, args) => triggeredArgsB2 = args;
bindableStringByteDictionary.Remove(item);
Assert.That(triggeredArgsA1, Is.Not.Null);
Assert.That(triggeredArgsA2, Is.Not.Null);
Assert.That(triggeredArgsB1, Is.Not.Null);
Assert.That(triggeredArgsB2, Is.Not.Null);
}
[Test]
public void TestRemoveDoesNotNotifySubscribersBeforeItemIsRemoved()
{
const string item = "item";
bindableStringByteDictionary.Add(item, 0);
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgs = null;
bindableStringByteDictionary.CollectionChanged += (_, args) => triggeredArgs = args;
Assert.That(triggeredArgs, Is.Null);
}
#endregion
#region .Clear()
[Test]
public void TestClear()
{
for (byte i = 0; i < 5; i++)
bindableStringByteDictionary.Add($"test{i}", i);
bindableStringByteDictionary.Clear();
Assert.IsEmpty(bindableStringByteDictionary);
}
[Test]
public void TestClearWithDisabledDictionaryThrowsInvalidOperationException()
{
for (byte i = 0; i < 5; i++)
bindableStringByteDictionary.Add($"test{i}", i);
bindableStringByteDictionary.Disabled = true;
Assert.Throws(typeof(InvalidOperationException), () => bindableStringByteDictionary.Clear());
}
[Test]
public void TestClearWithEmptyDisabledDictionaryThrowsInvalidOperationException()
{
bindableStringByteDictionary.Disabled = true;
Assert.Throws(typeof(InvalidOperationException), () => bindableStringByteDictionary.Clear());
}
[Test]
public void TestClearUpdatesCountProperty()
{
for (byte i = 0; i < 5; i++)
bindableStringByteDictionary.Add($"test{i}", i);
bindableStringByteDictionary.Clear();
Assert.AreEqual(0, bindableStringByteDictionary.Count);
}
[Test]
public void TestClearNotifiesSubscriber()
{
var items = new[]
{
new KeyValuePair<string, byte>("test0", 0),
new KeyValuePair<string, byte>("test1", 1),
new KeyValuePair<string, byte>("test2", 2),
new KeyValuePair<string, byte>("test3", 3),
new KeyValuePair<string, byte>("test4", 4)
};
foreach ((string key, byte value) in items)
bindableStringByteDictionary.Add(key, value);
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgs = null;
bindableStringByteDictionary.CollectionChanged += (_, args) => triggeredArgs = args;
bindableStringByteDictionary.Clear();
Assert.That(triggeredArgs.Action, Is.EqualTo(NotifyDictionaryChangedAction.Remove));
Assert.That(triggeredArgs.OldItems, Is.EquivalentTo(items));
}
[Test]
public void TestClearDoesNotNotifySubscriberBeforeClear()
{
for (byte i = 0; i < 5; i++)
bindableStringByteDictionary.Add($"test{i}", i);
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgs = null;
bindableStringByteDictionary.CollectionChanged += (_, args) => triggeredArgs = args;
Assert.That(triggeredArgs, Is.Null);
bindableStringByteDictionary.Clear();
}
[Test]
public void TestClearNotifiesSubscribers()
{
for (byte i = 0; i < 5; i++)
bindableStringByteDictionary.Add($"test{i}", i);
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgsA = null;
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgsB = null;
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgsC = null;
bindableStringByteDictionary.CollectionChanged += (_, args) => triggeredArgsA = args;
bindableStringByteDictionary.CollectionChanged += (_, args) => triggeredArgsB = args;
bindableStringByteDictionary.CollectionChanged += (_, args) => triggeredArgsC = args;
bindableStringByteDictionary.Clear();
Assert.That(triggeredArgsA, Is.Not.Null);
Assert.That(triggeredArgsB, Is.Not.Null);
Assert.That(triggeredArgsC, Is.Not.Null);
}
[Test]
public void TestClearNotifiesBoundBindable()
{
var bindableDict = new BindableDictionary<string, byte>();
bindableDict.BindTo(bindableStringByteDictionary);
for (byte i = 0; i < 5; i++)
bindableStringByteDictionary.Add($"testA{i}", i);
for (byte i = 0; i < 5; i++)
bindableDict.Add($"testB{i}", i);
bindableStringByteDictionary.Clear();
Assert.IsEmpty(bindableDict);
}
[Test]
public void TestClearNotifiesBoundBindables()
{
var bindableDictA = new BindableDictionary<string, byte>();
bindableDictA.BindTo(bindableStringByteDictionary);
var bindableDictB = new BindableDictionary<string, byte>();
bindableDictB.BindTo(bindableStringByteDictionary);
var bindableDictC = new BindableDictionary<string, byte>();
bindableDictC.BindTo(bindableStringByteDictionary);
for (byte i = 0; i < 5; i++)
bindableStringByteDictionary.Add($"testA{i}", i);
for (byte i = 0; i < 5; i++)
bindableDictA.Add($"testB{i}", i);
for (byte i = 0; i < 5; i++)
bindableDictB.Add($"testC{i}", i);
for (byte i = 0; i < 5; i++)
bindableDictC.Add($"testD{i}", i);
bindableStringByteDictionary.Clear();
Assert.Multiple(() =>
{
Assert.IsEmpty(bindableDictA);
Assert.IsEmpty(bindableDictB);
Assert.IsEmpty(bindableDictC);
});
}
[Test]
public void TestClearDoesNotNotifyBoundBindablesBeforeClear()
{
var bindableDictA = new BindableDictionary<string, byte>();
bindableDictA.BindTo(bindableStringByteDictionary);
var bindableDictB = new BindableDictionary<string, byte>();
bindableDictB.BindTo(bindableStringByteDictionary);
var bindableDictC = new BindableDictionary<string, byte>();
bindableDictC.BindTo(bindableStringByteDictionary);
for (byte i = 0; i < 5; i++)
bindableStringByteDictionary.Add($"testA{i}", i);
for (byte i = 0; i < 5; i++)
bindableDictA.Add($"testB{i}", i);
for (byte i = 0; i < 5; i++)
bindableDictB.Add($"testC{i}", i);
for (byte i = 0; i < 5; i++)
bindableDictC.Add($"testD{i}", i);
Assert.Multiple(() =>
{
Assert.IsNotEmpty(bindableDictA);
Assert.IsNotEmpty(bindableDictB);
Assert.IsNotEmpty(bindableDictC);
});
bindableStringByteDictionary.Clear();
}
#endregion
#region .Disabled
[Test]
public void TestDisabledWhenSetToTrueNotifiesSubscriber()
{
bool? isDisabled = null;
bindableStringByteDictionary.DisabledChanged += b => isDisabled = b;
bindableStringByteDictionary.Disabled = true;
Assert.Multiple(() =>
{
Assert.IsNotNull(isDisabled);
Assert.IsTrue(isDisabled.Value);
});
}
[Test]
public void TestDisabledWhenSetToTrueNotifiesSubscribers()
{
bool? isDisabledA = null;
bool? isDisabledB = null;
bool? isDisabledC = null;
bindableStringByteDictionary.DisabledChanged += b => isDisabledA = b;
bindableStringByteDictionary.DisabledChanged += b => isDisabledB = b;
bindableStringByteDictionary.DisabledChanged += b => isDisabledC = b;
bindableStringByteDictionary.Disabled = true;
Assert.Multiple(() =>
{
Assert.IsNotNull(isDisabledA);
Assert.IsTrue(isDisabledA.Value);
Assert.IsNotNull(isDisabledB);
Assert.IsTrue(isDisabledB.Value);
Assert.IsNotNull(isDisabledC);
Assert.IsTrue(isDisabledC.Value);
});
}
[Test]
public void TestDisabledWhenSetToCurrentValueDoesNotNotifySubscriber()
{
bindableStringByteDictionary.DisabledChanged += b => Assert.Fail();
bindableStringByteDictionary.Disabled = bindableStringByteDictionary.Disabled;
}
[Test]
public void TestDisabledWhenSetToCurrentValueDoesNotNotifySubscribers()
{
bindableStringByteDictionary.DisabledChanged += b => Assert.Fail();
bindableStringByteDictionary.DisabledChanged += b => Assert.Fail();
bindableStringByteDictionary.DisabledChanged += b => Assert.Fail();
bindableStringByteDictionary.Disabled = bindableStringByteDictionary.Disabled;
}
[Test]
public void TestDisabledNotifiesBoundDictionaries()
{
var dict = new BindableDictionary<string, byte>();
dict.BindTo(bindableStringByteDictionary);
bindableStringByteDictionary.Disabled = true;
Assert.IsTrue(dict.Disabled);
}
#endregion
#region .GetEnumberator()
[Test]
public void TestGetEnumeratorDoesNotReturnNull()
{
Assert.NotNull(bindableStringByteDictionary.GetEnumerator());
}
[Test]
public void TestGetEnumeratorWhenCopyConstructorIsUsedDoesNotReturnTheEnumeratorOfTheInputtedEnumerator()
{
var array = new[] { new KeyValuePair<string, byte>("", 0) };
var dict = new BindableDictionary<string, byte>(array);
var enumerator = dict.GetEnumerator();
Assert.AreNotEqual(array.GetEnumerator(), enumerator);
}
#endregion
#region .Description
[Test]
public void TestDescriptionWhenSetReturnsSetValue()
{
const string description = "The dictionary used for testing.";
bindableStringByteDictionary.Description = description;
Assert.AreEqual(description, bindableStringByteDictionary.Description);
}
#endregion
#region .Parse(obj)
[Test]
public void TestParseWithNullClearsDictionary()
{
bindableStringByteDictionary.Add("a item", 0);
bindableStringByteDictionary.Parse(null);
Assert.IsEmpty(bindableStringByteDictionary);
}
[Test]
public void TestParseWithArray()
{
var array = new[]
{
new KeyValuePair<string, byte>("testA", 0),
new KeyValuePair<string, byte>("testB", 1),
};
bindableStringByteDictionary.Parse(array);
CollectionAssert.AreEquivalent(array, bindableStringByteDictionary);
}
[Test]
public void TestParseWithDisabledDictionaryThrowsInvalidOperationException()
{
bindableStringByteDictionary.Disabled = true;
Assert.Multiple(() =>
{
Assert.Throws(typeof(InvalidOperationException), () => bindableStringByteDictionary.Parse(null));
Assert.Throws(typeof(InvalidOperationException), () => bindableStringByteDictionary.Parse(new[]
{
new KeyValuePair<string, byte>("test", 0),
new KeyValuePair<string, byte>("testabc", 1),
new KeyValuePair<string, byte>("asdasdasdasd", 1),
}));
});
}
[Test]
public void TestParseWithInvalidArgumentTypesThrowsArgumentException()
{
Assert.Multiple(() =>
{
Assert.Throws(typeof(ArgumentException), () => bindableStringByteDictionary.Parse(1));
Assert.Throws(typeof(ArgumentException), () => bindableStringByteDictionary.Parse(""));
Assert.Throws(typeof(ArgumentException), () => bindableStringByteDictionary.Parse(new object()));
Assert.Throws(typeof(ArgumentException), () => bindableStringByteDictionary.Parse(1.1));
Assert.Throws(typeof(ArgumentException), () => bindableStringByteDictionary.Parse(1.1f));
Assert.Throws(typeof(ArgumentException), () => bindableStringByteDictionary.Parse("test123"));
Assert.Throws(typeof(ArgumentException), () => bindableStringByteDictionary.Parse(29387L));
});
}
[Test]
public void TestParseWithNullNotifiesClearSubscribers()
{
var array = new[]
{
new KeyValuePair<string, byte>("testA", 0),
new KeyValuePair<string, byte>("testB", 1),
new KeyValuePair<string, byte>("testC", 2),
};
foreach ((string key, byte value) in array)
bindableStringByteDictionary.Add(key, value);
var triggeredArgs = new List<NotifyDictionaryChangedEventArgs<string, byte>>();
bindableStringByteDictionary.CollectionChanged += (_, args) => triggeredArgs.Add(args);
bindableStringByteDictionary.Parse(null);
Assert.That(triggeredArgs, Has.Count.EqualTo(1));
Assert.That(triggeredArgs.First().Action, Is.EqualTo(NotifyDictionaryChangedAction.Remove));
Assert.That(triggeredArgs.First().OldItems, Is.EquivalentTo(array));
}
[Test]
public void TestParseWithItemsNotifiesAddRangeAndClearSubscribers()
{
bindableStringByteDictionary.Add("test123", 0);
var array = new[]
{
new KeyValuePair<string, byte>("testA", 0),
new KeyValuePair<string, byte>("testB", 1),
};
var triggeredArgs = new List<NotifyDictionaryChangedEventArgs<string, byte>>();
bindableStringByteDictionary.CollectionChanged += (_, args) => triggeredArgs.Add(args);
bindableStringByteDictionary.Parse(array);
Assert.That(triggeredArgs, Has.Count.EqualTo(2));
Assert.That(triggeredArgs.First().Action, Is.EqualTo(NotifyDictionaryChangedAction.Remove));
Assert.That(triggeredArgs.First().OldItems, Is.EquivalentTo(new KeyValuePair<string, byte>("test123", 0).Yield()));
Assert.That(triggeredArgs.ElementAt(1).Action, Is.EqualTo(NotifyDictionaryChangedAction.Add));
Assert.That(triggeredArgs.ElementAt(1).NewItems, Is.EquivalentTo(array));
}
#endregion
#region GetBoundCopy()
[Test]
public void TestBoundCopyWithAdd()
{
var boundCopy = bindableStringByteDictionary.GetBoundCopy();
NotifyDictionaryChangedEventArgs<string, byte> triggeredArgs = null;
boundCopy.CollectionChanged += (_, args) => triggeredArgs = args;
bindableStringByteDictionary.Add("test", 0);
Assert.That(triggeredArgs.Action, Is.EqualTo(NotifyDictionaryChangedAction.Add));
Assert.That(triggeredArgs.NewItems, Is.EquivalentTo(new KeyValuePair<string, byte>("test", 0).Yield()));
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Client
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Client;
/// <summary>
/// Handles client features based on protocol version and feature flags.
/// </summary>
internal class ClientFeatures
{
/** Bit mask of all features. */
public static readonly byte[] AllFeatures = GetAllFeatures();
/** Current features. */
public static readonly ClientFeatures CurrentFeatures =
new ClientFeatures(ClientSocket.CurrentProtocolVersion, new BitArray(AllFeatures));
/** */
private static readonly Dictionary<ClientOp, ClientProtocolVersion> OpVersion =
new Dictionary<ClientOp, ClientProtocolVersion>
{
{ClientOp.CachePartitions, new ClientProtocolVersion(1, 4, 0)},
{ClientOp.ClusterIsActive, new ClientProtocolVersion(1, 5, 0)},
{ClientOp.ClusterChangeState, new ClientProtocolVersion(1, 5, 0)},
{ClientOp.ClusterChangeWalState, new ClientProtocolVersion(1, 5, 0)},
{ClientOp.ClusterGetWalState, new ClientProtocolVersion(1, 5, 0)},
{ClientOp.TxStart, new ClientProtocolVersion(1, 5, 0)},
{ClientOp.TxEnd, new ClientProtocolVersion(1, 5, 0)},
};
/** */
private static readonly Dictionary<ClientOp, ClientBitmaskFeature> OpFeature =
new Dictionary<ClientOp, ClientBitmaskFeature>
{
{ClientOp.ClusterGroupGetNodesEndpoints, ClientBitmaskFeature.ClusterGroupGetNodesEndpoints},
{ClientOp.ComputeTaskExecute, ClientBitmaskFeature.ExecuteTaskByName},
{ClientOp.ClusterGroupGetNodeIds, ClientBitmaskFeature.ClusterGroups},
{ClientOp.ClusterGroupGetNodesInfo, ClientBitmaskFeature.ClusterGroups}
};
/** */
private readonly ClientProtocolVersion _protocolVersion;
/** */
private readonly BitArray _features;
/// <summary>
/// Initializes a new instance of <see cref="ClientFeatures"/>.
/// </summary>
public ClientFeatures(ClientProtocolVersion protocolVersion, BitArray features)
{
_protocolVersion = protocolVersion;
_features = features;
}
/// <summary>
/// Returns a value indicating whether specified feature is supported.
/// </summary>
public bool HasFeature(ClientBitmaskFeature feature)
{
var index = (int) feature;
return _features != null && index >= 0 && index < _features.Count && _features.Get(index);
}
/// <summary>
/// Returns a value indicating whether specified operation is supported.
/// </summary>
public bool HasOp(ClientOp op)
{
return ValidateOp(op, false);
}
/// <summary>
/// Checks whether WithExpiryPolicy request flag is supported. Throws an exception when not supported.
/// </summary>
public void ValidateWithExpiryPolicyFlag()
{
var requiredVersion = ClientSocket.Ver150;
if (_protocolVersion < requiredVersion)
{
ThrowMinimumVersionException("WithExpiryPolicy", requiredVersion);
}
}
/// <summary>
/// Returns a value indicating whether <see cref="QueryField.Precision"/> and <see cref="QueryField.Scale"/>
/// are supported.
/// </summary>
public bool HasQueryFieldPrecisionAndScale()
{
return _protocolVersion >= ClientSocket.Ver120;
}
/// <summary>
/// Returns a value indicating whether <see cref="CacheConfiguration.ExpiryPolicyFactory"/> is supported.
/// </summary>
public bool HasCacheConfigurationExpiryPolicyFactory()
{
return _protocolVersion >= ClientSocket.Ver160;
}
/// <summary>
/// Gets minimum protocol version that is required to perform specified operation.
/// </summary>
/// <param name="op">Operation.</param>
/// <returns>Minimum protocol version.</returns>
public static ClientProtocolVersion GetMinVersion(ClientOp op)
{
ClientProtocolVersion minVersion;
return OpVersion.TryGetValue(op, out minVersion)
? minVersion
: ClientSocket.Ver100;
}
/// <summary>
/// Validates specified op code against current protocol version and features.
/// </summary>
/// <param name="operation">Operation.</param>
public void ValidateOp(ClientOp operation)
{
ValidateOp(operation, true);
}
/// <summary>
/// Validates specified op code against current protocol version and features.
/// </summary>
private bool ValidateOp(ClientOp operation, bool shouldThrow)
{
var requiredProtocolVersion = GetMinVersion(operation);
if (_protocolVersion < requiredProtocolVersion)
{
if (shouldThrow)
{
ThrowMinimumVersionException(operation, requiredProtocolVersion);
}
return false;
}
var requiredFeature = GetFeature(operation);
if (requiredFeature != null && (_features == null || !_features.Get((int) requiredFeature.Value)))
{
if (shouldThrow)
{
throw new IgniteClientException(string.Format(
"Operation {0} is not supported by the server. Feature {1} is missing.",
operation, requiredFeature.Value));
}
return false;
}
return true;
}
/// <summary>
/// Throws minimum version exception.
/// </summary>
private void ThrowMinimumVersionException(object operation, ClientProtocolVersion requiredProtocolVersion)
{
var message = string.Format("Operation {0} is not supported by protocol version {1}. " +
"Minimum protocol version required is {2}.",
operation, _protocolVersion, requiredProtocolVersion);
throw new IgniteClientException(message);
}
/// <summary>
/// Gets <see cref="ClientBitmaskFeature"/> that is required to perform specified operation.
/// </summary>
/// <param name="op">Operation.</param>
/// <returns>Required feature flag, or null.</returns>
private static ClientBitmaskFeature? GetFeature(ClientOp op)
{
ClientBitmaskFeature feature;
return OpFeature.TryGetValue(op, out feature)
? feature
: (ClientBitmaskFeature?) null;
}
/// <summary>
/// Gets a bit array with all supported features.
/// </summary>
private static byte[] GetAllFeatures()
{
var values = Enum.GetValues(typeof(ClientBitmaskFeature))
.Cast<int>()
.ToArray();
var bits = new BitArray(values.Max() + 1);
foreach (var feature in values)
{
bits.Set(feature, true);
}
var bytes = new byte[1 + values.Length / 8];
bits.CopyTo(bytes, 0);
return bytes;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Diagnostics
namespace test
{
public class Program
{
public void Main(string[] args)
{
Console.WriteLine("Hello World");
// play with variables
// declaration
int num = 452147483648;
sbyte smallnum = 126;
ulong biggestPossible = 184467440737039;
// the ulong is the longest one
sbyte a = 80;
sbyte s = a + 10;
int result = a + s;
bool test = true;
float temp;
string name = "Andre";
char firstLetter = "A";
int[] source = (3,4,5,6,2,1,34,3);
var limit = 5;
var query = from item in source where item <= limit select item;
foreach (int s in source) {
Console.WriteLine(s);
}
@"the A staff before the string is VERBATUM to escape anything special in the string
also the spaces
as many as you like"
}
}
}
// accessing the text and modifing it
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class textController : MonoBehaviour {
public Text text;
void Start () {
text.text = "Text to display on the screen!!"
}
void Update () {
if (Input.GetKeyDown("space")) {
text.text = "This is the changed version of the text on space press";
}
}
}
// completed game of choice with different states to be changed
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class TextController : MonoBehaviour {
public Text text;
private enum States {cell, sheet_0, sheet_1, lock_0, lock_1, mirror, cell_mirror, freedom};
private States myState;
void Start() {
myState = States.cell;
}
void Update() {
print (myState);
switch (myState) {
case States.cell:
state_cell();
break;
case States.sheet_0:
state_sheet_0();
break;
case States.sheet_1:
state_sheet_1();
break;
case States.lock_1:
state_lock_1();
break;
case States.lock_0:
state_lock_0();
break;
case States.mirror:
state_mirror();
break;
}
}
void state_cell() {
text.text = "Here is the beging of the game \n" +
"press s to view sheets, m to see the mirror and l to view the lock";
if (Input.GetKeyDown(KeyCode.S)) {
myState = States.sheet_0;
}
else if (Input.GetKeyDown(KeyCode.M)) {
myState = States.mirror;
}
else if (Input.GetKeyDown(KeyCode.L)) {
myState = States.lock_0;
}
}
void state_sheet_0() {
text.text = "You are next to the sheets \n" +
"press n to view further, m to see the mirror and l to view the lock, " +
"and c to get back where you where before";
if (Input.GetKeyDown(KeyCode.N)) {
myState = States.sheet_1;
}
else if (Input.GetKeyDown(KeyCode.M)) {
myState = States.mirror;
}
else if (Input.GetKeyDown(KeyCode.L)) {
myState = States.lock_0;
}
else if (Input.GetKeyDown(KeyCode.C)) {
myState = States.cell;
}
}
void state_sheet_1() {
text.text = "You are next to the sheets \n" +
"press s to get back to old sheets, m to see the mirror and l to view the lock, " +
"and c to get back where you where before";
if (Input.GetKeyDown(KeyCode.S)) {
myState = States.sheet_0;
}
else if (Input.GetKeyDown(KeyCode.M)) {
myState = States.mirror;
}
else if (Input.GetKeyDown(KeyCode.L)) {
myState = States.lock_0;
}
else if (Input.GetKeyDown(KeyCode.C)) {
myState = States.cell;
}
}
void state_lock_0() {
text.text = "You are next to the cell lock \n" +
"press s to get back to old sheets, m to see the mirror, " +
"and c to get back where you where before \n" +
" press n to look closer at the lock";
if (Input.GetKeyDown(KeyCode.S)) {
myState = States.sheet_0;
}
else if (Input.GetKeyDown(KeyCode.M)) {
myState = States.mirror;
}
else if (Input.GetKeyDown(KeyCode.N)) {
myState = States.lock_1;
}
else if (Input.GetKeyDown(KeyCode.C)) {
myState = States.cell;
}
}
void state_lock_1() {
text.text = "You are next to the cell lock \n" +
"press s to get back to old sheets, m to see the mirror, " +
"and c to get back where you where before, press l to go to old lock";
if (Input.GetKeyDown(KeyCode.S)) {
myState = States.sheet_0;
}
else if (Input.GetKeyDown(KeyCode.M)) {
myState = States.mirror;
}
else if (Input.GetKeyDown(KeyCode.L)) {
myState = States.lock_0;
}
else if (Input.GetKeyDown(KeyCode.C)) {
myState = States.cell;
}
}
void state_lock_1() {
text.text = "Well you are infront of the mirror, look pretty shitty today...";
if (Input.GetKeyDown(KeyCode.S)) {
myState = States.sheet_0;
}
else if (Input.GetKeyDown(KeyCode.L)) {
myState = States.lock_0;
}
else if (Input.GetKeyDown(KeyCode.C)) {
myState = States.cell;
}
}
}
// logic for the number game
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class NumberWizard : MonoBehaviour {
int max;
int min;
int guess;
int compGuess = 10;
public Text foo;
// Use this for initialization
void Start () {
StartGame();
}
void StartGame () {
max = 1001;
min = 1;
NextGuess();
}
public void GuessLower() {
max = guess;
NextGuess();
}
public void GuessHigher() {
min = guess;
NextGuess();
}
void NextGuess () {
guess = Random.Range(min, max+1);
compGuess = compGuess - 1;
foo.text = guess.ToString();
if(compGuess <= 0) {
Application.LoadLevel("Win");
}
}
}
| |
// 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.Globalization;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Reflection
{
[Flags]
internal enum MdSigCallingConvention : byte
{
CallConvMask = 0x0f, // Calling convention is bottom 4 bits
Default = 0x00,
C = 0x01,
StdCall = 0x02,
ThisCall = 0x03,
FastCall = 0x04,
Vararg = 0x05,
Field = 0x06,
LocalSig = 0x07,
Property = 0x08,
Unmgd = 0x09,
GenericInst = 0x0a, // generic method instantiation
Generic = 0x10, // Generic method sig with explicit number of type arguments (precedes ordinary parameter count)
HasThis = 0x20, // Top bit indicates a 'this' parameter
ExplicitThis = 0x40, // This parameter is explicitly in the signature
}
[Flags]
internal enum PInvokeAttributes
{
NoMangle = 0x0001,
CharSetMask = 0x0006,
CharSetNotSpec = 0x0000,
CharSetAnsi = 0x0002,
CharSetUnicode = 0x0004,
CharSetAuto = 0x0006,
BestFitUseAssem = 0x0000,
BestFitEnabled = 0x0010,
BestFitDisabled = 0x0020,
BestFitMask = 0x0030,
ThrowOnUnmappableCharUseAssem = 0x0000,
ThrowOnUnmappableCharEnabled = 0x1000,
ThrowOnUnmappableCharDisabled = 0x2000,
ThrowOnUnmappableCharMask = 0x3000,
SupportsLastError = 0x0040,
CallConvMask = 0x0700,
CallConvWinapi = 0x0100,
CallConvCdecl = 0x0200,
CallConvStdcall = 0x0300,
CallConvThiscall = 0x0400,
CallConvFastcall = 0x0500,
MaxValue = 0xFFFF,
}
[Flags]
internal enum MethodSemanticsAttributes
{
Setter = 0x0001,
Getter = 0x0002,
Other = 0x0004,
AddOn = 0x0008,
RemoveOn = 0x0010,
Fire = 0x0020,
}
internal enum MetadataTokenType
{
Module = 0x00000000,
TypeRef = 0x01000000,
TypeDef = 0x02000000,
FieldDef = 0x04000000,
MethodDef = 0x06000000,
ParamDef = 0x08000000,
InterfaceImpl = 0x09000000,
MemberRef = 0x0a000000,
CustomAttribute = 0x0c000000,
Permission = 0x0e000000,
Signature = 0x11000000,
Event = 0x14000000,
Property = 0x17000000,
ModuleRef = 0x1a000000,
TypeSpec = 0x1b000000,
Assembly = 0x20000000,
AssemblyRef = 0x23000000,
File = 0x26000000,
ExportedType = 0x27000000,
ManifestResource = 0x28000000,
GenericPar = 0x2a000000,
MethodSpec = 0x2b000000,
String = 0x70000000,
Name = 0x71000000,
BaseType = 0x72000000,
Invalid = 0x7FFFFFFF,
}
internal readonly struct ConstArray
{
// Keep the definition in sync with vm\ManagedMdImport.hpp
internal readonly int m_length;
internal readonly IntPtr m_constArray;
public IntPtr Signature => m_constArray;
public int Length => m_length;
public byte this[int index]
{
get
{
if (index < 0 || index >= m_length)
throw new IndexOutOfRangeException();
unsafe
{
return ((byte*)m_constArray.ToPointer())[index];
}
}
}
}
internal struct MetadataToken
{
public int Value;
public static implicit operator int(MetadataToken token) => token.Value;
public static implicit operator MetadataToken(int token) => new MetadataToken(token);
public static bool IsTokenOfType(int token, params MetadataTokenType[] types)
{
for (int i = 0; i < types.Length; i++)
{
if ((int)(token & 0xFF000000) == (int)types[i])
return true;
}
return false;
}
public static bool IsNullToken(int token) => (token & 0x00FFFFFF) == 0;
public MetadataToken(int token) { Value = token; }
public bool IsGlobalTypeDefToken => Value == 0x02000001;
public MetadataTokenType TokenType => (MetadataTokenType)(Value & 0xFF000000);
public bool IsTypeRef => TokenType == MetadataTokenType.TypeRef;
public bool IsTypeDef => TokenType == MetadataTokenType.TypeDef;
public bool IsFieldDef => TokenType == MetadataTokenType.FieldDef;
public bool IsMethodDef => TokenType == MetadataTokenType.MethodDef;
public bool IsMemberRef => TokenType == MetadataTokenType.MemberRef;
public bool IsEvent => TokenType == MetadataTokenType.Event;
public bool IsProperty => TokenType == MetadataTokenType.Property;
public bool IsParamDef => TokenType == MetadataTokenType.ParamDef;
public bool IsTypeSpec => TokenType == MetadataTokenType.TypeSpec;
public bool IsMethodSpec => TokenType == MetadataTokenType.MethodSpec;
public bool IsString => TokenType == MetadataTokenType.String;
public bool IsSignature => TokenType == MetadataTokenType.Signature;
public bool IsModule => TokenType == MetadataTokenType.Module;
public bool IsAssembly => TokenType == MetadataTokenType.Assembly;
public bool IsGenericPar => TokenType == MetadataTokenType.GenericPar;
public override string ToString() => string.Format(CultureInfo.InvariantCulture, "0x{0:x8}", Value);
}
internal unsafe struct MetadataEnumResult
{
// Keep the definition in sync with vm\ManagedMdImport.hpp
private int[] largeResult;
private int length;
private fixed int smallResult[16];
public int Length => length;
public int this[int index]
{
get
{
Debug.Assert(0 <= index && index < Length);
if (largeResult != null)
return largeResult[index];
fixed (int* p = smallResult)
return p[index];
}
}
}
internal readonly struct MetadataImport
{
private readonly IntPtr m_metadataImport2;
private readonly object? m_keepalive;
#region Override methods from Object
internal static readonly MetadataImport EmptyImport = new MetadataImport((IntPtr)0, null);
public override int GetHashCode()
{
return ValueType.GetHashCodeOfPtr(m_metadataImport2);
}
public override bool Equals(object? obj)
{
if (!(obj is MetadataImport))
return false;
return Equals((MetadataImport)obj);
}
private bool Equals(MetadataImport import)
{
return import.m_metadataImport2 == m_metadataImport2;
}
#endregion
#region Static Members
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _GetMarshalAs(IntPtr pNativeType, int cNativeType, out int unmanagedType, out int safeArraySubType, out string? safeArrayUserDefinedSubType,
out int arraySubType, out int sizeParamIndex, out int sizeConst, out string? marshalType, out string? marshalCookie,
out int iidParamIndex);
internal static void GetMarshalAs(ConstArray nativeType,
out UnmanagedType unmanagedType, out VarEnum safeArraySubType, out string? safeArrayUserDefinedSubType,
out UnmanagedType arraySubType, out int sizeParamIndex, out int sizeConst, out string? marshalType, out string? marshalCookie,
out int iidParamIndex)
{
int _unmanagedType, _safeArraySubType, _arraySubType;
_GetMarshalAs(nativeType.Signature, (int)nativeType.Length,
out _unmanagedType, out _safeArraySubType, out safeArrayUserDefinedSubType,
out _arraySubType, out sizeParamIndex, out sizeConst, out marshalType, out marshalCookie,
out iidParamIndex);
unmanagedType = (UnmanagedType)_unmanagedType;
safeArraySubType = (VarEnum)_safeArraySubType;
arraySubType = (UnmanagedType)_arraySubType;
}
#endregion
#region Internal Static Members
internal static void ThrowError(int hResult)
{
throw new MetadataException(hResult);
}
#endregion
#region Constructor
internal MetadataImport(IntPtr metadataImport2, object? keepalive)
{
m_metadataImport2 = metadataImport2;
m_keepalive = keepalive;
}
#endregion
#region FCalls
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _Enum(IntPtr scope, int type, int parent, out MetadataEnumResult result);
public void Enum(MetadataTokenType type, int parent, out MetadataEnumResult result)
{
_Enum(m_metadataImport2, (int)type, parent, out result);
}
public void EnumNestedTypes(int mdTypeDef, out MetadataEnumResult result)
{
Enum(MetadataTokenType.TypeDef, mdTypeDef, out result);
}
public void EnumCustomAttributes(int mdToken, out MetadataEnumResult result)
{
Enum(MetadataTokenType.CustomAttribute, mdToken, out result);
}
public void EnumParams(int mdMethodDef, out MetadataEnumResult result)
{
Enum(MetadataTokenType.ParamDef, mdMethodDef, out result);
}
public void EnumFields(int mdTypeDef, out MetadataEnumResult result)
{
Enum(MetadataTokenType.FieldDef, mdTypeDef, out result);
}
public void EnumProperties(int mdTypeDef, out MetadataEnumResult result)
{
Enum(MetadataTokenType.Property, mdTypeDef, out result);
}
public void EnumEvents(int mdTypeDef, out MetadataEnumResult result)
{
Enum(MetadataTokenType.Event, mdTypeDef, out result);
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern string? _GetDefaultValue(IntPtr scope, int mdToken, out long value, out int length, out int corElementType);
public string? GetDefaultValue(int mdToken, out long value, out int length, out CorElementType corElementType)
{
int _corElementType;
string? stringVal = _GetDefaultValue(m_metadataImport2, mdToken, out value, out length, out _corElementType);
corElementType = (CorElementType)_corElementType;
return stringVal;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern unsafe void _GetUserString(IntPtr scope, int mdToken, void** name, out int length);
public unsafe string? GetUserString(int mdToken)
{
void* name;
int length;
_GetUserString(m_metadataImport2, mdToken, &name, out length);
return name != null ?
new string((char*)name, 0, length) :
null;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern unsafe void _GetName(IntPtr scope, int mdToken, void** name);
public unsafe MdUtf8String GetName(int mdToken)
{
void* name;
_GetName(m_metadataImport2, mdToken, &name);
return new MdUtf8String(name);
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern unsafe void _GetNamespace(IntPtr scope, int mdToken, void** namesp);
public unsafe MdUtf8String GetNamespace(int mdToken)
{
void* namesp;
_GetNamespace(m_metadataImport2, mdToken, &namesp);
return new MdUtf8String(namesp);
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern unsafe void _GetEventProps(IntPtr scope, int mdToken, void** name, out int eventAttributes);
public unsafe void GetEventProps(int mdToken, out void* name, out EventAttributes eventAttributes)
{
int _eventAttributes;
void* _name;
_GetEventProps(m_metadataImport2, mdToken, &_name, out _eventAttributes);
name = _name;
eventAttributes = (EventAttributes)_eventAttributes;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _GetFieldDefProps(IntPtr scope, int mdToken, out int fieldAttributes);
public void GetFieldDefProps(int mdToken, out FieldAttributes fieldAttributes)
{
int _fieldAttributes;
_GetFieldDefProps(m_metadataImport2, mdToken, out _fieldAttributes);
fieldAttributes = (FieldAttributes)_fieldAttributes;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern unsafe void _GetPropertyProps(IntPtr scope,
int mdToken, void** name, out int propertyAttributes, out ConstArray signature);
public unsafe void GetPropertyProps(int mdToken, out void* name, out PropertyAttributes propertyAttributes, out ConstArray signature)
{
int _propertyAttributes;
void* _name;
_GetPropertyProps(m_metadataImport2, mdToken, &_name, out _propertyAttributes, out signature);
name = _name;
propertyAttributes = (PropertyAttributes)_propertyAttributes;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _GetParentToken(IntPtr scope,
int mdToken, out int tkParent);
public int GetParentToken(int tkToken)
{
int tkParent;
_GetParentToken(m_metadataImport2, tkToken, out tkParent);
return tkParent;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _GetParamDefProps(IntPtr scope,
int parameterToken, out int sequence, out int attributes);
public void GetParamDefProps(int parameterToken, out int sequence, out ParameterAttributes attributes)
{
int _attributes;
_GetParamDefProps(m_metadataImport2, parameterToken, out sequence, out _attributes);
attributes = (ParameterAttributes)_attributes;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _GetGenericParamProps(IntPtr scope,
int genericParameter,
out int flags);
public void GetGenericParamProps(
int genericParameter,
out GenericParameterAttributes attributes)
{
int _attributes;
_GetGenericParamProps(m_metadataImport2, genericParameter, out _attributes);
attributes = (GenericParameterAttributes)_attributes;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _GetScopeProps(IntPtr scope,
out Guid mvid);
public void GetScopeProps(
out Guid mvid)
{
_GetScopeProps(m_metadataImport2, out mvid);
}
public ConstArray GetMethodSignature(MetadataToken token)
{
if (token.IsMemberRef)
return GetMemberRefProps(token);
return GetSigOfMethodDef(token);
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _GetSigOfMethodDef(IntPtr scope,
int methodToken,
ref ConstArray signature);
public ConstArray GetSigOfMethodDef(int methodToken)
{
ConstArray signature = new ConstArray();
_GetSigOfMethodDef(m_metadataImport2, methodToken, ref signature);
return signature;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _GetSignatureFromToken(IntPtr scope,
int methodToken,
ref ConstArray signature);
public ConstArray GetSignatureFromToken(int token)
{
ConstArray signature = new ConstArray();
_GetSignatureFromToken(m_metadataImport2, token, ref signature);
return signature;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _GetMemberRefProps(IntPtr scope,
int memberTokenRef,
out ConstArray signature);
public ConstArray GetMemberRefProps(int memberTokenRef)
{
ConstArray signature;
_GetMemberRefProps(m_metadataImport2, memberTokenRef, out signature);
return signature;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _GetCustomAttributeProps(IntPtr scope,
int customAttributeToken,
out int constructorToken,
out ConstArray signature);
public void GetCustomAttributeProps(
int customAttributeToken,
out int constructorToken,
out ConstArray signature)
{
_GetCustomAttributeProps(m_metadataImport2, customAttributeToken,
out constructorToken, out signature);
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _GetClassLayout(IntPtr scope,
int typeTokenDef, out int packSize, out int classSize);
public void GetClassLayout(
int typeTokenDef,
out int packSize,
out int classSize)
{
_GetClassLayout(m_metadataImport2, typeTokenDef, out packSize, out classSize);
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern bool _GetFieldOffset(IntPtr scope,
int typeTokenDef, int fieldTokenDef, out int offset);
public bool GetFieldOffset(
int typeTokenDef,
int fieldTokenDef,
out int offset)
{
return _GetFieldOffset(m_metadataImport2, typeTokenDef, fieldTokenDef, out offset);
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _GetSigOfFieldDef(IntPtr scope,
int fieldToken,
ref ConstArray fieldMarshal);
public ConstArray GetSigOfFieldDef(int fieldToken)
{
ConstArray fieldMarshal = new ConstArray();
_GetSigOfFieldDef(m_metadataImport2, fieldToken, ref fieldMarshal);
return fieldMarshal;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _GetFieldMarshal(IntPtr scope,
int fieldToken,
ref ConstArray fieldMarshal);
public ConstArray GetFieldMarshal(int fieldToken)
{
ConstArray fieldMarshal = new ConstArray();
_GetFieldMarshal(m_metadataImport2, fieldToken, ref fieldMarshal);
return fieldMarshal;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern unsafe void _GetPInvokeMap(IntPtr scope,
int token,
out int attributes,
void** importName,
void** importDll);
public unsafe void GetPInvokeMap(
int token,
out PInvokeAttributes attributes,
out string importName,
out string importDll)
{
int _attributes;
void* _importName, _importDll;
_GetPInvokeMap(m_metadataImport2, token, out _attributes, &_importName, &_importDll);
importName = new MdUtf8String(_importName).ToString();
importDll = new MdUtf8String(_importDll).ToString();
attributes = (PInvokeAttributes)_attributes;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern bool _IsValidToken(IntPtr scope, int token);
public bool IsValidToken(int token)
{
return _IsValidToken(m_metadataImport2, token);
}
#endregion
}
internal class MetadataException : Exception
{
private int m_hr;
internal MetadataException(int hr) { m_hr = hr; }
public override string ToString()
{
return string.Format("MetadataException HResult = {0:x}.", m_hr);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.IO;
using System.Text;
namespace Microsoft.Azure.Batch
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Batch.Common;
using Microsoft.Azure.Batch.FileStaging;
using Microsoft.Rest.Azure;
using Models = Microsoft.Azure.Batch.Protocol.Models;
/// <summary>
/// An Azure Batch task. A task is a piece of work that is associated with a job and runs on a compute node.
/// </summary>
public partial class CloudTask : IRefreshable
{
#region // Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CloudTask"/> class.
/// </summary>
/// <param name="id">The id of the task.</param>
/// <param name="commandline">The command line of the task.</param>
/// <remarks>The newly created CloudTask is initially not associated with any task in the Batch service.
/// To associate it with a job and submit it to the Batch service, use <see cref="JobOperations.AddTaskAsync(string, IEnumerable{CloudTask}, BatchClientParallelOptions, ConcurrentBag{ConcurrentDictionary{Type, IFileStagingArtifact}}, TimeSpan?, IEnumerable{BatchClientBehavior})"/>.</remarks>
public CloudTask(string id, string commandline)
{
this.propertyContainer = new PropertyContainer();
// set initial conditions
this.Id = id;
this.CommandLine = commandline;
// set up custom behaviors
InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, null);
}
#endregion // Constructors
internal BindingState BindingState
{
get { return this.propertyContainer.BindingState; }
}
/// <summary>
/// Stages the files listed in the <see cref="FilesToStage"/> list.
/// </summary>
/// <param name="allFileStagingArtifacts">An optional collection to customize and receive information about the file staging process.
/// For more information see <see cref="IFileStagingArtifact"/>.</param>
/// <returns>A <see cref="System.Threading.Tasks.Task"/> that represents the asynchronous operation.</returns>
/// <remarks>The staging operation runs asynchronously.</remarks>
public async System.Threading.Tasks.Task StageFilesAsync(ConcurrentDictionary<Type, IFileStagingArtifact> allFileStagingArtifacts = null)
{
// stage all these files
// TODO: align this copy with threadsafe implementation of the IList<>
List<IFileStagingProvider> allFiles = this.FilesToStage == null ? new List<IFileStagingProvider>() : new List<IFileStagingProvider>(this.FilesToStage);
//TODO: There is a threading issue doing this - expose a change tracking box directly and use a lock?
if (this.FilesToStage != null && this.ResourceFiles == null)
{
this.ResourceFiles = new List<ResourceFile>(); //We're about to have some resource files
}
// now we have all files, send off to file staging machine
System.Threading.Tasks.Task fileStagingTask = FileStagingUtils.StageFilesAsync(allFiles, allFileStagingArtifacts);
// wait for file staging async task
await fileStagingTask.ConfigureAwait(continueOnCapturedContext: false);
// now update Task with its new ResourceFiles
foreach (IFileStagingProvider curFile in allFiles)
{
IEnumerable<ResourceFile> curStagedFiles = curFile.StagedFiles;
foreach (ResourceFile curStagedFile in curStagedFiles)
{
this.ResourceFiles.Add(curStagedFile);
}
}
}
/// <summary>
/// Stages the files listed in the <see cref="FilesToStage"/> list.
/// </summary>
/// <returns>A collection of information about the file staging process.
/// For more information see <see cref="IFileStagingArtifact"/>.</returns>
/// <remarks>This is a blocking operation. For a non-blocking equivalent, see <see cref="StageFilesAsync"/>.</remarks>
public ConcurrentDictionary<Type, IFileStagingArtifact> StageFiles()
{
ConcurrentDictionary<Type, IFileStagingArtifact> allFileStagingArtifacts = new ConcurrentDictionary<Type,IFileStagingArtifact>();
Task asyncTask = StageFilesAsync(allFileStagingArtifacts);
asyncTask.WaitAndUnaggregateException();
return allFileStagingArtifacts;
}
/// <summary>
/// Enumerates the files in the <see cref="CloudTask"/>'s directory on its compute node.
/// </summary>
/// <param name="recursive">If true, performs a recursive list of all files of the task. If false, returns only the files in the root task directory.</param>
/// <param name="detailLevel">A <see cref="DetailLevel"/> used for filtering the list and for controlling which properties are retrieved from the service.</param>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/> and <paramref name="detailLevel"/>.</param>
/// <returns>An <see cref="IPagedEnumerable{NodeFile}"/> that can be used to enumerate files asynchronously or synchronously.</returns>
/// <remarks>This method returns immediately; the file data is retrieved from the Batch service only when the collection is enumerated.
/// Retrieval is non-atomic; file data is retrieved in pages during enumeration of the collection.</remarks>
public IPagedEnumerable<NodeFile> ListNodeFiles(bool? recursive = null, DetailLevel detailLevel = null, IEnumerable<BatchClientBehavior> additionalBehaviors = null)
{
UtilitiesInternal.ThrowOnUnbound(this.propertyContainer.BindingState);
// craft the behavior manager for this call
BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors);
IPagedEnumerable<NodeFile> enumerator = this.parentBatchClient.JobOperations.ListNodeFilesImpl(this.parentJobId, this.Id, recursive, bhMgr, detailLevel);
return enumerator;
}
/// <summary>
/// Enumerates the subtasks of the multi-instance <see cref="CloudTask"/>.
/// </summary>
/// <param name="detailLevel">A <see cref="DetailLevel"/> used for filtering the list and for controlling which properties are retrieved from the service.</param>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/> and <paramref name="detailLevel"/>.</param>
/// <returns>An <see cref="IPagedEnumerable{SubtaskInformation}"/> that can be used to enumerate files asynchronously or synchronously.</returns>
/// <remarks>This method returns immediately; the file data is retrieved from the Batch service only when the collection is enumerated.
/// Retrieval is non-atomic; file data is retrieved in pages during enumeration of the collection.</remarks>
public IPagedEnumerable<SubtaskInformation> ListSubtasks(DetailLevel detailLevel = null, IEnumerable<BatchClientBehavior> additionalBehaviors = null)
{
UtilitiesInternal.ThrowOnUnbound(this.propertyContainer.BindingState);
// craft the behavior manager for this call
BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors);
IPagedEnumerable<SubtaskInformation> enumerator = this.parentBatchClient.JobOperations.ListSubtasksImpl(this.parentJobId, this.Id, bhMgr, detailLevel);
return enumerator;
}
/// <summary>
/// Commits all pending changes to this <see cref="CloudTask" /> to the Azure Batch service.
/// </summary>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param>
/// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns>
/// <remarks>The commit operation runs asynchronously.</remarks>
public async System.Threading.Tasks.Task CommitAsync(IEnumerable<BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken))
{
this.propertyContainer.IsReadOnly = true;
// craft the behavior manager for this call
BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors);
if (BindingState.Unbound == this.propertyContainer.BindingState)
{
//TODO: Implement task submission via .Commit here
UtilitiesInternal.ThrowOnUnbound(this.propertyContainer.BindingState);
}
else
{
Models.TaskConstraints protoTaskConstraints = UtilitiesInternal.CreateObjectWithNullCheck(this.Constraints, o => o.GetTransportObject());
System.Threading.Tasks.Task<AzureOperationHeaderResponse<Models.TaskUpdateHeaders>> asyncTaskUpdate =
this.parentBatchClient.ProtocolLayer.UpdateTask(
this.parentJobId,
this.Id,
protoTaskConstraints,
bhMgr,
cancellationToken);
await asyncTaskUpdate.ConfigureAwait(continueOnCapturedContext: false);
}
}
/// <summary>
/// Commits all pending changes to this <see cref="CloudTask" /> to the Azure Batch service.
/// </summary>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
/// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns>
/// <remarks>
/// <para>This is a blocking operation. For a non-blocking equivalent, see <see cref="CommitAsync"/>.</para>
/// </remarks>
public void Commit(IEnumerable<BatchClientBehavior> additionalBehaviors = null)
{
Task asyncTask = CommitAsync(additionalBehaviors);
asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors);
}
/// <summary>
/// Terminates this <see cref="CloudTask"/>, marking it as completed.
/// </summary>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param>
/// <returns>A <see cref="Task"/> object that represents the asynchronous operation.</returns>
/// <remarks>The terminate operation runs asynchronously.</remarks>
public System.Threading.Tasks.Task TerminateAsync(IEnumerable<BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken))
{
UtilitiesInternal.ThrowOnUnbound(this.propertyContainer.BindingState);
// create the behavior manager
BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors);
System.Threading.Tasks.Task asyncTask = this.parentBatchClient.ProtocolLayer.TerminateTask(
this.parentJobId,
this.Id,
bhMgr,
cancellationToken);
return asyncTask;
}
/// <summary>
/// Terminates this <see cref="CloudTask"/>, marking it as completed.
/// </summary>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
/// <remarks>This is a blocking operation. For a non-blocking equivalent, see <see cref="TerminateAsync"/>.</remarks>
public void Terminate(IEnumerable<BatchClientBehavior> additionalBehaviors = null)
{
Task asyncTask = TerminateAsync(additionalBehaviors);
asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors);
}
/// <summary>
/// Deletes this <see cref="CloudTask"/>.
/// </summary>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param>
/// <returns>A <see cref="System.Threading.Tasks.Task"/> that represents the asynchronous operation.</returns>
/// <remarks>The delete operation runs asynchronously.</remarks>
public System.Threading.Tasks.Task DeleteAsync(IEnumerable<BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken))
{
UtilitiesInternal.ThrowOnUnbound(this.propertyContainer.BindingState);
// create the behavior manager
BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors);
System.Threading.Tasks.Task asyncTask = this.parentBatchClient.ProtocolLayer.DeleteTask(
this.parentJobId,
this.Id,
bhMgr,
cancellationToken);
return asyncTask;
}
/// <summary>
/// Deletes this <see cref="CloudTask"/>.
/// </summary>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
/// <remarks>This is a blocking operation. For a non-blocking equivalent, see <see cref="DeleteAsync"/>.</remarks>
public void Delete(IEnumerable<BatchClientBehavior> additionalBehaviors = null)
{
Task asyncTask = DeleteAsync(additionalBehaviors);
asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors);
}
/// <summary>
/// Reactivates this <see cref="CloudTask"/>, allowing it to run again even if its retry count has been exhausted.
/// </summary>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param>
/// <returns>A <see cref="System.Threading.Tasks.Task"/> that represents the asynchronous operation.</returns>
/// <remarks>
/// <para>
/// Reactivation makes a task eligible to be retried again up to its maximum retry count.
/// </para>
/// <para>
/// This operation will fail for tasks that are not completed or that previously completed successfully (with an exit code of 0).
/// Additionally, this will fail if the job is in the <see cref="JobState.Completed"/> or <see cref="JobState.Terminating"/> or <see cref="JobState.Deleting"/> state.
/// </para>
/// <para>
/// The reactivate operation runs asynchronously.
/// </para>
/// </remarks>
public System.Threading.Tasks.Task ReactivateAsync(IEnumerable<BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken))
{
UtilitiesInternal.ThrowOnUnbound(this.propertyContainer.BindingState);
// create the behavior manager
BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors);
System.Threading.Tasks.Task asyncTask = this.parentBatchClient.ProtocolLayer.ReactivateTask(
this.parentJobId,
this.Id,
bhMgr,
cancellationToken);
return asyncTask;
}
/// <summary>
/// Reactivates this <see cref="CloudTask"/>, allowing it to run again even if its retry count has been exhausted.
/// </summary>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
/// <remarks>
/// <para>
/// Reactivation makes a task eligible to be retried again up to its maximum retry count.
/// </para>
/// <para>
/// This operation will fail for tasks that are not completed or that previously completed successfully (with an exit code of 0).
/// Additionally, this will fail if the job is in the <see cref="JobState.Completed"/> or <see cref="JobState.Terminating"/> or <see cref="JobState.Deleting"/> state.
/// </para>
/// <para>
/// This is a blocking operation. For a non-blocking equivalent, see <see cref="ReactivateAsync"/>.
/// </para>
/// </remarks>
public void Reactivate(IEnumerable<BatchClientBehavior> additionalBehaviors = null)
{
Task asyncTask = ReactivateAsync(additionalBehaviors);
asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors);
}
/// <summary>
/// Gets the specified <see cref="NodeFile"/> from the <see cref="CloudTask"/>'s directory on its compute node.
/// </summary>
/// <param name="filePath">The path of the file to retrieve.</param>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param>
/// <returns>A <see cref="NodeFile"/> representing the specified file.</returns>
/// <remarks>The get file operation runs asynchronously.</remarks>
public System.Threading.Tasks.Task<NodeFile> GetNodeFileAsync(
string filePath,
IEnumerable<BatchClientBehavior> additionalBehaviors = null,
CancellationToken cancellationToken = default(CancellationToken))
{
UtilitiesInternal.ThrowOnUnbound(this.propertyContainer.BindingState);
//create the behavior manager
BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors);
//make the call
System.Threading.Tasks.Task<NodeFile> asyncTask = this.parentBatchClient.JobOperations.GetNodeFileAsyncImpl(this.parentJobId, this.Id, filePath, bhMgr, cancellationToken);
return asyncTask;
}
/// <summary>
/// Gets the specified <see cref="NodeFile"/> from the <see cref="CloudTask"/>'s directory on its compute node.
/// </summary>
/// <param name="filePath">The path of the file to retrieve.</param>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
/// <returns>A <see cref="NodeFile"/> representing the specified file.</returns>
/// <remarks>This is a blocking operation. For a non-blocking equivalent, see <see cref="GetNodeFileAsync"/>.</remarks>
public NodeFile GetNodeFile(string filePath, IEnumerable<BatchClientBehavior> additionalBehaviors = null)
{
Task<NodeFile> asyncTask = this.GetNodeFileAsync(filePath, additionalBehaviors);
NodeFile file = asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors);
return file;
}
/// <summary>
/// Copies the contents of a file in the task's directory from the node to the given <see cref="Stream"/>.
/// </summary>
/// <param name="filePath">The path of the file to retrieve.</param>
/// <param name="stream">The stream to copy the file contents to.</param>
/// <param name="byteRange">A byte range defining what section of the file to copy. If omitted, the entire file is downloaded.</param>
/// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param>
/// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns>
public Task CopyNodeFileContentToStreamAsync(
string filePath,
Stream stream,
GetFileRequestByteRange byteRange = null,
IEnumerable<BatchClientBehavior> additionalBehaviors = null,
CancellationToken cancellationToken = default(CancellationToken))
{
// create the behavior manager
BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors);
Task asyncTask = this.parentBatchClient.JobOperations.CopyNodeFileContentToStreamAsyncImpl(
this.parentJobId,
this.Id,
filePath,
stream,
byteRange,
bhMgr,
cancellationToken);
return asyncTask;
}
/// <summary>
/// Copies the contents of a file in the task's directory from the node to the given <see cref="Stream"/>.
/// </summary>
/// <param name="filePath">The path of the file to retrieve.</param>
/// <param name="stream">The stream to copy the file contents to.</param>
/// <param name="byteRange">A byte range defining what section of the file to copy. If omitted, the entire file is downloaded.</param>
/// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object.</param>
/// <returns>A bound <see cref="NodeFile"/> object.</returns>
public void CopyNodeFileContentToStream(
string filePath,
Stream stream,
GetFileRequestByteRange byteRange = null,
IEnumerable<BatchClientBehavior> additionalBehaviors = null)
{
Task asyncTask = this.CopyNodeFileContentToStreamAsync(filePath, stream, byteRange, additionalBehaviors);
asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors);
}
/// <summary>
/// Reads the contents of a file in the task's directory on its compute node into a string.
/// </summary>
/// <param name="filePath">The path of the file to retrieve.</param>
/// <param name="encoding">The encoding to use. If no value or null is specified, UTF8 is used.</param>
/// <param name="byteRange">A byte range defining what section of the file to copy. If omitted, the entire file is downloaded.</param>
/// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param>
/// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns>
public Task<string> CopyNodeFileContentToStringAsync(
string filePath,
Encoding encoding = null,
GetFileRequestByteRange byteRange = null,
IEnumerable<BatchClientBehavior> additionalBehaviors = null,
CancellationToken cancellationToken = default(CancellationToken))
{
// create the behavior manager
BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors);
return this.parentBatchClient.JobOperations.CopyNodeFileContentToStringAsyncImpl(
this.parentJobId,
this.Id,
filePath,
encoding,
byteRange,
bhMgr,
cancellationToken);
}
/// <summary>
/// Reads the contents of a file in the task's directory on its compute node into a string.
/// </summary>
/// <param name="filePath">The path of the file to retrieve.</param>
/// <param name="encoding">The encoding to use. If no value or null is specified, UTF8 is used.</param>
/// <param name="byteRange">A byte range defining what section of the file to copy. If omitted, the entire file is downloaded.</param>
/// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object.</param>
/// <returns>A bound <see cref="NodeFile"/> object.</returns>
public string CopyNodeFileContentToString(
string filePath,
Encoding encoding = null,
GetFileRequestByteRange byteRange = null,
IEnumerable<BatchClientBehavior> additionalBehaviors = null)
{
Task<string> asyncTask = this.CopyNodeFileContentToStringAsync(filePath, encoding, byteRange, additionalBehaviors);
return asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors);
}
#region IRefreshable
/// <summary>
/// Refreshes the current <see cref="CloudTask"/>.
/// </summary>
/// <param name="detailLevel">The detail level for the refresh. If a detail level which omits the <see cref="Id"/> property is specified, refresh will fail.</param>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param>
/// <returns>A <see cref="System.Threading.Tasks.Task"/> that represents the asynchronous operation.</returns>
public async System.Threading.Tasks.Task RefreshAsync(
DetailLevel detailLevel = null,
IEnumerable<BatchClientBehavior> additionalBehaviors = null,
CancellationToken cancellationToken = default(CancellationToken))
{
UtilitiesInternal.ThrowOnUnbound(this.propertyContainer.BindingState);
// create the behavior managaer
BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors, detailLevel);
System.Threading.Tasks.Task<AzureOperationResponse<Models.CloudTask, Models.TaskGetHeaders>> asyncTask =
this.parentBatchClient.ProtocolLayer.GetTask(
this.parentJobId,
this.Id,
bhMgr,
cancellationToken);
AzureOperationResponse<Models.CloudTask, Models.TaskGetHeaders> response = await asyncTask.ConfigureAwait(continueOnCapturedContext: false);
// get task from response
Models.CloudTask newProtocolTask = response.Body;
// immediately available to all threads
this.propertyContainer = new PropertyContainer(newProtocolTask);
}
/// <summary>
/// Refreshes the current <see cref="CloudTask"/>.
/// </summary>
/// <param name="detailLevel">The detail level for the refresh. If a detail level which omits the <see cref="Id"/> property is specified, refresh will fail.</param>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
public void Refresh(
DetailLevel detailLevel = null,
IEnumerable<BatchClientBehavior> additionalBehaviors = null)
{
Task asyncTask = RefreshAsync(detailLevel, additionalBehaviors);
asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors);
}
#endregion IRefreshable
}
}
| |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.Collections.Generic;
using VoidEngine.VGame;
namespace VoidEngine.VGUI
{
/// <summary>
/// The button class for the VoidEngine
/// </summary>
public class Checkbox : Sprite
{
/// <summary>
/// This is the Void Engine button's state enum
/// </summary>
protected enum ButtonStates
{
Hover,
Up,
Down,
Released
}
/// <summary>
/// This is the Void Engine button's state enum
/// </summary>
protected enum CheckboxStates
{
Checked,
Unchecked
}
/// <summary>
/// The types of buttons on the mouse.
/// </summary>
public enum ButtonTypes
{
Left,
Right,
Middle
}
protected ButtonStates CheckButtonState = new ButtonStates(); // This is the button state variable
protected CheckboxStates CheckboxState = new CheckboxStates();
protected ButtonTypes PrimaryButton = new ButtonTypes();
protected bool MousePressed, PreviousMousePressed;
protected Point MouseCords;
protected Rectangle CollisionBounds;
public string test = "Hi";
public Color test2;
/// <summary>
/// Creates the Checkbox class.
/// </summary>
/// <param name="position"></param>
/// <param name="color"></param>
/// <param name="primaryButton"></param>
/// <param name="defaultButtonPositions"></param>
/// <param name="animationSetList"></param>
public Checkbox(Vector2 position, Color color, ButtonTypes primaryButton, List<Sprite.AnimationSet> animationSetList)
: base(position, color, animationSetList)
{
AnimationSets = animationSetList;
Color = color;
PrimaryButton = primaryButton;
CheckboxState = CheckboxStates.Unchecked;
}
public Checkbox(Texture2D texture, Vector2 position, ButtonTypes primaryButton, Color color)
: base(position, color, texture)
{
AddAnimations(texture);
Color = color;
PrimaryButton = primaryButton;
CheckboxState = CheckboxStates.Unchecked;
CheckButtonState = ButtonStates.Up;
}
/// <summary>
/// Returns if the button is hovered over or not.
/// </summary>
/// <param name="tx">The texture of the button</param>
/// <param name="ty">The texture's y</param>
/// <param name="frameTex">the texture's width and height in Point</param>
/// <param name="x">the x of mouse</param>
/// <param name="y">the y of mouse</param>
/// <returns>Boolean</returns>
protected bool hitButtonAlpha(Vector2 position, Point frameSize, Point mouseCords)
{
CollisionBounds = new Rectangle((int)position.X, (int)position.Y, frameSize.X, frameSize.Y);
if (CollisionBounds.Intersects(new Rectangle(mouseCords.X, mouseCords.Y, 1, 1)))
{
return true;
}
return false;
}
/// <summary>
/// Updates the button with the mouse's cords and state
/// </summary>
/// <param name="gameTime">The game time that the game runs off of.</param>
public override void Update(GameTime gameTime)
{
MouseState MouseState = Mouse.GetState();
MouseCords = new Point(MouseState.X, MouseState.Y);
PreviousMousePressed = MousePressed;
//MousePressed = (PrimaryButton == ButtonTypes.Left && MouseState.LeftButton == ButtonState.Pressed) || (PrimaryButton == ButtonTypes.Right && MouseState.RightButton == ButtonState.Pressed) || (PrimaryButton == ButtonTypes.Middle && MouseState.MiddleButton == ButtonState.Pressed);
MousePressed = MouseState.LeftButton == ButtonState.Pressed;
inbounds = new Rectangle(0, 0, CurrentAnimation.frameSize.X, CurrentAnimation.frameSize.Y);
if (CheckboxState == CheckboxStates.Checked)
{
test = "Checked";
if (CheckButtonState == ButtonStates.Hover)
{
test = "Checked Hover";
}
else if (CheckButtonState == ButtonStates.Up)
{
test = "Checked UP";
}
}
else if (CheckboxState == CheckboxStates.Unchecked)
{
test = "Unchecked";
if (CheckButtonState == ButtonStates.Hover)
{
test = "Unchecked Hover";
}
else if (CheckButtonState == ButtonStates.Up)
{
test = "Unchecked UP";
}
}
if (hitButtonAlpha(position, CurrentAnimation.frameSize, MouseCords))
{
if (CheckboxState == CheckboxStates.Unchecked && (!MousePressed && PreviousMousePressed))
{
test2 = Color.Aqua;
//CheckButtonState = ButtonStates.Down;
CheckboxState = CheckboxStates.Checked;
SetAnimation("CHECKED");
}
else if (CheckboxState == CheckboxStates.Checked && (!MousePressed && PreviousMousePressed))
{
test2 = Color.Red;
//CheckButtonState = ButtonStates.Down;
CheckboxState = CheckboxStates.Unchecked;
SetAnimation("UNCHECKED");
}
if (CheckButtonState == ButtonStates.Up)
{
if (CheckboxState == CheckboxStates.Unchecked)
{
test2 = Color.Blue;
CheckButtonState = ButtonStates.Hover;
SetAnimation("HOVERUNCHECKED");
}
else if (CheckboxState == CheckboxStates.Checked)
{
test2 = Color.Blue;
CheckButtonState = ButtonStates.Hover;
SetAnimation("HOVERCHECKED");
}
}
}
else
{
if (CheckButtonState == ButtonStates.Hover)
{
if (CheckboxState == CheckboxStates.Unchecked)
{
test2 = Color.Lime;
CheckButtonState = ButtonStates.Up;
SetAnimation("UNCHECKED");
}
else if (CheckboxState == CheckboxStates.Checked)
{
test2 = Color.Lime;
CheckButtonState = ButtonStates.Up;
SetAnimation("CHECKED");
}
}
}
}
/// <summary>
/// Returns weither if the button was clicked.
/// </summary>
/// <returns>Boolean</returns>
public bool isChecked
{
get
{
if (CheckboxState == CheckboxStates.Checked)
{
return true;
}
return false;
}
}
/// <summary>
/// Used to draw the button.
/// </summary>
/// <param name="gameTime">The game time that the game runs off of.</param>
/// <param name="spriteBatch">The sprite batch used to draw with.</param>
public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
base.Draw(gameTime, spriteBatch);
}
protected override void AddAnimations(Texture2D texture)
{
AddAnimation("UNCHECKED", texture, new Point(texture.Width / 4, texture.Height), new Point(1, 1), new Point((texture.Width / 4) * 1, 0), 1600, true);
AddAnimation("HOVERUNCHECKED", texture, new Point(texture.Width / 4, texture.Height), new Point(1, 1), new Point((texture.Width / 4) * 0, 0), 1600, true);
AddAnimation("CHECKED", texture, new Point(texture.Width / 4, texture.Height), new Point(1, 1), new Point((texture.Width / 4) * 2, 0), 1600, true);
AddAnimation("HOVERCHECKED", texture, new Point(texture.Width / 4, texture.Height), new Point(1, 1), new Point((texture.Width / 4) * 3, 0), 1600, true);
SetAnimation("UNCHECKED");
base.AddAnimations(texture);
}
}
}
| |
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 FWWebService.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class PreDecrementAssignTests : IncDecAssignTests
{
[Theory]
[PerCompilationType(nameof(Int16sAndDecrements))]
[PerCompilationType(nameof(NullableInt16sAndDecrements))]
[PerCompilationType(nameof(UInt16sAndDecrements))]
[PerCompilationType(nameof(NullableUInt16sAndDecrements))]
[PerCompilationType(nameof(Int32sAndDecrements))]
[PerCompilationType(nameof(NullableInt32sAndDecrements))]
[PerCompilationType(nameof(UInt32sAndDecrements))]
[PerCompilationType(nameof(NullableUInt32sAndDecrements))]
[PerCompilationType(nameof(Int64sAndDecrements))]
[PerCompilationType(nameof(NullableInt64sAndDecrements))]
[PerCompilationType(nameof(UInt64sAndDecrements))]
[PerCompilationType(nameof(NullableUInt64sAndDecrements))]
[PerCompilationType(nameof(DecimalsAndDecrements))]
[PerCompilationType(nameof(NullableDecimalsAndDecrements))]
[PerCompilationType(nameof(SinglesAndDecrements))]
[PerCompilationType(nameof(NullableSinglesAndDecrements))]
[PerCompilationType(nameof(DoublesAndDecrements))]
[PerCompilationType(nameof(NullableDoublesAndDecrements))]
public void ReturnsCorrectValues(Type type, object value, object result, bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(type);
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(value, type)),
Expression.PreDecrementAssign(variable)
);
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(result, type), block)).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(Int16sAndDecrements))]
[PerCompilationType(nameof(NullableInt16sAndDecrements))]
[PerCompilationType(nameof(UInt16sAndDecrements))]
[PerCompilationType(nameof(NullableUInt16sAndDecrements))]
[PerCompilationType(nameof(Int32sAndDecrements))]
[PerCompilationType(nameof(NullableInt32sAndDecrements))]
[PerCompilationType(nameof(UInt32sAndDecrements))]
[PerCompilationType(nameof(NullableUInt32sAndDecrements))]
[PerCompilationType(nameof(Int64sAndDecrements))]
[PerCompilationType(nameof(NullableInt64sAndDecrements))]
[PerCompilationType(nameof(UInt64sAndDecrements))]
[PerCompilationType(nameof(NullableUInt64sAndDecrements))]
[PerCompilationType(nameof(DecimalsAndDecrements))]
[PerCompilationType(nameof(NullableDecimalsAndDecrements))]
[PerCompilationType(nameof(SinglesAndDecrements))]
[PerCompilationType(nameof(NullableSinglesAndDecrements))]
[PerCompilationType(nameof(DoublesAndDecrements))]
[PerCompilationType(nameof(NullableDoublesAndDecrements))]
public void AssignsCorrectValues(Type type, object value, object result, bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(type);
LabelTarget target = Expression.Label(type);
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(value, type)),
Expression.PreDecrementAssign(variable),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(type))
);
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(result, type), block)).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void SingleNanToNan(bool useInterpreter)
{
TestPropertyClass<float> instance = new TestPropertyClass<float>();
instance.TestInstance = float.NaN;
Assert.True(float.IsNaN(
Expression.Lambda<Func<float>>(
Expression.PreDecrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<float>),
"TestInstance"
)
)
).Compile(useInterpreter)()
));
Assert.True(float.IsNaN(instance.TestInstance));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void DoubleNanToNan(bool useInterpreter)
{
TestPropertyClass<double> instance = new TestPropertyClass<double>();
instance.TestInstance = double.NaN;
Assert.True(double.IsNaN(
Expression.Lambda<Func<double>>(
Expression.PreDecrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<double>),
"TestInstance"
)
)
).Compile(useInterpreter)()
));
Assert.True(double.IsNaN(instance.TestInstance));
}
[Theory]
[PerCompilationType(nameof(DecrementOverflowingValues))]
public void OverflowingValuesThrow(object value, bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(value.GetType());
Action overflow = Expression.Lambda<Action>(
Expression.Block(
typeof(void),
new[] { variable },
Expression.Assign(variable, Expression.Constant(value)),
Expression.PreDecrementAssign(variable)
)
).Compile(useInterpreter);
Assert.Throws<OverflowException>(overflow);
}
[Theory]
[MemberData(nameof(UnincrementableAndUndecrementableTypes))]
public void InvalidOperandType(Type type)
{
ParameterExpression variable = Expression.Variable(type);
Assert.Throws<InvalidOperationException>(() => Expression.PreDecrementAssign(variable));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void MethodCorrectResult(bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(typeof(string));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant("hello")),
Expression.PreDecrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod"))
);
Assert.Equal("Eggplant", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void MethodCorrectAssign(bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(typeof(string));
LabelTarget target = Expression.Label(typeof(string));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant("hello")),
Expression.PreDecrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod")),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(typeof(string)))
);
Assert.Equal("Eggplant", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)());
}
[Fact]
public void IncorrectMethodType()
{
Expression variable = Expression.Variable(typeof(int));
MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod");
Assert.Throws<InvalidOperationException>(() => Expression.PreDecrementAssign(variable, method));
}
[Fact]
public void IncorrectMethodParameterCount()
{
Expression variable = Expression.Variable(typeof(string));
MethodInfo method = typeof(object).GetTypeInfo().GetDeclaredMethod("ReferenceEquals");
Assert.Throws<ArgumentException>(null, () => Expression.PreDecrementAssign(variable, method));
}
[Fact]
public void IncorrectMethodReturnType()
{
Expression variable = Expression.Variable(typeof(int));
MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("GetString");
Assert.Throws<ArgumentException>(null, () => Expression.PreDecrementAssign(variable, method));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void StaticMemberAccessCorrect(bool useInterpreter)
{
TestPropertyClass<int>.TestStatic = 2;
Assert.Equal(
1,
Expression.Lambda<Func<int>>(
Expression.PreDecrementAssign(
Expression.Property(null, typeof(TestPropertyClass<int>), "TestStatic")
)
).Compile(useInterpreter)()
);
Assert.Equal(1, TestPropertyClass<int>.TestStatic);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void InstanceMemberAccessCorrect(bool useInterpreter)
{
TestPropertyClass<int> instance = new TestPropertyClass<int>();
instance.TestInstance = 2;
Assert.Equal(
1,
Expression.Lambda<Func<int>>(
Expression.PreDecrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<int>),
"TestInstance"
)
)
).Compile(useInterpreter)()
);
Assert.Equal(1, instance.TestInstance);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void ArrayAccessCorrect(bool useInterpreter)
{
int[] array = new int[1];
array[0] = 2;
Assert.Equal(
1,
Expression.Lambda<Func<int>>(
Expression.PreDecrementAssign(
Expression.ArrayAccess(Expression.Constant(array), Expression.Constant(0))
)
).Compile(useInterpreter)()
);
Assert.Equal(1, array[0]);
}
[Fact]
public void CanReduce()
{
ParameterExpression variable = Expression.Variable(typeof(int));
UnaryExpression op = Expression.PreDecrementAssign(variable);
Assert.True(op.CanReduce);
Assert.NotSame(op, op.ReduceAndCheck());
}
[Fact]
public void NullOperand()
{
Assert.Throws<ArgumentNullException>("expression", () => Expression.PreDecrementAssign(null));
}
[Fact]
public void UnwritableOperand()
{
Assert.Throws<ArgumentException>("expression", () => Expression.PreDecrementAssign(Expression.Constant(1)));
}
[Fact]
public void UnreadableOperand()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("expression", () => Expression.PreDecrementAssign(value));
}
[Fact]
public void UpdateSameOperandSameNode()
{
UnaryExpression op = Expression.PreDecrementAssign(Expression.Variable(typeof(int)));
Assert.Same(op, op.Update(op.Operand));
Assert.Same(op, NoOpVisitor.Instance.Visit(op));
}
[Fact]
public void UpdateDiffOperandDiffNode()
{
UnaryExpression op = Expression.PreDecrementAssign(Expression.Variable(typeof(int)));
Assert.NotSame(op, op.Update(Expression.Variable(typeof(int))));
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Reflection.Internal;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
namespace System.Reflection.Metadata
{
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
public unsafe struct BlobReader
{
/// <summary>An array containing the '\0' character.</summary>
private static readonly char[] _nullCharArray = new char[1] { '\0' };
internal const int InvalidCompressedInteger = Int32.MaxValue;
private readonly MemoryBlock block;
// Points right behind the last byte of the block.
private readonly byte* endPointer;
private byte* currentPointer;
public unsafe BlobReader(byte* buffer, int length)
{
if (length < 0)
{
throw new ArgumentOutOfRangeException("length");
}
if (buffer == null && length != 0)
{
throw new ArgumentNullException("buffer");
}
// the reader performs little-endian specific operations
if (!BitConverter.IsLittleEndian)
{
throw new PlatformNotSupportedException(MetadataResources.LitteEndianArchitectureRequired);
}
this = new BlobReader(new MemoryBlock(buffer, length));
}
internal BlobReader(MemoryBlock block)
{
Debug.Assert(BitConverter.IsLittleEndian && block.Length >= 0 && (block.Pointer != null || block.Length == 0));
this.block = block;
this.currentPointer = block.Pointer;
this.endPointer = block.Pointer + block.Length;
}
private string GetDebuggerDisplay()
{
if (block.Pointer == null)
{
return "<null>";
}
int displayedBytes;
string display = block.GetDebuggerDisplay(out displayedBytes);
if (this.Offset < displayedBytes)
{
display = display.Insert(this.Offset * 3, "*");
}
else if (displayedBytes == block.Length)
{
display += "*";
}
else
{
display += "*...";
}
return display;
}
#region Offset, Skipping, Marking, Alignment, Bounds Checking
public int Length
{
get
{
return block.Length;
}
}
public int Offset
{
get
{
return (int)(this.currentPointer - block.Pointer);
}
}
public int RemainingBytes
{
get
{
return (int)(this.endPointer - this.currentPointer);
}
}
public void Reset()
{
this.currentPointer = block.Pointer;
}
internal bool SeekOffset(int offset)
{
if (unchecked((uint)offset) >= (uint)block.Length)
{
return false;
}
this.currentPointer = block.Pointer + offset;
return true;
}
internal void SkipBytes(int count)
{
GetCurrentPointerAndAdvance(count);
}
internal void Align(byte alignment)
{
if (!TryAlign(alignment))
{
ThrowOutOfBounds();
}
}
internal bool TryAlign(byte alignment)
{
int remainder = this.Offset & (alignment - 1);
Debug.Assert((alignment & (alignment - 1)) == 0, "Alignment must be a power of two.");
Debug.Assert(remainder >= 0 && remainder < alignment);
if (remainder != 0)
{
int bytesToSkip = alignment - remainder;
if (bytesToSkip > RemainingBytes)
{
return false;
}
this.currentPointer += bytesToSkip;
}
return true;
}
internal MemoryBlock GetMemoryBlockAt(int offset, int length)
{
CheckBounds(offset, length);
return new MemoryBlock(this.currentPointer + offset, length);
}
#endregion
#region Bounds Checking
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowOutOfBounds()
{
throw new BadImageFormatException(MetadataResources.OutOfBoundsRead);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CheckBounds(int offset, int byteCount)
{
if (unchecked((ulong)(uint)offset + (uint)byteCount) > (ulong)(this.endPointer - this.currentPointer))
{
ThrowOutOfBounds();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CheckBounds(int byteCount)
{
if (unchecked((uint)byteCount) > (this.endPointer - this.currentPointer))
{
ThrowOutOfBounds();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private byte* GetCurrentPointerAndAdvance(int length)
{
byte* p = this.currentPointer;
if (unchecked((uint)length) > (uint)(this.endPointer - p))
{
ThrowOutOfBounds();
}
this.currentPointer = p + length;
return p;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private byte* GetCurrentPointerAndAdvance1()
{
byte* p = this.currentPointer;
if (p == this.endPointer)
{
ThrowOutOfBounds();
}
this.currentPointer = p + 1;
return p;
}
#endregion
#region Read Methods
public bool ReadBoolean()
{
return ReadByte() == 1;
}
public SByte ReadSByte()
{
return *(SByte*)GetCurrentPointerAndAdvance1();
}
public Byte ReadByte()
{
return *(Byte*)GetCurrentPointerAndAdvance1();
}
public Char ReadChar()
{
return *(Char*)GetCurrentPointerAndAdvance(sizeof(Char));
}
public Int16 ReadInt16()
{
return *(Int16*)GetCurrentPointerAndAdvance(sizeof(Int16));
}
public UInt16 ReadUInt16()
{
return *(UInt16*)GetCurrentPointerAndAdvance(sizeof(UInt16));
}
public Int32 ReadInt32()
{
return *(Int32*)GetCurrentPointerAndAdvance(sizeof(Int32));
}
public UInt32 ReadUInt32()
{
return *(UInt32*)GetCurrentPointerAndAdvance(sizeof(UInt32));
}
public Int64 ReadInt64()
{
return *(Int64*)GetCurrentPointerAndAdvance(sizeof(Int64));
}
public UInt64 ReadUInt64()
{
return *(UInt64*)GetCurrentPointerAndAdvance(sizeof(UInt64));
}
public Single ReadSingle()
{
return *(Single*)GetCurrentPointerAndAdvance(sizeof(Single));
}
public Double ReadDouble()
{
return *(Double*)GetCurrentPointerAndAdvance(sizeof(UInt64));
}
public SignatureHeader ReadSignatureHeader()
{
return new SignatureHeader(ReadByte());
}
/// <summary>
/// Reads UTF8 encoded string starting at the current position.
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <returns>The string.</returns>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public string ReadUTF8(int byteCount)
{
string s = this.block.PeekUtf8(this.Offset, byteCount);
this.currentPointer += byteCount;
return s;
}
/// <summary>
/// Reads UTF16 (little-endian) encoded string starting at the current position.
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <returns>The string.</returns>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public string ReadUTF16(int byteCount)
{
string s = this.block.PeekUtf16(this.Offset, byteCount);
this.currentPointer += byteCount;
return s;
}
/// <summary>
/// Reads bytes starting at the current position.
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <returns>The byte array.</returns>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public byte[] ReadBytes(int byteCount)
{
byte[] bytes = this.block.PeekBytes(this.Offset, byteCount);
this.currentPointer += byteCount;
return bytes;
}
internal string ReadUtf8NullTerminated()
{
int bytesRead;
string value = this.block.PeekUtf8NullTerminated(this.Offset, null, MetadataStringDecoder.DefaultUTF8, out bytesRead, '\0');
this.currentPointer += bytesRead;
return value;
}
private int ReadCompressedIntegerOrInvalid()
{
int bytesRead;
int value = this.block.PeekCompressedInteger(this.Offset, out bytesRead);
this.currentPointer += bytesRead;
return value;
}
/// <summary>
/// Reads an unsigned compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <param name="value">The value of the compressed integer that was read.</param>
/// <returns>true if the value was read successfully. false if the data at the current position was not a valid compressed integer.</returns>
public bool TryReadCompressedInteger(out int value)
{
value = ReadCompressedIntegerOrInvalid();
return value != InvalidCompressedInteger;
}
/// <summary>
/// Reads an unsigned compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <returns>The value of the compressed integer that was read.</returns>
/// <exception cref="System.BadImageFormatException">The data at the current position was not a valid compressed integer.</exception>
public int ReadCompressedInteger()
{
int value;
if (!TryReadCompressedInteger(out value))
{
ThrowInvalidCompressedInteger();
}
return value;
}
/// <summary>
/// Reads a signed compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <param name="value">The value of the compressed integer that was read.</param>
/// <returns>true if the value was read successfully. false if the data at the current position was not a valid compressed integer.</returns>
public bool TryReadCompressedSignedInteger(out int value)
{
int bytesRead;
value = this.block.PeekCompressedInteger(this.Offset, out bytesRead);
if (value == InvalidCompressedInteger)
{
return false;
}
bool signExtend = (value & 0x1) != 0;
value >>= 1;
if (signExtend)
{
switch (bytesRead)
{
case 1:
value |= unchecked((int)0xffffffc0);
break;
case 2:
value |= unchecked((int)0xffffe000);
break;
default:
Debug.Assert(bytesRead == 4);
value |= unchecked((int)0xf0000000);
break;
}
}
this.currentPointer += bytesRead;
return true;
}
/// <summary>
/// Reads a signed compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <returns>The value of the compressed integer that was read.</returns>
/// <exception cref="System.BadImageFormatException">The data at the current position was not a valid compressed integer.</exception>
public int ReadCompressedSignedInteger()
{
int value;
if (!TryReadCompressedSignedInteger(out value))
{
ThrowInvalidCompressedInteger();
}
return value;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowInvalidCompressedInteger()
{
throw new BadImageFormatException(MetadataResources.InvalidCompressedInteger);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowInvalidSerializedString()
{
throw new BadImageFormatException(MetadataResources.InvalidSerializedString);
}
/// <summary>
/// Reads type code encoded in a serialized custom attribute value.
/// </summary>
public SerializationTypeCode ReadSerializationTypeCode()
{
int value = ReadCompressedIntegerOrInvalid();
if (value > Byte.MaxValue)
{
return SerializationTypeCode.Invalid;
}
return unchecked((SerializationTypeCode)value);
}
/// <summary>
/// Reads type code encoded in a signature.
/// </summary>
public SignatureTypeCode ReadSignatureTypeCode()
{
int value = ReadCompressedIntegerOrInvalid();
switch (value)
{
case (int)CorElementType.ELEMENT_TYPE_CLASS:
case (int)CorElementType.ELEMENT_TYPE_VALUETYPE:
return SignatureTypeCode.TypeHandle;
default:
if (value > Byte.MaxValue)
{
return SignatureTypeCode.Invalid;
}
return unchecked((SignatureTypeCode)value);
}
}
/// <summary>
/// Reads a string encoded as a compressed integer containing its length followed by
/// its contents in UTF8. Null strings are encoded as a single 0xFF byte.
/// </summary>
/// <remarks>Defined as a 'SerString' in the Ecma CLI specification.</remarks>
/// <returns>String value or null.</returns>
public string ReadSerializedString()
{
int length;
if (TryReadCompressedInteger(out length))
{
// Removal of trailing '\0' is a departure from the spec, but required
// for compatibility with legacy compilers.
return ReadUTF8(length).TrimEnd(_nullCharArray);
}
if (ReadByte() != 0xFF)
{
ThrowInvalidSerializedString();
}
return null;
}
/// <summary>
/// Reads a type handle encoded in a signature as (CLASS | VALUETYPE) TypeDefOrRefOrSpecEncoded.
/// </summary>
/// <returns>The handle or nil if the encoding is invalid.</returns>
public Handle ReadTypeHandle()
{
uint value = (uint)ReadCompressedIntegerOrInvalid();
uint tokenType = corEncodeTokenArray[value & 0x3];
if (value == InvalidCompressedInteger || tokenType == 0)
{
return default(Handle);
}
return new Handle(tokenType | (value >> 2));
}
private static readonly uint[] corEncodeTokenArray = new uint[] { TokenTypeIds.TypeDef, TokenTypeIds.TypeRef, TokenTypeIds.TypeSpec, 0 };
#endregion
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagr = Google.Api.Gax.ResourceNames;
using gccv = Google.Cloud.ContactCenterInsights.V1;
namespace Google.Cloud.ContactCenterInsights.V1
{
public partial class CalculateStatsRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Location"/> resource name property.
/// </summary>
public gagr::LocationName LocationAsLocationName
{
get => string.IsNullOrEmpty(Location) ? null : gagr::LocationName.Parse(Location, allowUnparsed: true);
set => Location = value?.ToString() ?? "";
}
}
public partial class CreateAnalysisOperationMetadata
{
/// <summary>
/// <see cref="ConversationName"/>-typed view over the <see cref="Conversation"/> resource name property.
/// </summary>
public ConversationName ConversationAsConversationName
{
get => string.IsNullOrEmpty(Conversation) ? null : ConversationName.Parse(Conversation, allowUnparsed: true);
set => Conversation = value?.ToString() ?? "";
}
}
public partial class CreateConversationRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class ListConversationsRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetConversationRequest
{
/// <summary>
/// <see cref="gccv::ConversationName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gccv::ConversationName ConversationName
{
get => string.IsNullOrEmpty(Name) ? null : gccv::ConversationName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class DeleteConversationRequest
{
/// <summary>
/// <see cref="gccv::ConversationName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gccv::ConversationName ConversationName
{
get => string.IsNullOrEmpty(Name) ? null : gccv::ConversationName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateAnalysisRequest
{
/// <summary>
/// <see cref="ConversationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public ConversationName ParentAsConversationName
{
get => string.IsNullOrEmpty(Parent) ? null : ConversationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class ListAnalysesRequest
{
/// <summary>
/// <see cref="ConversationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public ConversationName ParentAsConversationName
{
get => string.IsNullOrEmpty(Parent) ? null : ConversationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetAnalysisRequest
{
/// <summary>
/// <see cref="gccv::AnalysisName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gccv::AnalysisName AnalysisName
{
get => string.IsNullOrEmpty(Name) ? null : gccv::AnalysisName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class DeleteAnalysisRequest
{
/// <summary>
/// <see cref="gccv::AnalysisName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gccv::AnalysisName AnalysisName
{
get => string.IsNullOrEmpty(Name) ? null : gccv::AnalysisName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ExportInsightsDataRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class CreateIssueModelRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class ListIssueModelsRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetIssueModelRequest
{
/// <summary>
/// <see cref="gccv::IssueModelName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gccv::IssueModelName IssueModelName
{
get => string.IsNullOrEmpty(Name) ? null : gccv::IssueModelName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class DeleteIssueModelRequest
{
/// <summary>
/// <see cref="gccv::IssueModelName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gccv::IssueModelName IssueModelName
{
get => string.IsNullOrEmpty(Name) ? null : gccv::IssueModelName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class DeployIssueModelRequest
{
/// <summary>
/// <see cref="gccv::IssueModelName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gccv::IssueModelName IssueModelName
{
get => string.IsNullOrEmpty(Name) ? null : gccv::IssueModelName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class UndeployIssueModelRequest
{
/// <summary>
/// <see cref="gccv::IssueModelName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gccv::IssueModelName IssueModelName
{
get => string.IsNullOrEmpty(Name) ? null : gccv::IssueModelName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetIssueRequest
{
/// <summary>
/// <see cref="gccv::IssueName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gccv::IssueName IssueName
{
get => string.IsNullOrEmpty(Name) ? null : gccv::IssueName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListIssuesRequest
{
/// <summary>
/// <see cref="IssueModelName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public IssueModelName ParentAsIssueModelName
{
get => string.IsNullOrEmpty(Parent) ? null : IssueModelName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class CalculateIssueModelStatsRequest
{
/// <summary>
/// <see cref="IssueModelName"/>-typed view over the <see cref="IssueModel"/> resource name property.
/// </summary>
public IssueModelName IssueModelAsIssueModelName
{
get => string.IsNullOrEmpty(IssueModel) ? null : IssueModelName.Parse(IssueModel, allowUnparsed: true);
set => IssueModel = value?.ToString() ?? "";
}
}
public partial class CreatePhraseMatcherRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class ListPhraseMatchersRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetPhraseMatcherRequest
{
/// <summary>
/// <see cref="gccv::PhraseMatcherName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gccv::PhraseMatcherName PhraseMatcherName
{
get => string.IsNullOrEmpty(Name) ? null : gccv::PhraseMatcherName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class DeletePhraseMatcherRequest
{
/// <summary>
/// <see cref="gccv::PhraseMatcherName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gccv::PhraseMatcherName PhraseMatcherName
{
get => string.IsNullOrEmpty(Name) ? null : gccv::PhraseMatcherName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetSettingsRequest
{
/// <summary>
/// <see cref="gccv::SettingsName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gccv::SettingsName SettingsName
{
get => string.IsNullOrEmpty(Name) ? null : gccv::SettingsName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateViewRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetViewRequest
{
/// <summary>
/// <see cref="gccv::ViewName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gccv::ViewName ViewName
{
get => string.IsNullOrEmpty(Name) ? null : gccv::ViewName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListViewsRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteViewRequest
{
/// <summary>
/// <see cref="gccv::ViewName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gccv::ViewName ViewName
{
get => string.IsNullOrEmpty(Name) ? null : gccv::ViewName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2017 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using System.Collections.Generic;
#if CORE_CLR || NETSTANDARD1_1
using Contract = MsgPack.MPContract;
#else
using System.Diagnostics.Contracts;
#endif // CORE_CLR || NETSTANDARD1_1
using System.Linq;
using System.Reflection;
#if FEATURE_TAP
using System.Threading.Tasks;
#endif // FEATURE_TAP
using MsgPack.Serialization.Reflection;
namespace MsgPack.Serialization.AbstractSerializers
{
partial class SerializerBuilder<TContext, TConstruct>
{
private void BuildTupleSerializer( TContext context, IList<PolymorphismSchema> itemSchemaList, out SerializationTarget targetInfo )
{
var itemTypes = TupleItems.GetTupleItemTypes( this.TargetType );
targetInfo = SerializationTarget.CreateForTuple( itemTypes );
var isValueTuple = this.TargetType.GetIsValueType();
this.BuildTuplePackTo( context, itemTypes, itemSchemaList, isValueTuple, false );
#if FEATURE_TAP
if ( this.WithAsync( context ) )
{
this.BuildTuplePackTo( context, itemTypes, itemSchemaList, isValueTuple, true );
}
#endif // FEATURE_TAP
this.BuildTupleUnpackFrom( context, itemTypes, itemSchemaList, isValueTuple, false );
#if FEATURE_TAP
if ( this.WithAsync( context ) )
{
this.BuildTupleUnpackFrom( context, itemTypes, itemSchemaList, isValueTuple, true );
}
#endif // FEATURE_TAP
}
#region -- PackTo --
private void BuildTuplePackTo( TContext context, IList<Type> itemTypes, IList<PolymorphismSchema> itemSchemaList, bool isValueTuple, bool isAsync )
{
/*
packer.PackArrayHeader( cardinarity );
_serializer0.PackTo( packer, tuple.Item1 );
:
_serializer6.PackTo( packer, tuple.item7 );
_serializer7.PackTo( packer, tuple.Rest.Item1 );
*/
var methodName =
#if FEATURE_TAP
isAsync ? MethodName.PackToAsyncCore :
#endif // FEATURE_TAP
MethodName.PackToCore;
context.BeginMethodOverride( methodName );
context.EndMethodOverride(
methodName,
this.EmitSequentialStatements(
context,
TypeDefinition.VoidType,
this.BuildTuplePackToCore( context, itemTypes, itemSchemaList, isValueTuple, isAsync )
)
);
}
private IEnumerable<TConstruct> BuildTuplePackToCore( TContext context, IList<Type> itemTypes, IList<PolymorphismSchema> itemSchemaList, bool isValueTuple, bool isAsync )
{
return
isValueTuple
? BuildTuplePackToCore( context, itemTypes, itemSchemaList, ( t, n ) => t.GetField( n ), ( c, s, m ) => this.EmitGetFieldExpression( c, s, m ), isAsync )
: BuildTuplePackToCore( context, itemTypes, itemSchemaList, ( t, n ) => t.GetProperty( n ), ( c, s, m )=> this.EmitGetPropertyExpression( c, s, m ), isAsync );
}
private IEnumerable<TConstruct> BuildTuplePackToCore<TInfo>( TContext context, IList<Type> itemTypes, IList<PolymorphismSchema> itemSchemaList, Func<Type, string, TInfo> memberFactory, Func<TContext, TConstruct, TInfo, TConstruct> chainConstructFactory, bool isAsync )
{
// Note: cardinality is put as array length by PackHelper.
var depth = -1;
var tupleTypeList = TupleItems.CreateTupleTypeList( this.TargetType );
var memberInvocationChain = new List<TInfo>( itemTypes.Count % 7 + 1 );
var packValueArguments =
new[] { context.Packer, context.PackToTarget }
#if FEATURE_TAP
.Concat( isAsync ? new[] { this.ReferCancellationToken( context, 3 ) } : NoConstructs ).ToArray()
#endif // FEATURE_TAP
;
for ( var i = 0; i < itemTypes.Count; i++ )
{
if ( i % 7 == 0 )
{
depth++;
}
for ( var j = 0; j < depth; j++ )
{
// .TRest.TRest ...
var restMember = memberFactory( tupleTypeList[ j ], "Rest" );
#if DEBUG
Contract.Assert( restMember != null, tupleTypeList[ j ].GetFullName() + ".Rest is not defined" );
#endif
memberInvocationChain.Add( restMember );
}
var itemNMember = memberFactory( tupleTypeList[ depth ], "Item" + ( ( i % 7 ) + 1 ) );
memberInvocationChain.Add( itemNMember );
#if DEBUG
Contract.Assert(
itemNMember != null,
tupleTypeList[ depth ].GetFullName() + "::Item" + ( ( i % 7 ) + 1 ) + " [ " + depth + " ] @ " + i
);
#endif
var count = i;
DefinePrivateMethod(
context,
AdjustName( MethodNamePrefix.PackValue + SerializationTarget.GetTupleItemNameFromIndex( i ), isAsync ),
false, // isStatic
#if FEATURE_TAP
isAsync ? TypeDefinition.TaskType :
#endif // FEATURE_TAP
TypeDefinition.VoidType,
() => this.EmitSequentialStatements(
context,
TypeDefinition.VoidType,
this.EmitPackTupleItemStatements(
context,
itemTypes[ count ],
context.Packer,
context.PackToTarget,
memberInvocationChain,
itemSchemaList.Count == 0 ? null : itemSchemaList[ count ],
chainConstructFactory,
isAsync
)
),
packValueArguments
);
memberInvocationChain.Clear();
}
var packHelperArguments =
new Dictionary<string, TConstruct>
{
{ "Packer", context.Packer },
{ "Target", context.PackToTarget },
{ "Operations", this.EmitGetActionsExpression( context, ActionType.PackToArray, isAsync ) }
};
#if FEATURE_TAP
if ( isAsync )
{
packHelperArguments.Add( "CancellationToken", this.ReferCancellationToken( context, 3 ) );
}
#endif // FEATURE_TAP
var packHelperParameterTypeDefinition =
#if FEATURE_TAP
isAsync ? typeof( PackToArrayAsyncParameters<> ) :
#endif // FEATURE_TAP
typeof( PackToArrayParameters<> );
var packHelperParameterType =
TypeDefinition.GenericValueType( packHelperParameterTypeDefinition, this.TargetType );
var packHelperMethod =
new MethodDefinition(
AdjustName( MethodName.PackToArray, isAsync ),
new [] { TypeDefinition.Object( this.TargetType ) },
TypeDefinition.PackHelpersType,
true, // isStatic
#if FEATURE_TAP
isAsync ? TypeDefinition.TaskType :
#endif // FEATURE_TAP
TypeDefinition.VoidType,
packHelperParameterType
);
var packHelperParameters = this.DeclareLocal( context, packHelperParameterType, "packHelperParameters" );
yield return packHelperParameters;
foreach ( var construct in this.CreatePackUnpackHelperArgumentInitialization( context, packHelperParameters, packHelperArguments ) )
{
yield return construct;
}
var methodInvocation =
this.EmitInvokeMethodExpression(
context,
null,
packHelperMethod,
this.EmitMakeRef( context, packHelperParameters )
);
if ( isAsync )
{
// Wrap with return to return Task
methodInvocation = this.EmitRetrunStatement( context, methodInvocation );
}
yield return methodInvocation;
}
private IEnumerable<TConstruct> EmitPackTupleItemStatements<TInfo>(
TContext context,
Type itemType,
TConstruct currentPacker,
TConstruct tuple,
IEnumerable<TInfo> memberInvocationChain,
PolymorphismSchema itemsSchema,
Func<TContext, TConstruct, TInfo, TConstruct> chainConstructFactory,
bool isAsync
)
{
return
this.EmitPackItemStatements(
context,
currentPacker,
itemType,
NilImplication.Null,
null,
memberInvocationChain.Aggregate(
tuple, ( memberSource, member ) => chainConstructFactory( context, memberSource, member )
),
null,
itemsSchema,
isAsync
);
}
#endregion -- PackTo --
#region -- UnpackFrom --
private void BuildTupleUnpackFrom( TContext context, IList<Type> itemTypes, IList<PolymorphismSchema> itemSchemaList, bool isValueTuple, bool isAsync )
{
/*
* checked
* {
* if (!unpacker.IsArrayHeader)
* {
* throw SerializationExceptions.NewIsNotArrayHeader();
* }
*
* if ((int)unpacker.ItemsCount != n)
* {
* throw SerializationExceptions.NewTupleCardinarityIsNotMatch(n, (int)unpacker.ItemsCount);
* }
*
* return
* new Tuple<...>(
* GET_VALUE_OR_DEFAULT( DESERIALIZE_VALUE( unpacker, typeof( T1? ) ) ),
* :
* GET_VALUE_OR_DEFAULT( DESERIALIZE_VALUE( unpacker, typeof( T7? ) ) ),
* new Tuple<...>(
* GET_VALUE_OR_DEFAULT( DESERIALIZE_VALUE( unpacker, typeof( T8? ) ) ),
* :
* )
* );
* }
*/
var methodName =
#if FEATURE_TAP
isAsync ? MethodName.UnpackFromAsyncCore :
#endif // FEATURE_TAP
MethodName.UnpackFromCore;
context.BeginMethodOverride( methodName );
context.EndMethodOverride(
methodName,
this.EmitSequentialStatements(
context,
this.TargetType,
this.BuildTupleUnpackFromCore( context, itemTypes, itemSchemaList, isValueTuple, isAsync )
)
);
}
private IEnumerable<TConstruct> BuildTupleUnpackFromCore( TContext context, IList<Type> itemTypes, IList<PolymorphismSchema> itemSchemaList, bool isValueTuple, bool isAsync )
{
return
isValueTuple
? BuildTupleUnpackFromCore( context, itemTypes, itemSchemaList, ( t, n ) => t.GetField( n ), isAsync )
: BuildTupleUnpackFromCore( context, itemTypes, itemSchemaList, ( t, n ) => t.GetProperty( n ), isAsync );
}
private IEnumerable<TConstruct> BuildTupleUnpackFromCore<TInfo>( TContext context, IList<Type> itemTypes, IList<PolymorphismSchema> itemSchemaList, Func<Type, string, TInfo> memberFactory, bool isAsync )
{
var tupleTypeList = TupleItems.CreateTupleTypeList( this.TargetType );
yield return
this.EmitCheckIsArrayHeaderExpression( context, context.Unpacker );
yield return
this.EmitCheckTupleCardinarityExpression(
context,
context.Unpacker,
itemTypes.Count
);
var unpackingContext = this.GetTupleUnpackingContextInfo( context, itemTypes );
foreach ( var statement in unpackingContext.Statements )
{
yield return statement;
}
var unpackValueArguments =
new[] { context.Unpacker, context.UnpackingContextInUnpackValueMethods, context.IndexOfItem, context.ItemsCount }
#if FEATURE_TAP
.Concat( isAsync ? new[] { this.ReferCancellationToken( context, 2 ) } : NoConstructs ).ToArray()
#endif // FEATURE_TAP
;
for ( var i = 0; i < itemTypes.Count; i++ )
{
var memberName = SerializationTarget.GetTupleItemNameFromIndex( i );
var unpackedItem = context.DefineUnpackedItemParameterInSetValueMethods( itemTypes[ i ] );
var setUnpackValueOfMethodName = MethodNamePrefix.SetUnpackedValueOf + memberName;
var index = i;
this.ExtractPrivateMethod(
context,
AdjustName( MethodNamePrefix.UnpackValue + memberName, isAsync ),
false, // isStatic
#if FEATURE_TAP
isAsync ? TypeDefinition.TaskType :
#endif // FEATURE_TAP
TypeDefinition.VoidType,
() => this.EmitUnpackItemValueStatement(
context,
itemTypes[ index ],
this.MakeStringLiteral( context, memberName ),
context.TupleItemNilImplication,
null, // memberInfo
itemSchemaList.Count == 0 ? null : itemSchemaList[ index ],
context.Unpacker,
context.UnpackingContextInUnpackValueMethods,
context.IndexOfItem,
context.ItemsCount,
context.IsDeclaredMethod( setUnpackValueOfMethodName )
? this.EmitGetPrivateMethodDelegateExpression(
context,
context.GetDeclaredMethod( setUnpackValueOfMethodName )
)
: this.ExtractPrivateMethod(
context,
setUnpackValueOfMethodName,
false, // isStatic
TypeDefinition.VoidType,
() =>
this.EmitSetField(
context,
context.UnpackingContextInSetValueMethods,
unpackingContext.VariableType,
memberName,
unpackedItem
),
context.UnpackingContextInSetValueMethods,
unpackedItem
),
isAsync
),
unpackValueArguments
);
}
TConstruct currentTuple = null;
for ( var nest = tupleTypeList.Count - 1; nest >= 0; nest-- )
{
var gets =
Enumerable.Range( nest * 7, Math.Min( itemTypes.Count - nest * 7, 7 ) )
.Select( i =>
this.EmitGetFieldExpression(
context,
context.UnpackingContextInCreateObjectFromContext,
new FieldDefinition(
unpackingContext.VariableType,
SerializationTarget.GetTupleItemNameFromIndex( i ),
itemTypes[ i ]
)
)
);
if ( currentTuple != null )
{
gets = gets.Concat( new[] { currentTuple } );
}
var constructor = tupleTypeList[ nest ].GetConstructors().SingleOrDefault();
if ( constructor == null )
{
// arity 0 value tuple
#if DEBUG
Contract.Assert( tupleTypeList[ nest ].GetFullName() == "System.ValueTuple", tupleTypeList[ nest ].GetFullName() + " == System.ValueTuple");
#endif
currentTuple = this.MakeDefaultLiteral( context, tupleTypeList[ nest ] );
}
else
{
var tempVariable = default( TConstruct );
if ( tupleTypeList[ nest ].GetIsValueType() )
{
// Temp var is required for value type (that is, ValueTuple)
tempVariable = this.DeclareLocal( context, tupleTypeList[ nest ], context.GetUniqueVariableName( "tuple" ) );
}
currentTuple =
this.EmitCreateNewObjectExpression(
context,
tempVariable, // Tuple is reference contextType.
constructor,
gets.ToArray()
);
}
}
#if DEBUG
Contract.Assert( currentTuple != null );
#endif
unpackingContext.Factory =
this.EmitNewPrivateMethodDelegateExpressionWithCreation(
context,
new MethodDefinition(
MethodName.CreateObjectFromContext,
null,
null,
true, // isStatic
this.TargetType,
unpackingContext.Type
),
() => this.EmitRetrunStatement(
context,
currentTuple
),
context.UnpackingContextInCreateObjectFromContext
);
var unpackHelperArguments =
new[]
{
context.Unpacker,
unpackingContext.Variable,
unpackingContext.Factory,
this.EmitGetMemberNamesExpression( context ),
this.EmitGetActionsExpression( context, ActionType.UnpackFromArray, isAsync )
}
#if FEATURE_TAP
.Concat( isAsync ? new[] { this.ReferCancellationToken( context, 2 ) } : NoConstructs ).ToArray()
#endif // FEATURE_TAP
;
yield return
this.EmitRetrunStatement(
context,
this.EmitInvokeMethodExpression(
context,
null,
new MethodDefinition(
AdjustName( MethodName.UnpackFromArray, isAsync ),
new [] { unpackingContext.Type, this.TargetType },
TypeDefinition.UnpackHelpersType,
true, // isStatic
#if FEATURE_TAP
isAsync ? typeof( Task<> ).MakeGenericType( this.TargetType ) :
#endif // FEATURE_TAP
this.TargetType,
unpackHelperArguments.Select( a => a.ContextType ).ToArray()
),
unpackHelperArguments
)
);
}
private UnpackingContextInfo GetTupleUnpackingContextInfo( TContext context, IList<Type> itemTypes )
{
TypeDefinition type;
ConstructorDefinition constructor;
context.DefineUnpackingContext(
itemTypes.Select( ( t, i ) =>
new KeyValuePair<string, TypeDefinition>( SerializationTarget.GetTupleItemNameFromIndex( i ), t )
).ToArray(),
out type,
out constructor
);
var unpackingContext = UnpackingContextInfo.Create( type, constructor, new HashSet<string>() );
unpackingContext.Variable = this.DeclareLocal( context, unpackingContext.VariableType, "unpackingContext" );
unpackingContext.Statements.Add( unpackingContext.Variable );
unpackingContext.Statements.Add(
this.EmitStoreVariableStatement(
context,
unpackingContext.Variable,
this.EmitCreateNewObjectExpression(
context,
unpackingContext.Variable,
unpackingContext.Constructor,
itemTypes.Select( t => this.MakeDefaultLiteral( context, t ) ).ToArray()
)
)
);
return unpackingContext;
}
private TConstruct EmitCheckTupleCardinarityExpression( TContext context, TConstruct unpacker, int cardinarity )
{
return
this.EmitConditionalExpression(
context,
this.EmitNotEqualsExpression(
context,
this.EmitGetPropertyExpression( context, unpacker, Metadata._Unpacker.ItemsCount ),
this.MakeInt64Literal( context, cardinarity ) // as i8 for compile time optimization
),
this.EmitInvokeVoidMethod(
context,
null,
SerializationExceptions.ThrowTupleCardinarityIsNotMatchMethod,
this.MakeInt32Literal( context, cardinarity ), // as i4 for valid API call
this.EmitGetPropertyExpression( context, unpacker, Metadata._Unpacker.ItemsCount ),
context.Unpacker
),
null
);
}
#endregion -- UnpackFrom --
}
}
| |
//Copyright (C) 2005 Richard J. Northedge
//
// 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 program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//This file is based on the ParserME.java source file found in the
//original java implementation of OpenNLP. That source file contains the following header:
//Copyright (C) 2003 Thomas Morton
//
//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 program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace OpenNLP.Tools.Parser
{
/// <summary>
/// Class for a shift reduce style parser based on Adwait Ratnaparki's 1998 thesis.
/// </summary>
public class MaximumEntropyParser
{
/// <summary>
/// The maximum number of parses advanced from all preceding parses at each derivation step.
/// </summary>
private readonly int m;
///<summary>
///The maximum number of parses to advance from a single preceding parse.
///</summary>
private readonly int k;
///<summary>
///The minimum total probability mass of advanced outcomes.
///</summary>
private readonly double q;
///<summary>
///The default beam size used if no beam size is given.
///</summary>
public const int DefaultBeamSize = 20;
///<summary>
///The default amount of probability mass required of advanced outcomes.
///</summary>
public const double DefaultAdvancePercentage = 0.95;
private readonly IParserTagger posTagger;
private readonly IParserChunker basalChunker;
private readonly SharpEntropy.IMaximumEntropyModel buildModel;
private readonly SharpEntropy.IMaximumEntropyModel checkModel;
private readonly BuildContextGenerator buildContextGenerator;
private readonly CheckContextGenerator checkContextGenerator;
private readonly IHeadRules headRules;
public const string TopNode = "TOP";
public const string TokenNode = "TK";
public const int Zero = 0;
/// <summary>
/// Prefix for outcomes starting a constituent.
/// </summary>
public const string StartPrefix = "S-";
/// <summary>
/// Prefix for outcomes continuing a constituent.
/// </summary>
public const string ContinuePrefix = "C-";
/// <summary>
/// Outcome for token which is not contained in a basal constituent.
/// </summary>
public const string OtherOutcome = "O";
/// <summary>
/// Outcome used when a constituent is complete.
/// </summary>
public const string CompleteOutcome = "c";
/// <summary>
/// Outcome used when a constituent is incomplete.
/// </summary>
public const string IncompleteOutcome = "i";
private const string MTopStart = StartPrefix + TopNode;
private readonly int topStartIndex;
private readonly Dictionary<string, string> startTypeMap;
private readonly Dictionary<string, string> continueTypeMap;
private readonly int completeIndex;
private readonly int incompleteIndex;
private const bool CreateDerivationString = false;
// Constructors -------------------------
///<summary>
///Creates a new parser using the specified models and head rules.
///</summary>
///<param name="buildModel">
///The model to assign constituent labels.
///</param>
///<param name="checkModel">
///The model to determine a constituent is complete.
///</param>
///<param name="tagger">
///The model to assign pos-tags.
///</param>
///<param name="chunker">
///The model to assign flat constituent labels.
///</param>
///<param name="headRules">
///The head rules for head word perculation.
///</param>
public MaximumEntropyParser(SharpEntropy.IMaximumEntropyModel buildModel, SharpEntropy.IMaximumEntropyModel checkModel, IParserTagger tagger, IParserChunker chunker, IHeadRules headRules) : this(buildModel, checkModel, tagger, chunker, headRules, DefaultBeamSize, DefaultAdvancePercentage)
{}
///<summary>
///Creates a new parser using the specified models and head rules using the specified beam size and advance percentage.
///</summary>
///<param name="buildModel">
///The model to assign constituent labels.
///</param>
///<param name="checkModel">
///The model to determine a constituent is complete.
///</param>
///<param name="tagger">
///The model to assign pos-tags.
///</param>
///<param name="chunker">
///The model to assign flat constituent labels.
///</param>
///<param name="headRules">
///The head rules for head word perculation.
///</param>
///<param name="beamSize">
///The number of different parses kept during parsing.
///</param>
///<param name="advancePercentage">
///The minimal amount of probability mass which advanced outcomes must represent.
///Only outcomes which contribute to the top "advancePercentage" will be explored.
///</param>
public MaximumEntropyParser(SharpEntropy.IMaximumEntropyModel buildModel, SharpEntropy.IMaximumEntropyModel checkModel, IParserTagger tagger, IParserChunker chunker, IHeadRules headRules, int beamSize, double advancePercentage)
{
posTagger = tagger;
basalChunker = chunker;
this.buildModel = buildModel;
this.checkModel = checkModel;
m = beamSize;
k = beamSize;
q = advancePercentage;
buildContextGenerator = new BuildContextGenerator();
checkContextGenerator = new CheckContextGenerator();
this.headRules = headRules;
startTypeMap = new Dictionary<string, string>();
continueTypeMap = new Dictionary<string, string>();
for (int buildOutcomeIndex = 0, buildOutcomeCount = buildModel.OutcomeCount; buildOutcomeIndex < buildOutcomeCount; buildOutcomeIndex++)
{
string outcome = buildModel.GetOutcomeName(buildOutcomeIndex);
if (outcome.StartsWith(StartPrefix))
{
//System.Console.Error.WriteLine("startMap " + outcome + "->" + outcome.Substring(StartPrefix.Length));
startTypeMap.Add(outcome, outcome.Substring(StartPrefix.Length));
}
else if (outcome.StartsWith(ContinuePrefix))
{
//System.Console.Error.WriteLine("contMap " + outcome + "->" + outcome.Substring(ContinuePrefix.Length));
continueTypeMap.Add(outcome, outcome.Substring(ContinuePrefix.Length));
}
}
topStartIndex = buildModel.GetOutcomeIndex(MTopStart);
completeIndex = checkModel.GetOutcomeIndex(CompleteOutcome);
incompleteIndex = checkModel.GetOutcomeIndex(IncompleteOutcome);
}
// Methods ------------------------------
/// <summary>
/// Returns a parse for the specified parse of tokens.
/// </summary>
/// <param name="flatParse">
/// A flat parse containing only tokens and a root node, p.
/// </param>
/// <param name="parseCount">
/// the number of parses required
/// </param>
/// <returns>
/// A full parse of the specified tokens or the flat chunks of the tokens if a full parse could not be found.
/// </returns>
public virtual Parse[] FullParse(Parse flatParse, int parseCount)
{
if (CreateDerivationString)
{
flatParse.InitializeDerivationBuffer();
}
var oldDerivationsHeap = new Util.SortedSet<Parse>();
var parses = new Util.SortedSet<Parse>();
int derivationLength = 0;
int maxDerivationLength = 2 * flatParse.ChildCount + 3;
oldDerivationsHeap.Add(flatParse);
Parse guessParse = null;
double bestComplete = - 100000; //approximating -infinity/0 in ln domain
var buildProbabilities = new double[this.buildModel.OutcomeCount];
var checkProbabilities = new double[this.checkModel.OutcomeCount];
while (parses.Count < m && derivationLength < maxDerivationLength)
{
var newDerivationsHeap = new Util.TreeSet<Parse>();
if (oldDerivationsHeap.Count > 0)
{
int derivationsProcessed = 0;
foreach (Parse currentParse in oldDerivationsHeap)
{
derivationsProcessed++;
if (derivationsProcessed >= k)
{
break;
}
// for each derivation
//Parse currentParse = (Parse) pi.Current;
if (currentParse.Probability < bestComplete) //this parse and the ones which follow will never win, stop advancing.
{
break;
}
if (guessParse == null && derivationLength == 2)
{
guessParse = currentParse;
}
Parse[] newDerivations = null;
if (0 == derivationLength)
{
newDerivations = AdvanceTags(currentParse);
}
else if (derivationLength == 1)
{
if (newDerivationsHeap.Count < k)
{
newDerivations = AdvanceChunks(currentParse, bestComplete);
}
else
{
newDerivations = AdvanceChunks(currentParse, newDerivationsHeap.Last().Probability);
}
}
else
{ // derivationLength > 1
newDerivations = AdvanceParses(currentParse, q, buildProbabilities, checkProbabilities);
}
if (newDerivations != null)
{
for (int currentDerivation = 0, derivationCount = newDerivations.Length; currentDerivation < derivationCount; currentDerivation++)
{
if (newDerivations[currentDerivation].IsComplete)
{
AdvanceTop(newDerivations[currentDerivation], buildProbabilities, checkProbabilities);
if (newDerivations[currentDerivation].Probability > bestComplete)
{
bestComplete = newDerivations[currentDerivation].Probability;
}
parses.Add(newDerivations[currentDerivation]);
}
else
{
newDerivationsHeap.Add(newDerivations[currentDerivation]);
}
}
//RN added sort
newDerivationsHeap.Sort();
}
else
{
//Console.Error.WriteLine("Couldn't advance parse " + derivationLength + " stage " + derivationsProcessed + "!\n");
}
}
derivationLength++;
oldDerivationsHeap = newDerivationsHeap;
}
else
{
break;
}
}
//RN added sort
parses.Sort();
if (parses.Count == 0)
{
//Console.Error.WriteLine("Couldn't find parse for: " + flatParse);
//oFullParse = (Parse) mOldDerivationsHeap.First();
return new Parse[] {guessParse};
}
else if (parseCount == 1)
{
//RN added parent adjustment
Parse topParse = parses.First();
topParse.UpdateChildParents();
return new Parse[] {topParse};
}
else
{
var topParses = new List<Parse>(parseCount);
while(!parses.IsEmpty() && topParses.Count < parseCount)
{
Parse topParse = parses.First();
//RN added parent adjustment
topParse.UpdateChildParents();
topParses.Add(topParse);
parses.Remove(topParse);
}
return topParses.ToArray();
}
}
private void AdvanceTop(Parse inputParse, double[] buildProbabilities, double[] checkProbabilities)
{
buildModel.Evaluate(buildContextGenerator.GetContext(inputParse.GetChildren(), 0), buildProbabilities);
inputParse.AddProbability(Math.Log(buildProbabilities[topStartIndex]));
checkModel.Evaluate(checkContextGenerator.GetContext(inputParse.GetChildren(), TopNode, 0, 0), checkProbabilities);
inputParse.AddProbability(Math.Log(checkProbabilities[completeIndex]));
inputParse.Type = TopNode;
}
///<summary>
///Advances the specified parse and returns the an array advanced parses whose probability accounts for
///more than the speicficed amount of probability mass, Q.
///</summary>
///<param name="inputParse">
///The parse to advance.
///</param>
///<param name="qParam">
///The amount of probability mass that should be accounted for by the advanced parses.
///</param>
private Parse[] AdvanceParses(Parse inputParse, double qParam, double[] buildProbabilities, double[] checkProbabilities)
{
double qOpp = 1 - qParam;
Parse lastStartNode = null; // The closest previous node which has been labeled as a start node.
int lastStartIndex = -1; // The index of the closest previous node which has been labeled as a start node.
string lastStartType = null; // The type of the closest previous node which has been labeled as a start node.
int advanceNodeIndex; // The index of the node which will be labeled in this iteration of advancing the parse.
Parse advanceNode = null; // The node which will be labeled in this iteration of advancing the parse.
Parse[] children = inputParse.GetChildren();
int nodeCount = children.Length;
//determines which node needs to be labeled and prior labels.
for (advanceNodeIndex = 0; advanceNodeIndex < nodeCount; advanceNodeIndex++)
{
advanceNode = children[advanceNodeIndex];
if (advanceNode.Label == null)
{
break;
}
else if (startTypeMap.ContainsKey(advanceNode.Label))
{
lastStartType = startTypeMap[advanceNode.Label];
lastStartNode = advanceNode;
lastStartIndex = advanceNodeIndex;
}
}
var newParsesList = new List<Parse>(buildModel.OutcomeCount);
//call build
buildModel.Evaluate(buildContextGenerator.GetContext(children, advanceNodeIndex), buildProbabilities);
double buildProbabilitiesSum = 0;
while (buildProbabilitiesSum < qParam)
{
// The largest unadvanced labeling.
int highestBuildProbabilityIndex = 0;
for (int probabilityIndex = 1; probabilityIndex < buildProbabilities.Length; probabilityIndex++)
{ //for each build outcome
if (buildProbabilities[probabilityIndex] > buildProbabilities[highestBuildProbabilityIndex])
{
highestBuildProbabilityIndex = probabilityIndex;
}
}
if (buildProbabilities[highestBuildProbabilityIndex] == 0)
{
break;
}
double highestBuildProbability = buildProbabilities[highestBuildProbabilityIndex];
buildProbabilities[highestBuildProbabilityIndex] = 0; //zero out so new max can be found
buildProbabilitiesSum += highestBuildProbability;
string tag = buildModel.GetOutcomeName(highestBuildProbabilityIndex);
//System.Console.Out.WriteLine("trying " + tag + " " + buildProbabilitiesSum + " lst=" + lst);
if (highestBuildProbabilityIndex == topStartIndex)
{ // can't have top until complete
continue;
}
//System.Console.Error.WriteLine(probabilityIndex + " " + tag + " " + highestBuildProbability);
if (startTypeMap.ContainsKey(tag))
{ //update last start
lastStartIndex = advanceNodeIndex;
lastStartNode = advanceNode;
lastStartType = startTypeMap[tag];
}
else if (continueTypeMap.ContainsKey(tag))
{
if (lastStartNode == null || lastStartType != continueTypeMap[tag])
{
continue; //Cont must match previous start or continue
}
}
var newParse1 = (Parse) inputParse.Clone(); //clone parse
if (CreateDerivationString)
{
newParse1.AppendDerivationBuffer(highestBuildProbabilityIndex.ToString(System.Globalization.CultureInfo.InvariantCulture));
newParse1.AppendDerivationBuffer("-");
}
newParse1.SetChild(advanceNodeIndex, tag); //replace constituent labeled
newParse1.AddProbability(Math.Log(highestBuildProbability));
//check
checkModel.Evaluate(checkContextGenerator.GetContext(newParse1.GetChildren(), lastStartType, lastStartIndex, advanceNodeIndex), checkProbabilities);
//System.Console.Out.WriteLine("check " + mCheckProbabilities[mCompleteIndex] + " " + mCheckProbabilities[mIncompleteIndex]);
Parse newParse2 = newParse1;
if (checkProbabilities[completeIndex] > qOpp)
{ //make sure a reduce is likely
newParse2 = (Parse) newParse1.Clone();
if (CreateDerivationString)
{
newParse2.AppendDerivationBuffer("1");
newParse2.AppendDerivationBuffer(".");
}
newParse2.AddProbability(System.Math.Log(checkProbabilities[1]));
var constituent = new Parse[advanceNodeIndex - lastStartIndex + 1];
bool isFlat = true;
//first
constituent[0] = lastStartNode;
if (constituent[0].Type != constituent[0].Head.Type)
{
isFlat = false;
}
//last
constituent[advanceNodeIndex - lastStartIndex] = advanceNode;
if (isFlat && constituent[advanceNodeIndex - lastStartIndex].Type != constituent[advanceNodeIndex - lastStartIndex].Head.Type)
{
isFlat = false;
}
//middle
for (int constituentIndex = 1; constituentIndex < advanceNodeIndex - lastStartIndex; constituentIndex++)
{
constituent[constituentIndex] = children[constituentIndex + lastStartIndex];
if (isFlat && constituent[constituentIndex].Type != constituent[constituentIndex].Head.Type)
{
isFlat = false;
}
}
if (!isFlat)
{ //flat chunks are done by chunker
newParse2.Insert(new Parse(inputParse.Text, new Util.Span(lastStartNode.Span.Start, advanceNode.Span.End), lastStartType, checkProbabilities[1], headRules.GetHead(constituent, lastStartType)));
newParsesList.Add(newParse2);
}
}
if (checkProbabilities[incompleteIndex] > qOpp)
{ //make sure a shift is likely
if (CreateDerivationString)
{
newParse1.AppendDerivationBuffer("0");
newParse1.AppendDerivationBuffer(".");
}
if (advanceNodeIndex != nodeCount - 1)
{ //can't shift last element
newParse1.AddProbability(Math.Log(checkProbabilities[0]));
newParsesList.Add(newParse1);
}
}
}
Parse[] newParses = newParsesList.ToArray();
return newParses;
}
///<summary>
///Returns the top chunk sequences for the specified parse.
///</summary>
///<param name="inputParse">
///A pos-tag assigned parse.
///</param>
/// <param name="minChunkScore">
/// the minimum probability for an allowed chunk sequence.
/// </param>
///<returns>
///The top chunk assignments to the specified parse.
///</returns>
private Parse[] AdvanceChunks(Parse inputParse, double minChunkScore)
{
// chunk
Parse[] children = inputParse.GetChildren();
var words = new string[children.Length];
var parseTags = new string[words.Length];
var probabilities = new double[words.Length];
for (int childParseIndex = 0, childParseCount = children.Length; childParseIndex < childParseCount; childParseIndex++)
{
Parse currentChildParse = children[childParseIndex];
words[childParseIndex] = currentChildParse.Head.ToString();
parseTags[childParseIndex] = currentChildParse.Type;
}
//System.Console.Error.WriteLine("adjusted min chunk score = " + (minChunkScore - inputParse.Probability));
Util.Sequence[] chunkerSequences = basalChunker.TopKSequences(words, parseTags, minChunkScore - inputParse.Probability);
var newParses = new Parse[chunkerSequences.Length];
for (int sequenceIndex = 0, sequenceCount = chunkerSequences.Length; sequenceIndex < sequenceCount; sequenceIndex++)
{
newParses[sequenceIndex] = (Parse) inputParse.Clone(); //copies top level
if (CreateDerivationString)
{
newParses[sequenceIndex].AppendDerivationBuffer(sequenceIndex.ToString(System.Globalization.CultureInfo.InvariantCulture));
newParses[sequenceIndex].AppendDerivationBuffer(".");
}
string[] tags = chunkerSequences[sequenceIndex].Outcomes.ToArray();
chunkerSequences[sequenceIndex].GetProbabilities(probabilities);
int start = -1;
int end = 0;
string type = null;
//System.Console.Error.Write("sequence " + sequenceIndex + " ");
for (int tagIndex = 0; tagIndex <= tags.Length; tagIndex++)
{
//if (tagIndex != tags.Length)
//{
// System.Console.Error.WriteLine(words[tagIndex] + " " + parseTags[tagIndex] + " " + tags[tagIndex] + " " + probabilities[tagIndex]);
//}
if (tagIndex != tags.Length)
{
newParses[sequenceIndex].AddProbability(Math.Log(probabilities[tagIndex]));
}
if (tagIndex != tags.Length && tags[tagIndex].StartsWith(ContinuePrefix))
{ // if continue just update end chunking tag don't use mContinueTypeMap
end = tagIndex;
}
else
{ //make previous constituent if it exists
if (type != null)
{
//System.Console.Error.WriteLine("inserting tag " + tags[tagIndex]);
Parse startParse = children[start];
Parse endParse = children[end];
//System.Console.Error.WriteLine("Putting " + type + " at " + start + "," + end + " " + newParses[sequenceIndex].Probability);
var consitituents = new Parse[end - start + 1];
consitituents[0] = startParse;
//consitituents[0].Label = "Start-" + type;
if (end - start != 0)
{
consitituents[end - start] = endParse;
//consitituents[end - start].Label = "Cont-" + type;
for (int constituentIndex = 1; constituentIndex < end - start; constituentIndex++)
{
consitituents[constituentIndex] = children[constituentIndex + start];
//consitituents[constituentIndex].Label = "Cont-" + type;
}
}
newParses[sequenceIndex].Insert(new Parse(startParse.Text, new Util.Span(startParse.Span.Start, endParse.Span.End), type, 1, headRules.GetHead(consitituents, type)));
}
if (tagIndex != tags.Length)
{ //update for new constituent
if (tags[tagIndex].StartsWith(StartPrefix))
{ // don't use mStartTypeMap these are chunk tags
type = tags[tagIndex].Substring(StartPrefix.Length);
start = tagIndex;
end = tagIndex;
}
else
{ // other
type = null;
}
}
}
}
//newParses[sequenceIndex].Show();
//System.Console.Out.WriteLine();
}
return newParses;
}
///<summary>
///Advances the parse by assigning it POS tags and returns multiple tag sequences.
///</summary>
///<param name="inputParse">
///The parse to be tagged.
///</param>
///<returns>
///Parses with different pos-tag sequence assignments.
///</returns>
private Parse[] AdvanceTags(Parse inputParse)
{
Parse[] children = inputParse.GetChildren();
var words = children.Select(ch => ch.ToString()).ToArray();
var probabilities = new double[words.Length];
Util.Sequence[] tagSequences = posTagger.TopKSequences(words);
if (tagSequences.Length == 0)
{
Console.Error.WriteLine("no tag sequence");
}
var newParses = new Parse[tagSequences.Length];
for (int tagSequenceIndex = 0; tagSequenceIndex < tagSequences.Length; tagSequenceIndex++)
{
string[] tags = tagSequences[tagSequenceIndex].Outcomes.ToArray();
tagSequences[tagSequenceIndex].GetProbabilities(probabilities);
newParses[tagSequenceIndex] = (Parse) inputParse.Clone(); //copies top level
if (CreateDerivationString)
{
newParses[tagSequenceIndex].AppendDerivationBuffer(tagSequenceIndex.ToString(System.Globalization.CultureInfo.InvariantCulture));
newParses[tagSequenceIndex].AppendDerivationBuffer(".");
}
for (int wordIndex = 0; wordIndex < words.Length; wordIndex++)
{
Parse wordParse = children[wordIndex];
//System.Console.Error.WriteLine("inserting tag " + tags[wordIndex]);
double wordProbability = probabilities[wordIndex];
newParses[tagSequenceIndex].Insert(new Parse(wordParse.Text, wordParse.Span, tags[wordIndex], wordProbability));
newParses[tagSequenceIndex].AddProbability(Math.Log(wordProbability));
//newParses[tagSequenceIndex].Show();
}
}
return newParses;
}
// Utilities -----------------------
private static SharpEntropy.GisModel Train(SharpEntropy.ITrainingEventReader eventStream, int iterations, int cut)
{
var trainer = new SharpEntropy.GisTrainer();
trainer.TrainModel(iterations, new SharpEntropy.TwoPassDataIndexer(eventStream, cut));
return new SharpEntropy.GisModel(trainer);
}
public static SharpEntropy.GisModel TrainModel(string trainingFile, EventType modelType, string headRulesFile)
{
return TrainModel(trainingFile, modelType, headRulesFile, 100, 5);
}
public static SharpEntropy.GisModel TrainModel(string trainingFile, EventType modelType, string headRulesFile, int iterations, int cutoff)
{
var rules = new EnglishHeadRules(headRulesFile);
SharpEntropy.ITrainingEventReader eventReader = new ParserEventReader(new SharpEntropy.PlainTextByLineDataReader(new StreamReader(trainingFile)), rules, modelType);
return Train(eventReader, iterations, cutoff);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Services
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Services;
/// <summary>
/// Static proxy methods.
/// </summary>
internal static class ServiceProxySerializer
{
/// <summary>
/// Writes proxy method invocation data to the specified writer.
/// </summary>
/// <param name="writer">Writer.</param>
/// <param name="methodName">Name of the method.</param>
/// <param name="method">Method (optional, can be null).</param>
/// <param name="arguments">Arguments.</param>
/// <param name="platformType">The platform.</param>
public static void WriteProxyMethod(BinaryWriter writer, string methodName, MethodBase method,
object[] arguments, PlatformType platformType)
{
Debug.Assert(writer != null);
writer.WriteString(methodName);
if (arguments != null)
{
writer.WriteBoolean(true);
writer.WriteInt(arguments.Length);
if (platformType == PlatformType.DotNet)
{
// Write as is for .NET.
foreach (var arg in arguments)
{
writer.WriteObjectDetached(arg);
}
}
else
{
// Other platforms do not support Serializable, need to convert arrays and collections
var mParams = method != null ? method.GetParameters() : null;
Debug.Assert(mParams == null || mParams.Length == arguments.Length);
for (var i = 0; i < arguments.Length; i++)
{
WriteArgForPlatforms(writer, mParams != null ? mParams[i].ParameterType : null,
arguments[i]);
}
}
}
else
writer.WriteBoolean(false);
}
/// <summary>
/// Reads proxy method invocation data from the specified reader.
/// </summary>
/// <param name="stream">Stream.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="mthdName">Method name.</param>
/// <param name="mthdArgs">Method arguments.</param>
public static void ReadProxyMethod(IBinaryStream stream, Marshaller marsh,
out string mthdName, out object[] mthdArgs)
{
var reader = marsh.StartUnmarshal(stream);
var srvKeepBinary = reader.ReadBoolean();
mthdName = reader.ReadString();
if (reader.ReadBoolean())
{
mthdArgs = new object[reader.ReadInt()];
if (srvKeepBinary)
reader = marsh.StartUnmarshal(stream, true);
for (var i = 0; i < mthdArgs.Length; i++)
mthdArgs[i] = reader.ReadObject<object>();
}
else
mthdArgs = null;
}
/// <summary>
/// Writes method invocation result.
/// </summary>
/// <param name="stream">Stream.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="methodResult">Method result.</param>
/// <param name="invocationError">Method invocation error.</param>
public static void WriteInvocationResult(IBinaryStream stream, Marshaller marsh, object methodResult,
Exception invocationError)
{
Debug.Assert(stream != null);
Debug.Assert(marsh != null);
var writer = marsh.StartMarshal(stream);
BinaryUtils.WriteInvocationResult(writer, invocationError == null, invocationError ?? methodResult);
marsh.FinishMarshal(writer);
}
/// <summary>
/// Reads method invocation result.
/// </summary>
/// <param name="stream">Stream.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="keepBinary">Binary flag.</param>
/// <returns>
/// Method invocation result, or exception in case of error.
/// </returns>
public static object ReadInvocationResult(IBinaryStream stream, Marshaller marsh, bool keepBinary)
{
Debug.Assert(stream != null);
Debug.Assert(marsh != null);
var mode = keepBinary ? BinaryMode.ForceBinary : BinaryMode.Deserialize;
var reader = marsh.StartUnmarshal(stream, mode);
object err;
var res = BinaryUtils.ReadInvocationResult(reader, out err);
if (err == null)
return res;
var binErr = err as IBinaryObject;
throw binErr != null
? new ServiceInvocationException("Proxy method invocation failed with a binary error. " +
"Examine BinaryCause for details.", binErr)
: new ServiceInvocationException("Proxy method invocation failed with an exception. " +
"Examine InnerException for details.", (Exception) err);
}
/// <summary>
/// Reads service deployment result.
/// </summary>
/// <param name="stream">Stream.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="keepBinary">Binary flag.</param>
/// <returns>
/// Method invocation result, or exception in case of error.
/// </returns>
public static void ReadDeploymentResult(IBinaryStream stream, Marshaller marsh, bool keepBinary)
{
Debug.Assert(stream != null);
Debug.Assert(marsh != null);
var mode = keepBinary ? BinaryMode.ForceBinary : BinaryMode.Deserialize;
var reader = marsh.StartUnmarshal(stream, mode);
object err;
BinaryUtils.ReadInvocationResult(reader, out err);
if (err == null)
{
return;
}
// read failed configurations
ICollection<ServiceConfiguration> failedCfgs;
try
{
// switch to BinaryMode.Deserialize mode to avoid IService casting exception
reader = marsh.StartUnmarshal(stream);
failedCfgs = reader.ReadNullableCollectionRaw(f => new ServiceConfiguration(f));
}
catch (Exception e)
{
throw new ServiceDeploymentException("Service deployment failed with an exception. " +
"Examine InnerException for details.", e);
}
var binErr = err as IBinaryObject;
throw binErr != null
? new ServiceDeploymentException("Service deployment failed with a binary error. " +
"Examine BinaryCause for details.", binErr, failedCfgs)
: new ServiceDeploymentException("Service deployment failed with an exception. " +
"Examine InnerException for details.", (Exception) err, failedCfgs);
}
/// <summary>
/// Writes the argument in platform-compatible format.
/// </summary>
private static void WriteArgForPlatforms(BinaryWriter writer, Type paramType, object arg)
{
var hnd = GetPlatformArgWriter(paramType, arg);
if (hnd != null)
{
hnd(writer, arg);
}
else
{
writer.WriteObjectDetached(arg);
}
}
/// <summary>
/// Gets arg writer for platform-compatible service calls.
/// </summary>
private static Action<BinaryWriter, object> GetPlatformArgWriter(Type paramType, object arg)
{
if (arg == null)
{
return null;
}
var type = paramType ?? arg.GetType();
// Unwrap nullable
type = Nullable.GetUnderlyingType(type) ?? type;
if (type.IsPrimitive)
return null;
if (type.IsArray)
{
Type elemType = type.GetElementType();
if (elemType == typeof(Guid?))
return (writer, o) => writer.WriteGuidArray((Guid?[]) o);
else if (elemType == typeof(DateTime?))
return (writer, o) => writer.WriteTimestampArray((DateTime?[]) o);
}
var handler = BinarySystemHandlers.GetWriteHandler(type, true);
if (handler != null)
return null;
if (type.IsArray)
return (writer, o) => writer.WriteArrayInternal((Array) o);
if (arg is IDictionary)
return (writer, o) => writer.WriteDictionary((IDictionary) o);
if (arg is ICollection)
return (writer, o) => writer.WriteCollection((ICollection) o);
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Diagnostics;
namespace System.Runtime.Serialization.Formatters.Binary
{
internal sealed class ObjectReader
{
// System.Serializer information
internal Stream _stream;
internal ISurrogateSelector _surrogates;
internal StreamingContext _context;
internal ObjectManager _objectManager;
internal InternalFE _formatterEnums;
internal SerializationBinder _binder;
// Top object and headers
internal long _topId;
internal bool _isSimpleAssembly = false;
internal object _topObject;
internal SerObjectInfoInit _serObjectInfoInit;
internal IFormatterConverter _formatterConverter;
// Stack of Object ParseRecords
internal SerStack _stack;
// ValueType Fixup Stack
private SerStack _valueFixupStack;
// Cross AppDomain
internal object[] _crossAppDomainArray; //Set by the BinaryFormatter
//MethodCall and MethodReturn are handled special for perf reasons
private bool _fullDeserialization;
private SerStack ValueFixupStack => _valueFixupStack ?? (_valueFixupStack = new SerStack("ValueType Fixup Stack"));
// Older formatters generate ids for valuetypes using a different counter than ref types. Newer ones use
// a single counter, only value types have a negative value. Need a way to handle older formats.
private const int ThresholdForValueTypeIds = int.MaxValue;
private bool _oldFormatDetected = false;
private IntSizedArray _valTypeObjectIdTable;
private readonly NameCache _typeCache = new NameCache();
internal object TopObject
{
get { return _topObject; }
set
{
_topObject = value;
if (_objectManager != null)
{
_objectManager.TopObject = value;
}
}
}
internal ObjectReader(Stream stream, ISurrogateSelector selector, StreamingContext context, InternalFE formatterEnums, SerializationBinder binder)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
_stream = stream;
_surrogates = selector;
_context = context;
_binder = binder;
_formatterEnums = formatterEnums;
}
internal object Deserialize(BinaryParser serParser, bool fCheck)
{
if (serParser == null)
{
throw new ArgumentNullException(nameof(serParser));
}
_fullDeserialization = false;
TopObject = null;
_topId = 0;
_isSimpleAssembly = (_formatterEnums._assemblyFormat == FormatterAssemblyStyle.Simple);
if (_fullDeserialization)
{
// Reinitialize
_objectManager = new ObjectManager(_surrogates, _context, false, false);
_serObjectInfoInit = new SerObjectInfoInit();
}
// Will call back to ParseObject, ParseHeader for each object found
serParser.Run();
if (_fullDeserialization)
{
_objectManager.DoFixups();
}
if (TopObject == null)
{
throw new SerializationException(SR.Serialization_TopObject);
}
//if TopObject has a surrogate then the actual object may be changed during special fixup
//So refresh it using topID.
if (HasSurrogate(TopObject.GetType()) && _topId != 0)//Not yet resolved
{
TopObject = _objectManager.GetObject(_topId);
}
if (TopObject is IObjectReference)
{
TopObject = ((IObjectReference)TopObject).GetRealObject(_context);
}
if (_fullDeserialization)
{
_objectManager.RaiseDeserializationEvent(); // This will raise both IDeserialization and [OnDeserialized] events
}
return TopObject;
}
private bool HasSurrogate(Type t)
{
ISurrogateSelector ignored;
return _surrogates != null && _surrogates.GetSurrogate(t, _context, out ignored) != null;
}
private void CheckSerializable(Type t)
{
if (!t.IsSerializable && !HasSurrogate(t))
{
throw new SerializationException(string.Format(CultureInfo.InvariantCulture, SR.Serialization_NonSerType, t.FullName, t.Assembly.FullName));
}
}
private void InitFullDeserialization()
{
_fullDeserialization = true;
_stack = new SerStack("ObjectReader Object Stack");
_objectManager = new ObjectManager(_surrogates, _context, false, false);
if (_formatterConverter == null)
{
_formatterConverter = new FormatterConverter();
}
}
internal object CrossAppDomainArray(int index)
{
Debug.Assert(index < _crossAppDomainArray.Length, "[System.Runtime.Serialization.Formatters.BinaryObjectReader index out of range for CrossAppDomainArray]");
return _crossAppDomainArray[index];
}
internal ReadObjectInfo CreateReadObjectInfo(Type objectType)
{
return ReadObjectInfo.Create(objectType, _surrogates, _context, _objectManager, _serObjectInfoInit, _formatterConverter, _isSimpleAssembly);
}
internal ReadObjectInfo CreateReadObjectInfo(Type objectType, string[] memberNames, Type[] memberTypes)
{
return ReadObjectInfo.Create(objectType, memberNames, memberTypes, _surrogates, _context, _objectManager, _serObjectInfoInit, _formatterConverter, _isSimpleAssembly);
}
internal void Parse(ParseRecord pr)
{
switch (pr._parseTypeEnum)
{
case InternalParseTypeE.SerializedStreamHeader:
ParseSerializedStreamHeader(pr);
break;
case InternalParseTypeE.SerializedStreamHeaderEnd:
ParseSerializedStreamHeaderEnd(pr);
break;
case InternalParseTypeE.Object:
ParseObject(pr);
break;
case InternalParseTypeE.ObjectEnd:
ParseObjectEnd(pr);
break;
case InternalParseTypeE.Member:
ParseMember(pr);
break;
case InternalParseTypeE.MemberEnd:
ParseMemberEnd(pr);
break;
case InternalParseTypeE.Body:
case InternalParseTypeE.BodyEnd:
case InternalParseTypeE.Envelope:
case InternalParseTypeE.EnvelopeEnd:
break;
case InternalParseTypeE.Empty:
default:
throw new SerializationException(SR.Format(SR.Serialization_XMLElement, pr._name));
}
}
// Styled ParseError output
private void ParseError(ParseRecord processing, ParseRecord onStack)
{
throw new SerializationException(SR.Format(SR.Serialization_ParseError, onStack._name + " " + onStack._parseTypeEnum + " " + processing._name + " " + processing._parseTypeEnum));
}
// Parse the SerializedStreamHeader element. This is the first element in the stream if present
private void ParseSerializedStreamHeader(ParseRecord pr) => _stack.Push(pr);
// Parse the SerializedStreamHeader end element. This is the last element in the stream if present
private void ParseSerializedStreamHeaderEnd(ParseRecord pr) => _stack.Pop();
// New object encountered in stream
private void ParseObject(ParseRecord pr)
{
if (!_fullDeserialization)
{
InitFullDeserialization();
}
if (pr._objectPositionEnum == InternalObjectPositionE.Top)
{
_topId = pr._objectId;
}
if (pr._parseTypeEnum == InternalParseTypeE.Object)
{
_stack.Push(pr); // Nested objects member names are already on stack
}
if (pr._objectTypeEnum == InternalObjectTypeE.Array)
{
ParseArray(pr);
return;
}
// If the Type is null, this means we have a typeload issue
// mark the object with TypeLoadExceptionHolder
if (pr._dtType == null)
{
pr._newObj = new TypeLoadExceptionHolder(pr._keyDt);
return;
}
if (ReferenceEquals(pr._dtType, Converter.s_typeofString))
{
// String as a top level object
if (pr._value != null)
{
pr._newObj = pr._value;
if (pr._objectPositionEnum == InternalObjectPositionE.Top)
{
TopObject = pr._newObj;
return;
}
else
{
_stack.Pop();
RegisterObject(pr._newObj, pr, (ParseRecord)_stack.Peek());
return;
}
}
else
{
// xml Doesn't have the value until later
return;
}
}
else
{
CheckSerializable(pr._dtType);
pr._newObj = FormatterServices.GetUninitializedObject(pr._dtType);
// Run the OnDeserializing methods
_objectManager.RaiseOnDeserializingEvent(pr._newObj);
}
if (pr._newObj == null)
{
throw new SerializationException(SR.Format(SR.Serialization_TopObjectInstantiate, pr._dtType));
}
if (pr._objectPositionEnum == InternalObjectPositionE.Top)
{
TopObject = pr._newObj;
}
if (pr._objectInfo == null)
{
pr._objectInfo = ReadObjectInfo.Create(pr._dtType, _surrogates, _context, _objectManager, _serObjectInfoInit, _formatterConverter, _isSimpleAssembly);
}
}
// End of object encountered in stream
private void ParseObjectEnd(ParseRecord pr)
{
ParseRecord objectPr = (ParseRecord)_stack.Peek() ?? pr;
if (objectPr._objectPositionEnum == InternalObjectPositionE.Top)
{
if (ReferenceEquals(objectPr._dtType, Converter.s_typeofString))
{
objectPr._newObj = objectPr._value;
TopObject = objectPr._newObj;
return;
}
}
_stack.Pop();
ParseRecord parentPr = (ParseRecord)_stack.Peek();
if (objectPr._newObj == null)
{
return;
}
if (objectPr._objectTypeEnum == InternalObjectTypeE.Array)
{
if (objectPr._objectPositionEnum == InternalObjectPositionE.Top)
{
TopObject = objectPr._newObj;
}
RegisterObject(objectPr._newObj, objectPr, parentPr);
return;
}
objectPr._objectInfo.PopulateObjectMembers(objectPr._newObj, objectPr._memberData);
// Registration is after object is populated
if ((!objectPr._isRegistered) && (objectPr._objectId > 0))
{
RegisterObject(objectPr._newObj, objectPr, parentPr);
}
if (objectPr._isValueTypeFixup)
{
ValueFixup fixup = (ValueFixup)ValueFixupStack.Pop(); //Value fixup
fixup.Fixup(objectPr, parentPr); // Value fixup
}
if (objectPr._objectPositionEnum == InternalObjectPositionE.Top)
{
TopObject = objectPr._newObj;
}
objectPr._objectInfo.ObjectEnd();
}
// Array object encountered in stream
private void ParseArray(ParseRecord pr)
{
long genId = pr._objectId;
if (pr._arrayTypeEnum == InternalArrayTypeE.Base64)
{
// ByteArray
pr._newObj = pr._value.Length > 0 ?
Convert.FromBase64String(pr._value) :
Array.Empty<byte>();
if (_stack.Peek() == pr)
{
_stack.Pop();
}
if (pr._objectPositionEnum == InternalObjectPositionE.Top)
{
TopObject = pr._newObj;
}
ParseRecord parentPr = (ParseRecord)_stack.Peek();
// Base64 can be registered at this point because it is populated
RegisterObject(pr._newObj, pr, parentPr);
}
else if ((pr._newObj != null) && Converter.IsWriteAsByteArray(pr._arrayElementTypeCode))
{
// Primtive typed Array has already been read
if (pr._objectPositionEnum == InternalObjectPositionE.Top)
{
TopObject = pr._newObj;
}
ParseRecord parentPr = (ParseRecord)_stack.Peek();
// Primitive typed array can be registered at this point because it is populated
RegisterObject(pr._newObj, pr, parentPr);
}
else if ((pr._arrayTypeEnum == InternalArrayTypeE.Jagged) || (pr._arrayTypeEnum == InternalArrayTypeE.Single))
{
// Multidimensional jagged array or single array
bool couldBeValueType = true;
if ((pr._lowerBoundA == null) || (pr._lowerBoundA[0] == 0))
{
if (ReferenceEquals(pr._arrayElementType, Converter.s_typeofString))
{
pr._objectA = new string[pr._lengthA[0]];
pr._newObj = pr._objectA;
couldBeValueType = false;
}
else if (ReferenceEquals(pr._arrayElementType, Converter.s_typeofObject))
{
pr._objectA = new object[pr._lengthA[0]];
pr._newObj = pr._objectA;
couldBeValueType = false;
}
else if (pr._arrayElementType != null)
{
pr._newObj = Array.CreateInstance(pr._arrayElementType, pr._lengthA[0]);
}
pr._isLowerBound = false;
}
else
{
if (pr._arrayElementType != null)
{
pr._newObj = Array.CreateInstance(pr._arrayElementType, pr._lengthA, pr._lowerBoundA);
}
pr._isLowerBound = true;
}
if (pr._arrayTypeEnum == InternalArrayTypeE.Single)
{
if (!pr._isLowerBound && (Converter.IsWriteAsByteArray(pr._arrayElementTypeCode)))
{
pr._primitiveArray = new PrimitiveArray(pr._arrayElementTypeCode, (Array)pr._newObj);
}
else if (couldBeValueType && pr._arrayElementType != null)
{
if (!pr._arrayElementType.IsValueType && !pr._isLowerBound)
{
pr._objectA = (object[])pr._newObj;
}
}
}
pr._indexMap = new int[1];
}
else if (pr._arrayTypeEnum == InternalArrayTypeE.Rectangular)
{
// Rectangle array
pr._isLowerBound = false;
if (pr._lowerBoundA != null)
{
for (int i = 0; i < pr._rank; i++)
{
if (pr._lowerBoundA[i] != 0)
{
pr._isLowerBound = true;
}
}
}
if (pr._arrayElementType != null)
{
pr._newObj = !pr._isLowerBound ?
Array.CreateInstance(pr._arrayElementType, pr._lengthA) :
Array.CreateInstance(pr._arrayElementType, pr._lengthA, pr._lowerBoundA);
}
// Calculate number of items
int sum = 1;
for (int i = 0; i < pr._rank; i++)
{
sum = sum * pr._lengthA[i];
}
pr._indexMap = new int[pr._rank];
pr._rectangularMap = new int[pr._rank];
pr._linearlength = sum;
}
else
{
throw new SerializationException(SR.Format(SR.Serialization_ArrayType, pr._arrayTypeEnum));
}
}
// Builds a map for each item in an incoming rectangle array. The map specifies where the item is placed in the output Array Object
private void NextRectangleMap(ParseRecord pr)
{
// For each invocation, calculate the next rectangular array position
// example
// indexMap 0 [0,0,0]
// indexMap 1 [0,0,1]
// indexMap 2 [0,0,2]
// indexMap 3 [0,0,3]
// indexMap 4 [0,1,0]
for (int irank = pr._rank - 1; irank > -1; irank--)
{
// Find the current or lower dimension which can be incremented.
if (pr._rectangularMap[irank] < pr._lengthA[irank] - 1)
{
// The current dimension is at maximum. Increase the next lower dimension by 1
pr._rectangularMap[irank]++;
if (irank < pr._rank - 1)
{
// The current dimension and higher dimensions are zeroed.
for (int i = irank + 1; i < pr._rank; i++)
{
pr._rectangularMap[i] = 0;
}
}
Array.Copy(pr._rectangularMap, 0, pr._indexMap, 0, pr._rank);
break;
}
}
}
// Array object item encountered in stream
private void ParseArrayMember(ParseRecord pr)
{
ParseRecord objectPr = (ParseRecord)_stack.Peek();
// Set up for inserting value into correct array position
if (objectPr._arrayTypeEnum == InternalArrayTypeE.Rectangular)
{
if (objectPr._memberIndex > 0)
{
NextRectangleMap(objectPr); // Rectangle array, calculate position in array
}
if (objectPr._isLowerBound)
{
for (int i = 0; i < objectPr._rank; i++)
{
objectPr._indexMap[i] = objectPr._rectangularMap[i] + objectPr._lowerBoundA[i];
}
}
}
else
{
objectPr._indexMap[0] = !objectPr._isLowerBound ?
objectPr._memberIndex : // Zero based array
objectPr._lowerBoundA[0] + objectPr._memberIndex; // Lower Bound based array
}
// Set Array element according to type of element
if (pr._memberValueEnum == InternalMemberValueE.Reference)
{
// Object Reference
// See if object has already been instantiated
object refObj = _objectManager.GetObject(pr._idRef);
if (refObj == null)
{
// Object not instantiated
// Array fixup manager
int[] fixupIndex = new int[objectPr._rank];
Array.Copy(objectPr._indexMap, 0, fixupIndex, 0, objectPr._rank);
_objectManager.RecordArrayElementFixup(objectPr._objectId, fixupIndex, pr._idRef);
}
else
{
if (objectPr._objectA != null)
{
objectPr._objectA[objectPr._indexMap[0]] = refObj;
}
else
{
((Array)objectPr._newObj).SetValue(refObj, objectPr._indexMap); // Object has been instantiated
}
}
}
else if (pr._memberValueEnum == InternalMemberValueE.Nested)
{
//Set up dtType for ParseObject
if (pr._dtType == null)
{
pr._dtType = objectPr._arrayElementType;
}
ParseObject(pr);
_stack.Push(pr);
if (objectPr._arrayElementType != null)
{
if ((objectPr._arrayElementType.IsValueType) && (pr._arrayElementTypeCode == InternalPrimitiveTypeE.Invalid))
{
pr._isValueTypeFixup = true; //Valuefixup
ValueFixupStack.Push(new ValueFixup((Array)objectPr._newObj, objectPr._indexMap)); //valuefixup
}
else
{
if (objectPr._objectA != null)
{
objectPr._objectA[objectPr._indexMap[0]] = pr._newObj;
}
else
{
((Array)objectPr._newObj).SetValue(pr._newObj, objectPr._indexMap);
}
}
}
}
else if (pr._memberValueEnum == InternalMemberValueE.InlineValue)
{
if ((ReferenceEquals(objectPr._arrayElementType, Converter.s_typeofString)) || (ReferenceEquals(pr._dtType, Converter.s_typeofString)))
{
// String in either a string array, or a string element of an object array
ParseString(pr, objectPr);
if (objectPr._objectA != null)
{
objectPr._objectA[objectPr._indexMap[0]] = pr._value;
}
else
{
((Array)objectPr._newObj).SetValue(pr._value, objectPr._indexMap);
}
}
else if (objectPr._isArrayVariant)
{
// Array of type object
if (pr._keyDt == null)
{
throw new SerializationException(SR.Serialization_ArrayTypeObject);
}
object var = null;
if (ReferenceEquals(pr._dtType, Converter.s_typeofString))
{
ParseString(pr, objectPr);
var = pr._value;
}
else if (ReferenceEquals(pr._dtTypeCode, InternalPrimitiveTypeE.Invalid))
{
CheckSerializable(pr._dtType);
// Not nested and invalid, so it is an empty object
var = FormatterServices.GetUninitializedObject(pr._dtType);
}
else
{
var = pr._varValue != null ?
pr._varValue :
Converter.FromString(pr._value, pr._dtTypeCode);
}
if (objectPr._objectA != null)
{
objectPr._objectA[objectPr._indexMap[0]] = var;
}
else
{
((Array)objectPr._newObj).SetValue(var, objectPr._indexMap); // Primitive type
}
}
else
{
// Primitive type
if (objectPr._primitiveArray != null)
{
// Fast path for Soap primitive arrays. Binary was handled in the BinaryParser
objectPr._primitiveArray.SetValue(pr._value, objectPr._indexMap[0]);
}
else
{
object var = pr._varValue != null ?
pr._varValue :
Converter.FromString(pr._value, objectPr._arrayElementTypeCode);
if (objectPr._objectA != null)
{
objectPr._objectA[objectPr._indexMap[0]] = var;
}
else
{
((Array)objectPr._newObj).SetValue(var, objectPr._indexMap); // Primitive type
}
}
}
}
else if (pr._memberValueEnum == InternalMemberValueE.Null)
{
objectPr._memberIndex += pr._consecutiveNullArrayEntryCount - 1; //also incremented again below
}
else
{
ParseError(pr, objectPr);
}
objectPr._memberIndex++;
}
private void ParseArrayMemberEnd(ParseRecord pr)
{
// If this is a nested array object, then pop the stack
if (pr._memberValueEnum == InternalMemberValueE.Nested)
{
ParseObjectEnd(pr);
}
}
// Object member encountered in stream
private void ParseMember(ParseRecord pr)
{
ParseRecord objectPr = (ParseRecord)_stack.Peek();
string objName = objectPr?._name;
switch (pr._memberTypeEnum)
{
case InternalMemberTypeE.Item:
ParseArrayMember(pr);
return;
case InternalMemberTypeE.Field:
break;
}
//if ((pr.PRdtType == null) && !objectPr.PRobjectInfo.isSi)
if (pr._dtType == null && objectPr._objectInfo._isTyped)
{
pr._dtType = objectPr._objectInfo.GetType(pr._name);
if (pr._dtType != null)
{
pr._dtTypeCode = Converter.ToCode(pr._dtType);
}
}
if (pr._memberValueEnum == InternalMemberValueE.Null)
{
// Value is Null
objectPr._objectInfo.AddValue(pr._name, null, ref objectPr._si, ref objectPr._memberData);
}
else if (pr._memberValueEnum == InternalMemberValueE.Nested)
{
ParseObject(pr);
_stack.Push(pr);
if ((pr._objectInfo != null) && pr._objectInfo._objectType != null && (pr._objectInfo._objectType.IsValueType))
{
pr._isValueTypeFixup = true; //Valuefixup
ValueFixupStack.Push(new ValueFixup(objectPr._newObj, pr._name, objectPr._objectInfo));//valuefixup
}
else
{
objectPr._objectInfo.AddValue(pr._name, pr._newObj, ref objectPr._si, ref objectPr._memberData);
}
}
else if (pr._memberValueEnum == InternalMemberValueE.Reference)
{
// See if object has already been instantiated
object refObj = _objectManager.GetObject(pr._idRef);
if (refObj == null)
{
objectPr._objectInfo.AddValue(pr._name, null, ref objectPr._si, ref objectPr._memberData);
objectPr._objectInfo.RecordFixup(objectPr._objectId, pr._name, pr._idRef); // Object not instantiated
}
else
{
objectPr._objectInfo.AddValue(pr._name, refObj, ref objectPr._si, ref objectPr._memberData);
}
}
else if (pr._memberValueEnum == InternalMemberValueE.InlineValue)
{
// Primitive type or String
if (ReferenceEquals(pr._dtType, Converter.s_typeofString))
{
ParseString(pr, objectPr);
objectPr._objectInfo.AddValue(pr._name, pr._value, ref objectPr._si, ref objectPr._memberData);
}
else if (pr._dtTypeCode == InternalPrimitiveTypeE.Invalid)
{
// The member field was an object put the value is Inline either bin.Base64 or invalid
if (pr._arrayTypeEnum == InternalArrayTypeE.Base64)
{
objectPr._objectInfo.AddValue(pr._name, Convert.FromBase64String(pr._value), ref objectPr._si, ref objectPr._memberData);
}
else if (ReferenceEquals(pr._dtType, Converter.s_typeofObject))
{
throw new SerializationException(SR.Format(SR.Serialization_TypeMissing, pr._name));
}
else
{
ParseString(pr, objectPr); // Register the object if it has an objectId
// Object Class with no memberInfo data
// only special case where AddValue is needed?
if (ReferenceEquals(pr._dtType, Converter.s_typeofSystemVoid))
{
objectPr._objectInfo.AddValue(pr._name, pr._dtType, ref objectPr._si, ref objectPr._memberData);
}
else if (objectPr._objectInfo._isSi)
{
// ISerializable are added as strings, the conversion to type is done by the
// ISerializable object
objectPr._objectInfo.AddValue(pr._name, pr._value, ref objectPr._si, ref objectPr._memberData);
}
}
}
else
{
object var = pr._varValue != null ?
pr._varValue :
Converter.FromString(pr._value, pr._dtTypeCode);
objectPr._objectInfo.AddValue(pr._name, var, ref objectPr._si, ref objectPr._memberData);
}
}
else
{
ParseError(pr, objectPr);
}
}
// Object member end encountered in stream
private void ParseMemberEnd(ParseRecord pr)
{
switch (pr._memberTypeEnum)
{
case InternalMemberTypeE.Item:
ParseArrayMemberEnd(pr);
return;
case InternalMemberTypeE.Field:
if (pr._memberValueEnum == InternalMemberValueE.Nested)
{
ParseObjectEnd(pr);
}
break;
default:
ParseError(pr, (ParseRecord)_stack.Peek());
break;
}
}
// Processes a string object by getting an internal ID for it and registering it with the objectManager
private void ParseString(ParseRecord pr, ParseRecord parentPr)
{
// Process String class
if ((!pr._isRegistered) && (pr._objectId > 0))
{
// String is treated as an object if it has an id
//m_objectManager.RegisterObject(pr.PRvalue, pr.PRobjectId);
RegisterObject(pr._value, pr, parentPr, true);
}
}
private void RegisterObject(object obj, ParseRecord pr, ParseRecord objectPr)
{
RegisterObject(obj, pr, objectPr, false);
}
private void RegisterObject(object obj, ParseRecord pr, ParseRecord objectPr, bool bIsString)
{
if (!pr._isRegistered)
{
pr._isRegistered = true;
SerializationInfo si = null;
long parentId = 0;
MemberInfo memberInfo = null;
int[] indexMap = null;
if (objectPr != null)
{
indexMap = objectPr._indexMap;
parentId = objectPr._objectId;
if (objectPr._objectInfo != null)
{
if (!objectPr._objectInfo._isSi)
{
// ParentId is only used if there is a memberInfo
memberInfo = objectPr._objectInfo.GetMemberInfo(pr._name);
}
}
}
// SerializationInfo is always needed for ISerialization
si = pr._si;
if (bIsString)
{
_objectManager.RegisterString((string)obj, pr._objectId, si, parentId, memberInfo);
}
else
{
_objectManager.RegisterObject(obj, pr._objectId, si, parentId, memberInfo, indexMap);
}
}
}
// Assigns an internal ID associated with the binary id number
internal long GetId(long objectId)
{
if (!_fullDeserialization)
{
InitFullDeserialization();
}
if (objectId > 0)
{
return objectId;
}
if (_oldFormatDetected || objectId == -1)
{
// Alarm bells. This is an old format. Deal with it.
_oldFormatDetected = true;
if (_valTypeObjectIdTable == null)
{
_valTypeObjectIdTable = new IntSizedArray();
}
long tempObjId = 0;
if ((tempObjId = _valTypeObjectIdTable[(int)objectId]) == 0)
{
tempObjId = ThresholdForValueTypeIds + objectId;
_valTypeObjectIdTable[(int)objectId] = (int)tempObjId;
}
return tempObjId;
}
return -1 * objectId;
}
internal Type Bind(string assemblyString, string typeString)
{
Type type = null;
if (_binder != null)
{
type = _binder.BindToType(assemblyString, typeString);
}
if (type == null)
{
type = FastBindToType(assemblyString, typeString);
}
return type;
}
internal sealed class TypeNAssembly
{
public Type Type;
public string AssemblyName;
}
internal Type FastBindToType(string assemblyName, string typeName)
{
Type type = null;
TypeNAssembly entry = (TypeNAssembly)_typeCache.GetCachedValue(typeName);
if (entry == null || entry.AssemblyName != assemblyName)
{
Assembly assm = null;
try
{
assm = Assembly.Load(new AssemblyName(assemblyName));
}
catch { }
if (assm == null)
{
return null;
}
if (_isSimpleAssembly)
{
GetSimplyNamedTypeFromAssembly(assm, typeName, ref type);
}
else
{
type = FormatterServices.GetTypeFromAssembly(assm, typeName);
}
if (type == null)
{
return null;
}
// before adding it to cache, let us do the security check
CheckTypeForwardedTo(assm, type.Assembly, type);
entry = new TypeNAssembly();
entry.Type = type;
entry.AssemblyName = assemblyName;
_typeCache.SetCachedValue(entry);
}
return entry.Type;
}
private static void GetSimplyNamedTypeFromAssembly(Assembly assm, string typeName, ref Type type)
{
// Catching any exceptions that could be thrown from a failure on assembly load
// This is necessary, for example, if there are generic parameters that are qualified with a version of the assembly that predates the one available
try
{
type = FormatterServices.GetTypeFromAssembly(assm, typeName);
}
catch (TypeLoadException) { }
catch (FileNotFoundException) { }
catch (FileLoadException) { }
catch (BadImageFormatException) { }
}
private string _previousAssemblyString;
private string _previousName;
private Type _previousType;
internal Type GetType(BinaryAssemblyInfo assemblyInfo, string name)
{
Type objectType = null;
if (((_previousName != null) && (_previousName.Length == name.Length) && (_previousName.Equals(name))) &&
((_previousAssemblyString != null) && (_previousAssemblyString.Length == assemblyInfo._assemblyString.Length) && (_previousAssemblyString.Equals(assemblyInfo._assemblyString))))
{
objectType = _previousType;
}
else
{
objectType = Bind(assemblyInfo._assemblyString, name);
if (objectType == null)
{
Assembly sourceAssembly = assemblyInfo.GetAssembly();
if (_isSimpleAssembly)
{
GetSimplyNamedTypeFromAssembly(sourceAssembly, name, ref objectType);
}
else
{
objectType = FormatterServices.GetTypeFromAssembly(sourceAssembly, name);
}
// here let us do the security check
if (objectType != null)
{
CheckTypeForwardedTo(sourceAssembly, objectType.Assembly, objectType);
}
}
_previousAssemblyString = assemblyInfo._assemblyString;
_previousName = name;
_previousType = objectType;
}
return objectType;
}
private static void CheckTypeForwardedTo(Assembly sourceAssembly, Assembly destAssembly, Type resolvedType)
{
// nop on core
}
internal sealed class TopLevelAssemblyTypeResolver
{
private readonly Assembly _topLevelAssembly;
public TopLevelAssemblyTypeResolver(Assembly topLevelAssembly)
{
_topLevelAssembly = topLevelAssembly;
}
public Type ResolveType(Assembly assembly, string simpleTypeName, bool ignoreCase) =>
(assembly ?? _topLevelAssembly).GetType(simpleTypeName, false, ignoreCase);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors.Simulation;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using log4net;
using Nwc.XmlRpc;
using Nini.Config;
namespace OpenSim.Services.Connectors.Hypergrid
{
public class UserAgentServiceConnector : IUserAgentService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
string m_ServerURL;
Uri m_Uri;
public UserAgentServiceConnector(string url)
{
m_ServerURL = url;
try
{
m_Uri = new Uri(m_ServerURL);
IPAddress ip = Util.GetHostFromDNS(m_Uri.Host);
m_ServerURL = "http://" + ip.ToString() + ":" + m_Uri.Port;
}
catch (Exception e)
{
m_log.DebugFormat("[USER AGENT CONNECTOR]: Malformed Uri {0}: {1}", m_ServerURL, e.Message);
}
}
public UserAgentServiceConnector(IConfigSource config)
{
}
public bool LoginAgentToGrid(AgentCircuitData agent, GridRegion gatekeeper, GridRegion finalDestination, IPEndPoint ipaddress, out string reason)
{
// not available over remote calls
reason = "Method not available over remote calls";
return false;
}
public bool LoginAgentToGrid(AgentCircuitData aCircuit, GridRegion gatekeeper, GridRegion destination, out string reason)
{
reason = String.Empty;
if (destination == null)
{
reason = "Destination is null";
m_log.Debug("[USER AGENT CONNECTOR]: Given destination is null");
return false;
}
string uri = m_ServerURL + "/homeagent/" + aCircuit.AgentID + "/";
Console.WriteLine(" >>> LoginAgentToGrid <<< " + uri);
HttpWebRequest AgentCreateRequest = (HttpWebRequest)WebRequest.Create(uri);
AgentCreateRequest.Method = "POST";
AgentCreateRequest.ContentType = "application/json";
AgentCreateRequest.Timeout = 10000;
//AgentCreateRequest.KeepAlive = false;
//AgentCreateRequest.Headers.Add("Authorization", authKey);
// Fill it in
OSDMap args = PackCreateAgentArguments(aCircuit, gatekeeper, destination);
string strBuffer = "";
byte[] buffer = new byte[1];
try
{
strBuffer = OSDParser.SerializeJsonString(args);
Encoding str = Util.UTF8;
buffer = str.GetBytes(strBuffer);
}
catch (Exception e)
{
m_log.WarnFormat("[USER AGENT CONNECTOR]: Exception thrown on serialization of ChildCreate: {0}", e.Message);
// ignore. buffer will be empty, caller should check.
}
Stream os = null;
try
{ // send the Post
AgentCreateRequest.ContentLength = buffer.Length; //Count bytes to send
os = AgentCreateRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it
m_log.InfoFormat("[USER AGENT CONNECTOR]: Posted CreateAgent request to remote sim {0}, region {1}, x={2} y={3}",
uri, destination.RegionName, destination.RegionLocX, destination.RegionLocY);
}
//catch (WebException ex)
catch
{
//m_log.InfoFormat("[USER AGENT CONNECTOR]: Bad send on ChildAgentUpdate {0}", ex.Message);
reason = "cannot contact remote region";
return false;
}
finally
{
if (os != null)
os.Close();
}
// Let's wait for the response
//m_log.Info("[USER AGENT CONNECTOR]: Waiting for a reply after DoCreateChildAgentCall");
WebResponse webResponse = null;
StreamReader sr = null;
try
{
webResponse = AgentCreateRequest.GetResponse();
if (webResponse == null)
{
m_log.Info("[USER AGENT CONNECTOR]: Null reply on DoCreateChildAgentCall post");
}
else
{
sr = new StreamReader(webResponse.GetResponseStream());
string response = sr.ReadToEnd().Trim();
m_log.InfoFormat("[USER AGENT CONNECTOR]: DoCreateChildAgentCall reply was {0} ", response);
if (!String.IsNullOrEmpty(response))
{
try
{
// we assume we got an OSDMap back
OSDMap r = Util.GetOSDMap(response);
bool success = r["success"].AsBoolean();
reason = r["reason"].AsString();
return success;
}
catch (NullReferenceException e)
{
m_log.InfoFormat("[USER AGENT CONNECTOR]: exception on reply of DoCreateChildAgentCall {0}", e.Message);
// check for old style response
if (response.ToLower().StartsWith("true"))
return true;
return false;
}
}
}
}
catch (WebException ex)
{
m_log.InfoFormat("[USER AGENT CONNECTOR]: exception on reply of DoCreateChildAgentCall {0}", ex.Message);
reason = "Destination did not reply";
return false;
}
finally
{
if (sr != null)
sr.Close();
}
return true;
}
protected OSDMap PackCreateAgentArguments(AgentCircuitData aCircuit, GridRegion gatekeeper, GridRegion destination)
{
OSDMap args = null;
try
{
args = aCircuit.PackAgentCircuitData();
}
catch (Exception e)
{
m_log.Debug("[USER AGENT CONNECTOR]: PackAgentCircuitData failed with exception: " + e.Message);
}
// Add the input arguments
args["gatekeeper_host"] = OSD.FromString(gatekeeper.ExternalHostName);
args["gatekeeper_port"] = OSD.FromString(gatekeeper.HttpPort.ToString());
args["destination_x"] = OSD.FromString(destination.RegionLocX.ToString());
args["destination_y"] = OSD.FromString(destination.RegionLocY.ToString());
args["destination_name"] = OSD.FromString(destination.RegionName);
args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString());
return args;
}
public void SetClientToken(UUID sessionID, string token)
{
// no-op
}
public GridRegion GetHomeRegion(UUID userID, out Vector3 position, out Vector3 lookAt)
{
position = Vector3.UnitY; lookAt = Vector3.UnitY;
Hashtable hash = new Hashtable();
hash["userID"] = userID.ToString();
IList paramList = new ArrayList();
paramList.Add(hash);
XmlRpcRequest request = new XmlRpcRequest("get_home_region", paramList);
XmlRpcResponse response = null;
try
{
response = request.Send(m_ServerURL, 10000);
}
catch (Exception)
{
return null;
}
if (response.IsFault)
{
return null;
}
hash = (Hashtable)response.Value;
//foreach (Object o in hash)
// m_log.Debug(">> " + ((DictionaryEntry)o).Key + ":" + ((DictionaryEntry)o).Value);
try
{
bool success = false;
Boolean.TryParse((string)hash["result"], out success);
if (success)
{
GridRegion region = new GridRegion();
UUID.TryParse((string)hash["uuid"], out region.RegionID);
//m_log.Debug(">> HERE, uuid: " + region.RegionID);
int n = 0;
if (hash["x"] != null)
{
Int32.TryParse((string)hash["x"], out n);
region.RegionLocX = n;
//m_log.Debug(">> HERE, x: " + region.RegionLocX);
}
if (hash["y"] != null)
{
Int32.TryParse((string)hash["y"], out n);
region.RegionLocY = n;
//m_log.Debug(">> HERE, y: " + region.RegionLocY);
}
if (hash["region_name"] != null)
{
region.RegionName = (string)hash["region_name"];
//m_log.Debug(">> HERE, name: " + region.RegionName);
}
if (hash["hostname"] != null)
region.ExternalHostName = (string)hash["hostname"];
if (hash["http_port"] != null)
{
uint p = 0;
UInt32.TryParse((string)hash["http_port"], out p);
region.HttpPort = p;
}
if (hash["internal_port"] != null)
{
int p = 0;
Int32.TryParse((string)hash["internal_port"], out p);
region.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), p);
}
if (hash["position"] != null)
Vector3.TryParse((string)hash["position"], out position);
if (hash["lookAt"] != null)
Vector3.TryParse((string)hash["lookAt"], out lookAt);
// Successful return
return region;
}
}
catch (Exception)
{
return null;
}
return null;
}
public bool AgentIsComingHome(UUID sessionID, string thisGridExternalName)
{
Hashtable hash = new Hashtable();
hash["sessionID"] = sessionID.ToString();
hash["externalName"] = thisGridExternalName;
IList paramList = new ArrayList();
paramList.Add(hash);
XmlRpcRequest request = new XmlRpcRequest("agent_is_coming_home", paramList);
string reason = string.Empty;
return GetBoolResponse(request, out reason);
}
public bool VerifyAgent(UUID sessionID, string token)
{
Hashtable hash = new Hashtable();
hash["sessionID"] = sessionID.ToString();
hash["token"] = token;
IList paramList = new ArrayList();
paramList.Add(hash);
XmlRpcRequest request = new XmlRpcRequest("verify_agent", paramList);
string reason = string.Empty;
return GetBoolResponse(request, out reason);
}
public bool VerifyClient(UUID sessionID, string token)
{
Hashtable hash = new Hashtable();
hash["sessionID"] = sessionID.ToString();
hash["token"] = token;
IList paramList = new ArrayList();
paramList.Add(hash);
XmlRpcRequest request = new XmlRpcRequest("verify_client", paramList);
string reason = string.Empty;
return GetBoolResponse(request, out reason);
}
public void LogoutAgent(UUID userID, UUID sessionID)
{
Hashtable hash = new Hashtable();
hash["sessionID"] = sessionID.ToString();
hash["userID"] = userID.ToString();
IList paramList = new ArrayList();
paramList.Add(hash);
XmlRpcRequest request = new XmlRpcRequest("logout_agent", paramList);
string reason = string.Empty;
GetBoolResponse(request, out reason);
}
private bool GetBoolResponse(XmlRpcRequest request, out string reason)
{
//m_log.Debug("[USER AGENT CONNECTOR]: GetBoolResponse from/to " + m_ServerURL);
XmlRpcResponse response = null;
try
{
response = request.Send(m_ServerURL, 10000);
}
catch (Exception e)
{
m_log.DebugFormat("[USER AGENT CONNECTOR]: Unable to contact remote server {0}", m_ServerURL);
reason = "Exception: " + e.Message;
return false;
}
if (response.IsFault)
{
m_log.ErrorFormat("[USER AGENT CONNECTOR]: remote call to {0} returned an error: {1}", m_ServerURL, response.FaultString);
reason = "XMLRPC Fault";
return false;
}
Hashtable hash = (Hashtable)response.Value;
//foreach (Object o in hash)
// m_log.Debug(">> " + ((DictionaryEntry)o).Key + ":" + ((DictionaryEntry)o).Value);
try
{
if (hash == null)
{
m_log.ErrorFormat("[USER AGENT CONNECTOR]: Got null response from {0}! THIS IS BAAAAD", m_ServerURL);
reason = "Internal error 1";
return false;
}
bool success = false;
reason = string.Empty;
if (hash.ContainsKey("result"))
Boolean.TryParse((string)hash["result"], out success);
else
{
reason = "Internal error 2";
m_log.WarnFormat("[USER AGENT CONNECTOR]: response from {0} does not have expected key 'result'", m_ServerURL);
}
return success;
}
catch (Exception e)
{
m_log.ErrorFormat("[USER AGENT CONNECTOR]: Got exception on GetBoolResponse response.");
if (hash.ContainsKey("result") && hash["result"] != null)
m_log.ErrorFormat("Reply was ", (string)hash["result"]);
reason = "Exception: " + e.Message;
return false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Threading;
using Enyim.Caching.Configuration;
using Enyim.Collections;
using System.Security;
using Enyim.Caching.Memcached.Protocol.Binary;
using System.Runtime.Serialization;
using System.IO;
using Enyim.Caching.Memcached.Results;
using Enyim.Caching.Memcached.Results.Extensions;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Enyim.Caching.Memcached
{
/// <summary>
/// Represents a Memcached node in the pool.
/// </summary>
[DebuggerDisplay("{{MemcachedNode [ Address: {EndPoint}, IsAlive = {IsAlive} ]}}")]
public class MemcachedNode : IMemcachedNode
{
private readonly ILogger _logger;
private static readonly object SyncRoot = new Object();
private bool isDisposed;
private EndPoint endPoint;
private ISocketPoolConfiguration config;
private InternalPoolImpl internalPoolImpl;
private bool isInitialized;
public MemcachedNode(
EndPoint endpoint,
ISocketPoolConfiguration socketPoolConfig,
ILogger logger
)
{
this.endPoint = endpoint;
this.config = socketPoolConfig;
if (socketPoolConfig.ConnectionTimeout.TotalMilliseconds >= Int32.MaxValue)
throw new InvalidOperationException("ConnectionTimeout must be < Int32.MaxValue");
_logger = logger;
this.internalPoolImpl = new InternalPoolImpl(this, socketPoolConfig, _logger);
}
public event Action<IMemcachedNode> Failed;
private INodeFailurePolicy failurePolicy;
protected INodeFailurePolicy FailurePolicy
{
get { return this.failurePolicy ?? (this.failurePolicy = this.config.FailurePolicyFactory.Create(this)); }
}
/// <summary>
/// Gets the <see cref="T:IPEndPoint"/> of this instance
/// </summary>
public EndPoint EndPoint
{
get { return this.endPoint; }
}
/// <summary>
/// <para>Gets a value indicating whether the server is working or not. Returns a <b>cached</b> state.</para>
/// <para>To get real-time information and update the cached state, use the <see cref="M:Ping"/> method.</para>
/// </summary>
/// <remarks>Used by the <see cref="T:ServerPool"/> to quickly check if the server's state is valid.</remarks>
public bool IsAlive
{
get { return this.internalPoolImpl.IsAlive; }
}
/// <summary>
/// Gets a value indicating whether the server is working or not.
///
/// If the server is back online, we'll ercreate the internal socket pool and mark the server as alive so operations can target it.
/// </summary>
/// <returns>true if the server is alive; false otherwise.</returns>
public bool Ping()
{
// is the server working?
if (this.internalPoolImpl.IsAlive)
return true;
// this codepath is (should be) called very rarely
// if you get here hundreds of times then you have bigger issues
// and try to make the memcached instaces more stable and/or increase the deadTimeout
try
{
// we could connect to the server, let's recreate the socket pool
lock (SyncRoot)
{
if (this.isDisposed) return false;
// try to connect to the server
using (var socket = this.CreateSocket()) ;
if (this.internalPoolImpl.IsAlive)
return true;
// it's easier to create a new pool than reinitializing a dead one
// rewrite-then-dispose to avoid a race condition with Acquire (which does no locking)
var oldPool = this.internalPoolImpl;
var newPool = new InternalPoolImpl(this, this.config, _logger);
Interlocked.Exchange(ref this.internalPoolImpl, newPool);
try { oldPool.Dispose(); }
catch { }
}
return true;
}
//could not reconnect
catch { return false; }
}
/// <summary>
/// Acquires a new item from the pool
/// </summary>
/// <returns>An <see cref="T:PooledSocket"/> instance which is connected to the memcached server, or <value>null</value> if the pool is dead.</returns>
public IPooledSocketResult Acquire()
{
if (!this.isInitialized)
lock (this.internalPoolImpl)
if (!this.isInitialized)
{
var startTime = DateTime.Now;
this.internalPoolImpl.InitPool();
this.isInitialized = true;
_logger.LogInformation("MemcachedInitPool-cost: {0}ms", (DateTime.Now - startTime).TotalMilliseconds);
}
try
{
return this.internalPoolImpl.Acquire();
}
catch (Exception e)
{
var message = "Acquire failed. Maybe we're already disposed?";
_logger.LogError(message, e);
var result = new PooledSocketResult();
result.Fail(message, e);
return result;
}
}
~MemcachedNode()
{
try { ((IDisposable)this).Dispose(); }
catch { }
}
/// <summary>
/// Releases all resources allocated by this instance
/// </summary>
public void Dispose()
{
if (this.isDisposed) return;
GC.SuppressFinalize(this);
// this is not a graceful shutdown
// if someone uses a pooled item then it's 99% that an exception will be thrown
// somewhere. But since the dispose is mostly used when everyone else is finished
// this should not kill any kittens
lock (SyncRoot)
{
if (this.isDisposed) return;
this.isDisposed = true;
this.internalPoolImpl.Dispose();
}
}
void IDisposable.Dispose()
{
this.Dispose();
}
#region [ InternalPoolImpl ]
private class InternalPoolImpl : IDisposable
{
private readonly ILogger _logger;
private bool _isDebugEnabled;
/// <summary>
/// A list of already connected but free to use sockets
/// </summary>
private InterlockedStack<PooledSocket> freeItems;
private bool isDisposed;
private bool isAlive;
private DateTime markedAsDeadUtc;
private int minItems;
private int maxItems;
private MemcachedNode ownerNode;
private EndPoint endPoint;
private TimeSpan queueTimeout;
private Semaphore semaphore;
private object initLock = new Object();
internal InternalPoolImpl(
MemcachedNode ownerNode,
ISocketPoolConfiguration config,
ILogger logger)
{
if (config.MinPoolSize < 0)
throw new InvalidOperationException("minItems must be larger >= 0", null);
if (config.MaxPoolSize < config.MinPoolSize)
throw new InvalidOperationException("maxItems must be larger than minItems", null);
if (config.QueueTimeout < TimeSpan.Zero)
throw new InvalidOperationException("queueTimeout must be >= TimeSpan.Zero", null);
this.ownerNode = ownerNode;
this.isAlive = true;
this.endPoint = ownerNode.EndPoint;
this.queueTimeout = config.QueueTimeout;
this.minItems = config.MinPoolSize;
this.maxItems = config.MaxPoolSize;
this.semaphore = new Semaphore(maxItems, maxItems);
this.freeItems = new InterlockedStack<PooledSocket>();
_logger = logger;
_isDebugEnabled = _logger.IsEnabled(LogLevel.Debug);
}
internal void InitPool()
{
try
{
if (this.minItems > 0)
{
for (int i = 0; i < this.minItems; i++)
{
this.freeItems.Push(this.CreateSocket());
// cannot connect to the server
if (!this.isAlive)
break;
}
}
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug("Pool has been inited for {0} with {1} sockets", this.endPoint, this.minItems);
}
catch (Exception e)
{
_logger.LogError("Could not init pool.", new EventId(0), e);
this.MarkAsDead();
}
}
private PooledSocket CreateSocket()
{
var ps = this.ownerNode.CreateSocket();
ps.CleanupCallback = this.ReleaseSocket;
return ps;
}
public bool IsAlive
{
get { return this.isAlive; }
}
public DateTime MarkedAsDeadUtc
{
get { return this.markedAsDeadUtc; }
}
/// <summary>
/// Acquires a new item from the pool
/// </summary>
/// <returns>An <see cref="T:PooledSocket"/> instance which is connected to the memcached server, or <value>null</value> if the pool is dead.</returns>
public IPooledSocketResult Acquire()
{
var result = new PooledSocketResult();
var message = string.Empty;
if (_isDebugEnabled) _logger.LogDebug("Acquiring stream from pool. " + this.endPoint);
if (!this.isAlive || this.isDisposed)
{
message = "Pool is dead or disposed, returning null. " + this.endPoint;
result.Fail(message);
if (_isDebugEnabled) _logger.LogDebug(message);
return result;
}
PooledSocket retval = null;
if (!this.semaphore.WaitOne(this.queueTimeout))
{
message = "Pool is full, timeouting. " + this.endPoint;
if (_isDebugEnabled) _logger.LogDebug(message);
result.Fail(message, new TimeoutException());
// everyone is so busy
return result;
}
// maybe we died while waiting
if (!this.isAlive)
{
message = "Pool is dead, returning null. " + this.endPoint;
if (_isDebugEnabled) _logger.LogDebug(message);
result.Fail(message);
return result;
}
// do we have free items?
if (this.freeItems.TryPop(out retval))
{
#region [ get it from the pool ]
try
{
retval.Reset();
message = "Socket was reset. " + retval.InstanceId;
if (_isDebugEnabled) _logger.LogDebug(message);
result.Pass(message);
result.Value = retval;
return result;
}
catch (Exception e)
{
message = "Failed to reset an acquired socket.";
_logger.LogError(message, e);
this.MarkAsDead();
result.Fail(message, e);
return result;
}
#endregion
}
// free item pool is empty
message = "Could not get a socket from the pool, Creating a new item. " + this.endPoint;
if (_isDebugEnabled) _logger.LogDebug(message);
try
{
// okay, create the new item
var startTime = DateTime.Now;
retval = this.CreateSocket();
_logger.LogInformation("MemcachedAcquire-CreateSocket: {0}ms", (DateTime.Now - startTime).TotalMilliseconds);
result.Value = retval;
result.Pass();
}
catch (Exception e)
{
message = "Failed to create socket. " + this.endPoint;
_logger.LogError(message, e);
// eventhough this item failed the failure policy may keep the pool alive
// so we need to make sure to release the semaphore, so new connections can be
// acquired or created (otherwise dead conenctions would "fill up" the pool
// while the FP pretends that the pool is healthy)
semaphore.Release();
this.MarkAsDead();
result.Fail(message);
return result;
}
if (_isDebugEnabled) _logger.LogDebug("Done.");
return result;
}
private void MarkAsDead()
{
if (_isDebugEnabled) _logger.LogDebug("Mark as dead was requested for {0}", this.endPoint);
var shouldFail = ownerNode.FailurePolicy.ShouldFail();
if (_isDebugEnabled) _logger.LogDebug("FailurePolicy.ShouldFail(): " + shouldFail);
if (shouldFail)
{
if (_logger.IsEnabled(LogLevel.Warning)) _logger.LogWarning("Marking node {0} as dead", this.endPoint);
this.isAlive = false;
this.markedAsDeadUtc = DateTime.UtcNow;
var f = this.ownerNode.Failed;
if (f != null)
f(this.ownerNode);
}
}
/// <summary>
/// Releases an item back into the pool
/// </summary>
/// <param name="socket"></param>
private void ReleaseSocket(PooledSocket socket)
{
if (_isDebugEnabled)
{
_logger.LogDebug("Releasing socket " + socket.InstanceId);
_logger.LogDebug("Are we alive? " + this.isAlive);
}
if (this.isAlive)
{
// is it still working (i.e. the server is still connected)
if (socket.IsAlive)
{
// mark the item as free
this.freeItems.Push(socket);
// signal the event so if someone is waiting for it can reuse this item
this.semaphore.Release();
}
else
{
// kill this item
socket.Destroy();
// mark ourselves as not working for a while
this.MarkAsDead();
// make sure to signal the Acquire so it can create a new conenction
// if the failure policy keeps the pool alive
this.semaphore.Release();
}
}
else
{
// one of our previous sockets has died, so probably all of them
// are dead. so, kill the socket (this will eventually clear the pool as well)
socket.Destroy();
}
}
~InternalPoolImpl()
{
try { ((IDisposable)this).Dispose(); }
catch { }
}
/// <summary>
/// Releases all resources allocated by this instance
/// </summary>
public void Dispose()
{
// this is not a graceful shutdown
// if someone uses a pooled item then 99% that an exception will be thrown
// somewhere. But since the dispose is mostly used when everyone else is finished
// this should not kill any kittens
if (!this.isDisposed)
{
this.isAlive = false;
this.isDisposed = true;
PooledSocket ps;
while (this.freeItems.TryPop(out ps))
{
try { ps.Destroy(); }
catch { }
}
this.ownerNode = null;
this.semaphore.Dispose();
this.semaphore = null;
this.freeItems = null;
}
}
void IDisposable.Dispose()
{
this.Dispose();
}
}
#endregion
#region [ Comparer ]
internal sealed class Comparer : IEqualityComparer<IMemcachedNode>
{
public static readonly Comparer Instance = new Comparer();
bool IEqualityComparer<IMemcachedNode>.Equals(IMemcachedNode x, IMemcachedNode y)
{
return x.EndPoint.Equals(y.EndPoint);
}
int IEqualityComparer<IMemcachedNode>.GetHashCode(IMemcachedNode obj)
{
return obj.EndPoint.GetHashCode();
}
}
#endregion
protected internal virtual PooledSocket CreateSocket()
{
try
{
return new PooledSocket(this.endPoint, this.config.ConnectionTimeout, this.config.ReceiveTimeout, _logger);
}
catch(Exception ex)
{
_logger.LogError(new EventId (this.GetHashCode(), nameof(MemcachedNode) ), ex, $"Create {nameof(PooledSocket)}");
throw;
}
}
//protected internal virtual PooledSocket CreateSocket(IPEndPoint endpoint, TimeSpan connectionTimeout, TimeSpan receiveTimeout)
//{
// PooledSocket retval = new PooledSocket(endPoint, connectionTimeout, receiveTimeout);
// return retval;
//}
protected virtual IPooledSocketResult ExecuteOperation(IOperation op)
{
var result = this.Acquire();
if (result.Success && result.HasValue)
{
try
{
var socket = result.Value;
//if Get, call BinaryRequest.CreateBuffer()
var b = op.GetBuffer();
var startTime = DateTime.Now;
socket.Write(b);
LogExecutionTime("ExecuteOperation_socket_write", startTime, 50);
//if Get, call BinaryResponse
var readResult = op.ReadResponse(socket);
if (readResult.Success)
{
result.Pass();
}
else
{
readResult.Combine(result);
}
return result;
}
catch (IOException e)
{
_logger.LogError(nameof(MemcachedNode), e);
result.Fail("Exception reading response", e);
return result;
}
finally
{
((IDisposable)result.Value).Dispose();
}
}
else
{
result.Fail("Failed to obtain socket from pool");
return result;
}
}
protected async virtual Task<IPooledSocketResult> ExecuteOperationAsync(IOperation op)
{
var result = this.Acquire();
if (result.Success && result.HasValue)
{
try
{
var pooledSocket = result.Value;
//if Get, call BinaryRequest.CreateBuffer()
var b = op.GetBuffer();
await pooledSocket.WriteSync(b);
//if Get, call BinaryResponse
var readResult = op.ReadResponse(pooledSocket);
if (readResult.Success)
{
result.Pass();
}
else
{
readResult.Combine(result);
}
return result;
}
catch (IOException e)
{
_logger.LogError(nameof(MemcachedNode), e);
result.Fail("Exception reading response", e);
return result;
}
finally
{
((IDisposable)result.Value).Dispose();
}
}
else
{
result.Fail("Failed to obtain socket from pool");
return result;
}
}
protected virtual bool ExecuteOperationAsync(IOperation op, Action<bool> next)
{
var socket = this.Acquire().Value;
if (socket == null) return false;
//key(string) to buffer(btye[])
var b = op.GetBuffer();
try
{
socket.Write(b);
var rrs = op.ReadResponseAsync(socket, readSuccess =>
{
((IDisposable)socket).Dispose();
next(readSuccess);
});
return rrs;
}
catch (IOException e)
{
_logger.LogError(nameof(MemcachedNode), e);
((IDisposable)socket).Dispose();
return false;
}
}
private void LogExecutionTime(string title, DateTime startTime, int thresholdMs)
{
var duration = (DateTime.Now - startTime).TotalMilliseconds;
if (duration > thresholdMs)
{
_logger.LogWarning("MemcachedNode-{0}: {1}ms", title, duration);
}
}
#region [ IMemcachedNode ]
EndPoint IMemcachedNode.EndPoint
{
get { return this.EndPoint; }
}
bool IMemcachedNode.IsAlive
{
get { return this.IsAlive; }
}
bool IMemcachedNode.Ping()
{
return this.Ping();
}
IOperationResult IMemcachedNode.Execute(IOperation op)
{
return this.ExecuteOperation(op);
}
async Task<IOperationResult> IMemcachedNode.ExecuteAsync(IOperation op)
{
return await this.ExecuteOperationAsync(op);
}
bool IMemcachedNode.ExecuteAsync(IOperation op, Action<bool> next)
{
return this.ExecuteOperationAsync(op, next);
}
event Action<IMemcachedNode> IMemcachedNode.Failed
{
add { this.Failed += value; }
remove { this.Failed -= value; }
}
#endregion
}
}
#region [ License information ]
/* ************************************************************
*
* Copyright (c) 2010 Attila Kisk? enyim.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ************************************************************/
#endregion
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CSharp.RuntimeBinder;
using Xunit;
namespace Dynamic.Tests
{
public class ExplicitlyImplementedBasicTests
{
[Fact]
public void NonGenericInterface_OneInterface_Class()
{
dynamic d = new OneExplicitlyImplementedNonGenericInterface1();
Assert.Throws<RuntimeBinderException>(() => d.Foo());
}
[Fact]
public void NonGenericInterface_OneInterface_Struct()
{
dynamic d = new OneExplicitlyImplementedNonGenericInterface2();
Assert.Equal(2, d.Foo());
}
[Fact]
public void NonGenericInterface_TwoInterfaces_Class1()
{
dynamic d = new TwoExplicitlyImplementedNonGenericInterface1();
Assert.Throws<RuntimeBinderException>(() => d.Foo());
var x = Helpers.Cast<NonGenericInterface2>(d);
}
[Fact]
public void NonGenericInterface_TwoInterfaces_Class2()
{
dynamic d = new TwoExplicitlyImplementedNonGenericInterface2();
Assert.Throws<RuntimeBinderException>(() => d.Foo());
var x = Helpers.Cast<NonGenericInterface3>(d);
}
[Fact]
public void NonGenericInterface_OneInterfaceClass2()
{
dynamic d = new OneExplicitlyImplementedNonGenericInterface3();
Assert.Equal(2, d.Foo());
Assert.Throws<InvalidCastException>(() => Helpers.Cast<NonGenericInterface3>(d));
Assert.Throws<InvalidCastException>(() => ((NonGenericInterface3)d).Foo());
}
[Fact]
public void NonGenericInterface_WithGetter()
{
dynamic d = new ExplicitlyImplementedInterfaceWithGetter();
Assert.Throws<RuntimeBinderException>(() => d.Property);
var x = Helpers.Cast<InterfaceWithGetter>(d);
}
[Fact]
public void NonGenericInterface_WithSetter()
{
dynamic d = new ExplicitlyImplementedInterfaceWithSetter();
Assert.Throws<RuntimeBinderException>(() => d.Prop = 1);
var x = Helpers.Cast<InterfaceWithSetter>(d);
}
[Fact]
public void NonGenericInterface_WithGetterAndSetter()
{
dynamic d = new ExplicitlyImplementedInterfaceWithGetterAndSetter();
Assert.Throws<RuntimeBinderException>(() => d.Property);
Assert.Throws<RuntimeBinderException>(() => d.Property = 1);
var x = Helpers.Cast<InterfaceWithGetterAndSetter>(d);
}
[Fact]
public void NonGenericInterface_WithEvent()
{
dynamic d = new ExplicitlyImplementedInterfaceWithEvent();
Assert.Throws<RuntimeBinderException>(() => d.Event += (Func<int, int>)(y => y));
Assert.Throws<RuntimeBinderException>(() => d.Event -= (Func<int, int>)(y => y));
var x = Helpers.Cast<InterfaceWithEvent>(d);
}
[Fact]
public void NonGenericInterface_WithIndexer()
{
dynamic d = new ExplicitlyImplementedInterfaceWithIndexer();
Assert.Throws<RuntimeBinderException>(() => d[0]);
Assert.Throws<RuntimeBinderException>(() => d[0] = 1);
var x = Helpers.Cast<InterfaceWithIndexer>(d);
}
}
public interface NonGenericInterface1
{
int Foo();
int Bar();
}
public interface NonGenericInterface2
{
int Bar();
}
public interface NonGenericInterface3
{
int Foo();
}
public class OneExplicitlyImplementedNonGenericInterface1 : NonGenericInterface1
{
int NonGenericInterface1.Foo() => 0;
public int Bar() => 1;
}
public struct OneExplicitlyImplementedNonGenericInterface2 : NonGenericInterface1
{
int NonGenericInterface1.Foo() => 0;
public int Foo() => 2;
public int Bar() => 1;
}
public class OneExplicitlyImplementedNonGenericInterface3 : NonGenericInterface1
{
int NonGenericInterface1.Foo() => 0;
public int Foo() => 2;
public int Bar() => 1;
}
public class TwoExplicitlyImplementedNonGenericInterface1 : NonGenericInterface1, NonGenericInterface2
{
int NonGenericInterface1.Foo() => 0;
public int Bar() => 1;
}
public class TwoExplicitlyImplementedNonGenericInterface2 : NonGenericInterface1, NonGenericInterface3
{
int NonGenericInterface1.Foo() => 0;
int NonGenericInterface3.Foo() => 2;
public int Bar() => 1;
}
public interface InterfaceWithSetter
{
int Property { set; }
}
public class ExplicitlyImplementedInterfaceWithSetter : InterfaceWithSetter
{
public static bool s_setterCalled;
int InterfaceWithSetter.Property
{
set { s_setterCalled = true; }
}
}
public interface InterfaceWithGetter
{
int Property { get; }
}
public class ExplicitlyImplementedInterfaceWithGetter : InterfaceWithGetter
{
public static bool s_getterCalled;
int InterfaceWithGetter.Property
{
get { s_getterCalled = true; return 2; }
}
}
public interface InterfaceWithGetterAndSetter
{
int Property { get; set; }
}
public class ExplicitlyImplementedInterfaceWithGetterAndSetter : InterfaceWithGetterAndSetter
{
public static bool s_getterCalled;
public static bool s_setterCalled;
int InterfaceWithGetterAndSetter.Property
{
get { s_getterCalled = true; return 1; }
set { s_setterCalled = true; }
}
}
public interface InterfaceWithEvent
{
event Func<int, int> Event;
}
public class ExplicitlyImplementedInterfaceWithEvent : InterfaceWithEvent
{
public static bool s_addCalled;
public static bool s_removeCalled;
event Func<int, int> InterfaceWithEvent.Event
{
add { s_addCalled = true; }
remove { s_addCalled = true; }
}
}
public interface InterfaceWithIndexer
{
long this[byte index] { get; set; }
}
public class ExplicitlyImplementedInterfaceWithIndexer : InterfaceWithIndexer
{
public static bool s_getCalled;
public static bool s_setCalled;
long InterfaceWithIndexer.this[byte index]
{
get { s_getCalled = true; return 1; }
set { s_setCalled = true; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Abp.Application.Features;
using Abp.Auditing;
using Abp.Authorization;
using Abp.Collections.Extensions;
using Abp.Configuration;
using Abp.Domain.Uow;
using Abp.Events.Bus;
using Abp.Events.Bus.Exceptions;
using Abp.Localization;
using Abp.Localization.Sources;
using Abp.Logging;
using Abp.Reflection;
using Abp.Runtime.Session;
using Abp.Timing;
using Abp.Web.Models;
using Abp.Web.Mvc.Controllers.Results;
using Abp.Web.Mvc.Models;
using Castle.Core.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Abp.Web.Mvc.Controllers
{
/// <summary>
/// Base class for all MVC Controllers in Abp system.
/// </summary>
public abstract class AbpController : Controller
{
/// <summary>
/// Gets current session information.
/// </summary>
public IAbpSession AbpSession { get; set; }
/// <summary>
/// Gets the event bus.
/// </summary>
public IEventBus EventBus { get; set; }
/// <summary>
/// Reference to the permission manager.
/// </summary>
public IPermissionManager PermissionManager { get; set; }
/// <summary>
/// Reference to the setting manager.
/// </summary>
public ISettingManager SettingManager { get; set; }
/// <summary>
/// Reference to the permission checker.
/// </summary>
public IPermissionChecker PermissionChecker { protected get; set; }
/// <summary>
/// Reference to the feature manager.
/// </summary>
public IFeatureManager FeatureManager { protected get; set; }
/// <summary>
/// Reference to the permission checker.
/// </summary>
public IFeatureChecker FeatureChecker { protected get; set; }
/// <summary>
/// Reference to the localization manager.
/// </summary>
public ILocalizationManager LocalizationManager { protected get; set; }
/// <summary>
/// Gets/sets name of the localization source that is used in this application service.
/// It must be set in order to use <see cref="L(string)"/> and <see cref="L(string,CultureInfo)"/> methods.
/// </summary>
protected string LocalizationSourceName { get; set; }
/// <summary>
/// Gets localization source.
/// It's valid if <see cref="LocalizationSourceName"/> is set.
/// </summary>
protected ILocalizationSource LocalizationSource
{
get
{
if (LocalizationSourceName == null)
{
throw new AbpException("Must set LocalizationSourceName before, in order to get LocalizationSource");
}
if (_localizationSource == null || _localizationSource.Name != LocalizationSourceName)
{
_localizationSource = LocalizationManager.GetSource(LocalizationSourceName);
}
return _localizationSource;
}
}
private ILocalizationSource _localizationSource;
/// <summary>
/// Reference to the logger to write logs.
/// </summary>
public ILogger Logger { get; set; }
/// <summary>
/// Gets current session information.
/// </summary>
[Obsolete("Use AbpSession property instead. CurrentSession will be removed in future releases.")]
protected IAbpSession CurrentSession { get { return AbpSession; } }
/// <summary>
/// Reference to <see cref="IUnitOfWorkManager"/>.
/// </summary>
public IUnitOfWorkManager UnitOfWorkManager
{
get
{
if (_unitOfWorkManager == null)
{
throw new AbpException("Must set UnitOfWorkManager before use it.");
}
return _unitOfWorkManager;
}
set { _unitOfWorkManager = value; }
}
private IUnitOfWorkManager _unitOfWorkManager;
/// <summary>
/// Gets current unit of work.
/// </summary>
protected IActiveUnitOfWork CurrentUnitOfWork { get { return UnitOfWorkManager.Current; } }
public IAuditingConfiguration AuditingConfiguration { get; set; }
public IAuditInfoProvider AuditInfoProvider { get; set; }
public IAuditingStore AuditingStore { get; set; }
/// <summary>
/// This object is used to measure an action execute duration.
/// </summary>
private Stopwatch _actionStopwatch;
private AuditInfo _auditInfo;
/// <summary>
/// MethodInfo for currently executing action.
/// </summary>
private MethodInfo _currentMethodInfo;
/// <summary>
/// WrapResultAttribute for currently executing action.
/// </summary>
private WrapResultAttribute _wrapResultAttribute;
/// <summary>
/// Constructor.
/// </summary>
protected AbpController()
{
AbpSession = NullAbpSession.Instance;
Logger = NullLogger.Instance;
LocalizationManager = NullLocalizationManager.Instance;
PermissionChecker = NullPermissionChecker.Instance;
AuditingStore = SimpleLogAuditingStore.Instance;
EventBus = NullEventBus.Instance;
}
/// <summary>
/// Gets localized string for given key name and current language.
/// </summary>
/// <param name="name">Key name</param>
/// <returns>Localized string</returns>
protected virtual string L(string name)
{
return LocalizationSource.GetString(name);
}
/// <summary>
/// Gets localized string for given key name and current language with formatting strings.
/// </summary>
/// <param name="name">Key name</param>
/// <param name="args">Format arguments</param>
/// <returns>Localized string</returns>
protected string L(string name, params object[] args)
{
return LocalizationSource.GetString(name, args);
}
/// <summary>
/// Gets localized string for given key name and specified culture information.
/// </summary>
/// <param name="name">Key name</param>
/// <param name="culture">culture information</param>
/// <returns>Localized string</returns>
protected virtual string L(string name, CultureInfo culture)
{
return LocalizationSource.GetString(name, culture);
}
/// <summary>
/// Gets localized string for given key name and current language with formatting strings.
/// </summary>
/// <param name="name">Key name</param>
/// <param name="culture">culture information</param>
/// <param name="args">Format arguments</param>
/// <returns>Localized string</returns>
protected string L(string name, CultureInfo culture, params object[] args)
{
return LocalizationSource.GetString(name, culture, args);
}
/// <summary>
/// Checks if current user is granted for a permission.
/// </summary>
/// <param name="permissionName">Name of the permission</param>
protected Task<bool> IsGrantedAsync(string permissionName)
{
return PermissionChecker.IsGrantedAsync(permissionName);
}
/// <summary>
/// Checks if current user is granted for a permission.
/// </summary>
/// <param name="permissionName">Name of the permission</param>
protected bool IsGranted(string permissionName)
{
return PermissionChecker.IsGranted(permissionName);
}
/// <summary>
/// Checks if given feature is enabled for current tenant.
/// </summary>
/// <param name="featureName">Name of the feature</param>
/// <returns></returns>
protected virtual Task<bool> IsEnabledAsync(string featureName)
{
return FeatureChecker.IsEnabledAsync(featureName);
}
/// <summary>
/// Checks if given feature is enabled for current tenant.
/// </summary>
/// <param name="featureName">Name of the feature</param>
/// <returns></returns>
protected virtual bool IsEnabled(string featureName)
{
return FeatureChecker.IsEnabled(featureName);
}
/// <summary>
/// Json the specified data, contentType, contentEncoding and behavior.
/// </summary>
/// <param name="data">Data.</param>
/// <param name="contentType">Content type.</param>
/// <param name="contentEncoding">Content encoding.</param>
/// <param name="behavior">Behavior.</param>
protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
if (_wrapResultAttribute != null && !_wrapResultAttribute.WrapOnSuccess)
{
return base.Json(data, contentType, contentEncoding, behavior);
}
if (data == null)
{
data = new AjaxResponse();
}
else if (!ReflectionHelper.IsAssignableToGenericType(data.GetType(), typeof(AjaxResponse<>)))
{
data = new AjaxResponse(data);
}
return new AbpJsonResult
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior
};
}
#region OnActionExecuting / OnActionExecuted
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
SetCurrentMethodInfoAndWrapResultAttribute(filterContext);
HandleAuditingBeforeAction(filterContext);
base.OnActionExecuting(filterContext);
}
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
HandleAuditingAfterAction(filterContext);
}
private void SetCurrentMethodInfoAndWrapResultAttribute(ActionExecutingContext filterContext)
{
_currentMethodInfo = ActionDescriptorHelper.GetMethodInfo(filterContext.ActionDescriptor);
_wrapResultAttribute =
ReflectionHelper.GetSingleAttributeOfMemberOrDeclaringTypeOrNull<WrapResultAttribute>(_currentMethodInfo) ??
WrapResultAttribute.Default;
}
#endregion
#region Exception handling
protected override void OnException(ExceptionContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
//If exception handled before, do nothing.
//If this is child action, exception should be handled by main action.
if (context.ExceptionHandled || context.IsChildAction)
{
base.OnException(context);
return;
}
//Log exception
if (_wrapResultAttribute.LogError)
{
LogHelper.LogException(Logger, context.Exception);
}
// If custom errors are disabled, we need to let the normal ASP.NET exception handler
// execute so that the user can see useful debugging information.
if (!context.HttpContext.IsCustomErrorEnabled)
{
base.OnException(context);
return;
}
// If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method),
// ignore it.
if (new HttpException(null, context.Exception).GetHttpCode() != 500)
{
base.OnException(context);
return;
}
//Check WrapResultAttribute
if (!_wrapResultAttribute.WrapOnError)
{
base.OnException(context);
return;
}
//We handled the exception!
context.ExceptionHandled = true;
//Return a special error response to the client.
context.HttpContext.Response.Clear();
context.Result = IsJsonResult()
? GenerateJsonExceptionResult(context)
: GenerateNonJsonExceptionResult(context);
// Certain versions of IIS will sometimes use their own error page when
// they detect a server error. Setting this property indicates that we
// want it to try to render ASP.NET MVC's error page instead.
context.HttpContext.Response.TrySkipIisCustomErrors = true;
//Trigger an event, so we can register it.
EventBus.Trigger(this, new AbpHandledExceptionData(context.Exception));
}
protected virtual bool IsJsonResult()
{
return typeof (JsonResult).IsAssignableFrom(_currentMethodInfo.ReturnType) ||
typeof (Task<JsonResult>).IsAssignableFrom(_currentMethodInfo.ReturnType);
}
protected virtual ActionResult GenerateJsonExceptionResult(ExceptionContext context)
{
context.HttpContext.Response.StatusCode = 200; //TODO: Consider to return 500
return new AbpJsonResult(
new MvcAjaxResponse(
ErrorInfoBuilder.Instance.BuildForException(context.Exception),
context.Exception is AbpAuthorizationException
)
);
}
protected virtual ActionResult GenerateNonJsonExceptionResult(ExceptionContext context)
{
context.HttpContext.Response.StatusCode = 500;
return new ViewResult
{
ViewName = "Error",
MasterName = string.Empty,
ViewData = new ViewDataDictionary<ErrorViewModel>(new ErrorViewModel(context.Exception)),
TempData = context.Controller.TempData
};
}
#endregion
#region Auditing
private void HandleAuditingBeforeAction(ActionExecutingContext filterContext)
{
if (!ShouldSaveAudit(filterContext))
{
_auditInfo = null;
return;
}
_actionStopwatch = Stopwatch.StartNew();
_auditInfo = new AuditInfo
{
TenantId = AbpSession.TenantId,
UserId = AbpSession.UserId,
ImpersonatorUserId = AbpSession.ImpersonatorUserId,
ImpersonatorTenantId = AbpSession.ImpersonatorTenantId,
ServiceName = _currentMethodInfo.DeclaringType != null
? _currentMethodInfo.DeclaringType.FullName
: filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
MethodName = _currentMethodInfo.Name,
Parameters = ConvertArgumentsToJson(filterContext.ActionParameters),
ExecutionTime = Clock.Now
};
}
private void HandleAuditingAfterAction(ActionExecutedContext filterContext)
{
if (_auditInfo == null || _actionStopwatch == null)
{
return;
}
_actionStopwatch.Stop();
_auditInfo.ExecutionDuration = Convert.ToInt32(_actionStopwatch.Elapsed.TotalMilliseconds);
_auditInfo.Exception = filterContext.Exception;
if (AuditInfoProvider != null)
{
AuditInfoProvider.Fill(_auditInfo);
}
AuditingStore.Save(_auditInfo);
}
private bool ShouldSaveAudit(ActionExecutingContext filterContext)
{
if (AuditingConfiguration == null)
{
return false;
}
if (!AuditingConfiguration.MvcControllers.IsEnabled)
{
return false;
}
if (filterContext.IsChildAction && !AuditingConfiguration.MvcControllers.IsEnabledForChildActions)
{
return false;
}
return AuditingHelper.ShouldSaveAudit(
_currentMethodInfo,
AuditingConfiguration,
AbpSession,
true
);
}
private string ConvertArgumentsToJson(IDictionary<string, object> arguments)
{
try
{
if (arguments.IsNullOrEmpty())
{
return "{}";
}
var dictionary = new Dictionary<string, object>();
foreach (var argument in arguments)
{
dictionary[argument.Key] = argument.Value;
}
return JsonConvert.SerializeObject(
dictionary,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
}
catch (Exception ex)
{
Logger.Warn("Could not serialize arguments for method: " + _auditInfo.ServiceName + "." + _auditInfo.MethodName);
Logger.Warn(ex.ToString(), ex);
return "{}";
}
}
#endregion
}
}
| |
#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 log4net.Appender;
using log4net.Util;
using log4net.Core;
namespace log4net.Repository.Hierarchy
{
/// <summary>
/// Implementation of <see cref="ILogger"/> used by <see cref="Hierarchy"/>
/// </summary>
/// <remarks>
/// <para>
/// Internal class used to provide implementation of <see cref="ILogger"/>
/// interface. Applications should use <see cref="LogManager"/> to get
/// logger instances.
/// </para>
/// <para>
/// This is one of the central classes in the log4net implementation. One of the
/// distinctive features of log4net are hierarchical loggers and their
/// evaluation. The <see cref="Hierarchy"/> organizes the <see cref="Logger"/>
/// instances into a rooted tree hierarchy.
/// </para>
/// <para>
/// The <see cref="Logger"/> class is abstract. Only concrete subclasses of
/// <see cref="Logger"/> can be created. The <see cref="ILoggerFactory"/>
/// is used to create instances of this type for the <see cref="Hierarchy"/>.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
/// <author>Aspi Havewala</author>
/// <author>Douglas de la Torre</author>
public abstract class Logger : IAppenderAttachable, ILogger
{
#region Protected Instance Constructors
/// <summary>
/// This constructor created a new <see cref="Logger" /> instance and
/// sets its name.
/// </summary>
/// <param name="name">The name of the <see cref="Logger" />.</param>
/// <remarks>
/// <para>
/// This constructor is protected and designed to be used by
/// a subclass that is not abstract.
/// </para>
/// <para>
/// Loggers are constructed by <see cref="ILoggerFactory"/>
/// objects. See <see cref="DefaultLoggerFactory"/> for the default
/// logger creator.
/// </para>
/// </remarks>
protected Logger(string name)
{
#if NETCF
// NETCF: String.Intern causes Native Exception
m_name = name;
#else
m_name = string.Intern(name);
#endif
}
#endregion Protected Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets or sets the parent logger in the hierarchy.
/// </summary>
/// <value>
/// The parent logger in the hierarchy.
/// </value>
/// <remarks>
/// <para>
/// Part of the Composite pattern that makes the hierarchy.
/// The hierarchy is parent linked rather than child linked.
/// </para>
/// </remarks>
virtual public Logger Parent
{
get { return m_parent; }
set { m_parent = value; }
}
/// <summary>
/// Gets or sets a value indicating if child loggers inherit their parent's appenders.
/// </summary>
/// <value>
/// <c>true</c> if child loggers inherit their parent's appenders.
/// </value>
/// <remarks>
/// <para>
/// Additivity is set to <c>true</c> by default, that is children inherit
/// the appenders of their ancestors by default. If this variable is
/// set to <c>false</c> then the appenders found in the
/// ancestors of this logger are not used. However, the children
/// of this logger will inherit its appenders, unless the children
/// have their additivity flag set to <c>false</c> too. See
/// the user manual for more details.
/// </para>
/// </remarks>
virtual public bool Additivity
{
get { return m_additive; }
set { m_additive = value; }
}
/// <summary>
/// Gets the effective level for this logger.
/// </summary>
/// <returns>The nearest level in the logger hierarchy.</returns>
/// <remarks>
/// <para>
/// Starting from this logger, searches the logger hierarchy for a
/// non-null level and returns it. Otherwise, returns the level of the
/// root logger.
/// </para>
/// <para>The Logger class is designed so that this method executes as
/// quickly as possible.</para>
/// </remarks>
virtual public Level EffectiveLevel
{
get
{
for(Logger c = this; c != null; c = c.m_parent)
{
Level level = c.m_level;
// Casting level to Object for performance, otherwise the overloaded operator is called
if ((object)level != null)
{
return level;
}
}
return null; // If reached will cause an NullPointerException.
}
}
/// <summary>
/// Gets or sets the <see cref="Hierarchy"/> where this
/// <c>Logger</c> instance is attached to.
/// </summary>
/// <value>The hierarchy that this logger belongs to.</value>
/// <remarks>
/// <para>
/// This logger must be attached to a single <see cref="Hierarchy"/>.
/// </para>
/// </remarks>
virtual public Hierarchy Hierarchy
{
get { return m_hierarchy; }
set { m_hierarchy = value; }
}
/// <summary>
/// Gets or sets the assigned <see cref="Level"/>, if any, for this Logger.
/// </summary>
/// <value>
/// The <see cref="Level"/> of this logger.
/// </value>
/// <remarks>
/// <para>
/// The assigned <see cref="Level"/> can be <c>null</c>.
/// </para>
/// </remarks>
virtual public Level Level
{
get { return m_level; }
set { m_level = value; }
}
#endregion Public Instance Properties
#region Implementation of IAppenderAttachable
/// <summary>
/// Add <paramref name="newAppender"/> to the list of appenders of this
/// Logger instance.
/// </summary>
/// <param name="newAppender">An appender to add to this logger</param>
/// <remarks>
/// <para>
/// Add <paramref name="newAppender"/> to the list of appenders of this
/// Logger instance.
/// </para>
/// <para>
/// If <paramref name="newAppender"/> is already in the list of
/// appenders, then it won't be added again.
/// </para>
/// </remarks>
virtual public void AddAppender(IAppender newAppender)
{
if (newAppender == null)
{
throw new ArgumentNullException("newAppender");
}
m_appenderLock.AcquireWriterLock();
try
{
if (m_appenderAttachedImpl == null)
{
m_appenderAttachedImpl = new log4net.Util.AppenderAttachedImpl();
}
m_appenderAttachedImpl.AddAppender(newAppender);
}
finally
{
m_appenderLock.ReleaseWriterLock();
}
}
/// <summary>
/// Get the appenders contained in this logger as an
/// <see cref="System.Collections.ICollection"/>.
/// </summary>
/// <returns>A collection of the appenders in this logger</returns>
/// <remarks>
/// <para>
/// Get the appenders contained in this logger as an
/// <see cref="System.Collections.ICollection"/>. If no appenders
/// can be found, then a <see cref="EmptyCollection"/> is returned.
/// </para>
/// </remarks>
virtual public AppenderCollection Appenders
{
get
{
m_appenderLock.AcquireReaderLock();
try
{
if (m_appenderAttachedImpl == null)
{
return AppenderCollection.EmptyCollection;
}
else
{
return m_appenderAttachedImpl.Appenders;
}
}
finally
{
m_appenderLock.ReleaseReaderLock();
}
}
}
/// <summary>
/// Look for the appender named as <c>name</c>
/// </summary>
/// <param name="name">The name of the appender to lookup</param>
/// <returns>The appender with the name specified, or <c>null</c>.</returns>
/// <remarks>
/// <para>
/// Returns the named appender, or null if the appender is not found.
/// </para>
/// </remarks>
virtual public IAppender GetAppender(string name)
{
m_appenderLock.AcquireReaderLock();
try
{
if (m_appenderAttachedImpl == null || name == null)
{
return null;
}
return m_appenderAttachedImpl.GetAppender(name);
}
finally
{
m_appenderLock.ReleaseReaderLock();
}
}
/// <summary>
/// Remove all previously added appenders from this Logger instance.
/// </summary>
/// <remarks>
/// <para>
/// Remove all previously added appenders from this Logger instance.
/// </para>
/// <para>
/// This is useful when re-reading configuration information.
/// </para>
/// </remarks>
virtual public void RemoveAllAppenders()
{
m_appenderLock.AcquireWriterLock();
try
{
if (m_appenderAttachedImpl != null)
{
m_appenderAttachedImpl.RemoveAllAppenders();
m_appenderAttachedImpl = null;
}
}
finally
{
m_appenderLock.ReleaseWriterLock();
}
}
/// <summary>
/// Remove the appender passed as parameter form the list of appenders.
/// </summary>
/// <param name="appender">The appender to remove</param>
/// <returns>The appender removed from the list</returns>
/// <remarks>
/// <para>
/// Remove the appender passed as parameter form the list of appenders.
/// The appender removed is not closed.
/// If you are discarding the appender you must call
/// <see cref="IAppender.Close"/> on the appender removed.
/// </para>
/// </remarks>
virtual public IAppender RemoveAppender(IAppender appender)
{
m_appenderLock.AcquireWriterLock();
try
{
if (appender != null && m_appenderAttachedImpl != null)
{
return m_appenderAttachedImpl.RemoveAppender(appender);
}
}
finally
{
m_appenderLock.ReleaseWriterLock();
}
return null;
}
/// <summary>
/// Remove the appender passed as parameter form the list of appenders.
/// </summary>
/// <param name="name">The name of the appender to remove</param>
/// <returns>The appender removed from the list</returns>
/// <remarks>
/// <para>
/// Remove the named appender passed as parameter form the list of appenders.
/// The appender removed is not closed.
/// If you are discarding the appender you must call
/// <see cref="IAppender.Close"/> on the appender removed.
/// </para>
/// </remarks>
virtual public IAppender RemoveAppender(string name)
{
m_appenderLock.AcquireWriterLock();
try
{
if (name != null && m_appenderAttachedImpl != null)
{
return m_appenderAttachedImpl.RemoveAppender(name);
}
}
finally
{
m_appenderLock.ReleaseWriterLock();
}
return null;
}
#endregion
#region Implementation of ILogger
/// <summary>
/// Gets the logger name.
/// </summary>
/// <value>
/// The name of the logger.
/// </value>
/// <remarks>
/// <para>
/// The name of this logger
/// </para>
/// </remarks>
virtual public string Name
{
get { return m_name; }
}
/// <summary>
/// This generic form is intended to be used by wrappers.
/// </summary>
/// <param name="callerStackBoundaryDeclaringType">The declaring type of the method that is
/// the stack boundary into the logging system for this call.</param>
/// <param name="level">The level of the message to be logged.</param>
/// <param name="message">The message object to log.</param>
/// <param name="exception">The exception to log, including its stack trace.</param>
/// <remarks>
/// <para>
/// Generate a logging event for the specified <paramref name="level"/> using
/// the <paramref name="message"/> and <paramref name="exception"/>.
/// </para>
/// <para>
/// This method must not throw any exception to the caller.
/// </para>
/// </remarks>
virtual public void Log(Type callerStackBoundaryDeclaringType, Level level, object message, Exception exception)
{
try
{
if (IsEnabledFor(level))
{
ForcedLog((callerStackBoundaryDeclaringType != null) ? callerStackBoundaryDeclaringType : declaringType, level, message, exception);
}
}
catch (Exception ex)
{
log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex);
}
#if !MONO && !NET_2_0 && !NET_3_5 && !NET_4_0
// on .NET 2.0 (and higher) and Mono (all profiles),
// exceptions that do not derive from System.Exception will be
// wrapped in a RuntimeWrappedException by the runtime, and as
// such will be catched by the catch clause above
catch
{
log4net.Util.LogLog.Error(declaringType, "Exception while logging");
}
#endif
}
/// <summary>
/// This is the most generic printing method that is intended to be used
/// by wrappers.
/// </summary>
/// <param name="logEvent">The event being logged.</param>
/// <remarks>
/// <para>
/// Logs the specified logging event through this logger.
/// </para>
/// <para>
/// This method must not throw any exception to the caller.
/// </para>
/// </remarks>
virtual public void Log(LoggingEvent logEvent)
{
try
{
if (logEvent != null)
{
if (IsEnabledFor(logEvent.Level))
{
ForcedLog(logEvent);
}
}
}
catch (Exception ex)
{
log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex);
}
#if !MONO && !NET_2_0 && !NET_3_5 && !NET_4_0
// on .NET 2.0 (and higher) and Mono (all profiles),
// exceptions that do not derive from System.Exception will be
// wrapped in a RuntimeWrappedException by the runtime, and as
// such will be catched by the catch clause above
catch
{
log4net.Util.LogLog.Error(declaringType, "Exception while logging");
}
#endif
}
/// <summary>
/// Checks if this logger is enabled for a given <see cref="Level"/> passed as parameter.
/// </summary>
/// <param name="level">The level to check.</param>
/// <returns>
/// <c>true</c> if this logger is enabled for <c>level</c>, otherwise <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
/// Test if this logger is going to log events of the specified <paramref name="level"/>.
/// </para>
/// <para>
/// This method must not throw any exception to the caller.
/// </para>
/// </remarks>
virtual public bool IsEnabledFor(Level level)
{
try
{
if (level != null)
{
if (m_hierarchy.IsDisabled(level))
{
return false;
}
return level >= this.EffectiveLevel;
}
}
catch (Exception ex)
{
log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex);
}
#if !MONO && !NET_2_0 && !NET_3_5 && !NET_4_0
// on .NET 2.0 (and higher) and Mono (all profiles),
// exceptions that do not derive from System.Exception will be
// wrapped in a RuntimeWrappedException by the runtime, and as
// such will be catched by the catch clause above
catch
{
log4net.Util.LogLog.Error(declaringType, "Exception while logging");
}
#endif
return false;
}
/// <summary>
/// Gets the <see cref="ILoggerRepository"/> where this
/// <c>Logger</c> instance is attached to.
/// </summary>
/// <value>
/// The <see cref="ILoggerRepository" /> that this logger belongs to.
/// </value>
/// <remarks>
/// <para>
/// Gets the <see cref="ILoggerRepository"/> where this
/// <c>Logger</c> instance is attached to.
/// </para>
/// </remarks>
public ILoggerRepository Repository
{
get { return m_hierarchy; }
}
#endregion Implementation of ILogger
/// <summary>
/// Deliver the <see cref="LoggingEvent"/> to the attached appenders.
/// </summary>
/// <param name="loggingEvent">The event to log.</param>
/// <remarks>
/// <para>
/// Call the appenders in the hierarchy starting at
/// <c>this</c>. If no appenders could be found, emit a
/// warning.
/// </para>
/// <para>
/// This method calls all the appenders inherited from the
/// hierarchy circumventing any evaluation of whether to log or not
/// to log the particular log request.
/// </para>
/// </remarks>
virtual protected void CallAppenders(LoggingEvent loggingEvent)
{
if (loggingEvent == null)
{
throw new ArgumentNullException("loggingEvent");
}
int writes = 0;
for(Logger c=this; c != null; c=c.m_parent)
{
if (c.m_appenderAttachedImpl != null)
{
// Protected against simultaneous call to addAppender, removeAppender,...
c.m_appenderLock.AcquireReaderLock();
try
{
if (c.m_appenderAttachedImpl != null)
{
writes += c.m_appenderAttachedImpl.AppendLoopOnAppenders(loggingEvent);
}
}
finally
{
c.m_appenderLock.ReleaseReaderLock();
}
}
if (!c.m_additive)
{
break;
}
}
// No appenders in hierarchy, warn user only once.
//
// Note that by including the AppDomain values for the currently running
// thread, it becomes much easier to see which application the warning
// is from, which is especially helpful in a multi-AppDomain environment
// (like IIS with multiple VDIRS). Without this, it can be difficult
// or impossible to determine which .config file is missing appender
// definitions.
//
if (!m_hierarchy.EmittedNoAppenderWarning && writes == 0)
{
LogLog.Debug(declaringType, "No appenders could be found for logger [" + Name + "] repository [" + Repository.Name + "]");
LogLog.Debug(declaringType, "Please initialize the log4net system properly.");
try
{
LogLog.Debug(declaringType, " Current AppDomain context information: ");
LogLog.Debug(declaringType, " BaseDirectory : " + SystemInfo.ApplicationBaseDirectory);
#if !NETCF
LogLog.Debug(declaringType, " FriendlyName : " + AppDomain.CurrentDomain.FriendlyName);
LogLog.Debug(declaringType, " DynamicDirectory: " + AppDomain.CurrentDomain.DynamicDirectory);
#endif
}
catch(System.Security.SecurityException)
{
// Insufficient permissions to display info from the AppDomain
}
m_hierarchy.EmittedNoAppenderWarning = true;
}
}
/// <summary>
/// Closes all attached appenders implementing the <see cref="IAppenderAttachable"/> interface.
/// </summary>
/// <remarks>
/// <para>
/// Used to ensure that the appenders are correctly shutdown.
/// </para>
/// </remarks>
virtual public void CloseNestedAppenders()
{
m_appenderLock.AcquireWriterLock();
try
{
if (m_appenderAttachedImpl != null)
{
AppenderCollection appenders = m_appenderAttachedImpl.Appenders;
foreach(IAppender appender in appenders)
{
if (appender is IAppenderAttachable)
{
appender.Close();
}
}
}
}
finally
{
m_appenderLock.ReleaseWriterLock();
}
}
/// <summary>
/// This is the most generic printing method. This generic form is intended to be used by wrappers
/// </summary>
/// <param name="level">The level of the message to be logged.</param>
/// <param name="message">The message object to log.</param>
/// <param name="exception">The exception to log, including its stack trace.</param>
/// <remarks>
/// <para>
/// Generate a logging event for the specified <paramref name="level"/> using
/// the <paramref name="message"/>.
/// </para>
/// </remarks>
virtual public void Log(Level level, object message, Exception exception)
{
if (IsEnabledFor(level))
{
ForcedLog(declaringType, level, message, exception);
}
}
/// <summary>
/// Creates a new logging event and logs the event without further checks.
/// </summary>
/// <param name="callerStackBoundaryDeclaringType">The declaring type of the method that is
/// the stack boundary into the logging system for this call.</param>
/// <param name="level">The level of the message to be logged.</param>
/// <param name="message">The message object to log.</param>
/// <param name="exception">The exception to log, including its stack trace.</param>
/// <remarks>
/// <para>
/// Generates a logging event and delivers it to the attached
/// appenders.
/// </para>
/// </remarks>
virtual protected void ForcedLog(Type callerStackBoundaryDeclaringType, Level level, object message, Exception exception)
{
CallAppenders(new LoggingEvent(callerStackBoundaryDeclaringType, this.Hierarchy, this.Name, level, message, exception));
}
/// <summary>
/// Creates a new logging event and logs the event without further checks.
/// </summary>
/// <param name="logEvent">The event being logged.</param>
/// <remarks>
/// <para>
/// Delivers the logging event to the attached appenders.
/// </para>
/// </remarks>
virtual protected void ForcedLog(LoggingEvent logEvent)
{
// The logging event may not have been created by this logger
// the Repository may not be correctly set on the event. This
// is required for the appenders to correctly lookup renderers etc...
logEvent.EnsureRepository(this.Hierarchy);
CallAppenders(logEvent);
}
#region Private Static Fields
/// <summary>
/// The fully qualified type of the Logger class.
/// </summary>
private readonly static Type declaringType = typeof(Logger);
#endregion Private Static Fields
#region Private Instance Fields
/// <summary>
/// The name of this logger.
/// </summary>
private readonly string m_name;
/// <summary>
/// The assigned level of this logger.
/// </summary>
/// <remarks>
/// <para>
/// The <c>level</c> variable need not be
/// assigned a value in which case it is inherited
/// form the hierarchy.
/// </para>
/// </remarks>
private Level m_level;
/// <summary>
/// The parent of this logger.
/// </summary>
/// <remarks>
/// <para>
/// The parent of this logger.
/// All loggers have at least one ancestor which is the root logger.
/// </para>
/// </remarks>
private Logger m_parent;
/// <summary>
/// Loggers need to know what Hierarchy they are in.
/// </summary>
/// <remarks>
/// <para>
/// Loggers need to know what Hierarchy they are in.
/// The hierarchy that this logger is a member of is stored
/// here.
/// </para>
/// </remarks>
private Hierarchy m_hierarchy;
/// <summary>
/// Helper implementation of the <see cref="IAppenderAttachable"/> interface
/// </summary>
private log4net.Util.AppenderAttachedImpl m_appenderAttachedImpl;
/// <summary>
/// Flag indicating if child loggers inherit their parents appenders
/// </summary>
/// <remarks>
/// <para>
/// Additivity is set to true by default, that is children inherit
/// the appenders of their ancestors by default. If this variable is
/// set to <c>false</c> then the appenders found in the
/// ancestors of this logger are not used. However, the children
/// of this logger will inherit its appenders, unless the children
/// have their additivity flag set to <c>false</c> too. See
/// the user manual for more details.
/// </para>
/// </remarks>
private bool m_additive = true;
/// <summary>
/// Lock to protect AppenderAttachedImpl variable m_appenderAttachedImpl
/// </summary>
private readonly ReaderWriterLock m_appenderLock = new ReaderWriterLock();
#endregion
}
}
| |
// Generated by ProtoGen, Version=2.4.1.555, Culture=neutral, PublicKeyToken=55f7125234beb589. DO NOT EDIT!
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace Google.ProtocolBuffers.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class UnitTestRpcInterop {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_SearchRequest__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.SearchRequest, global::Google.ProtocolBuffers.TestProtos.SearchRequest.Builder> internal__static_SearchRequest__FieldAccessorTable;
internal static pbd::MessageDescriptor internal__static_SearchResponse__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.SearchResponse, global::Google.ProtocolBuffers.TestProtos.SearchResponse.Builder> internal__static_SearchResponse__FieldAccessorTable;
internal static pbd::MessageDescriptor internal__static_SearchResponse_ResultItem__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem, global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem.Builder> internal__static_SearchResponse_ResultItem__FieldAccessorTable;
internal static pbd::MessageDescriptor internal__static_RefineSearchRequest__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.RefineSearchRequest, global::Google.ProtocolBuffers.TestProtos.RefineSearchRequest.Builder> internal__static_RefineSearchRequest__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static UnitTestRpcInterop() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiFleHRlc3QvdW5pdHRlc3RfcnBjX2ludGVyb3AucHJvdG8aJGdvb2dsZS9w",
"cm90b2J1Zi9jc2hhcnBfb3B0aW9ucy5wcm90byIhCg1TZWFyY2hSZXF1ZXN0",
"EhAKCENyaXRlcmlhGAEgAygJImYKDlNlYXJjaFJlc3BvbnNlEisKB3Jlc3Vs",
"dHMYASADKAsyGi5TZWFyY2hSZXNwb25zZS5SZXN1bHRJdGVtGicKClJlc3Vs",
"dEl0ZW0SCwoDdXJsGAEgAigJEgwKBG5hbWUYAiABKAkiUgoTUmVmaW5lU2Vh",
"cmNoUmVxdWVzdBIQCghDcml0ZXJpYRgBIAMoCRIpChBwcmV2aW91c19yZXN1",
"bHRzGAIgAigLMg8uU2VhcmNoUmVzcG9uc2UycQoNU2VhcmNoU2VydmljZRIp",
"CgZTZWFyY2gSDi5TZWFyY2hSZXF1ZXN0Gg8uU2VhcmNoUmVzcG9uc2USNQoM",
"UmVmaW5lU2VhcmNoEhQuUmVmaW5lU2VhcmNoUmVxdWVzdBoPLlNlYXJjaFJl",
"c3BvbnNlQj9IAcI+OgohR29vZ2xlLlByb3RvY29sQnVmZmVycy5UZXN0UHJv",
"dG9zEhJVbml0VGVzdFJwY0ludGVyb3CIDgM="));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_SearchRequest__Descriptor = Descriptor.MessageTypes[0];
internal__static_SearchRequest__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.SearchRequest, global::Google.ProtocolBuffers.TestProtos.SearchRequest.Builder>(internal__static_SearchRequest__Descriptor,
new string[] { "Criteria", });
internal__static_SearchResponse__Descriptor = Descriptor.MessageTypes[1];
internal__static_SearchResponse__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.SearchResponse, global::Google.ProtocolBuffers.TestProtos.SearchResponse.Builder>(internal__static_SearchResponse__Descriptor,
new string[] { "Results", });
internal__static_SearchResponse_ResultItem__Descriptor = internal__static_SearchResponse__Descriptor.NestedTypes[0];
internal__static_SearchResponse_ResultItem__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem, global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem.Builder>(internal__static_SearchResponse_ResultItem__Descriptor,
new string[] { "Url", "Name", });
internal__static_RefineSearchRequest__Descriptor = Descriptor.MessageTypes[2];
internal__static_RefineSearchRequest__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.RefineSearchRequest, global::Google.ProtocolBuffers.TestProtos.RefineSearchRequest.Builder>(internal__static_RefineSearchRequest__Descriptor,
new string[] { "Criteria", "PreviousResults", });
pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
RegisterAllExtensions(registry);
global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.Descriptor,
}, assigner);
}
#endregion
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class SearchRequest : pb::GeneratedMessage<SearchRequest, SearchRequest.Builder> {
private SearchRequest() { }
private static readonly SearchRequest defaultInstance = new SearchRequest().MakeReadOnly();
private static readonly string[] _searchRequestFieldNames = new string[] { "Criteria" };
private static readonly uint[] _searchRequestFieldTags = new uint[] { 10 };
public static SearchRequest DefaultInstance {
get { return defaultInstance; }
}
public override SearchRequest DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override SearchRequest ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestRpcInterop.internal__static_SearchRequest__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<SearchRequest, SearchRequest.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestRpcInterop.internal__static_SearchRequest__FieldAccessorTable; }
}
public const int CriteriaFieldNumber = 1;
private pbc::PopsicleList<string> criteria_ = new pbc::PopsicleList<string>();
public scg::IList<string> CriteriaList {
get { return pbc::Lists.AsReadOnly(criteria_); }
}
public int CriteriaCount {
get { return criteria_.Count; }
}
public string GetCriteria(int index) {
return criteria_[index];
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _searchRequestFieldNames;
if (criteria_.Count > 0) {
output.WriteStringArray(1, field_names[0], criteria_);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
{
int dataSize = 0;
foreach (string element in CriteriaList) {
dataSize += pb::CodedOutputStream.ComputeStringSizeNoTag(element);
}
size += dataSize;
size += 1 * criteria_.Count;
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static SearchRequest ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static SearchRequest ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static SearchRequest ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static SearchRequest ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static SearchRequest ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static SearchRequest ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static SearchRequest ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static SearchRequest ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static SearchRequest ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static SearchRequest ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private SearchRequest MakeReadOnly() {
criteria_.MakeReadOnly();
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(SearchRequest prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<SearchRequest, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(SearchRequest cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private SearchRequest result;
private SearchRequest PrepareBuilder() {
if (resultIsReadOnly) {
SearchRequest original = result;
result = new SearchRequest();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override SearchRequest MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.TestProtos.SearchRequest.Descriptor; }
}
public override SearchRequest DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.SearchRequest.DefaultInstance; }
}
public override SearchRequest BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is SearchRequest) {
return MergeFrom((SearchRequest) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(SearchRequest other) {
if (other == global::Google.ProtocolBuffers.TestProtos.SearchRequest.DefaultInstance) return this;
PrepareBuilder();
if (other.criteria_.Count != 0) {
result.criteria_.Add(other.criteria_);
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_searchRequestFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _searchRequestFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 10: {
input.ReadStringArray(tag, field_name, result.criteria_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public pbc::IPopsicleList<string> CriteriaList {
get { return PrepareBuilder().criteria_; }
}
public int CriteriaCount {
get { return result.CriteriaCount; }
}
public string GetCriteria(int index) {
return result.GetCriteria(index);
}
public Builder SetCriteria(int index, string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.criteria_[index] = value;
return this;
}
public Builder AddCriteria(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.criteria_.Add(value);
return this;
}
public Builder AddRangeCriteria(scg::IEnumerable<string> values) {
PrepareBuilder();
result.criteria_.Add(values);
return this;
}
public Builder ClearCriteria() {
PrepareBuilder();
result.criteria_.Clear();
return this;
}
}
static SearchRequest() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnitTestRpcInterop.Descriptor, null);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class SearchResponse : pb::GeneratedMessage<SearchResponse, SearchResponse.Builder> {
private SearchResponse() { }
private static readonly SearchResponse defaultInstance = new SearchResponse().MakeReadOnly();
private static readonly string[] _searchResponseFieldNames = new string[] { "results" };
private static readonly uint[] _searchResponseFieldTags = new uint[] { 10 };
public static SearchResponse DefaultInstance {
get { return defaultInstance; }
}
public override SearchResponse DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override SearchResponse ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestRpcInterop.internal__static_SearchResponse__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<SearchResponse, SearchResponse.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestRpcInterop.internal__static_SearchResponse__FieldAccessorTable; }
}
#region Nested types
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Types {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class ResultItem : pb::GeneratedMessage<ResultItem, ResultItem.Builder> {
private ResultItem() { }
private static readonly ResultItem defaultInstance = new ResultItem().MakeReadOnly();
private static readonly string[] _resultItemFieldNames = new string[] { "name", "url" };
private static readonly uint[] _resultItemFieldTags = new uint[] { 18, 10 };
public static ResultItem DefaultInstance {
get { return defaultInstance; }
}
public override ResultItem DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override ResultItem ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestRpcInterop.internal__static_SearchResponse_ResultItem__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<ResultItem, ResultItem.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestRpcInterop.internal__static_SearchResponse_ResultItem__FieldAccessorTable; }
}
public const int UrlFieldNumber = 1;
private bool hasUrl;
private string url_ = "";
public bool HasUrl {
get { return hasUrl; }
}
public string Url {
get { return url_; }
}
public const int NameFieldNumber = 2;
private bool hasName;
private string name_ = "";
public bool HasName {
get { return hasName; }
}
public string Name {
get { return name_; }
}
public override bool IsInitialized {
get {
if (!hasUrl) return false;
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _resultItemFieldNames;
if (hasUrl) {
output.WriteString(1, field_names[1], Url);
}
if (hasName) {
output.WriteString(2, field_names[0], Name);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasUrl) {
size += pb::CodedOutputStream.ComputeStringSize(1, Url);
}
if (hasName) {
size += pb::CodedOutputStream.ComputeStringSize(2, Name);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static ResultItem ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static ResultItem ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static ResultItem ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static ResultItem ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static ResultItem ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static ResultItem ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static ResultItem ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static ResultItem ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static ResultItem ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static ResultItem ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private ResultItem MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(ResultItem prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<ResultItem, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(ResultItem cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private ResultItem result;
private ResultItem PrepareBuilder() {
if (resultIsReadOnly) {
ResultItem original = result;
result = new ResultItem();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override ResultItem MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem.Descriptor; }
}
public override ResultItem DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem.DefaultInstance; }
}
public override ResultItem BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is ResultItem) {
return MergeFrom((ResultItem) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(ResultItem other) {
if (other == global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem.DefaultInstance) return this;
PrepareBuilder();
if (other.HasUrl) {
Url = other.Url;
}
if (other.HasName) {
Name = other.Name;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_resultItemFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _resultItemFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 10: {
result.hasUrl = input.ReadString(ref result.url_);
break;
}
case 18: {
result.hasName = input.ReadString(ref result.name_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasUrl {
get { return result.hasUrl; }
}
public string Url {
get { return result.Url; }
set { SetUrl(value); }
}
public Builder SetUrl(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasUrl = true;
result.url_ = value;
return this;
}
public Builder ClearUrl() {
PrepareBuilder();
result.hasUrl = false;
result.url_ = "";
return this;
}
public bool HasName {
get { return result.hasName; }
}
public string Name {
get { return result.Name; }
set { SetName(value); }
}
public Builder SetName(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasName = true;
result.name_ = value;
return this;
}
public Builder ClearName() {
PrepareBuilder();
result.hasName = false;
result.name_ = "";
return this;
}
}
static ResultItem() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnitTestRpcInterop.Descriptor, null);
}
}
}
#endregion
public const int ResultsFieldNumber = 1;
private pbc::PopsicleList<global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem> results_ = new pbc::PopsicleList<global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem>();
public scg::IList<global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem> ResultsList {
get { return results_; }
}
public int ResultsCount {
get { return results_.Count; }
}
public global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem GetResults(int index) {
return results_[index];
}
public override bool IsInitialized {
get {
foreach (global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem element in ResultsList) {
if (!element.IsInitialized) return false;
}
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _searchResponseFieldNames;
if (results_.Count > 0) {
output.WriteMessageArray(1, field_names[0], results_);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
foreach (global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem element in ResultsList) {
size += pb::CodedOutputStream.ComputeMessageSize(1, element);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static SearchResponse ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static SearchResponse ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static SearchResponse ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static SearchResponse ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static SearchResponse ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static SearchResponse ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static SearchResponse ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static SearchResponse ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static SearchResponse ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static SearchResponse ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private SearchResponse MakeReadOnly() {
results_.MakeReadOnly();
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(SearchResponse prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<SearchResponse, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(SearchResponse cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private SearchResponse result;
private SearchResponse PrepareBuilder() {
if (resultIsReadOnly) {
SearchResponse original = result;
result = new SearchResponse();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override SearchResponse MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.TestProtos.SearchResponse.Descriptor; }
}
public override SearchResponse DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.SearchResponse.DefaultInstance; }
}
public override SearchResponse BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is SearchResponse) {
return MergeFrom((SearchResponse) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(SearchResponse other) {
if (other == global::Google.ProtocolBuffers.TestProtos.SearchResponse.DefaultInstance) return this;
PrepareBuilder();
if (other.results_.Count != 0) {
result.results_.Add(other.results_);
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_searchResponseFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _searchResponseFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 10: {
input.ReadMessageArray(tag, field_name, result.results_, global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem.DefaultInstance, extensionRegistry);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public pbc::IPopsicleList<global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem> ResultsList {
get { return PrepareBuilder().results_; }
}
public int ResultsCount {
get { return result.ResultsCount; }
}
public global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem GetResults(int index) {
return result.GetResults(index);
}
public Builder SetResults(int index, global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.results_[index] = value;
return this;
}
public Builder SetResults(int index, global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
PrepareBuilder();
result.results_[index] = builderForValue.Build();
return this;
}
public Builder AddResults(global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.results_.Add(value);
return this;
}
public Builder AddResults(global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
PrepareBuilder();
result.results_.Add(builderForValue.Build());
return this;
}
public Builder AddRangeResults(scg::IEnumerable<global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem> values) {
PrepareBuilder();
result.results_.Add(values);
return this;
}
public Builder ClearResults() {
PrepareBuilder();
result.results_.Clear();
return this;
}
}
static SearchResponse() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnitTestRpcInterop.Descriptor, null);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class RefineSearchRequest : pb::GeneratedMessage<RefineSearchRequest, RefineSearchRequest.Builder> {
private RefineSearchRequest() { }
private static readonly RefineSearchRequest defaultInstance = new RefineSearchRequest().MakeReadOnly();
private static readonly string[] _refineSearchRequestFieldNames = new string[] { "Criteria", "previous_results" };
private static readonly uint[] _refineSearchRequestFieldTags = new uint[] { 10, 18 };
public static RefineSearchRequest DefaultInstance {
get { return defaultInstance; }
}
public override RefineSearchRequest DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override RefineSearchRequest ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestRpcInterop.internal__static_RefineSearchRequest__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<RefineSearchRequest, RefineSearchRequest.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestRpcInterop.internal__static_RefineSearchRequest__FieldAccessorTable; }
}
public const int CriteriaFieldNumber = 1;
private pbc::PopsicleList<string> criteria_ = new pbc::PopsicleList<string>();
public scg::IList<string> CriteriaList {
get { return pbc::Lists.AsReadOnly(criteria_); }
}
public int CriteriaCount {
get { return criteria_.Count; }
}
public string GetCriteria(int index) {
return criteria_[index];
}
public const int PreviousResultsFieldNumber = 2;
private bool hasPreviousResults;
private global::Google.ProtocolBuffers.TestProtos.SearchResponse previousResults_;
public bool HasPreviousResults {
get { return hasPreviousResults; }
}
public global::Google.ProtocolBuffers.TestProtos.SearchResponse PreviousResults {
get { return previousResults_ ?? global::Google.ProtocolBuffers.TestProtos.SearchResponse.DefaultInstance; }
}
public override bool IsInitialized {
get {
if (!hasPreviousResults) return false;
if (!PreviousResults.IsInitialized) return false;
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _refineSearchRequestFieldNames;
if (criteria_.Count > 0) {
output.WriteStringArray(1, field_names[0], criteria_);
}
if (hasPreviousResults) {
output.WriteMessage(2, field_names[1], PreviousResults);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
{
int dataSize = 0;
foreach (string element in CriteriaList) {
dataSize += pb::CodedOutputStream.ComputeStringSizeNoTag(element);
}
size += dataSize;
size += 1 * criteria_.Count;
}
if (hasPreviousResults) {
size += pb::CodedOutputStream.ComputeMessageSize(2, PreviousResults);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static RefineSearchRequest ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static RefineSearchRequest ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static RefineSearchRequest ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static RefineSearchRequest ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static RefineSearchRequest ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static RefineSearchRequest ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static RefineSearchRequest ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static RefineSearchRequest ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static RefineSearchRequest ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static RefineSearchRequest ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private RefineSearchRequest MakeReadOnly() {
criteria_.MakeReadOnly();
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(RefineSearchRequest prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<RefineSearchRequest, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(RefineSearchRequest cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private RefineSearchRequest result;
private RefineSearchRequest PrepareBuilder() {
if (resultIsReadOnly) {
RefineSearchRequest original = result;
result = new RefineSearchRequest();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override RefineSearchRequest MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.TestProtos.RefineSearchRequest.Descriptor; }
}
public override RefineSearchRequest DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.RefineSearchRequest.DefaultInstance; }
}
public override RefineSearchRequest BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is RefineSearchRequest) {
return MergeFrom((RefineSearchRequest) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(RefineSearchRequest other) {
if (other == global::Google.ProtocolBuffers.TestProtos.RefineSearchRequest.DefaultInstance) return this;
PrepareBuilder();
if (other.criteria_.Count != 0) {
result.criteria_.Add(other.criteria_);
}
if (other.HasPreviousResults) {
MergePreviousResults(other.PreviousResults);
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_refineSearchRequestFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _refineSearchRequestFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 10: {
input.ReadStringArray(tag, field_name, result.criteria_);
break;
}
case 18: {
global::Google.ProtocolBuffers.TestProtos.SearchResponse.Builder subBuilder = global::Google.ProtocolBuffers.TestProtos.SearchResponse.CreateBuilder();
if (result.hasPreviousResults) {
subBuilder.MergeFrom(PreviousResults);
}
input.ReadMessage(subBuilder, extensionRegistry);
PreviousResults = subBuilder.BuildPartial();
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public pbc::IPopsicleList<string> CriteriaList {
get { return PrepareBuilder().criteria_; }
}
public int CriteriaCount {
get { return result.CriteriaCount; }
}
public string GetCriteria(int index) {
return result.GetCriteria(index);
}
public Builder SetCriteria(int index, string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.criteria_[index] = value;
return this;
}
public Builder AddCriteria(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.criteria_.Add(value);
return this;
}
public Builder AddRangeCriteria(scg::IEnumerable<string> values) {
PrepareBuilder();
result.criteria_.Add(values);
return this;
}
public Builder ClearCriteria() {
PrepareBuilder();
result.criteria_.Clear();
return this;
}
public bool HasPreviousResults {
get { return result.hasPreviousResults; }
}
public global::Google.ProtocolBuffers.TestProtos.SearchResponse PreviousResults {
get { return result.PreviousResults; }
set { SetPreviousResults(value); }
}
public Builder SetPreviousResults(global::Google.ProtocolBuffers.TestProtos.SearchResponse value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasPreviousResults = true;
result.previousResults_ = value;
return this;
}
public Builder SetPreviousResults(global::Google.ProtocolBuffers.TestProtos.SearchResponse.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
PrepareBuilder();
result.hasPreviousResults = true;
result.previousResults_ = builderForValue.Build();
return this;
}
public Builder MergePreviousResults(global::Google.ProtocolBuffers.TestProtos.SearchResponse value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
if (result.hasPreviousResults &&
result.previousResults_ != global::Google.ProtocolBuffers.TestProtos.SearchResponse.DefaultInstance) {
result.previousResults_ = global::Google.ProtocolBuffers.TestProtos.SearchResponse.CreateBuilder(result.previousResults_).MergeFrom(value).BuildPartial();
} else {
result.previousResults_ = value;
}
result.hasPreviousResults = true;
return this;
}
public Builder ClearPreviousResults() {
PrepareBuilder();
result.hasPreviousResults = false;
result.previousResults_ = null;
return this;
}
}
static RefineSearchRequest() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnitTestRpcInterop.Descriptor, null);
}
}
#endregion
#region Services
public partial interface ISearchService {
global::Google.ProtocolBuffers.TestProtos.SearchResponse Search(global::Google.ProtocolBuffers.TestProtos.SearchRequest searchRequest);
global::Google.ProtocolBuffers.TestProtos.SearchResponse RefineSearch(global::Google.ProtocolBuffers.TestProtos.RefineSearchRequest refineSearchRequest);
}
[global::System.CLSCompliant(false)]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public partial class SearchService : ISearchService, pb::IRpcDispatch, global::System.IDisposable {
private readonly bool dispose;
private readonly pb::IRpcDispatch dispatch;
public SearchService(pb::IRpcDispatch dispatch) : this(dispatch, true) {
}
public SearchService(pb::IRpcDispatch dispatch, bool dispose) {
pb::ThrowHelper.ThrowIfNull(this.dispatch = dispatch, "dispatch");
this.dispose = dispose && dispatch is global::System.IDisposable;
}
public void Dispose() {
if (dispose) ((global::System.IDisposable)dispatch).Dispose();
}
TMessage pb::IRpcDispatch.CallMethod<TMessage, TBuilder>(string method, pb::IMessageLite request, pb::IBuilderLite<TMessage, TBuilder> response) {
return dispatch.CallMethod(method, request, response);
}
public global::Google.ProtocolBuffers.TestProtos.SearchResponse Search(global::Google.ProtocolBuffers.TestProtos.SearchRequest searchRequest) {
return dispatch.CallMethod("Search", searchRequest, global::Google.ProtocolBuffers.TestProtos.SearchResponse.CreateBuilder());
}
public global::Google.ProtocolBuffers.TestProtos.SearchResponse RefineSearch(global::Google.ProtocolBuffers.TestProtos.RefineSearchRequest refineSearchRequest) {
return dispatch.CallMethod("RefineSearch", refineSearchRequest, global::Google.ProtocolBuffers.TestProtos.SearchResponse.CreateBuilder());
}
[global::System.CLSCompliant(false)]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public partial class Dispatch : pb::IRpcDispatch, global::System.IDisposable {
private readonly bool dispose;
private readonly ISearchService implementation;
public Dispatch(ISearchService implementation) : this(implementation, true) {
}
public Dispatch(ISearchService implementation, bool dispose) {
pb::ThrowHelper.ThrowIfNull(this.implementation = implementation, "implementation");
this.dispose = dispose && implementation is global::System.IDisposable;
}
public void Dispose() {
if (dispose) ((global::System.IDisposable)implementation).Dispose();
}
public TMessage CallMethod<TMessage, TBuilder>(string methodName, pb::IMessageLite request, pb::IBuilderLite<TMessage, TBuilder> response)
where TMessage : pb::IMessageLite<TMessage, TBuilder>
where TBuilder : pb::IBuilderLite<TMessage, TBuilder> {
switch(methodName) {
case "Search": return response.MergeFrom(implementation.Search((global::Google.ProtocolBuffers.TestProtos.SearchRequest)request)).Build();
case "RefineSearch": return response.MergeFrom(implementation.RefineSearch((global::Google.ProtocolBuffers.TestProtos.RefineSearchRequest)request)).Build();
default: throw pb::ThrowHelper.CreateMissingMethod(typeof(ISearchService), methodName);
}
}
}
[global::System.CLSCompliant(false)]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public partial class ServerStub : pb::IRpcServerStub, global::System.IDisposable {
private readonly bool dispose;
private readonly pb::IRpcDispatch implementation;
public ServerStub(ISearchService implementation) : this(implementation, true) {
}
public ServerStub(ISearchService implementation, bool dispose) : this(new Dispatch(implementation, dispose), dispose) {
}
public ServerStub(pb::IRpcDispatch implementation) : this(implementation, true) {
}
public ServerStub(pb::IRpcDispatch implementation, bool dispose) {
pb::ThrowHelper.ThrowIfNull(this.implementation = implementation, "implementation");
this.dispose = dispose && implementation is global::System.IDisposable;
}
public void Dispose() {
if (dispose) ((global::System.IDisposable)implementation).Dispose();
}
public pb::IMessageLite CallMethod(string methodName, pb::ICodedInputStream input, pb::ExtensionRegistry registry) {
switch(methodName) {
case "Search": return implementation.CallMethod(methodName, global::Google.ProtocolBuffers.TestProtos.SearchRequest.ParseFrom(input, registry), global::Google.ProtocolBuffers.TestProtos.SearchResponse.CreateBuilder());
case "RefineSearch": return implementation.CallMethod(methodName, global::Google.ProtocolBuffers.TestProtos.RefineSearchRequest.ParseFrom(input, registry), global::Google.ProtocolBuffers.TestProtos.SearchResponse.CreateBuilder());
default: throw pb::ThrowHelper.CreateMissingMethod(typeof(ISearchService), methodName);
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
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 SmartLMS.Areas.HelpPage.ModelDescriptions;
using SmartLMS.Areas.HelpPage.Models;
namespace SmartLMS.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);
}
}
}
}
| |
#region
/*
Copyright (c) 2002-2012, Bas Geertsema, Xih Solutions
(http://www.xihsolutions.net), Thiago.Sayao, Pang Wu, Ethem Evlice, Andy Phan, Chang Liu.
All rights reserved. http://code.google.com/p/msnp-sharp/
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 names of Bas Geertsema or Xih Solutions nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
namespace MSNPSharp
{
using MSNPSharp.Core;
/// <summary>
/// Msn protocol speaking
/// </summary>
public enum MsnProtocol
{
MSNP21 = 21
}
/// <summary>
/// Specifies the type of proxy servers that can be used
/// </summary>
public enum ProxyType
{
/// <summary>No proxy server.</summary>
None,
/// <summary>A SOCKS4[A] proxy server.</summary>
Socks4,
/// <summary>A SOCKS5 proxy server.</summary>
Socks5,
/// <summary>A HTTP proxy server.</summary>
Http,
}
/// <summary>
/// Specifieds the type of a notification message.
/// </summary>
public enum NotificationType
{
/// <summary>
/// A message a remote contact send from a mobile device.
/// </summary>
Mobile = 0,
/// <summary>
/// A calendar reminder.
/// </summary>
Calendar = 1,
/// <summary>
/// An alert notification.
/// </summary>
Alert = 2
}
/// <summary>
/// Specifies the online presence state
/// </summary>
public enum PresenceStatus
{
/// <summary>
/// Unknown presence state.
/// </summary>
Unknown = 0,
/// <summary>
/// Contact is offline (or a remote contact is hidden).
/// </summary>
Offline,
/// <summary>
/// The client owner is hidden.
/// </summary>
Hidden,
/// <summary>
/// The contact is online.
/// </summary>
Online,
/// <summary>
/// The contact is away.
/// </summary>
Away,
/// <summary>
/// The contact is busy.
/// </summary>
Busy,
/// <summary>
/// The contact will be right back.
/// </summary>
BRB,
/// <summary>
/// The contact is out to lunch.
/// </summary>
Lunch,
/// <summary>
/// The contact is on the phone.
/// </summary>
Phone,
/// <summary>
/// The contact is idle.
/// </summary>
Idle
}
/// <summary>
/// Defines why a user has (been) signed off.
/// </summary>
/// <remarks>
/// <b>OtherClient</b> is used when this account has signed in from another location. <b>ServerDown</b> is used when the msn server is going down.
/// </remarks>
public enum SignedOffReason
{
/// <summary>
/// None.
/// </summary>
None,
/// <summary>
/// User logged in on the other client.
/// </summary>
OtherClient,
/// <summary>
/// Server went down.
/// </summary>
ServerDown
}
/// <summary>
/// Roles used in the messenger network
/// </summary>
[FlagsAttribute]
public enum RoleLists
{
/// <summary>
/// No msn list
/// </summary>
None = 0,
/// <summary>
/// All contacts in your contactlist. You can send messages to those people.
/// </summary>
Forward = 1,
/// <summary>
/// All contacts who are allowed to see your status.
/// </summary>
Allow = 2,
/// <summary>
/// All contacts who you have blocked.
/// </summary>
[Obsolete("", true)]
Block = 4,
/// <summary>
/// All contacts who have you on their contactlist.
/// </summary>
[Obsolete("",true)]
Reverse = 8,
/// <summary>
/// All pending (for approval) contacts.
/// </summary>
Pending = 16,
/// <summary>
/// Forward+Block
/// </summary>
HideCompat = 5,
/// <summary>
/// Application contact
/// </summary>
ApplicationContact = 32,
/// <summary>
/// Show me offline but you can receive/send offline messages.
/// </summary>
Hide = 64
}
/// <summary>
/// The functions a (remote) client supports.
/// </summary>
[Flags]
public enum ClientCapabilities : long
{
None = 0x00,
OnlineViaMobile = 0x01,
OnlineViaTexas = 0x02,
SupportsGifInk = 0x04,
SupportsIsfInk = 0x08,
WebCamDetected = 0x10,
SupportsChunking = 0x20,
MobileEnabled = 0x40,
WebWatchEnabled = 0x80,
SupportsActivities = 0x100,
OnlineViaWebIM = 0x200,
MobileDevice = 0x400,
OnlineViaFederatedInterface = 0x800,
HasSpace = 0x1000,
IsMceUser = 0x2000,
SupportsDirectIM = 0x4000,
SupportsWinks = 0x8000,
SupportsSharedSearch = 0x10000,
IsBot = 0x20000,
SupportsVoiceIM = 0x40000,
SupportsSChannel = 0x80000,
SupportsSipInvite = 0x100000,
SupportsMultipartyMedia = 0x200000,
SupportsSDrive = 0x400000,
SupportsPageModeMessaging = 0x800000,
HasOneCare = 0x1000000,
SupportsTurn = 0x2000000,
SupportsDirectBootstrapping = 0x4000000,
UsingAlias = 0x8000000,
/// <summary>
/// MSNC1
/// </summary>
AppVersion60 = 0x10000000,
/// <summary>
/// MSNC2
/// </summary>
AppVersion61 = 0x20000000,
/// <summary>
/// MSNC3
/// </summary>
AppVersion62 = 0x30000000,
/// <summary>
/// MSNC4
/// </summary>
AppVersion70 = 0x40000000,
/// <summary>
/// MSNC5
/// </summary>
AppVersion75 = 0x50000000,
/// <summary>
/// MSNC6
/// </summary>
AppVersion80 = 0x60000000,
/// <summary>
///MSNC7
/// </summary>
AppVersion81 = 0x70000000,
/// <summary>
/// MSNC8 (MSNP15)
/// </summary>
AppVersion85 = 0x80000000,
/// <summary>
/// MSNC9 (MSNP16)
/// </summary>
AppVersion90 = 0x90000000,
/// <summary>
/// MSNC10 - MSN 14.0, Wave 3 (MSNP18)
/// </summary>
AppVersion2009 = 0xA0000000,
/// <summary>
/// MSNC11 - MSN 15.0, Wave 4 (MSNP21)
/// </summary>
AppVersion2011 = 0xB0000000,
/// <summary>
/// MSNC12 - MSN 16.0 Cloud, Wave 5 (MSNP21)
/// </summary>
AppVersion2012 = 0xC0000000,
AppVersion2___ = 0xD0000000,
AppVersion20__ = 0xE0000000,
/// <summary>
/// Mask for MSNC
/// </summary>
AppVersionMask = 0xF0000000,
DefaultIM = SupportsChunking | SupportsActivities | SupportsWinks | AppVersion2011,
DefaultPE = SupportsTurn | SupportsDirectBootstrapping
}
[Flags]
public enum ClientCapabilitiesEx : long
{
None = 0x00,
IsSmsOnly = 0x01,
SupportsVoiceOverMsnp = 0x02,
SupportsUucpSipStack = 0x04,
SupportsApplicationMessages = 0x08,
RTCVideoEnabled = 0x10,
SupportsPeerToPeerV2 = 0x20,
IsAuthenticatedWebIMUser = 0x40,
Supports1On1ViaGroup = 0x80,
SupportsOfflineIM = 0x100,
SupportsSharingVideo = 0x200,
SupportsNudges = 0x400, // (((:)))
CircleVoiceIMEnabled = 0x800,
SharingEnabled = 0x1000,
MobileSuspendIMFanoutDisable = 0x2000,
_0x4000 = 0x4000,
SupportsPeerToPeerMixerRelay = 0x8000,
_0x10000 = 0x10000,
ConvWindowFileTransfer = 0x20000,
VideoCallSupports16x9 = 0x40000,
SupportsPeerToPeerEnveloping = 0x80000,
_0x100000 = 0x100000,
_0x200000 = 0x200000,
YahooIMDisabled = 0x400000,
SIPTunnelVersion2 = 0x800000,
VoiceClipSupportsWMAFormat = 0x1000000,
VoiceClipSupportsCircleIM = 0x2000000,
SupportsSocialNewsObjectTypes = 0x4000000,
CustomEmoticonsCapable = 0x8000000,
SupportsUTF8MoodMessages = 0x10000000,
FTURNCapable = 0x20000000,
SupportsP4Activity = 0x40000000,
SupportsMultipartyConversations = 0x80000000,
DefaultIM = Supports1On1ViaGroup | SupportsOfflineIM | SupportsSharingVideo | SupportsNudges | SharingEnabled | ConvWindowFileTransfer | SIPTunnelVersion2 | CustomEmoticonsCapable | SupportsUTF8MoodMessages | SupportsMultipartyConversations,
DefaultPE = _0x4000 | SupportsPeerToPeerMixerRelay | _0x10000 | SupportsPeerToPeerEnveloping | _0x100000 | SupportsSocialNewsObjectTypes | SupportsP4Activity
}
/// <summary>
/// The text decorations messenger sends with a message
/// </summary>
[FlagsAttribute]
public enum TextDecorations
{
/// <summary>
/// No decoration.
/// </summary>
None = 0,
/// <summary>
/// Bold.
/// </summary>
Bold = 1,
/// <summary>
/// Italic.
/// </summary>
Italic = 2,
/// <summary>
/// Underline.
/// </summary>
Underline = 4,
/// <summary>
/// Strike-trough.
/// </summary>
Strike = 8
}
/// <summary>
/// Types of media used on UBX command
/// </summary>
public enum MediaType
{
None = 0,
Music = 1,
Games = 2,
Office = 3
}
/// <summary>
/// A charset that can be used in a message.
/// </summary>
public enum MessageCharSet
{
/// <summary>
/// ANSI
/// </summary>
Ansi = 0,
/// <summary>
/// Default charset.
/// </summary>
Default = 1,
/// <summary>
/// Symbol.
/// </summary>
Symbol = 2,
/// <summary>
/// Mac.
/// </summary>
Mac = 77,
/// <summary>
/// Shiftjis.
/// </summary>
Shiftjis = 128,
/// <summary>
/// Hangeul.
/// </summary>
Hangeul = 129,
/// <summary>
/// Johab.
/// </summary>
Johab = 130,
/// <summary>
/// GB2312.
/// </summary>
GB2312 = 134,
/// <summary>
/// Chines Big 5.
/// </summary>
ChineseBig5 = 136,
/// <summary>
/// Greek.
/// </summary>
Greek = 161,
/// <summary>
/// Turkish.
/// </summary>
Turkish = 162,
/// <summary>
/// Vietnamese.
/// </summary>
Vietnamese = 163,
/// <summary>
/// Hebrew.
/// </summary>
Hebrew = 177,
/// <summary>
/// Arabic.
/// </summary>
Arabic = 178,
/// <summary>
/// Baltic.
/// </summary>
Baltic = 186,
/// <summary>
/// Russian.
/// </summary>
Russian = 204,
/// <summary>
/// Thai.
/// </summary>
Thai = 222,
/// <summary>
/// Eastern Europe.
/// </summary>
EastEurope = 238,
/// <summary>
/// OEM.
/// </summary>
Oem = 255
}
/// <summary>
/// Instant message address info type.
/// </summary>
public enum IMAddressInfoType : int
{
/// <summary>
/// No client
/// </summary>
None = 0,
/// <summary>
/// Passport address
/// </summary>
WindowsLive = 1,
/// <summary>
/// Office Communicator address
/// </summary>
OfficeCommunicator = 2,
/// <summary>
/// Telephone number
/// </summary>
Telephone = 4,
/// <summary>
/// Mobile network
/// </summary>
MobileNetwork = 8,
/// <summary>
/// MSN group
/// </summary>
Circle = 9,
/// <summary>
/// Temporary group
/// </summary>
TemporaryGroup = 10,
/// <summary>
/// CID
/// </summary>
Cid = 11,
/// <summary>
/// Connect
/// </summary>
Connect = 13,
/// <summary>
/// Remote network, like FB
/// </summary>
RemoteNetwork = 14,
/// <summary>
/// Smtp
/// </summary>
Smtp = 16,
/// <summary>
/// Yahoo! address
/// </summary>
Yahoo = 32
}
/// <summary>
/// Specifies an error a MSN Server can send.
/// </summary>
public enum MSNError
{
/// <summary>
/// No error
/// </summary>
None = 0,
/// <summary>
/// Syntax error.
/// </summary>
SyntaxError = 200,
/// <summary>
/// Invalid parameter.
/// </summary>
InvalidParameter = 201,
/// <summary>
/// Invalid federated user
/// </summary>
InvalidFederatedUser = 203,
/// <summary>
/// Invalid contact network
/// </summary>
UnroutableUser = 204,
/// <summary>
/// Invalid user.
/// </summary>
InvalidUser = 205,
/// <summary>
/// Missing domain.
/// </summary>
MissingDomain = 206,
/// <summary>
/// The user is already logged in.
/// </summary>
AlreadyLoggedIn = 207,
/// <summary>
/// The username specified is invalid.
/// </summary>
InvalidUsername = 208,
/// <summary>
/// The full username specified is invalid.
/// </summary>
InvalidFullUsername = 209,
/// <summary>
/// User's contact list is full.
/// </summary>
UserListFull = 210,
/// <summary>
/// Invalid Name Request.
/// </summary>
InvalidNameRequest = 213,
/// <summary>
/// User is already specified.
/// </summary>
UserAlreadyThere = 215,
/// <summary>
/// User is already on the list.
/// </summary>
UserAlreadyOnList = 216,
/// <summary>
/// User is not accepting instant messages.
/// </summary>
NotAcceptingIMs = 217,
/// <summary>
/// Already in stated mode.
/// </summary>
AlreadyInMode = 218,
/// <summary>
/// User is in opposite (conflicting) list.
/// </summary>
UserInOppositeList = 219,
/// <summary>
/// NotAcceptingPages
/// </summary>
NotAcceptingPages = 220,
/// <summary>
/// Too Many Groups.
/// </summary>
TooManyGroups = 223,
/// <summary>
/// Invalid Group.
/// </summary>
InvalidGroup = 224,
/// <summary>
/// Principal not in group.
/// </summary>
PrincipalNotInGroup = 225,
/// <summary>
/// Principal not in group.
/// </summary>
GroupNotEmpty = 227,
/// <summary>
/// Contactgroup name already exists.
/// </summary>
ContactGroupNameExists = 228,
/// <summary>
/// Group name too long.
/// </summary>
GroupNameTooLong = 229,
/// <summary>
/// Cannot remove group zero
/// </summary>
CannotRemoveGroupZero = 230,
/// <summary>
/// InvalidMsisdn
/// </summary>
InvalidMsisdn = 232,
/// <summary>
/// UnknownMsisdn
/// </summary>
UnknownMsisdn = 233,
/// <summary>
/// UnknownKeitaiDomain
/// </summary>
UnknownKeitaiDomain = 234,
/// <summary>
/// If <d/> domain element specified in <ml/> mail list, at least one <c/> contact must be exists
/// </summary>
EmptyDomainElement = 240,
/// <summary>
/// ADL/RML commands accept FL(1)/AL(2)/BL(4) BUT RL(8)/PL(16).
/// </summary>
InvalidXmlData = 241,
/// <summary>
/// Switchboard request failed.
/// </summary>
SwitchboardFailed = 280,
/// <summary>
/// Switchboard transfer failed.
/// </summary>
SwitchboardTransferFailed = 281,
/// <summary>
/// Unknown P2P application.
/// </summary>
UnknownP2PApp = 282,
/// <summary>
/// UnknownUunApp
/// </summary>
UnknownUunApp = 283,
/// <summary>
/// MessageTooLong
/// </summary>
MessageTooLong = 285,
/// <summary>
/// SmsJustOutOfFunds
/// </summary>
SmsJustOutOfFunds = 290,
/// <summary>
/// Required field is missing.
/// </summary>
MissingRequiredField = 300,
/// <summary>
/// User is not logged in.
/// </summary>
NotLoggedIn = 302,
/// <summary>
/// Error accessing contact list.
/// </summary>
ErrorAccessingContactList = 402,
/// <summary>
/// Error accessing contact list.
/// </summary>
AddressBookError = 403,
/// <summary>
/// SmsSubscriptionRequired
/// </summary>
SmsSubscriptionRequired = 413,
/// <summary>
/// SmsSubscriptionDisabled
/// </summary>
SmsSubscriptionDisabled = 414,
/// <summary>
/// SmsOutOfFunds
/// </summary>
SmsOutOfFunds = 415,
/// <summary>
/// SmsDisabledMarket
/// </summary>
SmsDisabledMarket = 416,
/// <summary>
/// SmsDisabledGlobal
/// </summary>
SmsDisabledGlobal = 417,
/// <summary>
/// TryAgainLater
/// </summary>
TryAgainLater = 418,
/// <summary>
/// NoMarketSpecified
/// </summary>
NoMarketSpecified = 419,
/// <summary>
/// Invalid account permissions.
/// </summary>
InvalidAccountPermissions = 420,
/// <summary>
/// Internal server error.
/// </summary>
InternalServerError = 500,
/// <summary>
/// Databaseserver error.
/// </summary>
DatabaseServerError = 501,
/// <summary>
/// Command Disabled.
/// </summary>
CommandDisabled = 502,
/// <summary>
/// UpsDown
/// </summary>
UpsDown = 504,
/// <summary>
/// FederatedPartnerError
/// </summary>
FederatedPartnerError = 508,
/// <summary>
/// PageModeMessageError
/// </summary>
PageModeMessageError = 509,
/// <summary>
/// File operation failed.
/// </summary>
FileOperationFailed = 510,
/// <summary>
/// DetailedError.
/// </summary>
DetailedError = 511,
/// <summary>
/// Memory allocation failure.
/// </summary>
MemoryAllocationFailed = 520,
/// <summary>
/// Challenge response failed.
/// </summary>
ChallengeResponseFailed = 540,
SmsAccountMuted = 550,
SmsAccountDisabled = 551,
SmsAccountMaxed = 552,
SmsInternalServerError = 580,
SmsCarrierInvalid = 590,
SmsCarrierNoRoute = 591,
SmsCarrierErrored = 592,
SmsAddressMappingFull = 593,
SmsIncorrectSourceCountry = 594,
SmsMobileCacheFull = 595,
SmsIncorrectFormat = 596,
SmsInvalidText = 597,
SmsMessageTooLong = 598,
/// <summary>
/// Server is busy.
/// </summary>
ServerIsBusy = 600,
/// <summary>
/// Server is unavailable.
/// </summary>
ServerIsUnavailable = 601,
/// <summary>
/// Nameserver is down.
/// </summary>
NameServerDown = 602,
/// <summary>
/// Database connection failed.
/// </summary>
DatabaseConnectionFailed = 603,
/// <summary>
/// Server is going down.
/// </summary>
ServerGoingDown = 604,
/// <summary>
/// Server is unavailable.
/// </summary>
ServerUnavailable = 605,
/// <summary>
/// PagingUnavailable
/// </summary>
PagingUnavailable = 606,
/// <summary>
/// Connection creation failed.
/// </summary>
CouldNotCreateConnection = 700,
/// <summary>
/// Bad CVR parameters sent.
/// </summary>
BadCVRParameters = 710,
SessionRestricted = 711,
SessionOverloaded = 712,
UserTooActive = 713,
NotExpected = 715,
BadFriendFile = 717,
UserRestricted = 718,
SessionFederated = 719,
UserFederated = 726,
NotExpectedCVR = 731,
RoamingLogoff = 733,
TooManyEndpoints = 734,
/// <summary>
/// Changing too rapdly.
/// </summary>
RateLimitExceeded = 800,
/// <summary>
/// Server too busy.
/// </summary>
ServerTooBusy = 910,
/// <summary>
/// Authentication failed.
/// </summary>
AuthenticationFailed = 911,
/// <summary>
/// Action is not allowed when user is offline.
/// </summary>
NotAllowedWhenOffline = 913,
/// <summary>
/// New users are not accepted.
/// </summary>
NotAcceptingNewUsers = 920,
/// <summary>
/// Timed out.
/// </summary>
TimedOut = 921,
/// <summary>
/// Kids without parental consent.
/// </summary>
KidsWithoutParentalConsent = 923,
/// <summary>
/// Passport not yet verified.
/// </summary>
PassportNotYetVerified = 924,
ManagedUserLimitedAccessWrongClient = 926,
managedUserAccessDenied = 927,
AuthError = 928,
/// <summary>
/// Account not on this server
/// </summary>
DomainReserved = 931,
/// <summary>
/// The ADL command indicates some invalid contact to server.
/// </summary>
InvalidContactList = 933,
/// <summary>
/// Invalid signature
/// </summary>
InvalidSignature = 935
}
/// <summary>
/// Custom emoticon type.
/// </summary>
public enum EmoticonType
{
/// <summary>
/// Emoticon that is a static picture
/// </summary>
StaticEmoticon,
/// <summary>
/// Emoticon that will display as a animation.
/// </summary>
AnimEmoticon
}
/// <summary>
/// CacheKey for webservices
/// </summary>
[Serializable()]
public enum CacheKeyType
{
/// <summary>
/// CacheKey for contact service, which url is ***.omega.contacts.msn.com
/// </summary>
OmegaContactServiceCacheKey,
/// <summary>
/// CacheKey for profile storage service, which url is ***.storage.msn.com
/// </summary>
StorageServiceCacheKey
}
/// <summary>
/// The current p2p version used in p2p bridge.
/// </summary>
public enum P2PVersion
{
None = 0,
P2PV1 = 1,
P2PV2 = 2
}
/// <summary>
/// Mime header key constants.
/// </summary>
public static class MIMEHeaderStrings
{
public const string From = "From";
public const string To = "To";
public const string Via = "Via";
public const string Routing = "Routing";
public const string Reliability = "Reliability";
public const string Stream = "Stream";
public const string Segment = "Segment";
public const string Messaging = "Messaging";
public const string Publication = "Publication";
public const string Notification = "Notification";
/// <summary>
/// The value is: Content-Length
/// </summary>
public const string Content_Length = "Content-Length";
/// <summary>
/// The value is: Content-Type
/// </summary>
public const string Content_Type = "Content-Type";
/// <summary>
/// The value is: Content-Transfer-Encoding
/// </summary>
public const string Content_Transfer_Encoding = "Content-Transfer-Encoding";
/// <summary>
/// The value is: Message-Type
/// </summary>
public const string Message_Type = "Message-Type";
/// <summary>
/// The value is: Message-Subtype
/// </summary>
public const string Message_Subtype = "Message-Subtype";
/// <summary>
/// The value is: MIME-Version
/// </summary>
public const string MIME_Version = "MIME-Version";
public const string TypingUser = "TypingUser";
/// <summary>
/// The value is: X-MMS-IM-Format
/// </summary>
public const string X_MMS_IM_Format = "X-MMS-IM-Format";
public const string NotifType = "NotifType";
/// <summary>
/// The value is: P4-Context
/// </summary>
public const string P4_Context = "P4-Context";
/// <summary>
/// The value is: Max-Forwards
/// </summary>
public const string Max_Forwards = "Max-Forwards";
public const string Uri = "Uri";
/// <summary>
/// The key string for charset header
/// </summary>
public const string CharSet = " charset"; // Don't delete space
public const string EPID = "epid";
public const string Path = "path";
public const string ServiceChannel = "Service-Channel";
public const string Options = "Options";
public const string Flags = "Flags";
public const string Pipe = "Pipe";
public const string BridgingOffsets = "Bridging-Offsets";
internal const string KeyParam = ";";
/// <summary>
/// The separator of key-value pair in MIME header
/// </summary>
public const string KeyValueSeparator = ": ";
}
internal enum ReturnState : uint
{
None = 0,
ProcessNextContact = 1,
RequestCircleAddressBook = 2,
/// <summary>
/// Tell the caller initialize the circle first, then recall the UpdateContact with Recall scenario.
/// </summary>
LoadAddressBookFromFile = 4,
UpdateError = 8
}
internal enum Scenario : uint
{
None = 0,
/// <summary>
/// Restoring contacts from mcl file.
/// </summary>
Restore = 1,
Initial = 2,
DeltaRequest = 4,
/// <summary>
/// Processing the new added circles.
/// </summary>
NewCircles = 8,
/// <summary>
/// Processing the modified circles.
/// </summary>
ModifiedCircles = 16,
/// <summary>
/// Send the initial ADL command for contacts.
/// </summary>
SendInitialContactsADL = 32,
/// <summary>
/// Send the initial ADL command for circles.
/// </summary>
SendInitialCirclesADL = 64,
ContactServeAPI = 128,
InternalCall = 256,
}
internal enum InternalOperationReturnValues
{
Succeed,
NoExpressionProfile,
ProfileNotExist,
RequestFailed,
AddImageFailed,
AddRelationshipFailed,
AddImageRelationshipFailed
}
/// <summary>
/// The reason that fires <see cref="Contact.DisplayImageChanged"/> event.
/// </summary>
public enum DisplayImageChangedType
{
None,
/// <summary>
/// The <see cref="DisplayImage"/> is just recreate from file.
/// </summary>
Restore,
/// <summary>
/// The <see cref="DisplayImage"/> is just transmitted from the remote user.
/// </summary>
TransmissionCompleted,
/// <summary>
/// Remote user notified it has its <see cref="DisplayImage"/> changed.
/// </summary>
UpdateTransmissionRequired,
}
public enum PlaceChangedReason
{
None,
SignedIn,
SignedOut
}
/// <summary>
/// The special account of remote network's gateways, i.e. FaceBook and LinkedIn
/// </summary>
public static class RemoteNetworkGateways
{
/// <summary>
/// FaceBook Gateway account.
/// </summary>
public const string FaceBookGatewayAccount = "fb";
public const string WindowsLiveGateway = "wl";
public const string LinkedInGateway = "li";
}
/// <summary>
/// The keys for MIME Content Headers.
/// </summary>
public static class MIMEContentHeaders
{
/// <summary>
/// The key string for Content-Length header
/// </summary>
public const string ContentLength = MIMEHeaderStrings.Content_Length;
/// <summary>
/// The key string for Content-Type header
/// </summary>
public const string ContentType = MIMEHeaderStrings.Content_Type;
/// <summary>
/// The key string for charset header
/// </summary>
public const string CharSet = MIMEHeaderStrings.CharSet;
public const string Publication = MIMEHeaderStrings.Publication;
public const string Messaging = MIMEHeaderStrings.Messaging;
public const string Notification = MIMEHeaderStrings.Notification;
public const string URI = MIMEHeaderStrings.Uri;
public const string MessageType = MIMEHeaderStrings.Message_Type;
public const string MSIMFormat = MIMEHeaderStrings.X_MMS_IM_Format;
public const string ContentTransferEncoding = MIMEHeaderStrings.Content_Transfer_Encoding;
public const string Pipe = MIMEHeaderStrings.Pipe;
public const string BridgingOffsets = MIMEHeaderStrings.BridgingOffsets;
}
/// <summary>
/// The keys for MIME Reouting Header of MultiMimeMessage.
/// </summary>
public static class MIMERoutingHeaders
{
public const string Routing = MIMEHeaderStrings.Routing;
public const string From = MIMEHeaderStrings.From;
public const string To = MIMEHeaderStrings.To;
public const string EPID = MIMEHeaderStrings.EPID;
public const string Path = MIMEHeaderStrings.Path;
public const string Options = MIMEHeaderStrings.Options;
public const string Via = MIMEHeaderStrings.Via;
/// <summary>
/// The service that this message should sent through.
/// </summary>
public const string ServiceChannel = MIMEHeaderStrings.ServiceChannel;
}
/// <summary>
/// Keys for MIME header, reliability parts.
/// </summary>
public static class MIMEReliabilityHeaders
{
public const string Reliability = MIMEHeaderStrings.Reliability;
public const string Stream = MIMEHeaderStrings.Stream;
public const string Segment = MIMEHeaderStrings.Segment;
public const string Flags = MIMEHeaderStrings.Flags;
}
public static class MIMEContentTransferEncoding
{
public const string Binary = "binary";
}
public static class MessageTypes
{
public const string Text = "Text";
public const string Nudge = "Nudge";
public const string Wink = "Wink";
public const string CustomEmoticon = "CustomEmoticon";
public const string ControlTyping = "Control/Typing";
public const string Data = "Data";
public const string SignalP2P = "Signal/P2P";
public const string SignalForceAbchSync = "Signal/ForceAbchSync";
public const string SignalCloseIMWindow = "Signal/CloseIMWindow";
public const string SignalMarkIMWindowRead = "Signal/MarkIMWindowRead";
public const string SignalTurn = "Signal/Turn";
public const string SignalAudioMeta = "Signal/AudioMeta";
public const string SignalAudioTunnel = "Signal/AudioTunnel";
}
#region P2PFlag
/// <summary>
/// Defines the type of P2P message.
/// </summary>
[Flags]
public enum P2PFlag : uint
{
/// <summary>
/// Normal (protocol) message.
/// </summary>
Normal = 0,
/// <summary>
/// Negative Ack
/// </summary>
NegativeAck = 0x1,
/// <summary>
/// Acknowledgement message.
/// </summary>
Acknowledgement = 0x2,
/// <summary>
/// Required Ack
/// </summary>
RequireAck = 0x4,
/// <summary>
/// Messages notifies a binary error.
/// </summary>
Error = 0x8,
/// <summary>
/// File
/// </summary>
File = 0x10,
/// <summary>
/// Messages defines a msn object.
/// </summary>
Data = 0x20,
/// <summary>
/// Close session
/// </summary>
CloseSession = 0x40,
/// <summary>
/// Tlp error
/// </summary>
TlpError = 0x80,
/// <summary>
/// Direct handshake
/// </summary>
DirectHandshake = 0x100,
/// <summary>
/// Messages for info data, such as INVITE, 200 OK, 500 INTERNAL ERROR
/// </summary>
MSNSLPInfo = 0x01000000,
/// <summary>
/// Messages defines data for a filetransfer.
/// </summary>
FileData = MSNSLPInfo | P2PFlag.Data | P2PFlag.File,
/// <summary>
/// Messages defines data for a MSNObject transfer.
/// </summary>
MSNObjectData = MSNSLPInfo | P2PFlag.Data
}
#endregion
#region P2PConst
internal static class P2PConst
{
/// <summary>
/// The guid used in invitations for a filetransfer.
/// </summary>
public const string FileTransferGuid = "{5D3E02AB-6190-11D3-BBBB-00C04F795683}";
/// <summary>
/// The guid used in invitations for a user display transfer.
/// </summary>
public const string UserDisplayGuid = "{A4268EEC-FEC5-49E5-95C3-F126696BDBF6}";
/// <summary>
/// The guid used in invitations for a share photo.
/// </summary>
public const string SharePhotoGuid = "{41D3E74E-04A2-4B37-96F8-08ACDB610874}";
/// <summary>
/// The guid used in invitations for an activity.
/// </summary>
public const string ActivityGuid = "{6A13AF9C-5308-4F35-923A-67E8DDA40C2F}";
/// <summary>
/// Footer for a msn DisplayImage p2pMessage.
/// </summary>
public const uint DisplayImageFooter12 = 12;
/// <summary>
/// Footer for a filetransfer p2pMessage.
/// </summary>
public const uint FileTransFooter2 = 2;
/// <summary>
/// Footer for a msn CustomEmoticon p2pMessage.
/// </summary>
public const uint CustomEmoticonFooter11 = 11;
/// <summary>
/// Footer for a msn object p2pMessage.
/// </summary>
public const uint DisplayImageFooter1 = 1;
/// <summary>
/// Footer for a msn CustomEmoticon p2pMessage.
/// </summary>
public const uint CustomEmoticonFooter1 = 1;
/// <summary>
/// The value of protocol version field of Peer info TLV.
/// </summary>
public const ushort ProtocolVersion = 512;
/// <summary>
/// The value of implementation ID field of Peer info TLV.
/// </summary>
public const ushort ImplementationID = 0;
/// <summary>
/// The value of version field of Peer info TLV.
/// </summary>
public const ushort PeerInfoVersion = 3584;
/// <summary>
/// The unknown field of Peer info TLV.
/// </summary>
public const ushort PeerInfoReservedField = 0;
/// <summary>
/// The value of capabilities field of Peer info TLV.
/// </summary>
public const uint Capabilities = 271;
}
#endregion
#region OperationCode
public enum OperationCode : byte
{
/// <summary>
/// Nothing required
/// </summary>
None = 0x0,
/// <summary>
/// This is a SYN message.
/// </summary>
SYN = 0x1,
/// <summary>
/// Required ACK.
/// </summary>
RAK = 0x2
}
internal static class MSNSLPRequestMethod
{
public const string INVITE = "INVITE";
public const string BYE = "BYE";
public const string ACK = "ACK";
}
#endregion
};
| |
using UnityEngine;
using System;
namespace UnityStandardAssets.CinematicEffects
{
[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
[AddComponentMenu("Image Effects/Cinematic/Lens Aberrations")]
public class LensAberrations : MonoBehaviour
{
#region Attributes
[AttributeUsage(AttributeTargets.Field)]
public class SettingsGroup : Attribute
{}
[AttributeUsage(AttributeTargets.Field)]
public class AdvancedSetting : Attribute
{}
#endregion
#region Settings
[Serializable]
public struct DistortionSettings
{
public bool enabled;
[Range(-100f, 100f), Tooltip("Distortion amount.")]
public float amount;
[Range(-1f, 1f), Tooltip("Distortion center point (X axis).")]
public float centerX;
[Range(-1f, 1f), Tooltip("Distortion center point (Y axis).")]
public float centerY;
[Range(0f, 1f), Tooltip("Amount multiplier on X axis. Set it to 0 to disable distortion on this axis.")]
public float amountX;
[Range(0f, 1f), Tooltip("Amount multiplier on Y axis. Set it to 0 to disable distortion on this axis.")]
public float amountY;
[Range(0.01f, 5f), Tooltip("Global screen scaling.")]
public float scale;
public static DistortionSettings defaultSettings
{
get
{
return new DistortionSettings
{
enabled = false,
amount = 0f,
centerX = 0f,
centerY = 0f,
amountX = 1f,
amountY = 1f,
scale = 1f
};
}
}
}
[Serializable]
public struct VignetteSettings
{
public bool enabled;
[ColorUsage(false)]
[Tooltip("Vignette color. Use the alpha channel for transparency.")]
public Color color;
[Tooltip("Sets the vignette center point (screen center is [0.5,0.5]).")]
public Vector2 center;
[Range(0f, 3f), Tooltip("Amount of vignetting on screen.")]
public float intensity;
[Range(0.01f, 3f), Tooltip("Smoothness of the vignette borders.")]
public float smoothness;
[AdvancedSetting, Range(0f, 1f), Tooltip("Lower values will make a square-ish vignette.")]
public float roundness;
[Range(0f, 1f), Tooltip("Blurs the corners of the screen. Leave this at 0 to disable it.")]
public float blur;
[Range(0f, 1f), Tooltip("Desaturate the corners of the screen. Leave this to 0 to disable it.")]
public float desaturate;
public static VignetteSettings defaultSettings
{
get
{
return new VignetteSettings
{
enabled = false,
color = new Color(0f, 0f, 0f, 1f),
center = new Vector2(0.5f, 0.5f),
intensity = 1.4f,
smoothness = 0.8f,
roundness = 1f,
blur = 0f,
desaturate = 0f
};
}
}
}
[Serializable]
public struct ChromaticAberrationSettings
{
public bool enabled;
[ColorUsage(false)]
[Tooltip("Channels to apply chromatic aberration to.")]
public Color color;
[Range(-50f, 50f)]
[Tooltip("Amount of tangential distortion.")]
public float amount;
public static ChromaticAberrationSettings defaultSettings
{
get
{
return new ChromaticAberrationSettings
{
enabled = false,
color = Color.green,
amount = 0f
};
}
}
}
#endregion
[SettingsGroup]
public DistortionSettings distortion = DistortionSettings.defaultSettings;
[SettingsGroup]
public VignetteSettings vignette = VignetteSettings.defaultSettings;
[SettingsGroup]
public ChromaticAberrationSettings chromaticAberration = ChromaticAberrationSettings.defaultSettings;
private enum Pass
{
BlurPrePass,
Chroma,
Distort,
Vignette,
ChromaDistort,
ChromaVignette,
DistortVignette,
ChromaDistortVignette
}
[SerializeField]
private Shader m_Shader;
public Shader shader
{
get
{
if (m_Shader == null)
m_Shader = Shader.Find("Hidden/LensAberrations");
return m_Shader;
}
}
private Material m_Material;
public Material material
{
get
{
if (m_Material == null)
m_Material = ImageEffectHelper.CheckShaderAndCreateMaterial(shader);
return m_Material;
}
}
private RenderTextureUtility m_RTU;
// Shader properties
private int m_DistCenterScale;
private int m_DistAmount;
private int m_ChromaticAberration;
private int m_VignetteColor;
private int m_BlurPass;
private int m_BlurTex;
private int m_VignetteBlur;
private int m_VignetteDesat;
private int m_VignetteCenter;
private int m_VignetteSettings;
private void Awake()
{
m_DistCenterScale = Shader.PropertyToID("_DistCenterScale");
m_DistAmount = Shader.PropertyToID("_DistAmount");
m_ChromaticAberration = Shader.PropertyToID("_ChromaticAberration");
m_VignetteColor = Shader.PropertyToID("_VignetteColor");
m_BlurPass = Shader.PropertyToID("_BlurPass");
m_BlurTex = Shader.PropertyToID("_BlurTex");
m_VignetteBlur = Shader.PropertyToID("_VignetteBlur");
m_VignetteDesat = Shader.PropertyToID("_VignetteDesat");
m_VignetteCenter = Shader.PropertyToID("_VignetteCenter");
m_VignetteSettings = Shader.PropertyToID("_VignetteSettings");
}
private void OnEnable()
{
if (!ImageEffectHelper.IsSupported(shader, false, false, this))
enabled = false;
m_RTU = new RenderTextureUtility();
}
private void OnDisable()
{
if (m_Material != null)
DestroyImmediate(m_Material);
m_Material = null;
m_RTU.ReleaseAllTemporaryRenderTextures();
}
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (!vignette.enabled && !chromaticAberration.enabled && !distortion.enabled)
{
Graphics.Blit(source, destination);
return;
}
material.shaderKeywords = null;
if (distortion.enabled)
{
float amount = 1.6f * Math.Max(Mathf.Abs(distortion.amount), 1f);
float theta = 0.01745329251994f * Math.Min(160f, amount);
float sigma = 2f * Mathf.Tan(theta * 0.5f);
var p0 = new Vector4(distortion.centerX, distortion.centerY, Mathf.Max(distortion.amountX, 1e-4f), Mathf.Max(distortion.amountY, 1e-4f));
var p1 = new Vector3(distortion.amount >= 0f ? theta : 1f / theta, sigma, 1f / distortion.scale);
material.EnableKeyword(distortion.amount >= 0f ? "DISTORT" : "UNDISTORT");
material.SetVector(m_DistCenterScale, p0);
material.SetVector(m_DistAmount, p1);
}
if (chromaticAberration.enabled)
{
material.EnableKeyword("CHROMATIC_ABERRATION");
var chromaParams = new Vector4(chromaticAberration.color.r, chromaticAberration.color.g, chromaticAberration.color.b, chromaticAberration.amount * 0.001f);
material.SetVector(m_ChromaticAberration, chromaParams);
}
if (vignette.enabled)
{
material.SetColor(m_VignetteColor, vignette.color);
if (vignette.blur > 0f)
{
// Downscale + gaussian blur (2 passes)
int w = source.width / 2;
int h = source.height / 2;
var rt1 = m_RTU.GetTemporaryRenderTexture(w, h, 0, source.format);
var rt2 = m_RTU.GetTemporaryRenderTexture(w, h, 0, source.format);
material.SetVector(m_BlurPass, new Vector2(1f / w, 0f));
Graphics.Blit(source, rt1, material, (int)Pass.BlurPrePass);
if (distortion.enabled)
{
material.DisableKeyword("DISTORT");
material.DisableKeyword("UNDISTORT");
}
material.SetVector(m_BlurPass, new Vector2(0f, 1f / h));
Graphics.Blit(rt1, rt2, material, (int)Pass.BlurPrePass);
material.SetVector(m_BlurPass, new Vector2(1f / w, 0f));
Graphics.Blit(rt2, rt1, material, (int)Pass.BlurPrePass);
material.SetVector(m_BlurPass, new Vector2(0f, 1f / h));
Graphics.Blit(rt1, rt2, material, (int)Pass.BlurPrePass);
material.SetTexture(m_BlurTex, rt2);
material.SetFloat(m_VignetteBlur, vignette.blur * 3f);
material.EnableKeyword("VIGNETTE_BLUR");
if (distortion.enabled)
material.EnableKeyword(distortion.amount >= 0f ? "DISTORT" : "UNDISTORT");
}
if (vignette.desaturate > 0f)
{
material.EnableKeyword("VIGNETTE_DESAT");
material.SetFloat(m_VignetteDesat, 1f - vignette.desaturate);
}
material.SetVector(m_VignetteCenter, vignette.center);
if (Mathf.Approximately(vignette.roundness, 1f))
{
material.EnableKeyword("VIGNETTE_CLASSIC");
material.SetVector(m_VignetteSettings, new Vector2(vignette.intensity, vignette.smoothness));
}
else
{
material.EnableKeyword("VIGNETTE_FILMIC");
float roundness = (1f - vignette.roundness) * 6f + vignette.roundness;
material.SetVector(m_VignetteSettings, new Vector3(vignette.intensity, vignette.smoothness, roundness));
}
}
int pass = 0;
if (vignette.enabled && chromaticAberration.enabled && distortion.enabled)
pass = (int)Pass.ChromaDistortVignette;
else if (vignette.enabled && chromaticAberration.enabled)
pass = (int)Pass.ChromaVignette;
else if (vignette.enabled && distortion.enabled)
pass = (int)Pass.DistortVignette;
else if (chromaticAberration.enabled && distortion.enabled)
pass = (int)Pass.ChromaDistort;
else if (vignette.enabled)
pass = (int)Pass.Vignette;
else if (chromaticAberration.enabled)
pass = (int)Pass.Chroma;
else if (distortion.enabled)
pass = (int)Pass.Distort;
Graphics.Blit(source, destination, material, pass);
m_RTU.ReleaseAllTemporaryRenderTextures();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Build.Utilities
{
[Microsoft.Build.Framework.LoadInSeparateAppDomainAttribute]
public abstract partial class AppDomainIsolatedTask : System.MarshalByRefObject, Microsoft.Build.Framework.ITask
{
protected AppDomainIsolatedTask() { }
protected AppDomainIsolatedTask(System.Resources.ResourceManager taskResources) { }
protected AppDomainIsolatedTask(System.Resources.ResourceManager taskResources, string helpKeywordPrefix) { }
public Microsoft.Build.Framework.IBuildEngine BuildEngine { get { throw null; } set { } }
protected string HelpKeywordPrefix { get { throw null; } set { } }
public Microsoft.Build.Framework.ITaskHost HostObject { get { throw null; } set { } }
public Microsoft.Build.Utilities.TaskLoggingHelper Log { get { throw null; } }
protected System.Resources.ResourceManager TaskResources { get { throw null; } set { } }
public abstract bool Execute();
[System.Security.SecurityCriticalAttribute]
public override object InitializeLifetimeService() { throw null; }
}
public partial class AssemblyFoldersExInfo
{
public AssemblyFoldersExInfo(Microsoft.Win32.RegistryHive hive, Microsoft.Win32.RegistryView view, string registryKey, string directoryPath, System.Version targetFrameworkVersion) { }
public string DirectoryPath { get { throw null; } }
public Microsoft.Win32.RegistryHive Hive { get { throw null; } }
public string Key { get { throw null; } }
public System.Version TargetFrameworkVersion { get { throw null; } }
public Microsoft.Win32.RegistryView View { get { throw null; } }
}
public partial class AssemblyFoldersFromConfigInfo
{
public AssemblyFoldersFromConfigInfo(string directoryPath, System.Version targetFrameworkVersion) { }
public string DirectoryPath { get { throw null; } }
public System.Version TargetFrameworkVersion { get { throw null; } }
}
public partial class CanonicalTrackedInputFiles
{
public CanonicalTrackedInputFiles(Microsoft.Build.Framework.ITask ownerTask, Microsoft.Build.Framework.ITaskItem[] tlogFiles, Microsoft.Build.Framework.ITaskItem sourceFile, Microsoft.Build.Framework.ITaskItem[] excludedInputPaths, Microsoft.Build.Utilities.CanonicalTrackedOutputFiles outputs, bool useMinimalRebuildOptimization, bool maintainCompositeRootingMarkers) { }
public CanonicalTrackedInputFiles(Microsoft.Build.Framework.ITask ownerTask, Microsoft.Build.Framework.ITaskItem[] tlogFiles, Microsoft.Build.Framework.ITaskItem[] sourceFiles, Microsoft.Build.Framework.ITaskItem[] excludedInputPaths, Microsoft.Build.Framework.ITaskItem[] outputs, bool useMinimalRebuildOptimization, bool maintainCompositeRootingMarkers) { }
public CanonicalTrackedInputFiles(Microsoft.Build.Framework.ITask ownerTask, Microsoft.Build.Framework.ITaskItem[] tlogFiles, Microsoft.Build.Framework.ITaskItem[] sourceFiles, Microsoft.Build.Framework.ITaskItem[] excludedInputPaths, Microsoft.Build.Utilities.CanonicalTrackedOutputFiles outputs, bool useMinimalRebuildOptimization, bool maintainCompositeRootingMarkers) { }
public CanonicalTrackedInputFiles(Microsoft.Build.Framework.ITaskItem[] tlogFiles, Microsoft.Build.Framework.ITaskItem[] sourceFiles, Microsoft.Build.Framework.ITaskItem[] excludedInputPaths, Microsoft.Build.Utilities.CanonicalTrackedOutputFiles outputs, bool useMinimalRebuildOptimization, bool maintainCompositeRootingMarkers) { }
public CanonicalTrackedInputFiles(Microsoft.Build.Framework.ITaskItem[] tlogFiles, Microsoft.Build.Framework.ITaskItem[] sourceFiles, Microsoft.Build.Utilities.CanonicalTrackedOutputFiles outputs, bool useMinimalRebuildOptimization, bool maintainCompositeRootingMarkers) { }
public System.Collections.Generic.Dictionary<string, System.Collections.Generic.Dictionary<string, string>> DependencyTable { get { throw null; } }
public Microsoft.Build.Framework.ITaskItem[] ComputeSourcesNeedingCompilation() { throw null; }
public Microsoft.Build.Framework.ITaskItem[] ComputeSourcesNeedingCompilation(bool searchForSubRootsInCompositeRootingMarkers) { throw null; }
public bool FileIsExcludedFromDependencyCheck(string fileName) { throw null; }
public void RemoveDependenciesFromEntryIfMissing(Microsoft.Build.Framework.ITaskItem source) { }
public void RemoveDependenciesFromEntryIfMissing(Microsoft.Build.Framework.ITaskItem source, Microsoft.Build.Framework.ITaskItem correspondingOutput) { }
public void RemoveDependenciesFromEntryIfMissing(Microsoft.Build.Framework.ITaskItem[] source) { }
public void RemoveDependenciesFromEntryIfMissing(Microsoft.Build.Framework.ITaskItem[] source, Microsoft.Build.Framework.ITaskItem[] correspondingOutputs) { }
public void RemoveDependencyFromEntry(Microsoft.Build.Framework.ITaskItem source, Microsoft.Build.Framework.ITaskItem dependencyToRemove) { }
public void RemoveDependencyFromEntry(Microsoft.Build.Framework.ITaskItem[] sources, Microsoft.Build.Framework.ITaskItem dependencyToRemove) { }
public void RemoveEntriesForSource(Microsoft.Build.Framework.ITaskItem source) { }
public void RemoveEntriesForSource(Microsoft.Build.Framework.ITaskItem[] source) { }
public void RemoveEntryForSourceRoot(string rootingMarker) { }
public void SaveTlog() { }
public void SaveTlog(Microsoft.Build.Utilities.DependencyFilter includeInTLog) { }
}
public partial class CanonicalTrackedOutputFiles
{
public CanonicalTrackedOutputFiles(Microsoft.Build.Framework.ITask ownerTask, Microsoft.Build.Framework.ITaskItem[] tlogFiles) { }
public CanonicalTrackedOutputFiles(Microsoft.Build.Framework.ITask ownerTask, Microsoft.Build.Framework.ITaskItem[] tlogFiles, bool constructOutputsFromTLogs) { }
public CanonicalTrackedOutputFiles(Microsoft.Build.Framework.ITaskItem[] tlogFiles) { }
public System.Collections.Generic.Dictionary<string, System.Collections.Generic.Dictionary<string, System.DateTime>> DependencyTable { get { throw null; } }
public void AddComputedOutputForSourceRoot(string sourceKey, string computedOutput) { }
public void AddComputedOutputsForSourceRoot(string sourceKey, Microsoft.Build.Framework.ITaskItem[] computedOutputs) { }
public void AddComputedOutputsForSourceRoot(string sourceKey, string[] computedOutputs) { }
public Microsoft.Build.Framework.ITaskItem[] OutputsForNonCompositeSource(params Microsoft.Build.Framework.ITaskItem[] sources) { throw null; }
public Microsoft.Build.Framework.ITaskItem[] OutputsForSource(params Microsoft.Build.Framework.ITaskItem[] sources) { throw null; }
public Microsoft.Build.Framework.ITaskItem[] OutputsForSource(Microsoft.Build.Framework.ITaskItem[] sources, bool searchForSubRootsInCompositeRootingMarkers) { throw null; }
public void RemoveDependenciesFromEntryIfMissing(Microsoft.Build.Framework.ITaskItem source) { }
public void RemoveDependenciesFromEntryIfMissing(Microsoft.Build.Framework.ITaskItem source, Microsoft.Build.Framework.ITaskItem correspondingOutput) { }
public void RemoveDependenciesFromEntryIfMissing(Microsoft.Build.Framework.ITaskItem[] source) { }
public void RemoveDependenciesFromEntryIfMissing(Microsoft.Build.Framework.ITaskItem[] source, Microsoft.Build.Framework.ITaskItem[] correspondingOutputs) { }
public void RemoveDependencyFromEntry(Microsoft.Build.Framework.ITaskItem source, Microsoft.Build.Framework.ITaskItem dependencyToRemove) { }
public void RemoveDependencyFromEntry(Microsoft.Build.Framework.ITaskItem[] sources, Microsoft.Build.Framework.ITaskItem dependencyToRemove) { }
public void RemoveEntriesForSource(Microsoft.Build.Framework.ITaskItem source) { }
public void RemoveEntriesForSource(Microsoft.Build.Framework.ITaskItem source, Microsoft.Build.Framework.ITaskItem correspondingOutput) { }
public void RemoveEntriesForSource(Microsoft.Build.Framework.ITaskItem[] source) { }
public void RemoveEntriesForSource(Microsoft.Build.Framework.ITaskItem[] source, Microsoft.Build.Framework.ITaskItem[] correspondingOutputs) { }
public bool RemoveOutputForSourceRoot(string sourceRoot, string outputPathToRemove) { throw null; }
public string[] RemoveRootsWithSharedOutputs(Microsoft.Build.Framework.ITaskItem[] sources) { throw null; }
public void SaveTlog() { }
public void SaveTlog(Microsoft.Build.Utilities.DependencyFilter includeInTLog) { }
}
public partial class CommandLineBuilder
{
public CommandLineBuilder() { }
public CommandLineBuilder(bool quoteHyphensOnCommandLine) { }
public CommandLineBuilder(bool quoteHyphensOnCommandLine, bool useNewLineSeparator) { }
protected System.Text.StringBuilder CommandLine { get { throw null; } }
public int Length { get { throw null; } }
public void AppendFileNameIfNotNull(Microsoft.Build.Framework.ITaskItem fileItem) { }
public void AppendFileNameIfNotNull(string fileName) { }
public void AppendFileNamesIfNotNull(Microsoft.Build.Framework.ITaskItem[] fileItems, string delimiter) { }
public void AppendFileNamesIfNotNull(string[] fileNames, string delimiter) { }
protected void AppendFileNameWithQuoting(string fileName) { }
protected void AppendQuotedTextToBuffer(System.Text.StringBuilder buffer, string unquotedTextToAppend) { }
protected void AppendSpaceIfNotEmpty() { }
public void AppendSwitch(string switchName) { }
public void AppendSwitchIfNotNull(string switchName, Microsoft.Build.Framework.ITaskItem parameter) { }
public void AppendSwitchIfNotNull(string switchName, Microsoft.Build.Framework.ITaskItem[] parameters, string delimiter) { }
public void AppendSwitchIfNotNull(string switchName, string parameter) { }
public void AppendSwitchIfNotNull(string switchName, string[] parameters, string delimiter) { }
public void AppendSwitchUnquotedIfNotNull(string switchName, Microsoft.Build.Framework.ITaskItem parameter) { }
public void AppendSwitchUnquotedIfNotNull(string switchName, Microsoft.Build.Framework.ITaskItem[] parameters, string delimiter) { }
public void AppendSwitchUnquotedIfNotNull(string switchName, string parameter) { }
public void AppendSwitchUnquotedIfNotNull(string switchName, string[] parameters, string delimiter) { }
public void AppendTextUnquoted(string textToAppend) { }
protected void AppendTextWithQuoting(string textToAppend) { }
protected virtual bool IsQuotingRequired(string parameter) { throw null; }
public override string ToString() { throw null; }
protected virtual void VerifyThrowNoEmbeddedDoubleQuotes(string switchName, string parameter) { }
}
public delegate bool DependencyFilter(string fullPath);
public enum DotNetFrameworkArchitecture
{
Bitness32 = 1,
Bitness64 = 2,
Current = 0,
}
public enum ExecutableType
{
Managed32Bit = 3,
Managed64Bit = 4,
ManagedIL = 2,
Native32Bit = 0,
Native64Bit = 1,
SameAsCurrentProcess = 5,
}
public static partial class FileTracker
{
public static string CreateRootingMarkerResponseFile(Microsoft.Build.Framework.ITaskItem[] sources) { throw null; }
public static string CreateRootingMarkerResponseFile(string rootMarker) { throw null; }
public static void EndTrackingContext() { }
public static string EnsureFileTrackerOnPath() { throw null; }
public static string EnsureFileTrackerOnPath(string rootPath) { throw null; }
public static bool FileIsExcludedFromDependencies(string fileName) { throw null; }
public static bool FileIsUnderPath(string fileName, string path) { throw null; }
public static string FindTrackerOnPath() { throw null; }
public static bool ForceOutOfProcTracking(Microsoft.Build.Utilities.ExecutableType toolType) { throw null; }
public static bool ForceOutOfProcTracking(Microsoft.Build.Utilities.ExecutableType toolType, string dllName, string cancelEventName) { throw null; }
public static string FormatRootingMarker(Microsoft.Build.Framework.ITaskItem source) { throw null; }
public static string FormatRootingMarker(Microsoft.Build.Framework.ITaskItem source, Microsoft.Build.Framework.ITaskItem output) { throw null; }
public static string FormatRootingMarker(Microsoft.Build.Framework.ITaskItem[] sources) { throw null; }
public static string FormatRootingMarker(Microsoft.Build.Framework.ITaskItem[] sources, Microsoft.Build.Framework.ITaskItem[] outputs) { throw null; }
public static string GetFileTrackerPath(Microsoft.Build.Utilities.ExecutableType toolType) { throw null; }
public static string GetFileTrackerPath(Microsoft.Build.Utilities.ExecutableType toolType, string rootPath) { throw null; }
public static string GetTrackerPath(Microsoft.Build.Utilities.ExecutableType toolType) { throw null; }
public static string GetTrackerPath(Microsoft.Build.Utilities.ExecutableType toolType, string rootPath) { throw null; }
public static void ResumeTracking() { }
public static void SetThreadCount(int threadCount) { }
public static System.Diagnostics.Process StartProcess(string command, string arguments, Microsoft.Build.Utilities.ExecutableType toolType) { throw null; }
public static System.Diagnostics.Process StartProcess(string command, string arguments, Microsoft.Build.Utilities.ExecutableType toolType, string rootFiles) { throw null; }
public static System.Diagnostics.Process StartProcess(string command, string arguments, Microsoft.Build.Utilities.ExecutableType toolType, string intermediateDirectory, string rootFiles) { throw null; }
public static System.Diagnostics.Process StartProcess(string command, string arguments, Microsoft.Build.Utilities.ExecutableType toolType, string dllName, string intermediateDirectory, string rootFiles) { throw null; }
public static System.Diagnostics.Process StartProcess(string command, string arguments, Microsoft.Build.Utilities.ExecutableType toolType, string dllName, string intermediateDirectory, string rootFiles, string cancelEventName) { throw null; }
public static void StartTrackingContext(string intermediateDirectory, string taskName) { }
public static void StartTrackingContextWithRoot(string intermediateDirectory, string taskName, string rootMarkerResponseFile) { }
public static void StopTrackingAndCleanup() { }
public static void SuspendTracking() { }
public static string TrackerArguments(string command, string arguments, string dllName, string intermediateDirectory, string rootFiles) { throw null; }
public static string TrackerArguments(string command, string arguments, string dllName, string intermediateDirectory, string rootFiles, string cancelEventName) { throw null; }
public static string TrackerCommandArguments(string command, string arguments) { throw null; }
public static string TrackerResponseFileArguments(string dllName, string intermediateDirectory, string rootFiles) { throw null; }
public static string TrackerResponseFileArguments(string dllName, string intermediateDirectory, string rootFiles, string cancelEventName) { throw null; }
public static void WriteAllTLogs(string intermediateDirectory, string taskName) { }
public static void WriteContextTLogs(string intermediateDirectory, string taskName) { }
}
public partial class FlatTrackingData
{
public FlatTrackingData(Microsoft.Build.Framework.ITask ownerTask, Microsoft.Build.Framework.ITaskItem[] tlogFiles, bool skipMissingFiles) { }
public FlatTrackingData(Microsoft.Build.Framework.ITask ownerTask, Microsoft.Build.Framework.ITaskItem[] tlogFiles, System.DateTime missingFileTimeUtc) { }
public FlatTrackingData(Microsoft.Build.Framework.ITaskItem[] tlogFiles, Microsoft.Build.Framework.ITaskItem[] tlogFilesToIgnore, System.DateTime missingFileTimeUtc) { }
public FlatTrackingData(Microsoft.Build.Framework.ITaskItem[] tlogFiles, Microsoft.Build.Framework.ITaskItem[] tlogFilesToIgnore, System.DateTime missingFileTimeUtc, string[] excludedInputPaths, System.Collections.Generic.IDictionary<string, System.DateTime> sharedLastWriteTimeUtcCache) { }
public FlatTrackingData(Microsoft.Build.Framework.ITaskItem[] tlogFiles, Microsoft.Build.Framework.ITaskItem[] tlogFilesToIgnore, System.DateTime missingFileTimeUtc, string[] excludedInputPaths, System.Collections.Generic.IDictionary<string, System.DateTime> sharedLastWriteTimeUtcCache, bool treatRootMarkersAsEntries) { }
public FlatTrackingData(Microsoft.Build.Framework.ITaskItem[] tlogFiles, bool skipMissingFiles) { }
public FlatTrackingData(Microsoft.Build.Framework.ITaskItem[] tlogFiles, System.DateTime missingFileTimeUtc) { }
public System.Collections.Generic.List<string> MissingFiles { get { throw null; } set { } }
public string NewestFileName { get { throw null; } set { } }
public System.DateTime NewestFileTime { get { throw null; } set { } }
public System.DateTime NewestFileTimeUtc { get { throw null; } set { } }
public string NewestTLogFileName { get { throw null; } set { } }
public System.DateTime NewestTLogTime { get { throw null; } set { } }
public System.DateTime NewestTLogTimeUtc { get { throw null; } set { } }
public string OldestFileName { get { throw null; } set { } }
public System.DateTime OldestFileTime { get { throw null; } set { } }
public System.DateTime OldestFileTimeUtc { get { throw null; } set { } }
public bool SkipMissingFiles { get { throw null; } set { } }
public Microsoft.Build.Framework.ITaskItem[] TlogFiles { get { throw null; } set { } }
public bool TlogsAvailable { get { throw null; } set { } }
public bool TreatRootMarkersAsEntries { get { throw null; } set { } }
public bool FileIsExcludedFromDependencyCheck(string fileName) { throw null; }
public static void FinalizeTLogs(bool trackedOperationsSucceeded, Microsoft.Build.Framework.ITaskItem[] readTLogNames, Microsoft.Build.Framework.ITaskItem[] writeTLogNames, Microsoft.Build.Framework.ITaskItem[] trackedFilesToRemoveFromTLogs) { }
public System.DateTime GetLastWriteTimeUtc(string file) { throw null; }
public static bool IsUpToDate(Microsoft.Build.Utilities.Task hostTask, Microsoft.Build.Utilities.UpToDateCheckType upToDateCheckType, Microsoft.Build.Framework.ITaskItem[] readTLogNames, Microsoft.Build.Framework.ITaskItem[] writeTLogNames) { throw null; }
public static bool IsUpToDate(Microsoft.Build.Utilities.TaskLoggingHelper Log, Microsoft.Build.Utilities.UpToDateCheckType upToDateCheckType, Microsoft.Build.Utilities.FlatTrackingData inputs, Microsoft.Build.Utilities.FlatTrackingData outputs) { throw null; }
public void SaveTlog() { }
public void SaveTlog(Microsoft.Build.Utilities.DependencyFilter includeInTLog) { }
public void UpdateFileEntryDetails() { }
}
public enum HostObjectInitializationStatus
{
NoActionReturnFailure = 3,
NoActionReturnSuccess = 2,
UseAlternateToolToExecute = 1,
UseHostObjectToExecute = 0,
}
public abstract partial class Logger : Microsoft.Build.Framework.ILogger
{
protected Logger() { }
public virtual string Parameters { get { throw null; } set { } }
public virtual Microsoft.Build.Framework.LoggerVerbosity Verbosity { get { throw null; } set { } }
public virtual string FormatErrorEvent(Microsoft.Build.Framework.BuildErrorEventArgs args) { throw null; }
public virtual string FormatWarningEvent(Microsoft.Build.Framework.BuildWarningEventArgs args) { throw null; }
public abstract void Initialize(Microsoft.Build.Framework.IEventSource eventSource);
public bool IsVerbosityAtLeast(Microsoft.Build.Framework.LoggerVerbosity checkVerbosity) { throw null; }
public virtual void Shutdown() { }
}
public enum MultipleVersionSupport
{
Allow = 0,
Error = 2,
Warning = 1,
}
public partial class MuxLogger : Microsoft.Build.Framework.ILogger, Microsoft.Build.Framework.INodeLogger
{
public MuxLogger() { }
public bool IncludeEvaluationMetaprojects { get { throw null; } set { } }
public bool IncludeEvaluationProfiles { get { throw null; } set { } }
public bool IncludeTaskInputs { get { throw null; } set { } }
public string Parameters { get { throw null; } set { } }
public Microsoft.Build.Framework.LoggerVerbosity Verbosity { get { throw null; } set { } }
public void Initialize(Microsoft.Build.Framework.IEventSource eventSource) { }
public void Initialize(Microsoft.Build.Framework.IEventSource eventSource, int maxNodeCount) { }
public void RegisterLogger(int submissionId, Microsoft.Build.Framework.ILogger logger) { }
public void Shutdown() { }
public bool UnregisterLoggers(int submissionId) { throw null; }
}
public static partial class ProcessorArchitecture
{
public const string AMD64 = "AMD64";
public const string ARM = "ARM";
public const string ARM64 = "ARM64";
public const string IA64 = "IA64";
public const string MSIL = "MSIL";
public const string X86 = "x86";
public static string CurrentProcessArchitecture { get { throw null; } }
}
public partial class SDKManifest
{
public SDKManifest(string pathToSdk) { }
public System.Collections.Generic.IDictionary<string, string> AppxLocations { get { throw null; } }
public string CopyRedistToSubDirectory { get { throw null; } }
public string DependsOnSDK { get { throw null; } }
public string DisplayName { get { throw null; } }
public System.Collections.Generic.IDictionary<string, string> FrameworkIdentities { get { throw null; } }
public string FrameworkIdentity { get { throw null; } }
public string MaxOSVersionTested { get { throw null; } }
public string MaxPlatformVersion { get { throw null; } }
public string MinOSVersion { get { throw null; } }
public string MinVSVersion { get { throw null; } }
public string MoreInfo { get { throw null; } }
public string PlatformIdentity { get { throw null; } }
public string ProductFamilyName { get { throw null; } }
public bool ReadError { get { throw null; } }
public string ReadErrorMessage { get { throw null; } }
public Microsoft.Build.Utilities.SDKType SDKType { get { throw null; } }
public string SupportedArchitectures { get { throw null; } }
public string SupportPrefer32Bit { get { throw null; } }
public Microsoft.Build.Utilities.MultipleVersionSupport SupportsMultipleVersions { get { throw null; } }
public string TargetPlatform { get { throw null; } }
public string TargetPlatformMinVersion { get { throw null; } }
public string TargetPlatformVersion { get { throw null; } }
public static partial class Attributes
{
public const string APPX = "APPX";
public const string AppxLocation = "AppxLocation";
public const string CopyLocalExpandedReferenceAssemblies = "CopyLocalExpandedReferenceAssemblies";
public const string CopyRedist = "CopyRedist";
public const string CopyRedistToSubDirectory = "CopyRedistToSubDirectory";
public const string DependsOnSDK = "DependsOn";
public const string DisplayName = "DisplayName";
public const string ExpandReferenceAssemblies = "ExpandReferenceAssemblies";
public const string FrameworkIdentity = "FrameworkIdentity";
public const string MaxOSVersionTested = "MaxOSVersionTested";
public const string MaxPlatformVersion = "MaxPlatformVersion";
public const string MinOSVersion = "MinOSVersion";
public const string MinVSVersion = "MinVSVersion";
public const string MoreInfo = "MoreInfo";
public const string PlatformIdentity = "PlatformIdentity";
public const string ProductFamilyName = "ProductFamilyName";
public const string SDKType = "SDKType";
public const string SupportedArchitectures = "SupportedArchitectures";
public const string SupportPrefer32Bit = "SupportPrefer32Bit";
public const string SupportsMultipleVersions = "SupportsMultipleVersions";
public const string TargetedSDK = "TargetedSDKArchitecture";
public const string TargetedSDKConfiguration = "TargetedSDKConfiguration";
public const string TargetPlatform = "TargetPlatform";
public const string TargetPlatformMinVersion = "TargetPlatformMinVersion";
public const string TargetPlatformVersion = "TargetPlatformVersion";
}
}
public enum SDKType
{
External = 1,
Framework = 3,
Platform = 2,
Unspecified = 0,
}
public enum TargetDotNetFrameworkVersion
{
Latest = 9999,
Version11 = 0,
Version20 = 1,
Version30 = 2,
Version35 = 3,
Version40 = 4,
Version45 = 5,
Version451 = 6,
Version452 = 9,
Version46 = 7,
Version461 = 8,
Version462 = 10,
Version47 = 11,
Version471 = 12,
Version472 = 13,
Version48 = 14,
VersionLatest = 10,
}
public partial class TargetPlatformSDK : System.IEquatable<Microsoft.Build.Utilities.TargetPlatformSDK>
{
public TargetPlatformSDK(string targetPlatformIdentifier, System.Version targetPlatformVersion, string path) { }
public string DisplayName { get { throw null; } }
public System.Version MinOSVersion { get { throw null; } }
public System.Version MinVSVersion { get { throw null; } }
public string Path { get { throw null; } set { } }
public string TargetPlatformIdentifier { get { throw null; } }
public System.Version TargetPlatformVersion { get { throw null; } }
public bool ContainsPlatform(string targetPlatformIdentifier, string targetPlatformVersion) { throw null; }
public bool Equals(Microsoft.Build.Utilities.TargetPlatformSDK other) { throw null; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
}
public abstract partial class Task : Microsoft.Build.Framework.ITask
{
protected Task() { }
protected Task(System.Resources.ResourceManager taskResources) { }
protected Task(System.Resources.ResourceManager taskResources, string helpKeywordPrefix) { }
public Microsoft.Build.Framework.IBuildEngine BuildEngine { get { throw null; } set { } }
public Microsoft.Build.Framework.IBuildEngine2 BuildEngine2 { get { throw null; } }
public Microsoft.Build.Framework.IBuildEngine3 BuildEngine3 { get { throw null; } }
public Microsoft.Build.Framework.IBuildEngine4 BuildEngine4 { get { throw null; } }
public Microsoft.Build.Framework.IBuildEngine5 BuildEngine5 { get { throw null; } }
public Microsoft.Build.Framework.IBuildEngine6 BuildEngine6 { get { throw null; } }
protected string HelpKeywordPrefix { get { throw null; } set { } }
public Microsoft.Build.Framework.ITaskHost HostObject { get { throw null; } set { } }
public Microsoft.Build.Utilities.TaskLoggingHelper Log { get { throw null; } }
protected System.Resources.ResourceManager TaskResources { get { throw null; } set { } }
public abstract bool Execute();
}
public sealed partial class TaskItem : System.MarshalByRefObject, Microsoft.Build.Framework.ITaskItem, Microsoft.Build.Framework.ITaskItem2
{
public TaskItem() { }
public TaskItem(Microsoft.Build.Framework.ITaskItem sourceItem) { }
public TaskItem(string itemSpec) { }
public TaskItem(string itemSpec, System.Collections.IDictionary itemMetadata) { }
public string ItemSpec { get { throw null; } set { } }
public int MetadataCount { get { throw null; } }
public System.Collections.ICollection MetadataNames { get { throw null; } }
string Microsoft.Build.Framework.ITaskItem2.EvaluatedIncludeEscaped { get { throw null; } set { } }
public System.Collections.IDictionary CloneCustomMetadata() { throw null; }
public void CopyMetadataTo(Microsoft.Build.Framework.ITaskItem destinationItem) { }
public string GetMetadata(string metadataName) { throw null; }
[System.Security.SecurityCriticalAttribute]
public override object InitializeLifetimeService() { throw null; }
System.Collections.IDictionary Microsoft.Build.Framework.ITaskItem2.CloneCustomMetadataEscaped() { throw null; }
string Microsoft.Build.Framework.ITaskItem2.GetMetadataValueEscaped(string metadataName) { throw null; }
void Microsoft.Build.Framework.ITaskItem2.SetMetadataValueLiteral(string metadataName, string metadataValue) { }
public static explicit operator string (Microsoft.Build.Utilities.TaskItem taskItemToCast) { throw null; }
public void RemoveMetadata(string metadataName) { }
public void SetMetadata(string metadataName, string metadataValue) { }
public override string ToString() { throw null; }
}
public partial class TaskLoggingHelper : System.MarshalByRefObject
{
public TaskLoggingHelper(Microsoft.Build.Framework.IBuildEngine buildEngine, string taskName) { }
public TaskLoggingHelper(Microsoft.Build.Framework.ITask taskInstance) { }
protected Microsoft.Build.Framework.IBuildEngine BuildEngine { get { throw null; } }
public bool HasLoggedErrors { get { throw null; } }
public string HelpKeywordPrefix { get { throw null; } set { } }
protected string TaskName { get { throw null; } }
public System.Resources.ResourceManager TaskResources { get { throw null; } set { } }
public string ExtractMessageCode(string message, out string messageWithoutCodePrefix) { messageWithoutCodePrefix = default(string); throw null; }
public virtual string FormatResourceString(string resourceName, params object[] args) { throw null; }
public virtual string FormatString(string unformatted, params object[] args) { throw null; }
public virtual string GetResourceMessage(string resourceName) { throw null; }
public override object InitializeLifetimeService() { throw null; }
public void LogCommandLine(Microsoft.Build.Framework.MessageImportance importance, string commandLine) { }
public void LogCommandLine(string commandLine) { }
public void LogCriticalMessage(string subcategory, string code, string helpKeyword, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, params object[] messageArgs) { }
public void LogError(string message, params object[] messageArgs) { }
public void LogError(string subcategory, string errorCode, string helpKeyword, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, params object[] messageArgs) { }
public void LogErrorFromException(System.Exception exception) { }
public void LogErrorFromException(System.Exception exception, bool showStackTrace) { }
public void LogErrorFromException(System.Exception exception, bool showStackTrace, bool showDetail, string file) { }
public void LogErrorFromResources(string messageResourceName, params object[] messageArgs) { }
public void LogErrorFromResources(string subcategoryResourceName, string errorCode, string helpKeyword, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string messageResourceName, params object[] messageArgs) { }
public void LogErrorWithCodeFromResources(string messageResourceName, params object[] messageArgs) { }
public void LogErrorWithCodeFromResources(string subcategoryResourceName, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string messageResourceName, params object[] messageArgs) { }
public void LogExternalProjectFinished(string message, string helpKeyword, string projectFile, bool succeeded) { }
public void LogExternalProjectStarted(string message, string helpKeyword, string projectFile, string targetNames) { }
public void LogMessage(Microsoft.Build.Framework.MessageImportance importance, string message, params object[] messageArgs) { }
public void LogMessage(string message, params object[] messageArgs) { }
public void LogMessage(string subcategory, string code, string helpKeyword, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, Microsoft.Build.Framework.MessageImportance importance, string message, params object[] messageArgs) { }
public void LogMessageFromResources(Microsoft.Build.Framework.MessageImportance importance, string messageResourceName, params object[] messageArgs) { }
public void LogMessageFromResources(string messageResourceName, params object[] messageArgs) { }
public bool LogMessageFromText(string lineOfText, Microsoft.Build.Framework.MessageImportance messageImportance) { throw null; }
public bool LogMessagesFromFile(string fileName) { throw null; }
public bool LogMessagesFromFile(string fileName, Microsoft.Build.Framework.MessageImportance messageImportance) { throw null; }
public bool LogMessagesFromStream(System.IO.TextReader stream, Microsoft.Build.Framework.MessageImportance messageImportance) { throw null; }
public void LogTelemetry(string eventName, System.Collections.Generic.IDictionary<string, string> properties) { }
public void LogWarning(string message, params object[] messageArgs) { }
public void LogWarning(string subcategory, string warningCode, string helpKeyword, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, params object[] messageArgs) { }
public void LogWarningFromException(System.Exception exception) { }
public void LogWarningFromException(System.Exception exception, bool showStackTrace) { }
public void LogWarningFromResources(string messageResourceName, params object[] messageArgs) { }
public void LogWarningFromResources(string subcategoryResourceName, string warningCode, string helpKeyword, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string messageResourceName, params object[] messageArgs) { }
public void LogWarningWithCodeFromResources(string messageResourceName, params object[] messageArgs) { }
public void LogWarningWithCodeFromResources(string subcategoryResourceName, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string messageResourceName, params object[] messageArgs) { }
public void MarkAsInactive() { }
}
public static partial class ToolLocationHelper
{
public static string CurrentToolsVersion { get { throw null; } }
public static string PathToSystem { get { throw null; } }
public static void ClearSDKStaticCache() { }
public static System.Collections.Generic.IDictionary<string, string> FilterPlatformExtensionSDKs(System.Version targetPlatformVersion, System.Collections.Generic.IDictionary<string, string> extensionSdks) { throw null; }
public static System.Collections.Generic.IList<Microsoft.Build.Utilities.TargetPlatformSDK> FilterTargetPlatformSdks(System.Collections.Generic.IList<Microsoft.Build.Utilities.TargetPlatformSDK> targetPlatformSdkList, System.Version osVersion, System.Version vsVersion) { throw null; }
public static string FindRootFolderWhereAllFilesExist(string possibleRoots, string relativeFilePaths) { throw null; }
public static System.Collections.Generic.IList<Microsoft.Build.Utilities.AssemblyFoldersExInfo> GetAssemblyFoldersExInfo(string registryRoot, string targetFrameworkVersion, string registryKeySuffix, string osVersion, string platform, System.Reflection.ProcessorArchitecture targetProcessorArchitecture) { throw null; }
public static System.Collections.Generic.IList<Microsoft.Build.Utilities.AssemblyFoldersFromConfigInfo> GetAssemblyFoldersFromConfigInfo(string configFile, string targetFrameworkVersion, System.Reflection.ProcessorArchitecture targetProcessorArchitecture) { throw null; }
public static string GetDisplayNameForTargetFrameworkDirectory(string targetFrameworkDirectory, System.Runtime.Versioning.FrameworkName frameworkName) { throw null; }
public static string GetDotNetFrameworkRootRegistryKey(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version) { throw null; }
public static string GetDotNetFrameworkSdkInstallKeyValue(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version) { throw null; }
public static string GetDotNetFrameworkSdkInstallKeyValue(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version, Microsoft.Build.Utilities.VisualStudioVersion visualStudioVersion) { throw null; }
public static string GetDotNetFrameworkSdkRootRegistryKey(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version) { throw null; }
public static string GetDotNetFrameworkSdkRootRegistryKey(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version, Microsoft.Build.Utilities.VisualStudioVersion visualStudioVersion) { throw null; }
public static string GetDotNetFrameworkVersionFolderPrefix(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version) { throw null; }
public static System.Collections.Generic.IEnumerable<string> GetFoldersInVSInstalls(System.Version minVersion=null, System.Version maxVersion=null, string subFolder=null) { throw null; }
public static string GetFoldersInVSInstallsAsString(string minVersionString=null, string maxVersionString=null, string subFolder=null) { throw null; }
public static string GetLatestSDKTargetPlatformVersion(string sdkIdentifier, string sdkVersion) { throw null; }
public static string GetLatestSDKTargetPlatformVersion(string sdkIdentifier, string sdkVersion, string[] sdkRoots) { throw null; }
public static string GetPathToBuildTools(string toolsVersion) { throw null; }
public static string GetPathToBuildTools(string toolsVersion, Microsoft.Build.Utilities.DotNetFrameworkArchitecture architecture) { throw null; }
public static string GetPathToBuildToolsFile(string fileName, string toolsVersion) { throw null; }
public static string GetPathToBuildToolsFile(string fileName, string toolsVersion, Microsoft.Build.Utilities.DotNetFrameworkArchitecture architecture) { throw null; }
public static string GetPathToDotNetFramework(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version) { throw null; }
public static string GetPathToDotNetFramework(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version, Microsoft.Build.Utilities.DotNetFrameworkArchitecture architecture) { throw null; }
public static string GetPathToDotNetFrameworkFile(string fileName, Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version) { throw null; }
public static string GetPathToDotNetFrameworkFile(string fileName, Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version, Microsoft.Build.Utilities.DotNetFrameworkArchitecture architecture) { throw null; }
public static string GetPathToDotNetFrameworkReferenceAssemblies(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version) { throw null; }
public static string GetPathToDotNetFrameworkSdk() { throw null; }
public static string GetPathToDotNetFrameworkSdk(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version) { throw null; }
public static string GetPathToDotNetFrameworkSdk(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version, Microsoft.Build.Utilities.VisualStudioVersion visualStudioVersion) { throw null; }
public static string GetPathToDotNetFrameworkSdkFile(string fileName) { throw null; }
public static string GetPathToDotNetFrameworkSdkFile(string fileName, Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version) { throw null; }
public static string GetPathToDotNetFrameworkSdkFile(string fileName, Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version, Microsoft.Build.Utilities.DotNetFrameworkArchitecture architecture) { throw null; }
public static string GetPathToDotNetFrameworkSdkFile(string fileName, Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version, Microsoft.Build.Utilities.VisualStudioVersion visualStudioVersion) { throw null; }
public static string GetPathToDotNetFrameworkSdkFile(string fileName, Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version, Microsoft.Build.Utilities.VisualStudioVersion visualStudioVersion, Microsoft.Build.Utilities.DotNetFrameworkArchitecture architecture) { throw null; }
public static System.Collections.Generic.IList<string> GetPathToReferenceAssemblies(System.Runtime.Versioning.FrameworkName frameworkName) { throw null; }
public static System.Collections.Generic.IList<string> GetPathToReferenceAssemblies(string targetFrameworkRootPath, System.Runtime.Versioning.FrameworkName frameworkName) { throw null; }
public static System.Collections.Generic.IList<string> GetPathToReferenceAssemblies(string targetFrameworkRootPath, string targetFrameworkFallbackSearchPaths, System.Runtime.Versioning.FrameworkName frameworkName) { throw null; }
public static System.Collections.Generic.IList<string> GetPathToReferenceAssemblies(string targetFrameworkIdentifier, string targetFrameworkVersion, string targetFrameworkProfile) { throw null; }
public static System.Collections.Generic.IList<string> GetPathToReferenceAssemblies(string targetFrameworkIdentifier, string targetFrameworkVersion, string targetFrameworkProfile, string targetFrameworkRootPath) { throw null; }
public static System.Collections.Generic.IList<string> GetPathToReferenceAssemblies(string targetFrameworkIdentifier, string targetFrameworkVersion, string targetFrameworkProfile, string targetFrameworkRootPath, string targetFrameworkFallbackSearchPaths) { throw null; }
public static string GetPathToStandardLibraries(string targetFrameworkIdentifier, string targetFrameworkVersion, string targetFrameworkProfile) { throw null; }
public static string GetPathToStandardLibraries(string targetFrameworkIdentifier, string targetFrameworkVersion, string targetFrameworkProfile, string platformTarget) { throw null; }
public static string GetPathToStandardLibraries(string targetFrameworkIdentifier, string targetFrameworkVersion, string targetFrameworkProfile, string platformTarget, string targetFrameworkRootPath) { throw null; }
public static string GetPathToStandardLibraries(string targetFrameworkIdentifier, string targetFrameworkVersion, string targetFrameworkProfile, string platformTarget, string targetFrameworkRootPath, string targetFrameworkFallbackSearchPaths) { throw null; }
public static string GetPathToSystemFile(string fileName) { throw null; }
[System.ObsoleteAttribute("Consider using GetPlatformSDKLocation instead")]
public static string GetPathToWindowsSdk(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version, Microsoft.Build.Utilities.VisualStudioVersion visualStudioVersion) { throw null; }
[System.ObsoleteAttribute("Consider using GetPlatformSDKLocationFile instead")]
public static string GetPathToWindowsSdkFile(string fileName, Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version, Microsoft.Build.Utilities.VisualStudioVersion visualStudioVersion) { throw null; }
[System.ObsoleteAttribute("Consider using GetPlatformSDKLocationFile instead")]
public static string GetPathToWindowsSdkFile(string fileName, Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version, Microsoft.Build.Utilities.VisualStudioVersion visualStudioVersion, Microsoft.Build.Utilities.DotNetFrameworkArchitecture architecture) { throw null; }
public static string GetPlatformExtensionSDKLocation(string sdkMoniker, string targetPlatformIdentifier, string targetPlatformVersion) { throw null; }
public static string GetPlatformExtensionSDKLocation(string sdkMoniker, string targetPlatformIdentifier, string targetPlatformVersion, string diskRoots, string registryRoot) { throw null; }
public static string GetPlatformExtensionSDKLocation(string sdkMoniker, string targetPlatformIdentifier, string targetPlatformVersion, string diskRoots, string extensionDiskRoots, string registryRoot) { throw null; }
public static string GetPlatformExtensionSDKLocation(string sdkMoniker, string targetPlatformIdentifier, System.Version targetPlatformVersion) { throw null; }
public static string GetPlatformExtensionSDKLocation(string sdkMoniker, string targetPlatformIdentifier, System.Version targetPlatformVersion, string[] diskRoots, string registryRoot) { throw null; }
public static string GetPlatformExtensionSDKLocation(string sdkMoniker, string targetPlatformIdentifier, System.Version targetPlatformVersion, string[] diskRoots, string[] extensionDiskRoots, string registryRoot) { throw null; }
public static System.Collections.Generic.IDictionary<string, string> GetPlatformExtensionSDKLocations(string targetPlatformIdentifier, System.Version targetPlatformVersion) { throw null; }
public static System.Collections.Generic.IDictionary<string, string> GetPlatformExtensionSDKLocations(string[] diskRoots, string registryRoot, string targetPlatformIdentifier, System.Version targetPlatformVersion) { throw null; }
public static System.Collections.Generic.IDictionary<string, string> GetPlatformExtensionSDKLocations(string[] diskRoots, string[] extensionDiskRoots, string registryRoot, string targetPlatformIdentifier, System.Version targetPlatformVersion) { throw null; }
public static System.Collections.Generic.IDictionary<string, System.Tuple<string, string>> GetPlatformExtensionSDKLocationsAndVersions(string targetPlatformIdentifier, System.Version targetPlatformVersion) { throw null; }
public static System.Collections.Generic.IDictionary<string, System.Tuple<string, string>> GetPlatformExtensionSDKLocationsAndVersions(string[] diskRoots, string registryRoot, string targetPlatformIdentifier, System.Version targetPlatformVersion) { throw null; }
public static System.Collections.Generic.IDictionary<string, System.Tuple<string, string>> GetPlatformExtensionSDKLocationsAndVersions(string[] diskRoots, string[] multiPlatformDiskRoots, string registryRoot, string targetPlatformIdentifier, System.Version targetPlatformVersion) { throw null; }
public static string[] GetPlatformOrFrameworkExtensionSdkReferences(string extensionSdkMoniker, string targetSdkIdentifier, string targetSdkVersion, string diskRoots, string extensionDiskRoots, string registryRoot) { throw null; }
public static string[] GetPlatformOrFrameworkExtensionSdkReferences(string extensionSdkMoniker, string targetSdkIdentifier, string targetSdkVersion, string diskRoots, string extensionDiskRoots, string registryRoot, string targetPlatformIdentifier, string targetPlatformVersion) { throw null; }
public static string GetPlatformSDKDisplayName(string targetPlatformIdentifier, string targetPlatformVersion) { throw null; }
public static string GetPlatformSDKDisplayName(string targetPlatformIdentifier, string targetPlatformVersion, string diskRoots, string registryRoot) { throw null; }
public static string GetPlatformSDKLocation(string targetPlatformIdentifier, string targetPlatformVersion) { throw null; }
public static string GetPlatformSDKLocation(string targetPlatformIdentifier, string targetPlatformVersion, string diskRoots, string registryRoot) { throw null; }
public static string GetPlatformSDKLocation(string targetPlatformIdentifier, System.Version targetPlatformVersion) { throw null; }
public static string GetPlatformSDKLocation(string targetPlatformIdentifier, System.Version targetPlatformVersion, string[] diskRoots, string registryRoot) { throw null; }
public static string GetPlatformSDKPropsFileLocation(string sdkIdentifier, string sdkVersion, string targetPlatformIdentifier, string targetPlatformMinVersion, string targetPlatformVersion) { throw null; }
public static string GetPlatformSDKPropsFileLocation(string sdkIdentifier, string sdkVersion, string targetPlatformIdentifier, string targetPlatformMinVersion, string targetPlatformVersion, string diskRoots, string registryRoot) { throw null; }
public static System.Collections.Generic.IEnumerable<string> GetPlatformsForSDK(string sdkIdentifier, System.Version sdkVersion) { throw null; }
public static System.Collections.Generic.IEnumerable<string> GetPlatformsForSDK(string sdkIdentifier, System.Version sdkVersion, string[] diskRoots, string registryRoot) { throw null; }
public static string GetProgramFilesReferenceAssemblyRoot() { throw null; }
public static string GetSDKContentFolderPath(string sdkIdentifier, string sdkVersion, string targetPlatformIdentifier, string targetPlatformMinVersion, string targetPlatformVersion, string folderName, string diskRoot=null) { throw null; }
public static System.Collections.Generic.IList<string> GetSDKDesignTimeFolders(string sdkRoot) { throw null; }
public static System.Collections.Generic.IList<string> GetSDKDesignTimeFolders(string sdkRoot, string targetConfiguration, string targetArchitecture) { throw null; }
public static System.Collections.Generic.IList<string> GetSDKRedistFolders(string sdkRoot) { throw null; }
public static System.Collections.Generic.IList<string> GetSDKRedistFolders(string sdkRoot, string targetConfiguration, string targetArchitecture) { throw null; }
public static System.Collections.Generic.IList<string> GetSDKReferenceFolders(string sdkRoot) { throw null; }
public static System.Collections.Generic.IList<string> GetSDKReferenceFolders(string sdkRoot, string targetConfiguration, string targetArchitecture) { throw null; }
public static System.Collections.Generic.IList<string> GetSupportedTargetFrameworks() { throw null; }
public static string[] GetTargetPlatformReferences(string sdkIdentifier, string sdkVersion, string targetPlatformIdentifier, string targetPlatformMinVersion, string targetPlatformVersion) { throw null; }
public static string[] GetTargetPlatformReferences(string sdkIdentifier, string sdkVersion, string targetPlatformIdentifier, string targetPlatformMinVersion, string targetPlatformVersion, string diskRoots, string registryRoot) { throw null; }
public static System.Collections.Generic.IList<Microsoft.Build.Utilities.TargetPlatformSDK> GetTargetPlatformSdks() { throw null; }
public static System.Collections.Generic.IList<Microsoft.Build.Utilities.TargetPlatformSDK> GetTargetPlatformSdks(string[] diskRoots, string registryRoot) { throw null; }
public static System.Runtime.Versioning.FrameworkName HighestVersionOfTargetFrameworkIdentifier(string targetFrameworkRootDirectory, string frameworkIdentifier) { throw null; }
}
public abstract partial class ToolTask : Microsoft.Build.Utilities.Task, Microsoft.Build.Framework.ICancelableTask, Microsoft.Build.Framework.ITask
{
protected ToolTask() { }
protected ToolTask(System.Resources.ResourceManager taskResources) { }
protected ToolTask(System.Resources.ResourceManager taskResources, string helpKeywordPrefix) { }
public bool EchoOff { get { throw null; } set { } }
[System.ObsoleteAttribute("Use EnvironmentVariables property")]
protected virtual System.Collections.Generic.Dictionary<string, string> EnvironmentOverride { get { throw null; } }
public string[] EnvironmentVariables { get { throw null; } set { } }
[Microsoft.Build.Framework.OutputAttribute]
public int ExitCode { get { throw null; } }
protected virtual bool HasLoggedErrors { get { throw null; } }
public bool LogStandardErrorAsError { get { throw null; } set { } }
protected virtual System.Text.Encoding ResponseFileEncoding { get { throw null; } }
protected virtual System.Text.Encoding StandardErrorEncoding { get { throw null; } }
public string StandardErrorImportance { get { throw null; } set { } }
protected Microsoft.Build.Framework.MessageImportance StandardErrorImportanceToUse { get { throw null; } }
protected virtual Microsoft.Build.Framework.MessageImportance StandardErrorLoggingImportance { get { throw null; } }
protected virtual System.Text.Encoding StandardOutputEncoding { get { throw null; } }
public string StandardOutputImportance { get { throw null; } set { } }
protected Microsoft.Build.Framework.MessageImportance StandardOutputImportanceToUse { get { throw null; } }
protected virtual Microsoft.Build.Framework.MessageImportance StandardOutputLoggingImportance { get { throw null; } }
protected int TaskProcessTerminationTimeout { get { throw null; } set { } }
public virtual int Timeout { get { throw null; } set { } }
protected System.Threading.ManualResetEvent ToolCanceled { get { throw null; } }
public virtual string ToolExe { get { throw null; } set { } }
protected abstract string ToolName { get; }
public string ToolPath { get { throw null; } set { } }
public bool UseCommandProcessor { get { throw null; } set { } }
public bool YieldDuringToolExecution { get { throw null; } set { } }
protected virtual string AdjustCommandsForOperatingSystem(string input) { throw null; }
protected virtual bool CallHostObjectToExecute() { throw null; }
public virtual void Cancel() { }
protected void DeleteTempFile(string fileName) { }
public override bool Execute() { throw null; }
protected virtual int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands) { throw null; }
protected virtual string GenerateCommandLineCommands() { throw null; }
protected abstract string GenerateFullPathToTool();
protected virtual string GenerateResponseFileCommands() { throw null; }
protected virtual System.Diagnostics.ProcessStartInfo GetProcessStartInfo(string pathToTool, string commandLineCommands, string responseFileSwitch) { throw null; }
protected virtual string GetResponseFileSwitch(string responseFilePath) { throw null; }
protected virtual string GetWorkingDirectory() { throw null; }
protected virtual bool HandleTaskExecutionErrors() { throw null; }
protected virtual Microsoft.Build.Utilities.HostObjectInitializationStatus InitializeHostObject() { throw null; }
protected virtual void LogEventsFromTextOutput(string singleLine, Microsoft.Build.Framework.MessageImportance messageImportance) { }
protected virtual void LogPathToTool(string toolName, string pathToTool) { }
protected virtual void LogToolCommand(string message) { }
protected virtual void ProcessStarted() { }
protected virtual string ResponseFileEscape(string responseString) { throw null; }
protected virtual bool SkipTaskExecution() { throw null; }
protected internal virtual bool ValidateParameters() { throw null; }
}
public static partial class TrackedDependencies
{
public static Microsoft.Build.Framework.ITaskItem[] ExpandWildcards(Microsoft.Build.Framework.ITaskItem[] expand) { throw null; }
}
public enum UpToDateCheckType
{
InputNewerThanOutput = 0,
InputNewerThanTracking = 2,
InputOrOutputNewerThanTracking = 1,
}
public enum VisualStudioVersion
{
Version100 = 0,
Version110 = 1,
Version120 = 2,
Version140 = 3,
Version150 = 4,
VersionLatest = 4,
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="FormsAuthentication.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* FormsAuthentication class
*
* Copyright (c) 1999 Microsoft Corporation
*/
namespace FormsAuthOnly.Security
{
using System;
using System.Web;
using System.Text;
using FormsAuthOnly.Configuration;
using System.Collections;
using FormsAuthOnly.Util;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Threading;
using System.Globalization;
using System.Security.Permissions;
using System.Collections.Specialized;
using FormsAuthOnly.Security.Cryptography;
/// <devdoc>
/// This class consists of static methods that
/// provides helper utilities for manipulating authentication tickets.
/// </devdoc>
public sealed class FormsAuthentication
{
private const int MAX_TICKET_LENGTH = 4096;
private static object _lockObject = new object();
public FormsAuthentication() { }
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// Initialize this
/// <devdoc>
/// Initializes FormsAuthentication by reading
/// configuration and getting the cookie values and encryption keys for the given
/// application.
/// </devdoc>
public static void Initialize()
{
if (_Initialized)
return;
lock (_lockObject) {
if (_Initialized)
return;
//AuthenticationSection settings = RuntimeConfig.GetAppConfig().Authentication;
//settings.ValidateAuthenticationMode();
//_FormsName = settings.Forms.Name;
//_RequireSSL = settings.Forms.RequireSSL;
//_SlidingExpiration = settings.Forms.SlidingExpiration;
//if (_FormsName == null)
// _FormsName = CONFIG_DEFAULT_COOKIE;
//_Protection = settings.Forms.Protection;
//_Timeout = (int)settings.Forms.Timeout.TotalMinutes;
//_FormsCookiePath = settings.Forms.Path;
//_LoginUrl = settings.Forms.LoginUrl;
//if (_LoginUrl == null)
// _LoginUrl = "login.aspx";
//_DefaultUrl = settings.Forms.DefaultUrl;
//if (_DefaultUrl == null)
// _DefaultUrl = "default.aspx";
//_CookieMode = settings.Forms.Cookieless;
//_CookieDomain = settings.Forms.Domain;
//_EnableCrossAppRedirects = settings.Forms.EnableCrossAppRedirects;
//_TicketCompatibilityMode = settings.Forms.TicketCompatibilityMode;
_Initialized = true;
}
}
public static FormsAuthenticationTicket Decrypt(string encryptedTicket, string decryptionKey, string validationType, string validationKey)
{
var section = MachineKeySection.GetApplicationConfig();
section.DecryptionKey = decryptionKey;
section.Validation = (MachineKeyValidation)Enum.Parse(typeof(MachineKeyValidation), validationType);
section.ValidationKey = validationKey;
section.CompatibilityMode = MachineKeyCompatibilityMode.Framework20SP2;
return Decrypt(encryptedTicket);
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// Decrypt and get the auth ticket
/// <devdoc>
/// <para>Given an encrypted authenitcation ticket as
/// obtained from an HTTP cookie, this method returns an instance of a
/// FormsAuthenticationTicket class.</para>
/// </devdoc>
public static FormsAuthenticationTicket Decrypt(string encryptedTicket)
{
if (String.IsNullOrEmpty(encryptedTicket) || encryptedTicket.Length > MAX_TICKET_LENGTH)
throw new ArgumentException(SR.GetString(SR.InvalidArgumentValue, "encryptedTicket"));
Initialize();
byte[] bBlob = null;
if ((encryptedTicket.Length % 2) == 0) { // Could be a hex string
try {
bBlob = CryptoUtil.HexToBinary(encryptedTicket);
}
catch { }
}
if (bBlob == null)
throw new NotImplementedException(); //bBlob = HttpServerUtility.UrlTokenDecode(encryptedTicket);
if (bBlob == null || bBlob.Length < 1)
throw new ArgumentException(SR.GetString(SR.InvalidArgumentValue, "encryptedTicket"));
int ticketLength;
if (AspNetCryptoServiceProvider.Instance.IsDefaultProvider) {
// If new crypto routines are enabled, call them instead.
ICryptoService cryptoService = AspNetCryptoServiceProvider.Instance.GetCryptoService(Purpose.FormsAuthentication_Ticket);
byte[] unprotectedData = cryptoService.Unprotect(bBlob);
ticketLength = unprotectedData.Length;
bBlob = unprotectedData;
} else {
#pragma warning disable 618 // calling obsolete methods
// Otherwise call into MachineKeySection routines.
if (_Protection == FormsProtectionEnum.All || _Protection == FormsProtectionEnum.Encryption) {
// DevDiv Bugs 137864: Include a random IV if under the right compat mode
// for improved encryption semantics
bBlob = MachineKeySection.EncryptOrDecryptData(false, bBlob, null, 0, bBlob.Length, false, false, IVType.Random);
if (bBlob == null)
return null;
}
ticketLength = bBlob.Length;
if (_Protection == FormsProtectionEnum.All || _Protection == FormsProtectionEnum.Validation) {
if (!MachineKeySection.VerifyHashedData(bBlob))
return null;
ticketLength -= MachineKeySection.HashSize;
}
#pragma warning restore 618 // calling obsolete methods
}
//////////////////////////////////////////////////////////////////////
// Step 4: Change binary ticket to managed struct
// ** MSRC 11838 **
// Framework20 / Framework40 ticket generation modes are insecure. We should use a
// secure serialization mode by default.
if (!AppSettings.UseLegacyFormsAuthenticationTicketCompatibility) {
return FormsAuthenticationTicketSerializer.Deserialize(bBlob, ticketLength);
}
// ** MSRC 11838 **
// If we have reached this point of execution, the developer has explicitly elected
// to continue using the insecure code path instead of the secure one. We removed
// the Framework40 serialization mode, so everybody using the legacy code path is
// forced to Framework20.
int iSize = ((ticketLength > MAX_TICKET_LENGTH) ? MAX_TICKET_LENGTH : ticketLength);
StringBuilder name = new StringBuilder(iSize);
StringBuilder data = new StringBuilder(iSize);
StringBuilder path = new StringBuilder(iSize);
byte[] pBin = new byte[4];
long[] pDates = new long[2];
int iRet = UnsafeNativeMethods.CookieAuthParseTicket(bBlob, ticketLength,
name, iSize,
data, iSize,
path, iSize,
pBin, pDates);
if (iRet != 0)
return null;
DateTime dt1 = DateTime.FromFileTime(pDates[0]);
DateTime dt2 = DateTime.FromFileTime(pDates[1]);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket((int)pBin[0],
name.ToString(),
dt1,
dt2,
(bool)(pBin[1] != 0),
data.ToString(),
path.ToString());
return ticket;
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// Encrypt a ticket
/// <devdoc>
/// Given a FormsAuthenticationTicket, this
/// method produces a string containing an encrypted authentication ticket suitable
/// for use in an HTTP cookie.
/// </devdoc>
public static String Encrypt(FormsAuthenticationTicket ticket)
{
return Encrypt(ticket, true);
}
internal static String Encrypt(FormsAuthenticationTicket ticket, bool hexEncodedTicket)
{
if (ticket == null)
throw new ArgumentNullException("ticket");
Initialize();
//////////////////////////////////////////////////////////////////////
// Step 1a: Make it into a binary blob
byte[] bBlob = MakeTicketIntoBinaryBlob(ticket);
if (bBlob == null)
return null;
//////////////////////////////////////////////////////////////////////
// Step 1b: If new crypto routines are enabled, call them instead.
if (AspNetCryptoServiceProvider.Instance.IsDefaultProvider) {
ICryptoService cryptoService = AspNetCryptoServiceProvider.Instance.GetCryptoService(Purpose.FormsAuthentication_Ticket);
byte[] protectedData = cryptoService.Protect(bBlob);
bBlob = protectedData;
} else {
#pragma warning disable 618 // calling obsolete methods
// otherwise..
//////////////////////////////////////////////////////////////////////
// Step 2: Get the MAC and add to the blob
if (_Protection == FormsProtectionEnum.All || _Protection == FormsProtectionEnum.Validation) {
byte[] bMac = MachineKeySection.HashData(bBlob, null, 0, bBlob.Length);
if (bMac == null)
return null;
byte[] bAll = new byte[bMac.Length + bBlob.Length];
Buffer.BlockCopy(bBlob, 0, bAll, 0, bBlob.Length);
Buffer.BlockCopy(bMac, 0, bAll, bBlob.Length, bMac.Length);
bBlob = bAll;
}
if (_Protection == FormsProtectionEnum.All || _Protection == FormsProtectionEnum.Encryption) {
//////////////////////////////////////////////////////////////////////
// Step 3: Do the actual encryption
// DevDiv Bugs 137864: Include a random IV if under the right compat mode
// for improved encryption semantics
bBlob = MachineKeySection.EncryptOrDecryptData(true, bBlob, null, 0, bBlob.Length, false, false, IVType.Random);
}
#pragma warning restore 618 // calling obsolete methods
}
//if (!hexEncodedTicket)
// return HttpServerUtility.UrlTokenEncode(bBlob);
//else
return CryptoUtil.BinaryToHex(bBlob);
}
public static String FormsCookiePath { get { Initialize(); return _FormsCookiePath; } }
//public static TicketCompatibilityMode TicketCompatibilityMode { get { Initialize(); return _TicketCompatibilityMode; } }
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// Private stuff
/////////////////////////////////////////////////////////////////////////////
// Config Tags
private const String CONFIG_DEFAULT_COOKIE = ".ASPXAUTH";
/////////////////////////////////////////////////////////////////////////////
// Private data
private static bool _Initialized;
private static FormsProtectionEnum _Protection;
private static String _FormsCookiePath;
private static string _CookieDomain = null;
//private static TicketCompatibilityMode _TicketCompatibilityMode;
/////////////////////////////////////////////////////////////////////////////
private static byte[] MakeTicketIntoBinaryBlob(FormsAuthenticationTicket ticket)
{
// None of the modes (Framework20 / Framework40 / beyond) support null values for these fields;
// they always eventually just returned a null value.
if (ticket.Name == null || ticket.UserData == null || ticket.CookiePath == null) {
return null;
}
// ** MSRC 11838 **
// Framework20 / Framework40 ticket generation modes are insecure. We should use a
// secure serialization mode by default.
if (!AppSettings.UseLegacyFormsAuthenticationTicketCompatibility) {
return FormsAuthenticationTicketSerializer.Serialize(ticket);
}
// ** MSRC 11838 **
// If we have reached this point of execution, the developer has explicitly elected
// to continue using the insecure code path instead of the secure one. We removed
// the Framework40 serialization mode, so everybody using the legacy code path is
// forced to Framework20.
byte[] bData = new byte[4096];
byte[] pBin = new byte[4];
long[] pDates = new long[2];
byte[] pNull = { 0, 0, 0 };
// DevDiv Bugs 137864: 8 bytes may not be enough random bits as the length should be equal to the
// key size. In CompatMode > Framework20SP1, use the IVType.Random feature instead of these 8 bytes,
// but still include empty 8 bytes for compat with webengine.dll, where CookieAuthConstructTicket is.
// Note that even in CompatMode = Framework20SP2 we fill 8 bytes with random data if the ticket
// is not going to be encrypted.
bool willEncrypt = (_Protection == FormsProtectionEnum.All || _Protection == FormsProtectionEnum.Encryption);
bool legacyPadding = !willEncrypt || (MachineKeySection.CompatMode == MachineKeyCompatibilityMode.Framework20SP1);
if (legacyPadding) {
// Fill the first 8 bytes of the blob with random bits
byte[] bRandom = new byte[8];
RNGCryptoServiceProvider randgen = new RNGCryptoServiceProvider();
randgen.GetBytes(bRandom);
Buffer.BlockCopy(bRandom, 0, bData, 0, 8);
} else {
// use blank 8 bytes for compatibility with CookieAuthConstructTicket (do nothing)
}
pBin[0] = (byte)ticket.Version;
pBin[1] = (byte)(ticket.IsPersistent ? 1 : 0);
pDates[0] = ticket.IssueDate.ToFileTime();
pDates[1] = ticket.Expiration.ToFileTime();
int iRet = UnsafeNativeMethods.CookieAuthConstructTicket(
bData, bData.Length,
ticket.Name, ticket.UserData, ticket.CookiePath,
pBin, pDates);
if (iRet < 0)
return null;
byte[] ciphertext = new byte[iRet];
Buffer.BlockCopy(bData, 0, ciphertext, 0, iRet);
return ciphertext;
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
static private void RemoveQSVar(ref string strUrl, int posQ, string token, string sep, int lenAtStartToLeave)
{
for (int pos = strUrl.LastIndexOf(token, StringComparison.Ordinal); pos >= posQ; pos = strUrl.LastIndexOf(token, StringComparison.Ordinal)) {
int end = strUrl.IndexOf(sep, pos + token.Length, StringComparison.Ordinal) + sep.Length;
if (end < sep.Length || end >= strUrl.Length) { // ending separator not found or nothing is at the end
strUrl = strUrl.Substring(0, pos);
} else {
strUrl = strUrl.Substring(0, pos + lenAtStartToLeave) + strUrl.Substring(end);
}
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace Sirikata.Network.Protocol._PBJ_Internal {
public static partial class Time {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_Sirikata_Network_Protocol__PBJ_Internal_TimeSync__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Sirikata.Network.Protocol._PBJ_Internal.TimeSync, global::Sirikata.Network.Protocol._PBJ_Internal.TimeSync.Builder> internal__static_Sirikata_Network_Protocol__PBJ_Internal_TimeSync__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static Time() {
byte[] descriptorData = global::System.Convert.FromBase64String(
"CgpUaW1lLnByb3RvEidTaXJpa2F0YS5OZXR3b3JrLlByb3RvY29sLl9QQkpf" +
"SW50ZXJuYWwirQEKCFRpbWVTeW5jEhMKC2NsaWVudF90aW1lGAkgASgGEhMK" +
"C3NlcnZlcl90aW1lGAogASgGEhIKCnN5bmNfcm91bmQYCyABKAQSFgoOcmV0" +
"dXJuX29wdGlvbnMYDiABKA0SEwoKcm91bmRfdHJpcBiBFCABKAYiNgoNUmV0" +
"dXJuT3B0aW9ucxISCg5SRVBMWV9SRUxJQUJMRRABEhEKDVJFUExZX09SREVS" +
"RUQQAg==");
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_Sirikata_Network_Protocol__PBJ_Internal_TimeSync__Descriptor = Descriptor.MessageTypes[0];
internal__static_Sirikata_Network_Protocol__PBJ_Internal_TimeSync__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Sirikata.Network.Protocol._PBJ_Internal.TimeSync, global::Sirikata.Network.Protocol._PBJ_Internal.TimeSync.Builder>(internal__static_Sirikata_Network_Protocol__PBJ_Internal_TimeSync__Descriptor,
new string[] { "ClientTime", "ServerTime", "SyncRound", "ReturnOptions", "RoundTrip", });
return null;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
}, assigner);
}
#endregion
}
#region Messages
public sealed partial class TimeSync : pb::GeneratedMessage<TimeSync, TimeSync.Builder> {
private static readonly TimeSync defaultInstance = new Builder().BuildPartial();
public static TimeSync DefaultInstance {
get { return defaultInstance; }
}
public override TimeSync DefaultInstanceForType {
get { return defaultInstance; }
}
protected override TimeSync ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Sirikata.Network.Protocol._PBJ_Internal.Time.internal__static_Sirikata_Network_Protocol__PBJ_Internal_TimeSync__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<TimeSync, TimeSync.Builder> InternalFieldAccessors {
get { return global::Sirikata.Network.Protocol._PBJ_Internal.Time.internal__static_Sirikata_Network_Protocol__PBJ_Internal_TimeSync__FieldAccessorTable; }
}
#region Nested types
public static class Types {
public enum ReturnOptions {
REPLY_RELIABLE = 1,
REPLY_ORDERED = 2,
}
}
#endregion
public const int ClientTimeFieldNumber = 9;
private bool hasClientTime;
private ulong clientTime_ = 0;
public bool HasClientTime {
get { return hasClientTime; }
}
[global::System.CLSCompliant(false)]
public ulong ClientTime {
get { return clientTime_; }
}
public const int ServerTimeFieldNumber = 10;
private bool hasServerTime;
private ulong serverTime_ = 0;
public bool HasServerTime {
get { return hasServerTime; }
}
[global::System.CLSCompliant(false)]
public ulong ServerTime {
get { return serverTime_; }
}
public const int SyncRoundFieldNumber = 11;
private bool hasSyncRound;
private ulong syncRound_ = 0UL;
public bool HasSyncRound {
get { return hasSyncRound; }
}
[global::System.CLSCompliant(false)]
public ulong SyncRound {
get { return syncRound_; }
}
public const int ReturnOptionsFieldNumber = 14;
private bool hasReturnOptions;
private uint returnOptions_ = 0;
public bool HasReturnOptions {
get { return hasReturnOptions; }
}
[global::System.CLSCompliant(false)]
public uint ReturnOptions {
get { return returnOptions_; }
}
public const int RoundTripFieldNumber = 2561;
private bool hasRoundTrip;
private ulong roundTrip_ = 0;
public bool HasRoundTrip {
get { return hasRoundTrip; }
}
[global::System.CLSCompliant(false)]
public ulong RoundTrip {
get { return roundTrip_; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::CodedOutputStream output) {
if (HasClientTime) {
output.WriteFixed64(9, ClientTime);
}
if (HasServerTime) {
output.WriteFixed64(10, ServerTime);
}
if (HasSyncRound) {
output.WriteUInt64(11, SyncRound);
}
if (HasReturnOptions) {
output.WriteUInt32(14, ReturnOptions);
}
if (HasRoundTrip) {
output.WriteFixed64(2561, RoundTrip);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (HasClientTime) {
size += pb::CodedOutputStream.ComputeFixed64Size(9, ClientTime);
}
if (HasServerTime) {
size += pb::CodedOutputStream.ComputeFixed64Size(10, ServerTime);
}
if (HasSyncRound) {
size += pb::CodedOutputStream.ComputeUInt64Size(11, SyncRound);
}
if (HasReturnOptions) {
size += pb::CodedOutputStream.ComputeUInt32Size(14, ReturnOptions);
}
if (HasRoundTrip) {
size += pb::CodedOutputStream.ComputeFixed64Size(2561, RoundTrip);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
}
public static TimeSync ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static TimeSync ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static TimeSync ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static TimeSync ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static TimeSync ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static TimeSync ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static TimeSync ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static TimeSync ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static TimeSync ParseFrom(pb::CodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static TimeSync ParseFrom(pb::CodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(TimeSync prototype) {
return (Builder) new Builder().MergeFrom(prototype);
}
public sealed partial class Builder : pb::GeneratedBuilder<TimeSync, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {}
TimeSync result = new TimeSync();
protected override TimeSync MessageBeingBuilt {
get { return result; }
}
public override Builder Clear() {
result = new TimeSync();
return this;
}
public override Builder Clone() {
return new Builder().MergeFrom(result);
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Sirikata.Network.Protocol._PBJ_Internal.TimeSync.Descriptor; }
}
public override TimeSync DefaultInstanceForType {
get { return global::Sirikata.Network.Protocol._PBJ_Internal.TimeSync.DefaultInstance; }
}
public override TimeSync BuildPartial() {
if (result == null) {
throw new global::System.InvalidOperationException("build() has already been called on this Builder");
}
TimeSync returnMe = result;
result = null;
return returnMe;
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is TimeSync) {
return MergeFrom((TimeSync) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(TimeSync other) {
if (other == global::Sirikata.Network.Protocol._PBJ_Internal.TimeSync.DefaultInstance) return this;
if (other.HasClientTime) {
ClientTime = other.ClientTime;
}
if (other.HasServerTime) {
ServerTime = other.ServerTime;
}
if (other.HasSyncRound) {
SyncRound = other.SyncRound;
}
if (other.HasReturnOptions) {
ReturnOptions = other.ReturnOptions;
}
if (other.HasRoundTrip) {
RoundTrip = other.RoundTrip;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::CodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::CodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
pb::UnknownFieldSet.Builder unknownFields = null;
while (true) {
uint tag = input.ReadTag();
switch (tag) {
case 0: {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag);
break;
}
case 73: {
ClientTime = input.ReadFixed64();
break;
}
case 81: {
ServerTime = input.ReadFixed64();
break;
}
case 88: {
SyncRound = input.ReadUInt64();
break;
}
case 112: {
ReturnOptions = input.ReadUInt32();
break;
}
case 20489: {
RoundTrip = input.ReadFixed64();
break;
}
}
}
}
public bool HasClientTime {
get { return result.HasClientTime; }
}
[global::System.CLSCompliant(false)]
public ulong ClientTime {
get { return result.ClientTime; }
set { SetClientTime(value); }
}
[global::System.CLSCompliant(false)]
public Builder SetClientTime(ulong value) {
result.hasClientTime = true;
result.clientTime_ = value;
return this;
}
public Builder ClearClientTime() {
result.hasClientTime = false;
result.clientTime_ = 0;
return this;
}
public bool HasServerTime {
get { return result.HasServerTime; }
}
[global::System.CLSCompliant(false)]
public ulong ServerTime {
get { return result.ServerTime; }
set { SetServerTime(value); }
}
[global::System.CLSCompliant(false)]
public Builder SetServerTime(ulong value) {
result.hasServerTime = true;
result.serverTime_ = value;
return this;
}
public Builder ClearServerTime() {
result.hasServerTime = false;
result.serverTime_ = 0;
return this;
}
public bool HasSyncRound {
get { return result.HasSyncRound; }
}
[global::System.CLSCompliant(false)]
public ulong SyncRound {
get { return result.SyncRound; }
set { SetSyncRound(value); }
}
[global::System.CLSCompliant(false)]
public Builder SetSyncRound(ulong value) {
result.hasSyncRound = true;
result.syncRound_ = value;
return this;
}
public Builder ClearSyncRound() {
result.hasSyncRound = false;
result.syncRound_ = 0UL;
return this;
}
public bool HasReturnOptions {
get { return result.HasReturnOptions; }
}
[global::System.CLSCompliant(false)]
public uint ReturnOptions {
get { return result.ReturnOptions; }
set { SetReturnOptions(value); }
}
[global::System.CLSCompliant(false)]
public Builder SetReturnOptions(uint value) {
result.hasReturnOptions = true;
result.returnOptions_ = value;
return this;
}
public Builder ClearReturnOptions() {
result.hasReturnOptions = false;
result.returnOptions_ = 0;
return this;
}
public bool HasRoundTrip {
get { return result.HasRoundTrip; }
}
[global::System.CLSCompliant(false)]
public ulong RoundTrip {
get { return result.RoundTrip; }
set { SetRoundTrip(value); }
}
[global::System.CLSCompliant(false)]
public Builder SetRoundTrip(ulong value) {
result.hasRoundTrip = true;
result.roundTrip_ = value;
return this;
}
public Builder ClearRoundTrip() {
result.hasRoundTrip = false;
result.roundTrip_ = 0;
return this;
}
}
static TimeSync() {
object.ReferenceEquals(global::Sirikata.Network.Protocol._PBJ_Internal.Time.Descriptor, null);
}
}
#endregion
}
| |
//#define SA_DEBUG_MODE
using UnityEngine;
using System.Collections;
public class RTM_Game_Example : AndroidNativeExampleBase {
public GameObject avatar;
public GameObject hi;
public SA_Label playerLabel;
public SA_Label gameState;
public SA_Label parisipants;
public DefaultPreviewButton connectButton;
public DefaultPreviewButton helloButton;
public DefaultPreviewButton leaveRoomButton;
public DefaultPreviewButton showRoomButton;
public DefaultPreviewButton[] ConnectionDependedntButtons;
public SA_PartisipantUI[] patrisipants;
private Texture defaulttexture;
void Start() {
playerLabel.text = "Player Diconnected";
defaulttexture = avatar.renderer.material.mainTexture;
//listen for GooglePlayConnection events
GooglePlayRTM.instance.addEventListener (GooglePlayRTM.ON_INVITATION_RECEIVED, OnInvite);
GooglePlayRTM.instance.addEventListener (GooglePlayRTM.ON_ROOM_CREATED, OnRoomCreated);
GooglePlayConnection.instance.addEventListener (GooglePlayConnection.PLAYER_CONNECTED, OnPlayerConnected);
GooglePlayConnection.instance.addEventListener (GooglePlayConnection.PLAYER_DISCONNECTED, OnPlayerDisconnected);
GooglePlayConnection.instance.addEventListener(GooglePlayConnection.CONNECTION_RESULT_RECEIVED, OnConnectionResult);
if(GooglePlayConnection.state == GPConnectionState.STATE_CONNECTED) {
//checking if player already connected
OnPlayerConnected ();
}
//networking eventd
GooglePlayRTM.instance.addEventListener(GooglePlayRTM.DATA_RECIEVED, OnGCDataReceived);
}
private void ConncetButtonPress() {
Debug.Log("GooglePlayManager State -> " + GooglePlayConnection.state.ToString());
if(GooglePlayConnection.state == GPConnectionState.STATE_CONNECTED) {
SA_StatusBar.text = "Disconnecting from Play Service...";
GooglePlayConnection.instance.disconnect ();
} else {
SA_StatusBar.text = "Connecting to Play Service...";
GooglePlayConnection.instance.connect ();
}
}
private void ShowWatingRoom() {
GooglePlayRTM.instance.ShowWaitingRoomIntent();
}
private void findMatch() {
GooglePlayRTM.instance.FindMatch(1, 2);
}
private void InviteFriends() {
GooglePlayRTM.instance.OpenInvitationBoxUI(1, 2);
}
private void SendHello() {
#if (UNITY_ANDROID && !UNITY_EDITOR) || SA_DEBUG_MODE
string msg = "hello world";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] data = encoding.GetBytes(msg);
GooglePlayRTM.instance.SendDataToAll(data, GP_RTM_PackageType.RELIABLE);
#endif
}
private void LeaveRoom() {
GooglePlayRTM.instance.LeaveRoom();
}
private void DrawPartisipants() {
UpdateGameState("Room State: " + GooglePlayRTM.instance.currentRoom.status.ToString());
parisipants.text = "Total Room Partisipants: " + GooglePlayRTM.instance.currentRoom.partisipants.Count;
foreach(SA_PartisipantUI p in patrisipants) {
p.gameObject.SetActive(false);
}
int i = 0;
foreach(GP_Partisipant p in GooglePlayRTM.instance.currentRoom.partisipants) {
patrisipants[i].gameObject.SetActive(true);
patrisipants[i].SetPartisipant(p);
i++;
}
}
private void UpdateGameState(string msg) {
gameState.text = msg;
}
void FixedUpdate() {
DrawPartisipants();
if(GooglePlayRTM.instance.currentRoom.status!= GP_RTM_RoomStatus.ROOM_VARIANT_DEFAULT && GooglePlayRTM.instance.currentRoom.status!= GP_RTM_RoomStatus.ROOM_STATUS_ACTIVE) {
showRoomButton.EnabledButton();
} else {
showRoomButton.DisabledButton();
}
if(GooglePlayRTM.instance.currentRoom.status == GP_RTM_RoomStatus.ROOM_VARIANT_DEFAULT) {
leaveRoomButton.DisabledButton();
} else {
leaveRoomButton.EnabledButton();
}
if(GooglePlayRTM.instance.currentRoom.status == GP_RTM_RoomStatus.ROOM_STATUS_ACTIVE) {
helloButton.EnabledButton();
hi.SetActive(true);
} else {
helloButton.DisabledButton();
hi.SetActive(false);
}
if(GooglePlayConnection.state == GPConnectionState.STATE_CONNECTED) {
if(GooglePlayManager.instance.player.icon != null) {
avatar.renderer.material.mainTexture = GooglePlayManager.instance.player.icon;
}
} else {
avatar.renderer.material.mainTexture = defaulttexture;
}
string title = "Connect";
if(GooglePlayConnection.state == GPConnectionState.STATE_CONNECTED) {
title = "Disconnect";
foreach(DefaultPreviewButton btn in ConnectionDependedntButtons) {
btn.EnabledButton();
}
} else {
foreach(DefaultPreviewButton btn in ConnectionDependedntButtons) {
btn.DisabledButton();
}
if(GooglePlayConnection.state == GPConnectionState.STATE_DISCONNECTED || GooglePlayConnection.state == GPConnectionState.STATE_UNCONFIGURED) {
title = "Connect";
} else {
title = "Connecting..";
}
}
connectButton.text = title;
}
private void OnPlayerDisconnected() {
SA_StatusBar.text = "Player Diconnected";
playerLabel.text = "Player Diconnected";
}
private void OnPlayerConnected() {
SA_StatusBar.text = "Player Connected";
playerLabel.text = GooglePlayManager.instance.player.name;
}
private void OnConnectionResult(CEvent e) {
GooglePlayConnectionResult result = e.data as GooglePlayConnectionResult;
SA_StatusBar.text = "ConnectionResul: " + result.code.ToString();
Debug.Log(result.code.ToString());
}
private string invitationId;
private void OnInvite(CEvent e) {
invitationId = (string) e.data;
AndroidDialog dialog = AndroidDialog.Create("Invite", "You have new invite from firend", "Start Playing", "Open Inbox");
dialog.addEventListener(BaseEvent.COMPLETE, OnInvDialogComplete);
}
private void OnRoomCreated(CEvent e) {
GP_GamesStatusCodes code = (GP_GamesStatusCodes) e.data;
SA_StatusBar.text = "Room Create Result: " + code.ToString();
}
private void OnInvDialogComplete(CEvent e) {
//removing listner
(e.dispatcher as AndroidDialog).removeEventListener(BaseEvent.COMPLETE, OnInvDialogComplete);
//parsing result
switch((AndroidDialogResult)e.data) {
case AndroidDialogResult.YES:
GooglePlayRTM.instance.AcceptInviteToRoom(invitationId);
break;
case AndroidDialogResult.NO:
GooglePlayRTM.instance.OpenInvitationInBoxUI();
break;
}
}
private void OnGCDataReceived(CEvent e) {
#if (UNITY_ANDROID && !UNITY_EDITOR) || SA_DEBUG_MODE
GP_RTM_Network_Package package = e.data as GP_RTM_Network_Package;
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
string str = enc.GetString(package.buffer);
string name = package.participantId;
GP_Partisipant p = GooglePlayRTM.instance.currentRoom.GetPartisipantById(package.participantId);
if(p != null) {
GooglePlayerTemplate player = GooglePlayManager.instance.GetPlayerById(p.playerId);
if(player != null) {
name = player.name;
}
}
AndroidMessage.Create("Data Eeceived", "player " + name + " \n " + "data: " + str);
#endif
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using Xunit;
namespace System.Collections.ArrayListTests
{
public class SortTests
{
#region "Test Data - Keep the data close to tests so it can vary independently from other tests"
string[] strHeroes =
{
"Green Arrow",
"Atom",
"Batman",
"Steel",
"Superman",
"Wonder Woman",
"Hawkman",
"Flash",
"Aquaman",
"Green Lantern",
"Catwoman",
"Huntress",
"Robin",
"Captain Atom",
"Wildcat",
"Nightwing",
"Ironman",
"SpiderMan",
"Black Canary",
"Thor",
"Cyborg",
"Captain America",
};
string[] strHeroesSorted =
{
"Aquaman",
"Atom",
"Batman",
"Black Canary",
"Captain America",
"Captain Atom",
"Catwoman",
"Cyborg",
"Flash",
"Green Arrow",
"Green Lantern",
"Hawkman",
"Huntress",
"Ironman",
"Nightwing",
"Robin",
"SpiderMan",
"Steel",
"Superman",
"Thor",
"Wildcat",
"Wonder Woman",
};
#endregion
[Fact]
public void TestAscendingAndDecendingSort()
{
//--------------------------------------------------------------------------
// Variable definitions.
//--------------------------------------------------------------------------
ArrayList arrList = null;
string[] strHeroesUnsorted = null;
//
// Test ascending sort.
//
// Construct unsorted array.
strHeroesUnsorted = new String[strHeroes.Length];
System.Array.Copy(strHeroes, 0, strHeroesUnsorted, 0, strHeroes.Length);
// Sort ascending the array list.
System.Array.Sort(strHeroesUnsorted, 0, strHeroesUnsorted.Length, new SortTests_Assending());
// Verify ascending sort.
for (int ii = 0; ii < strHeroesUnsorted.Length; ++ii)
{
Assert.Equal(0, strHeroesSorted[ii].CompareTo(strHeroesUnsorted[ii]));
}
//
// Test decending sort.
//
// Construct unsorted array.
strHeroesUnsorted = new String[strHeroes.Length];
System.Array.Copy(strHeroes, 0, strHeroesUnsorted, 0, strHeroes.Length);
// Sort decending the array list.
System.Array.Sort(strHeroesUnsorted, 0, strHeroesUnsorted.Length, new SortTests_Decending());
// Verify descending sort.
for (int ii = 0; ii < strHeroesUnsorted.Length; ++ii)
{
Assert.Equal(0, strHeroesSorted[ii].CompareTo(strHeroesUnsorted[strHeroesUnsorted.Length - ii - 1]));
}
//
// [] Sort array list using default comparer.
//
arrList = new ArrayList((ICollection)strHeroesUnsorted);
Assert.NotNull(arrList);
// Sort decending the array list.
arrList.Sort(null);
// Verify sort.
for (int ii = 0; ii < arrList.Count; ++ii)
{
Assert.Equal(0, strHeroesSorted[ii].CompareTo((string)arrList[ii]));
}
//
// [] Sort array list our ascending comparer.
//
arrList = new ArrayList((ICollection)strHeroesUnsorted);
Assert.NotNull(arrList);
// Sort decending the array list.
arrList.Sort(new SortTests_Assending());
// Verify sort.
for (int ii = 0; ii < arrList.Count; ++ii)
{
Assert.Equal(0, strHeroesSorted[ii].CompareTo((String)arrList[ii]));
}
//
// [] Sort array list our ascending comparer.
//
arrList = new ArrayList((ICollection)strHeroesUnsorted);
Assert.NotNull(arrList);
// Sort decending the array list.
arrList.Sort(new SortTests_Decending());
// Verify sort.
for (int ii = 0, jj = arrList.Count - 1; ii < arrList.Count; ++ii, jj--)
{
Assert.Equal(0, strHeroesSorted[ii].CompareTo((string)arrList[jj]));
}
}
[Fact]
public void TestInvalidIndexOrCount()
{
//--------------------------------------------------------------------------
// Variable definitions.
//--------------------------------------------------------------------------
ArrayList arrList = null;
string[] strHeroesUnsorted = null;
//
// Test ascending sort.
//
// Construct unsorted array.
strHeroesUnsorted = new String[strHeroes.Length];
System.Array.Copy(strHeroes, 0, strHeroesUnsorted, 0, strHeroes.Length);
// Sort ascending the array list.
System.Array.Sort(strHeroesUnsorted, 0, strHeroesUnsorted.Length, new SortTests_Assending());
// Verify ascending sort.
for (int ii = 0; ii < strHeroesUnsorted.Length; ++ii)
{
Assert.Equal(0, strHeroesSorted[ii].CompareTo(strHeroesUnsorted[ii]));
}
//
// Test decending sort.
//
// Construct unsorted array.
strHeroesUnsorted = new String[strHeroes.Length];
System.Array.Copy(strHeroes, 0, strHeroesUnsorted, 0, strHeroes.Length);
// Sort decending the array list.
System.Array.Sort(strHeroesUnsorted, 0, strHeroesUnsorted.Length, new SortTests_Decending());
// Verify descending sort.
for (int ii = 0; ii < strHeroesUnsorted.Length; ++ii)
{
Assert.Equal(0, strHeroesSorted[ii].CompareTo(strHeroesUnsorted[strHeroesUnsorted.Length - ii - 1]));
}
arrList = new ArrayList((ICollection)strHeroesUnsorted);
//Adapter, GetRange, Synchronized, ReadOnly returns a slightly different version of
//BinarySearch, Following variable cotains each one of these types of array lists
ArrayList[] arrayListTypes = {
(ArrayList)arrList.Clone(),
(ArrayList)ArrayList.Adapter(arrList).Clone(),
(ArrayList)ArrayList.FixedSize(arrList).Clone(),
(ArrayList)arrList.GetRange(0, arrList.Count).Clone(),
(ArrayList)ArrayList.Synchronized(arrList).Clone()};
foreach (ArrayList arrayListType in arrayListTypes)
{
arrList = arrayListType;
//
// [] Sort array list using default comparer.
//
Assert.NotNull(arrList);
// Sort decending the array list.
arrList.Sort(0, arrList.Count, null);
// Verify sort.
for (int ii = 0; ii < arrList.Count; ++ii)
{
Assert.Equal(0, strHeroesSorted[ii].CompareTo((string)arrList[ii]));
}
//
// [] Bogus negative index.
//
Assert.Throws<ArgumentOutOfRangeException>(() => arrList.Sort(-1000, arrList.Count, null));
//
// [] Bogus out of bounds index.
//
Assert.Throws<ArgumentException>(() => arrList.Sort(1000, arrList.Count, null));
//
// [] Bogus negative size parmeter.
//
Assert.Throws<ArgumentOutOfRangeException>(() => arrList.Sort(0, -1000, null));
//
// [] Bogus out of bounds size parmeter.
//
Assert.Throws<ArgumentException>(() => arrList.Sort(0, 1000, null));
}
}
internal class SortTests_Assending : IComparer
{
public virtual int Compare(Object x, Object y)
{
return ((String)x).CompareTo((String)y);
}
}
internal class SortTests_Decending : IComparer
{
public virtual int Compare(Object x, Object y)
{
return -((String)x).CompareTo((String)y);
}
}
[Fact]
public void TestMultipleDataTypes()
{
//--------------------------------------------------------------------------
// Variable definitions.
//--------------------------------------------------------------------------
ArrayList arrList = null;
//
// [] Sort array list using default comparer.
//
arrList = new ArrayList((ICollection)strHeroes);
// Sort decending the array list.
arrList.Sort();
// Verify sort.
for (int ii = 0; ii < arrList.Count; ++ii)
{
Assert.Equal(0, strHeroesSorted[ii].CompareTo((String)arrList[ii]));
}
//[]Team review feedback - Sort an empty ArrayList
arrList = new ArrayList();
arrList.Sort();
Assert.Equal(0, arrList.Count);
//[] Sort an ArrayList with multiple data types. This will throw
short i16;
int i32;
long i64;
ushort ui16;
uint ui32;
ulong ui64;
ArrayList alst;
i16 = 1;
i32 = 2;
i64 = 3;
ui16 = 4;
ui32 = 5;
ui64 = 6;
alst = new ArrayList();
alst.Add(i16);
alst.Add(i32);
alst.Add(i64);
alst.Add(ui16);
alst.Add(ui32);
alst.Add(ui64);
Assert.Throws<InvalidOperationException>(() => alst.Sort());
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_ASNOTE
{
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestSuites.Common.DataStructures;
using Microsoft.Protocols.TestTools;
using Request = Microsoft.Protocols.TestSuites.Common.Request;
/// <summary>
/// A static class contains all helper methods used in test cases.
/// </summary>
internal static class TestSuiteHelper
{
/// <summary>
/// This method is used to check the Sync Change commands.
/// </summary>
/// <param name="result">The sync result which is returned from server</param>
/// <param name="subject">The expected note's subject</param>
/// <param name="site">An instance of interface ITestSite which provides logging, assertions, and adapters for test code onto its execution context.</param>
/// <returns>The boolean value which represents whether the note with expected subject is found or not in sync result</returns>
internal static bool CheckSyncChangeCommands(SyncStore result, string subject, ITestSite site)
{
site.Assert.AreEqual<byte>(
1,
result.CollectionStatus,
"The server should return a Status 1 in the Sync command response indicate sync command succeed.");
bool isNoteFound = false;
foreach (Sync sync in result.ChangeElements)
{
site.Assert.IsNotNull(
sync,
@"The Change element in response should not be null.");
site.Assert.IsNotNull(
sync.Note,
@"The note class in response should not be null.");
if (sync.Note.Subject.Equals(subject))
{
isNoteFound = true;
}
}
return isNoteFound;
}
/// <summary>
/// Combines the to-be-changed elements with the added elements to form a dictionary of changed elements for the note
/// </summary>
/// <param name="addElements">All the elements of the created note</param>
/// <param name="changeElements">The to-be-changed elements of the note</param>
/// <returns>All the elements of the note to be changed</returns>
internal static Dictionary<Request.ItemsChoiceType7, object> CombineChangeAndAddNoteElements(Dictionary<Request.ItemsChoiceType8, object> addElements, Dictionary<Request.ItemsChoiceType7, object> changeElements)
{
foreach (Request.ItemsChoiceType8 addElementName in addElements.Keys)
{
Request.ItemsChoiceType7 changeElementName = (Request.ItemsChoiceType7)System.Enum.Parse(typeof(Request.ItemsChoiceType7), addElementName.ToString());
if (!changeElements.ContainsKey(changeElementName) && addElementName == Request.ItemsChoiceType8.Categories2)
{
changeElements.Add(Request.ItemsChoiceType7.Categories3, addElements[addElementName]);
}
else if (!changeElements.ContainsKey(changeElementName))
{
changeElements.Add(changeElementName, addElements[addElementName]);
}
}
return changeElements;
}
/// <summary>
/// Builds a initial Sync request by using the specified collection Id.
/// </summary>
/// <param name="collectionId">Folder collection Id to be synchronized.</param>
/// <returns>Returns the SyncRequest instance</returns>
internal static SyncRequest CreateInitialSyncRequest(string collectionId)
{
Request.SyncCollection syncCollection = new Request.SyncCollection
{
CollectionId = collectionId,
SyncKey = "0"
};
return Common.CreateSyncRequest(new Request.SyncCollection[] { syncCollection });
}
/// <summary>
/// Builds a ItemOperations request to fetch the whole content of the notes
/// </summary>
/// <param name="collectionId">Specifies the notes folder</param>
/// <param name="serverIds">Specifies a unique identifier that is assigned by the server for the notes</param>
/// <param name="longIds">Specifies a unique identifier that is assigned by the server to each result returned by a previous Search response.</param>
/// <param name="bodyPreference">Sets preference information related to the type and size of the body.</param>
/// <param name="schema">Specifies the schema of the item to be fetched.</param>
/// <returns>Returns the ItemOperationsRequest instance</returns>
internal static ItemOperationsRequest CreateItemOperationsFetchRequest(
string collectionId,
List<string> serverIds,
List<string> longIds,
Request.BodyPreference bodyPreference,
Request.Schema schema)
{
Request.ItemOperationsFetchOptions fetchOptions = new Request.ItemOperationsFetchOptions();
List<object> fetchOptionItems = new List<object>();
List<Request.ItemsChoiceType5> fetchOptionItemsName = new List<Request.ItemsChoiceType5>();
if (null != bodyPreference)
{
fetchOptionItemsName.Add(Request.ItemsChoiceType5.BodyPreference);
fetchOptionItems.Add(bodyPreference);
}
if (null != schema)
{
fetchOptionItemsName.Add(Request.ItemsChoiceType5.Schema);
fetchOptionItems.Add(schema);
}
fetchOptions.Items = fetchOptionItems.ToArray();
fetchOptions.ItemsElementName = fetchOptionItemsName.ToArray();
List<Request.ItemOperationsFetch> fetchElements = new List<Request.ItemOperationsFetch>();
if (serverIds != null)
{
foreach (string serverId in serverIds)
{
Request.ItemOperationsFetch fetchElement = new Request.ItemOperationsFetch()
{
CollectionId = collectionId,
ServerId = serverId,
Store = SearchName.Mailbox.ToString(),
Options = fetchOptions
};
fetchElements.Add(fetchElement);
}
}
if (longIds != null)
{
foreach (string longId in longIds)
{
Request.ItemOperationsFetch fetchElement = new Request.ItemOperationsFetch()
{
LongId = longId,
Store = SearchName.Mailbox.ToString(),
Options = fetchOptions
};
fetchElements.Add(fetchElement);
}
}
return Common.CreateItemOperationsRequest(fetchElements.ToArray());
}
/// <summary>
/// Builds a generic Sync request without command references by using the specified sync key, folder collection ID and body preference option.
/// </summary>
/// <param name="syncKey">Specifies the sync key obtained from the last sync response.</param>
/// <param name="collectionId">Specifies the server ID of the folder to be synchronized.</param>
/// <param name="bodyPreference">Sets preference information related to the type and size of information for body.</param>
/// <returns>Returns the SyncRequest instance</returns>
internal static SyncRequest CreateSyncRequest(string syncKey, string collectionId, Request.BodyPreference bodyPreference)
{
Request.SyncCollection syncCollection = new Request.SyncCollection
{
SyncKey = syncKey,
CollectionId = collectionId
};
// Sets Getchanges only if SyncKey != 0 since fail response is returned when the SyncKey element value is 0.
if (syncKey != "0")
{
syncCollection.GetChanges = true;
syncCollection.GetChangesSpecified = true;
}
syncCollection.WindowSize = "512";
Request.Options syncOptions = new Request.Options();
List<object> syncOptionItems = new List<object>();
List<Request.ItemsChoiceType1> syncOptionItemsName = new List<Request.ItemsChoiceType1>();
if (null != bodyPreference)
{
syncOptionItemsName.Add(Request.ItemsChoiceType1.BodyPreference);
syncOptionItems.Add(bodyPreference);
}
syncOptions.Items = syncOptionItems.ToArray();
syncOptions.ItemsElementName = syncOptionItemsName.ToArray();
syncCollection.Options = new Request.Options[] { syncOptions };
return Common.CreateSyncRequest(new Request.SyncCollection[] { syncCollection });
}
/// <summary>
/// Builds a Sync change request by using the specified sync key, folder collection ID and change application data.
/// </summary>
/// <param name="syncKey">Specifies the sync key obtained from the last sync response.</param>
/// <param name="collectionId">Specifies the server ID of the folder to be synchronized.</param>
/// <param name="data">Contains the data used to specify the Change element for Sync command.</param>
/// <returns>Returns the SyncRequest instance</returns>
internal static SyncRequest CreateSyncRequest(string syncKey, string collectionId, List<object> data)
{
Request.SyncCollection syncCollection = new Request.SyncCollection
{
SyncKey = syncKey,
GetChanges = true,
GetChangesSpecified = true,
DeletesAsMoves = false,
DeletesAsMovesSpecified = true,
CollectionId = collectionId
};
Request.Options option = new Request.Options();
Request.BodyPreference preference = new Request.BodyPreference
{
Type = 2,
Preview = 0,
PreviewSpecified = true
};
option.Items = new object[] { preference };
option.ItemsElementName = new Request.ItemsChoiceType1[]
{
Request.ItemsChoiceType1.BodyPreference,
};
syncCollection.Options = new Request.Options[1];
syncCollection.Options[0] = option;
syncCollection.WindowSize = "512";
syncCollection.Commands = data.ToArray();
return Common.CreateSyncRequest(new Request.SyncCollection[] { syncCollection });
}
/// <summary>
/// Whether the content is in HTML format
/// </summary>
/// <param name="content">The string to be checked</param>
/// <returns>Returns the value to represent whether the content is in HTML format or not</returns>
internal static bool IsHTML(string content)
{
Regex reg = new Regex(@"<(html)>(.*\n*)*<\/\1>", RegexOptions.IgnoreCase);
bool isHTML = reg.IsMatch(content);
return isHTML;
}
}
}
| |
//////////////////////////////////////////////////////////////////////////
// Code Named: VG-Ripper
// Function : Extracts Images posted on RiP forums and attempts to fetch
// them to disk.
//
// This software is licensed under the MIT license. See license.txt for
// details.
//
// Copyright (c) The Watcher
// Partial Rights Reserved.
//
//////////////////////////////////////////////////////////////////////////
// This file is part of the RiP Ripper project base.
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Threading;
namespace Ripper
{
using Ripper.Core.Components;
using Ripper.Core.Objects;
/// <summary>
/// Worker class to get images from ImageHaven.net
/// </summary>
public class ImageHaven : ServiceTemplate
{
public ImageHaven(ref string sSavePath, ref string strURL, ref string thumbURL, ref string imageName, ref int imageNumber, ref Hashtable hashtable)
: base(sSavePath, strURL, thumbURL, imageName, imageNumber, ref hashtable)
{
}
protected override bool DoDownload()
{
var strImgURL = this.ImageLinkURL;
if (this.EventTable.ContainsKey(strImgURL))
{
return true;
}
var strFilePath = string.Empty;
if (strImgURL.Contains("_"))
{
strFilePath = strImgURL.Substring(strImgURL.IndexOf("_") + 1);
}
else
{
strFilePath = strImgURL.Substring(strImgURL.LastIndexOf("?id=") + 13);
}
try
{
if (!Directory.Exists(this.SavePath))
Directory.CreateDirectory(this.SavePath);
}
catch (IOException ex)
{
// MainForm.DeleteMessage = ex.Message;
// MainForm.Delete = true;
return false;
}
strFilePath = Path.Combine(this.SavePath, Utility.RemoveIllegalCharecters(strFilePath));
var CCObj = new CacheObject();
CCObj.IsDownloaded = false;
CCObj.FilePath = strFilePath;
CCObj.Url = strImgURL;
try
{
this.EventTable.Add(strImgURL, CCObj);
}
catch (ThreadAbortException)
{
return true;
}
catch (Exception)
{
if (this.EventTable.ContainsKey(strImgURL))
{
return false;
}
else
{
this.EventTable.Add(strImgURL, CCObj);
}
}
var strIVPage = string.Empty;
try
{
strIVPage = this.GetRealLink(strImgURL);
}
catch (Exception)
{
return false;
}
var strNewURL = string.Empty;
var iStartSRC = 0;
var iEndSRC = 0;
iStartSRC = strIVPage.IndexOf("<img src='.");
if (iStartSRC < 0)
{
return false;
}
iStartSRC += 11;
iEndSRC = strIVPage.IndexOf("' id=\"image\"", iStartSRC);
if (iEndSRC < 0)
{
return false;
}
var sAltUrl = strImgURL;
sAltUrl = sAltUrl.Remove(strImgURL.IndexOf("/img.php"));
strNewURL = $"{sAltUrl}{strIVPage.Substring(iStartSRC, iEndSRC - iStartSRC)}";
//////////////////////////////////////////////////////////////////////////
try
{
var client = new WebClient();
client.Headers.Add("Referer: " + strImgURL);
client.Headers.Add("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6");
client.DownloadFile(strNewURL, strFilePath);
}
catch (ThreadAbortException)
{
((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);
return true;
}
catch (IOException ex)
{
// MainForm.DeleteMessage = ex.Message;
// MainForm.Delete = true;
((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);
return true;
}
catch (WebException)
{
((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);
return false;
}
((CacheObject)this.EventTable[this.ImageLinkURL]).IsDownloaded = true;
CacheController.Instance().LastPic =((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath;
return true;
}
protected string GetRealLink(string strURL)
{
HttpWebRequest lHttpWebRequest;
HttpWebResponse lHttpWebResponse;
Stream lHttpWebResponseStream;
lHttpWebRequest = (HttpWebRequest)WebRequest.Create(strURL);
lHttpWebRequest.UserAgent = @"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; Q312461; .NET CLR 1.1.4322)";
lHttpWebRequest.Headers.Add("Accept-Language: en-us,en;q=0.5");
lHttpWebRequest.Headers.Add("Accept-Encoding: gzip,deflate");
lHttpWebRequest.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
lHttpWebRequest.Headers.Add("Cookie: " + "imageshowcookie_1=yes");
lHttpWebRequest.Referer = strURL;
lHttpWebRequest.KeepAlive = true;
lHttpWebResponse = (HttpWebResponse)lHttpWebRequest.GetResponse();
lHttpWebResponseStream = lHttpWebRequest.GetResponse().GetResponseStream();
var streamReader = new StreamReader(lHttpWebResponseStream);
var sPage = streamReader.ReadToEnd();
return sPage;
}
//////////////////////////////////////////////////////////////////////////
}
}
| |
using System.Collections.Generic;
namespace TagLib.Mpeg4
{
public class Box
{
//////////////////////////////////////////////////////////////////////////
// private properties
//////////////////////////////////////////////////////////////////////////
private BoxHeader header;
private Box parent;
private ByteVector data;
private bool load_children_started;
private List<Box> children;
//////////////////////////////////////////////////////////////////////////
// public methods
//////////////////////////////////////////////////////////////////////////
public Box (BoxHeader header, Box parent)
{
// Initialize everything.
this.header = header;
this.parent = parent;
this.data = null;
this.children = new List<Box> ();
this.load_children_started = false;
}
// Do the same as above, but accept a box type.
public Box (ByteVector type, Box parent) : this (new BoxHeader (type), parent)
{
}
// Who needs a parent? I'm all grown up.
public Box (ByteVector type) : this (type, null)
{
}
// Render the complete box including children.
public virtual ByteVector Render ()
{
return Render (new ByteVector ());
}
// Overwrite the box's header with a new header incorporating a size
// change.
public virtual void OverwriteHeader (long size_change)
{
// If we don't have a header we can't do anything.
if (header == null || header.Position < 0)
{
Debugger.Debug ("Box.OverWriteHeader() - No header to overwrite.");
return;
}
// Make sure this alteration won't screw up the reading of children.
LoadChildren ();
// Save the header's original position and size.
long position = header.Position;
long old_size = header.HeaderSize;
// Update the data size.
header.DataSize = (ulong) ((long) header.DataSize + size_change);
// Render the header onto the file.
File.Insert (header.Render (), position, old_size);
}
// Find the first child with a given box type.
public Box FindChild (ByteVector type)
{
foreach (Box child in Children)
if (child.BoxType == type)
return child;
return null;
}
// Find the first child with a given System.Type.
public Box FindChild (System.Type type)
{
foreach (Box child in Children)
if (child.GetType () == type)
return child;
return null;
}
// Recursively find the first child with a given box type giving
// preference to the current depth.
public Box FindChildDeep (ByteVector type)
{
foreach (Box child in Children)
if (child.BoxType == type)
return child;
foreach (Box child in Children)
{
Box success = child.FindChildDeep (type);
if (success != null)
return success;
}
return null;
}
// Recursively find the first child with a given System.Type giving
// preference to the current depth.
public Box FindChildDeep (System.Type type)
{
foreach (Box child in Children)
if (child.GetType () == type)
return child;
foreach (Box child in Children)
{
Box success = child.FindChildDeep (type);
if (success != null)
return success;
}
return null;
}
// Add a child to this box.
public void AddChild (Box child)
{
children.Add (child);
child.Parent = this;
}
// Remove a child from this box.
public void RemoveChild (Box child)
{
children.Remove (child);
child.Parent = null;
}
// Remove all children with a given box type.
public void RemoveChildren (ByteVector type)
{
Box box;
while ((box = FindChild (type)) != null)
RemoveChild (box);
}
// Remove all children with a given System.Type.
public void RemoveChildren (System.Type type)
{
Box box;
while ((box = FindChild (type)) != null)
RemoveChild (box);
}
// Detach the current box from its parent.
public void RemoveFromParent ()
{
if (Parent != null)
Parent.RemoveChild (this);
}
// Remove all children from this box.
public void ClearChildren ()
{
foreach (Box box in children)
box.Parent = null;
children.Clear ();
}
// Replace a child with a new one.
public void ReplaceChild (Box old_child, Box new_child)
{
int index = children.IndexOf (old_child);
if (index >= 0)
{
children [index] = new_child;
old_child.Parent = null;
new_child.Parent = this;
}
else
AddChild (new_child);
}
// Replace this box with another one.
public void ReplaceWith (Box box)
{
if (Parent != null)
Parent.ReplaceChild (this, box);
}
// Load this box's children as well as their children.
public void LoadChildren ()
{
if (!HasChildren || children.Count != 0 || load_children_started)
return;
load_children_started = true;
Box box = FirstChild;
while (box != null)
{
box.LoadChildren ();
children.Add (box);
box = NextChild (box);
}
}
// Load the data stored in this box.
public void LoadData ()
{
if (data == null && this.File != null && this.File.Mode != File.AccessMode.Closed)
{
File.Seek (DataPosition);
data = File.ReadBlock ((int) DataSize);
}
}
//////////////////////////////////////////////////////////////////////////
// public properties
//////////////////////////////////////////////////////////////////////////
// Is the box valid?
public virtual bool IsValid {get {return header.IsValid;}}
// The file associated with this box.
public virtual File File {get {return header.File;}}
// The box's parent box.
public Box Parent {get {return parent;} set {parent = value;}}
// The box type.
public virtual ByteVector BoxType {get {return header.BoxType;}}
// The total size of the box.
public virtual ulong BoxSize {get {return header.BoxSize;}}
// The size of the non-header data.
protected virtual ulong DataSize {get {return header.DataSize;}}
// The stream position of the box's data.
protected virtual long DataPosition {get {return header.DataPosition;}}
// Whether or not the box can have children.
public virtual bool HasChildren {get {return false;}}
// The stream position of the next box.
public virtual long NextBoxPosition {get {return header.NextBoxPosition;}}
// All child boxes of this box.
public Box [] Children {get {LoadChildren (); return (Box []) children.ToArray ();}}
private ByteVector internal_data = null;
public ByteVector InternalData
{
get
{
if (internal_data == null)
{
File.Seek (header.DataPosition);
internal_data = File.ReadBlock ((int)(DataPosition - header.DataPosition));
}
return internal_data;
}
}
// The handler used for this box.
public IsoHandlerBox Handler
{
get
{
Box box = this;
// Look in all parent boxes.
while (box != null)
{
// Handlers will be contained in "meta" and "mdia" boxes.
if (box.BoxType == "mdia" || box.BoxType == "meta")
{
// See if you can find a handler, and return if you can.
IsoHandlerBox handler = (IsoHandlerBox) box.FindChild (typeof (IsoHandlerBox));
if (handler != null)
return handler;
}
// Check the parent next.
box = box.Parent;
}
// Failure.
return null;
}
}
//////////////////////////////////////////////////////////////////////////
// public static methods
//////////////////////////////////////////////////////////////////////////
// Create a box by reading the file and add it to "parent".
public static Box Create (File file, long position, Box parent)
{
// Read the box header.
BoxHeader h = new BoxHeader (file, position);
// If we're not even valid, quit.
if (!h.IsValid)
return null;
// IF we're in a SampleDescriptionBox and haven't loaded all the
// entries, try loading an appropriate entry.
if (parent.BoxType == "stsd" && parent.Children.Length < ((IsoSampleDescriptionBox) parent).EntryCount)
{
IsoHandlerBox handler = parent.Handler;
if (handler != null && handler.HandlerType == "soun")
return new IsoAudioSampleEntry (h, parent);
else
return new IsoSampleEntry (h, parent);
}
//
// A bunch of standard items.
//
if (h.BoxType == "moov")
return new IsoMovieBox (h, parent);
if (h.BoxType == "mvhd")
return new IsoMovieHeaderBox (h, parent);
if (h.BoxType == "mdia")
return new IsoMediaBox (h, parent);
if (h.BoxType == "minf")
return new IsoMediaInformationBox (h, parent);
if (h.BoxType == "stbl")
return new IsoSampleTableBox (h, parent);
if (h.BoxType == "stsd")
return new IsoSampleDescriptionBox (h, parent);
if (h.BoxType == "stco")
return new IsoChunkOffsetBox (h, parent);
if (h.BoxType == "co64")
return new IsoChunkLargeOffsetBox (h, parent);
if (h.BoxType == "trak")
return new IsoTrackBox (h, parent);
if (h.BoxType == "hdlr")
return new IsoHandlerBox (h, parent);
if (h.BoxType == "udta")
return new IsoUserDataBox (h, parent);
if (h.BoxType == "meta")
return new IsoMetaBox (h, parent);
if (h.BoxType == "ilst")
return new AppleItemListBox (h, parent);
if (h.BoxType == "data")
return new AppleDataBox (h, parent);
if (h.BoxType == "esds")
return new AppleElementaryStreamDescriptor (h, parent);
if (h.BoxType == "free" || h.BoxType == "skip")
return new IsoFreeSpaceBox (h, parent);
if (h.BoxType == "mean" || h.BoxType == "name")
return new AppleAdditionalInfoBox (h, parent);
// If we still don't have a tag, and we're inside an ItemLisBox, load
// lthe box as an AnnotationBox (Apple tag item).
if (parent.GetType () == typeof (AppleItemListBox))
return new AppleAnnotationBox (h, parent);
// Nothing good. Go generic.
return new UnknownBox (h, parent);
}
// The data contained within this box.
public virtual ByteVector Data
{
get
{
LoadData ();
return data;
}
set
{
data = value;
}
}
//////////////////////////////////////////////////////////////////////////
// protected methods
//////////////////////////////////////////////////////////////////////////
// Render a box with the "data" before its content.
protected virtual ByteVector Render (ByteVector data)
{
bool free_found = false;
ByteVector output = new ByteVector ();
// If we have children, render them if they aren't "free", otherwise
// render the box's data.
if (HasChildren)
foreach (Box box in Children)
if (box.GetType () == typeof (IsoFreeSpaceBox))
free_found = true;
else
output.Add (box.Render ());
else
output.Add (Data);
// If there was a free, don't take it away, and let meta be a special case.
if (free_found || BoxType == "meta")
{
long size_difference = (long) DataSize - (long) output.Count;
// If we have room for free space, add it so we don't have to resize the file.
if (header.DataSize != 0 && size_difference >= 8)
output. Add ((new IsoFreeSpaceBox ((ulong) size_difference, this)).Render ());
// If we're getting bigger, get a lot bigger so we might not have to again.
else
output.Add ((new IsoFreeSpaceBox (2048, this)).Render ());
}
// Adjust the header's data size to match the content.
header.DataSize = (ulong) (data.Count + output.Count);
// Render the full box.
output.Insert (0, data);
output.Insert (0, header.Render ());
return output;
}
//////////////////////////////////////////////////////////////////////////
// private members
//////////////////////////////////////////////////////////////////////////
// If the file is readable and the box can have children and there is
// enough space to read the data, get the first child box by reading the
// file.
private Box FirstChild
{
get
{
if (HasChildren && this.File != null && (GetType () == typeof (FileBox) || DataSize >= 8))
return Box.Create (File, DataPosition, this);
return null;
}
}
// If the file is readable and the box can have children and there is
// enough space to read the data, get the next box by reading from the end
// of the first box.
private Box NextChild (Box child)
{
if (HasChildren && this.File != null && child.NextBoxPosition >= DataPosition && child.NextBoxPosition < NextBoxPosition)
return Box.Create (File, child.NextBoxPosition, this);
return null;
}
}
}
| |
// Copyright 2009 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NodaTime.Calendars;
using NodaTime.TimeZones.IO;
using NodaTime.Utility;
using System;
namespace NodaTime.TimeZones
{
/// <summary>
/// Extends <see cref="ZoneYearOffset"/> with a name and savings.
/// </summary>
/// <remarks>
/// <para>
/// This represents a recurring transition from or to a daylight savings time. The name is the
/// name of the time zone during this period (e.g. PST or PDT). The savings is usually 0 or the
/// daylight offset. This is also used to support some of the tricky transitions that occurred
/// before the time zones were normalized (i.e. when they were still tightly longitude-based,
/// with multiple towns in the same country observing different times).
/// </para>
/// <para>
/// Immutable, thread safe.
/// </para>
/// </remarks>
internal sealed class ZoneRecurrence : IEquatable<ZoneRecurrence?>
{
private readonly LocalInstant maxLocalInstant;
private readonly LocalInstant minLocalInstant;
public string Name { get; }
public Offset Savings { get; }
public ZoneYearOffset YearOffset { get; }
public int FromYear { get; }
public int ToYear { get; }
public bool IsInfinite => ToYear == Int32.MaxValue;
/// <summary>
/// Initializes a new instance of the <see cref="ZoneRecurrence"/> class.
/// </summary>
/// <param name="name">The name of the time zone period e.g. PST.</param>
/// <param name="savings">The savings for this period.</param>
/// <param name="yearOffset">The year offset of when this period starts in a year.</param>
/// <param name="fromYear">The first year in which this recurrence is valid</param>
/// <param name="toYear">The last year in which this recurrence is valid</param>
public ZoneRecurrence(String name, Offset savings, ZoneYearOffset yearOffset, int fromYear, int toYear)
{
Preconditions.CheckNotNull(name, nameof(name));
Preconditions.CheckNotNull(yearOffset, nameof(yearOffset));
Preconditions.CheckArgument(fromYear == int.MinValue || (fromYear >= -9998 && fromYear <= 9999), nameof(fromYear),
"fromYear must be in the range [-9998, 9999] or Int32.MinValue");
Preconditions.CheckArgument(toYear == int.MaxValue || (toYear >= -9998 && toYear <= 9999), nameof(toYear),
"toYear must be in the range [-9998, 9999] or Int32.MaxValue");
this.Name = name;
this.Savings = savings;
this.YearOffset = yearOffset;
this.FromYear = fromYear;
this.ToYear = toYear;
this.minLocalInstant = fromYear == int.MinValue ? LocalInstant.BeforeMinValue : yearOffset.GetOccurrenceForYear(fromYear);
this.maxLocalInstant = toYear == int.MaxValue ? LocalInstant.AfterMaxValue : yearOffset.GetOccurrenceForYear(toYear);
}
/// <summary>
/// Returns a new recurrence which has the same values as this, but a different name.
/// </summary>
internal ZoneRecurrence WithName(string name) =>
new ZoneRecurrence(name, Savings, YearOffset, FromYear, ToYear);
/// <summary>
/// Returns a new recurrence with the same values as this, but just for a single year.
/// </summary>
internal ZoneRecurrence ForSingleYear(int year)
{
return new ZoneRecurrence(Name, Savings, YearOffset, year, year);
}
#region IEquatable<ZoneRecurrence> Members
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter;
/// otherwise, false.
/// </returns>
public bool Equals(ZoneRecurrence? other)
{
if (other is null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Savings == other.Savings && FromYear == other.FromYear && ToYear == other.ToYear && Name == other.Name && YearOffset.Equals(other.YearOffset);
}
#endregion
/// <summary>
/// Returns the first transition which occurs strictly after the given instant.
/// </summary>
/// <remarks>
/// If the given instant is before the starting year, the year of the given instant is
/// adjusted to the beginning of the starting year. The first transition after the
/// adjusted instant is determined. If the next adjustment is after the ending year, this
/// method returns null; otherwise the next transition is returned.
/// </remarks>
/// <param name="instant">The <see cref="Instant"/> lower bound for the next transition.</param>
/// <param name="standardOffset">The <see cref="Offset"/> standard offset.</param>
/// <param name="previousSavings">The <see cref="Offset"/> savings adjustment at the given Instant.</param>
/// <returns>The next transition, or null if there is no next transition. The transition may be
/// infinite, i.e. after the end of representable time.</returns>
internal Transition? Next(Instant instant, Offset standardOffset, Offset previousSavings)
{
Offset ruleOffset = YearOffset.GetRuleOffset(standardOffset, previousSavings);
Offset newOffset = standardOffset + Savings;
LocalInstant safeLocal = instant.SafePlus(ruleOffset);
int targetYear;
if (safeLocal < minLocalInstant)
{
// Asked for a transition after some point before the first transition: crop to first year (so we get the first transition)
targetYear = FromYear;
}
else if (safeLocal >= maxLocalInstant)
{
// Asked for a transition after our final transition... or both are beyond the end of time (in which case
// we can return an infinite transition). This branch will always be taken for transitions beyond the end
// of time.
return maxLocalInstant == LocalInstant.AfterMaxValue ? new Transition(Instant.AfterMaxValue, newOffset) : (Transition?) null;
}
else if (safeLocal == LocalInstant.BeforeMinValue)
{
// We've been asked to find the next transition after some point which is a valid instant, but is before the
// start of valid local time after applying the rule offset. For example, passing Instant.MinValue for a rule which says
// "transition uses wall time, which is UTC-5". Proceed as if we'd been asked for something in -9998.
// I *think* that works...
targetYear = GregorianYearMonthDayCalculator.MinGregorianYear;
}
else
{
// Simple case: we were asked for a "normal" value in the range of years for which this recurrence is valid.
targetYear = CalendarSystem.Iso.YearMonthDayCalculator.GetYear(safeLocal.DaysSinceEpoch, out int ignoredDayOfYear);
}
LocalInstant transition = YearOffset.GetOccurrenceForYear(targetYear);
Instant safeTransition = transition.SafeMinus(ruleOffset);
if (safeTransition > instant)
{
return new Transition(safeTransition, newOffset);
}
// We've got a transition earlier than we were asked for. Try next year.
// Note that this will stil be within the FromYear/ToYear range, otherwise
// safeLocal >= maxLocalInstant would have been triggered earlier.
targetYear++;
// Handle infinite transitions
if (targetYear > GregorianYearMonthDayCalculator.MaxGregorianYear)
{
return new Transition(Instant.AfterMaxValue, newOffset);
}
// It's fine for this to be "end of time", and it can't be "start of time" because we're at least finding a transition in -9997.
safeTransition = YearOffset.GetOccurrenceForYear(targetYear).SafeMinus(ruleOffset);
return new Transition(safeTransition, newOffset);
}
/// <summary>
/// Returns the last transition which occurs before or on the given instant.
/// </summary>
/// <param name="instant">The <see cref="Instant"/> lower bound for the next trasnition.</param>
/// <param name="standardOffset">The <see cref="Offset"/> standard offset.</param>
/// <param name="previousSavings">The <see cref="Offset"/> savings adjustment at the given Instant.</param>
/// <returns>The previous transition, or null if there is no previous transition. The transition may be
/// infinite, i.e. before the start of representable time.</returns>
internal Transition? PreviousOrSame(Instant instant, Offset standardOffset, Offset previousSavings)
{
Offset ruleOffset = YearOffset.GetRuleOffset(standardOffset, previousSavings);
Offset newOffset = standardOffset + Savings;
LocalInstant safeLocal = instant.SafePlus(ruleOffset);
int targetYear;
if (safeLocal > maxLocalInstant)
{
// Asked for a transition before some point after our last year: crop to last year.
targetYear = ToYear;
}
// Deliberately < here; "previous or same" means if safeLocal==minLocalInstant, we should compute it for this year.
else if (safeLocal < minLocalInstant)
{
// Asked for a transition before our first one
return null;
}
else if (!safeLocal.IsValid)
{
if (safeLocal == LocalInstant.BeforeMinValue)
{
// We've been asked to find the next transition before some point which is a valid instant, but is before the
// start of valid local time after applying the rule offset. It's possible that the next transition *would*
// be representable as an instant (e.g. 1pm Dec 31st -9999 with an offset of -5) but it's reasonable to
// just return an infinite transition.
return new Transition(Instant.BeforeMinValue, newOffset);
}
else
{
// We've been asked to find the next transition before some point which is a valid instant, but is after the
// end of valid local time after applying the rule offset. For example, passing Instant.MaxValue for a rule which says
// "transition uses wall time, which is UTC+5". Proceed as if we'd been asked for something in 9999.
// I *think* that works...
targetYear = GregorianYearMonthDayCalculator.MaxGregorianYear;
}
}
else
{
// Simple case: we were asked for a "normal" value in the range of years for which this recurrence is valid.
targetYear = CalendarSystem.Iso.YearMonthDayCalculator.GetYear(safeLocal.DaysSinceEpoch, out int ignoredDayOfYear);
}
LocalInstant transition = YearOffset.GetOccurrenceForYear(targetYear);
Instant safeTransition = transition.SafeMinus(ruleOffset);
if (safeTransition <= instant)
{
return new Transition(safeTransition, newOffset);
}
// We've got a transition later than we were asked for. Try next year.
// Note that this will stil be within the FromYear/ToYear range, otherwise
// safeLocal < minLocalInstant would have been triggered earlier.
targetYear--;
// Handle infinite transitions
if (targetYear < GregorianYearMonthDayCalculator.MinGregorianYear)
{
return new Transition(Instant.BeforeMinValue, newOffset);
}
// It's fine for this to be "start of time", and it can't be "end of time" because we're at latest finding a transition in 9998.
safeTransition = YearOffset.GetOccurrenceForYear(targetYear).SafeMinus(ruleOffset);
return new Transition(safeTransition, newOffset);
}
/// <summary>
/// Piggy-backs onto Next, but fails with an InvalidOperationException if there's no such transition.
/// </summary>
internal Transition NextOrFail(Instant instant, Offset standardOffset, Offset previousSavings)
{
Transition? next = Next(instant, standardOffset, previousSavings);
if (next is null)
{
throw new InvalidOperationException(
$"Noda Time bug or bad data: Expected a transition later than {instant}; standard offset = {standardOffset}; previousSavings = {previousSavings}; recurrence = {this}");
}
return next.Value;
}
/// <summary>
/// Piggy-backs onto PreviousOrSame, but fails with a descriptive InvalidOperationException if there's no such transition.
/// </summary>
internal Transition PreviousOrSameOrFail(Instant instant, Offset standardOffset, Offset previousSavings)
{
Transition? previous = PreviousOrSame(instant, standardOffset, previousSavings);
if (previous is null)
{
throw new InvalidOperationException(
$"Noda Time bug or bad data: Expected a transition earlier than {instant}; standard offset = {standardOffset}; previousSavings = {previousSavings}; recurrence = {this}");
}
return previous.Value;
}
/// <summary>
/// Writes this object to the given <see cref="DateTimeZoneWriter"/>.
/// </summary>
/// <param name="writer">Where to send the output.</param>
internal void Write(IDateTimeZoneWriter writer)
{
writer.WriteString(Name);
writer.WriteOffset(Savings);
YearOffset.Write(writer);
// We'll never have time zones with recurrences between the beginning of time and 0AD,
// so we can treat anything negative as 0, and go to the beginning of time when reading.
writer.WriteCount(Math.Max(FromYear, 0));
writer.WriteCount(ToYear);
}
/// <summary>
/// Reads a recurrence from the specified reader.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>The recurrence read from the reader.</returns>
public static ZoneRecurrence Read(IDateTimeZoneReader reader)
{
Preconditions.CheckNotNull(reader, nameof(reader));
string name = reader.ReadString();
Offset savings = reader.ReadOffset();
ZoneYearOffset yearOffset = ZoneYearOffset.Read(reader);
int fromYear = reader.ReadCount();
if (fromYear == 0)
{
fromYear = int.MinValue;
}
int toYear = reader.ReadCount();
return new ZoneRecurrence(name, savings, yearOffset, fromYear, toYear);
}
#region Object overrides
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance;
/// otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object? obj) => Equals(obj as ZoneRecurrence);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data
/// structures like a hash table.
/// </returns>
public override int GetHashCode() => HashCodeHelper.Hash(Savings, Name, YearOffset);
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString() => $"{Name} {Savings} {YearOffset} [{FromYear}-{ToYear}]";
#endregion // Object overrides
/// <summary>
/// Returns either "this" (if this zone recurrence already has a from year of int.MinValue)
/// or a new zone recurrence which is identical but with a from year of int.MinValue.
/// </summary>
internal ZoneRecurrence ToStartOfTime() =>
FromYear == int.MinValue ? this : new ZoneRecurrence(Name, Savings, YearOffset, int.MinValue, ToYear);
}
}
| |
#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 Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Linq
{
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data.
/// </summary>
public class JTokenReader : JsonReader, IJsonLineInfo
{
private readonly JToken _root;
private JToken _parent;
private JToken _current;
/// <summary>
/// Initializes a new instance of the <see cref="JTokenReader"/> class.
/// </summary>
/// <param name="token">The token to read from.</param>
public JTokenReader(JToken token)
{
ValidationUtils.ArgumentNotNull(token, "token");
_root = token;
_current = token;
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>.
/// </summary>
/// <returns>
/// A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null. This method will return <c>null</c> at the end of an array.
/// </returns>
public override byte[] ReadAsBytes()
{
return ReadAsBytesInternal();
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns>
public override decimal? ReadAsDecimal()
{
return ReadAsDecimalInternal();
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Int32}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Int32}"/>. This method will return <c>null</c> at the end of an array.</returns>
public override int? ReadAsInt32()
{
return ReadAsInt32Internal();
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="String"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public override string ReadAsString()
{
return ReadAsStringInternal();
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTime}"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public override DateTime? ReadAsDateTime()
{
return ReadAsDateTimeInternal();
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{DateTimeOffset}"/>. This method will return <c>null</c> at the end of an array.</returns>
public override DateTimeOffset? ReadAsDateTimeOffset()
{
return ReadAsDateTimeOffsetInternal();
}
internal override bool ReadInternal()
{
if (CurrentState != State.Start)
{
JContainer container = _current as JContainer;
if (container != null && _parent != container)
return ReadInto(container);
else
return ReadOver(_current);
}
SetToken(_current);
return true;
}
/// <summary>
/// Reads the next JSON token from the stream.
/// </summary>
/// <returns>
/// true if the next token was read successfully; false if there are no more tokens to read.
/// </returns>
public override bool Read()
{
_readType = ReadType.Read;
return ReadInternal();
}
private bool ReadOver(JToken t)
{
if (t == _root)
return ReadToEnd();
JToken next = t.Next;
if ((next == null || next == t) || t == t.Parent.Last)
{
if (t.Parent == null)
return ReadToEnd();
return SetEnd(t.Parent);
}
else
{
_current = next;
SetToken(_current);
return true;
}
}
private bool ReadToEnd()
{
SetToken(JsonToken.None);
return false;
}
private bool IsEndElement
{
get { return (_current == _parent); }
}
private JsonToken? GetEndToken(JContainer c)
{
switch (c.Type)
{
case JTokenType.Object:
return JsonToken.EndObject;
case JTokenType.Array:
return JsonToken.EndArray;
case JTokenType.Constructor:
return JsonToken.EndConstructor;
case JTokenType.Property:
return null;
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException("Type", c.Type, "Unexpected JContainer type.");
}
}
private bool ReadInto(JContainer c)
{
JToken firstChild = c.First;
if (firstChild == null)
{
return SetEnd(c);
}
else
{
SetToken(firstChild);
_current = firstChild;
_parent = c;
return true;
}
}
private bool SetEnd(JContainer c)
{
JsonToken? endToken = GetEndToken(c);
if (endToken != null)
{
SetToken(endToken.Value);
_current = c;
_parent = c;
return true;
}
else
{
return ReadOver(c);
}
}
private void SetToken(JToken token)
{
switch (token.Type)
{
case JTokenType.Object:
SetToken(JsonToken.StartObject);
break;
case JTokenType.Array:
SetToken(JsonToken.StartArray);
break;
case JTokenType.Constructor:
SetToken(JsonToken.StartConstructor);
break;
case JTokenType.Property:
SetToken(JsonToken.PropertyName, ((JProperty)token).Name);
break;
case JTokenType.Comment:
SetToken(JsonToken.Comment, ((JValue)token).Value);
break;
case JTokenType.Integer:
SetToken(JsonToken.Integer, ((JValue)token).Value);
break;
case JTokenType.Float:
SetToken(JsonToken.Float, ((JValue)token).Value);
break;
case JTokenType.String:
SetToken(JsonToken.String, ((JValue)token).Value);
break;
case JTokenType.Boolean:
SetToken(JsonToken.Boolean, ((JValue)token).Value);
break;
case JTokenType.Null:
SetToken(JsonToken.Null, ((JValue)token).Value);
break;
case JTokenType.Undefined:
SetToken(JsonToken.Undefined, ((JValue)token).Value);
break;
case JTokenType.Date:
SetToken(JsonToken.Date, ((JValue)token).Value);
break;
case JTokenType.Raw:
SetToken(JsonToken.Raw, ((JValue)token).Value);
break;
case JTokenType.Bytes:
SetToken(JsonToken.Bytes, ((JValue)token).Value);
break;
case JTokenType.Guid:
SetToken(JsonToken.String, SafeToString(((JValue)token).Value));
break;
case JTokenType.Uri:
SetToken(JsonToken.String, SafeToString(((JValue)token).Value));
break;
case JTokenType.TimeSpan:
SetToken(JsonToken.String, SafeToString(((JValue)token).Value));
break;
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException("Type", token.Type, "Unexpected JTokenType.");
}
}
private string SafeToString(object value)
{
return (value != null) ? value.ToString() : null;
}
bool IJsonLineInfo.HasLineInfo()
{
if (CurrentState == State.Start)
return false;
IJsonLineInfo info = IsEndElement ? null : _current;
return (info != null && info.HasLineInfo());
}
int IJsonLineInfo.LineNumber
{
get
{
if (CurrentState == State.Start)
return 0;
IJsonLineInfo info = IsEndElement ? null : _current;
if (info != null)
return info.LineNumber;
return 0;
}
}
int IJsonLineInfo.LinePosition
{
get
{
if (CurrentState == State.Start)
return 0;
IJsonLineInfo info = IsEndElement ? null : _current;
if (info != null)
return info.LinePosition;
return 0;
}
}
}
}
#endif
| |
using J2N.Numerics;
using Lucene.Net.Diagnostics;
using Lucene.Net.Support;
using System;
using System.Diagnostics;
namespace Lucene.Net.Codecs.Compressing
{
/*
* 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 DataInput = Lucene.Net.Store.DataInput;
using DataOutput = Lucene.Net.Store.DataOutput;
using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s;
/// <summary>
/// LZ4 compression and decompression routines.
/// <para/>
/// http://code.google.com/p/lz4/
/// http://fastcompression.blogspot.fr/p/lz4.html
/// </summary>
public sealed class LZ4
{
private LZ4()
{
}
internal const int MEMORY_USAGE = 14;
internal const int MIN_MATCH = 4; // minimum length of a match
internal static readonly int MAX_DISTANCE = 1 << 16; // maximum distance of a reference
internal const int LAST_LITERALS = 5; // the last 5 bytes must be encoded as literals
internal const int HASH_LOG_HC = 15; // log size of the dictionary for compressHC
internal static readonly int HASH_TABLE_SIZE_HC = 1 << HASH_LOG_HC;
internal static readonly int OPTIMAL_ML = 0x0F + 4 - 1; // match length that doesn't require an additional byte
private static int Hash(int i, int hashBits)
{
return (i * -1640531535).TripleShift(32 - hashBits);
}
private static int HashHC(int i)
{
return Hash(i, HASH_LOG_HC);
}
/// <summary>
/// NOTE: This was readInt() in Lucene.
/// </summary>
private static int ReadInt32(byte[] buf, int i)
{
return ((((sbyte)buf[i]) & 0xFF) << 24) | ((((sbyte)buf[i + 1]) & 0xFF) << 16) | ((((sbyte)buf[i + 2]) & 0xFF) << 8) |
(((sbyte)buf[i + 3]) & 0xFF);
}
/// <summary>
/// NOTE: This was readIntEquals() in Lucene.
/// </summary>
private static bool ReadInt32Equals(byte[] buf, int i, int j)
{
return ReadInt32(buf, i) == ReadInt32(buf, j);
}
private static int CommonBytes(byte[] b, int o1, int o2, int limit)
{
if (Debugging.AssertsEnabled) Debugging.Assert(o1 < o2);
int count = 0;
while (o2 < limit && b[o1++] == b[o2++])
{
++count;
}
return count;
}
private static int CommonBytesBackward(byte[] b, int o1, int o2, int l1, int l2)
{
int count = 0;
while (o1 > l1 && o2 > l2 && b[--o1] == b[--o2])
{
++count;
}
return count;
}
/// <summary>
/// Decompress at least <paramref name="decompressedLen"/> bytes into
/// <c>dest[dOff]</c>. Please note that <paramref name="dest"/> must be large
/// enough to be able to hold <b>all</b> decompressed data (meaning that you
/// need to know the total decompressed length).
/// </summary>
public static int Decompress(DataInput compressed, int decompressedLen, byte[] dest, int dOff)
{
int destEnd = dest.Length;
do
{
// literals
int token = compressed.ReadByte() & 0xFF;
int literalLen = (int)(((uint)token) >> 4);
if (literalLen != 0)
{
if (literalLen == 0x0F)
{
byte len;
while ((len = compressed.ReadByte()) == 0xFF)
{
literalLen += 0xFF;
}
literalLen += len & 0xFF;
}
compressed.ReadBytes(dest, dOff, literalLen);
dOff += literalLen;
}
if (dOff >= decompressedLen)
{
break;
}
// matchs
var byte1 = compressed.ReadByte();
var byte2 = compressed.ReadByte();
int matchDec = (byte1 & 0xFF) | ((byte2 & 0xFF) << 8);
if (Debugging.AssertsEnabled) Debugging.Assert(matchDec > 0);
int matchLen = token & 0x0F;
if (matchLen == 0x0F)
{
int len;
while ((len = compressed.ReadByte()) == 0xFF)
{
matchLen += 0xFF;
}
matchLen += len & 0xFF;
}
matchLen += MIN_MATCH;
// copying a multiple of 8 bytes can make decompression from 5% to 10% faster
int fastLen = (int)((matchLen + 7) & 0xFFFFFFF8);
if (matchDec < matchLen || dOff + fastLen > destEnd)
{
// overlap -> naive incremental copy
for (int @ref = dOff - matchDec, end = dOff + matchLen; dOff < end; ++@ref, ++dOff)
{
dest[dOff] = dest[@ref];
}
}
else
{
// no overlap -> arraycopy
Array.Copy(dest, dOff - matchDec, dest, dOff, fastLen);
dOff += matchLen;
}
} while (dOff < decompressedLen);
return dOff;
}
private static void EncodeLen(int l, DataOutput @out)
{
while (l >= 0xFF)
{
@out.WriteByte(unchecked((byte)(sbyte)0xFF));
l -= 0xFF;
}
@out.WriteByte((byte)(sbyte)l);
}
private static void EncodeLiterals(byte[] bytes, int token, int anchor, int literalLen, DataOutput @out)
{
@out.WriteByte((byte)(sbyte)token);
// encode literal length
if (literalLen >= 0x0F)
{
EncodeLen(literalLen - 0x0F, @out);
}
// encode literals
@out.WriteBytes(bytes, anchor, literalLen);
}
private static void EncodeLastLiterals(byte[] bytes, int anchor, int literalLen, DataOutput @out)
{
int token = Math.Min(literalLen, 0x0F) << 4;
EncodeLiterals(bytes, token, anchor, literalLen, @out);
}
private static void EncodeSequence(byte[] bytes, int anchor, int matchRef, int matchOff, int matchLen, DataOutput @out)
{
int literalLen = matchOff - anchor;
if (Debugging.AssertsEnabled) Debugging.Assert(matchLen >= 4);
// encode token
int token = (Math.Min(literalLen, 0x0F) << 4) | Math.Min(matchLen - 4, 0x0F);
EncodeLiterals(bytes, token, anchor, literalLen, @out);
// encode match dec
int matchDec = matchOff - matchRef;
if (Debugging.AssertsEnabled) Debugging.Assert(matchDec > 0 && matchDec < 1 << 16);
@out.WriteByte((byte)(sbyte)matchDec);
@out.WriteByte((byte)(sbyte)((int)((uint)matchDec >> 8)));
// encode match len
if (matchLen >= MIN_MATCH + 0x0F)
{
EncodeLen(matchLen - 0x0F - MIN_MATCH, @out);
}
}
public sealed class HashTable
{
internal int hashLog;
internal PackedInt32s.Mutable hashTable;
internal void Reset(int len)
{
int bitsPerOffset = PackedInt32s.BitsRequired(len - LAST_LITERALS);
int bitsPerOffsetLog = 32 - (bitsPerOffset - 1).LeadingZeroCount();
hashLog = MEMORY_USAGE + 3 - bitsPerOffsetLog;
if (hashTable == null || hashTable.Count < 1 << hashLog || hashTable.BitsPerValue < bitsPerOffset)
{
hashTable = PackedInt32s.GetMutable(1 << hashLog, bitsPerOffset, PackedInt32s.DEFAULT);
}
else
{
hashTable.Clear();
}
}
}
/// <summary>
/// Compress <c>bytes[off:off+len]</c> into <paramref name="out"/> using
/// at most 16KB of memory. <paramref name="ht"/> shouldn't be shared across threads
/// but can safely be reused.
/// </summary>
public static void Compress(byte[] bytes, int off, int len, DataOutput @out, HashTable ht)
{
int @base = off;
int end = off + len;
int anchor = off++;
if (len > LAST_LITERALS + MIN_MATCH)
{
int limit = end - LAST_LITERALS;
int matchLimit = limit - MIN_MATCH;
ht.Reset(len);
int hashLog = ht.hashLog;
PackedInt32s.Mutable hashTable = ht.hashTable;
while (off <= limit)
{
// find a match
int @ref;
while (true)
{
if (off >= matchLimit)
{
goto mainBreak;
}
int v = ReadInt32(bytes, off);
int h = Hash(v, hashLog);
@ref = @base + (int)hashTable.Get(h);
if (Debugging.AssertsEnabled) Debugging.Assert(PackedInt32s.BitsRequired(off - @base) <= hashTable.BitsPerValue);
hashTable.Set(h, off - @base);
if (off - @ref < MAX_DISTANCE && ReadInt32(bytes, @ref) == v)
{
break;
}
++off;
}
// compute match length
int matchLen = MIN_MATCH + CommonBytes(bytes, @ref + MIN_MATCH, off + MIN_MATCH, limit);
EncodeSequence(bytes, anchor, @ref, off, matchLen, @out);
off += matchLen;
anchor = off;
//mainContinue: ; // LUCENENET NOTE: Not Referenced
}
mainBreak: ;
}
// last literals
int literalLen = end - anchor;
if (Debugging.AssertsEnabled) Debugging.Assert(literalLen >= LAST_LITERALS || literalLen == len);
EncodeLastLiterals(bytes, anchor, end - anchor, @out);
}
public class Match
{
internal int start, @ref, len;
internal virtual void Fix(int correction)
{
start += correction;
@ref += correction;
len -= correction;
}
internal virtual int End()
{
return start + len;
}
}
private static void CopyTo(Match m1, Match m2)
{
m2.len = m1.len;
m2.start = m1.start;
m2.@ref = m1.@ref;
}
public sealed class HCHashTable
{
internal const int MAX_ATTEMPTS = 256;
internal static readonly int MASK = MAX_DISTANCE - 1;
internal int nextToUpdate;
private int @base;
private readonly int[] hashTable;
private readonly short[] chainTable;
internal HCHashTable()
{
hashTable = new int[HASH_TABLE_SIZE_HC];
chainTable = new short[MAX_DISTANCE];
}
internal void Reset(int @base)
{
this.@base = @base;
nextToUpdate = @base;
Arrays.Fill(hashTable, -1);
Arrays.Fill(chainTable, (short)0);
}
private int HashPointer(byte[] bytes, int off)
{
int v = ReadInt32(bytes, off);
int h = HashHC(v);
return hashTable[h];
}
private int Next(int off)
{
return off - (chainTable[off & MASK] & 0xFFFF);
}
private void AddHash(byte[] bytes, int off)
{
int v = ReadInt32(bytes, off);
int h = HashHC(v);
int delta = off - hashTable[h];
if (Debugging.AssertsEnabled) Debugging.Assert(delta > 0, delta.ToString);
if (delta >= MAX_DISTANCE)
{
delta = MAX_DISTANCE - 1;
}
chainTable[off & MASK] = (short)delta;
hashTable[h] = off;
}
internal void Insert(int off, byte[] bytes)
{
for (; nextToUpdate < off; ++nextToUpdate)
{
AddHash(bytes, nextToUpdate);
}
}
internal bool InsertAndFindBestMatch(byte[] buf, int off, int matchLimit, Match match)
{
match.start = off;
match.len = 0;
int delta = 0;
int repl = 0;
Insert(off, buf);
int @ref = HashPointer(buf, off);
if (@ref >= off - 4 && @ref <= off && @ref >= @base) // potential repetition
{
if (ReadInt32Equals(buf, @ref, off)) // confirmed
{
delta = off - @ref;
repl = match.len = MIN_MATCH + CommonBytes(buf, @ref + MIN_MATCH, off + MIN_MATCH, matchLimit);
match.@ref = @ref;
}
@ref = Next(@ref);
}
for (int i = 0; i < MAX_ATTEMPTS; ++i)
{
if (@ref < Math.Max(@base, off - MAX_DISTANCE + 1) || @ref > off)
{
break;
}
if (buf[@ref + match.len] == buf[off + match.len] && ReadInt32Equals(buf, @ref, off))
{
int matchLen = MIN_MATCH + CommonBytes(buf, @ref + MIN_MATCH, off + MIN_MATCH, matchLimit);
if (matchLen > match.len)
{
match.@ref = @ref;
match.len = matchLen;
}
}
@ref = Next(@ref);
}
if (repl != 0)
{
int ptr = off;
int end = off + repl - (MIN_MATCH - 1);
while (ptr < end - delta)
{
chainTable[ptr & MASK] = (short)delta; // pre load
++ptr;
}
do
{
chainTable[ptr & MASK] = (short)delta;
hashTable[HashHC(ReadInt32(buf, ptr))] = ptr;
++ptr;
} while (ptr < end);
nextToUpdate = end;
}
return match.len != 0;
}
internal bool InsertAndFindWiderMatch(byte[] buf, int off, int startLimit, int matchLimit, int minLen, Match match)
{
match.len = minLen;
Insert(off, buf);
int delta = off - startLimit;
int @ref = HashPointer(buf, off);
for (int i = 0; i < MAX_ATTEMPTS; ++i)
{
if (@ref < Math.Max(@base, off - MAX_DISTANCE + 1) || @ref > off)
{
break;
}
if (buf[@ref - delta + match.len] == buf[startLimit + match.len] && ReadInt32Equals(buf, @ref, off))
{
int matchLenForward = MIN_MATCH + CommonBytes(buf, @ref + MIN_MATCH, off + MIN_MATCH, matchLimit);
int matchLenBackward = CommonBytesBackward(buf, @ref, off, @base, startLimit);
int matchLen = matchLenBackward + matchLenForward;
if (matchLen > match.len)
{
match.len = matchLen;
match.@ref = @ref - matchLenBackward;
match.start = off - matchLenBackward;
}
}
@ref = Next(@ref);
}
return match.len > minLen;
}
}
/// <summary>
/// Compress <c>bytes[off:off+len]</c> into <paramref name="out"/>. Compared to
/// <see cref="LZ4.Compress(byte[], int, int, DataOutput, HashTable)"/>, this method
/// is slower and uses more memory (~ 256KB per thread) but should provide
/// better compression ratios (especially on large inputs) because it chooses
/// the best match among up to 256 candidates and then performs trade-offs to
/// fix overlapping matches. <paramref name="ht"/> shouldn't be shared across threads
/// but can safely be reused.
/// </summary>
public static void CompressHC(byte[] src, int srcOff, int srcLen, DataOutput @out, HCHashTable ht)
{
int srcEnd = srcOff + srcLen;
int matchLimit = srcEnd - LAST_LITERALS;
int mfLimit = matchLimit - MIN_MATCH;
int sOff = srcOff;
int anchor = sOff++;
ht.Reset(srcOff);
Match match0 = new Match();
Match match1 = new Match();
Match match2 = new Match();
Match match3 = new Match();
while (sOff <= mfLimit)
{
if (!ht.InsertAndFindBestMatch(src, sOff, matchLimit, match1))
{
++sOff;
continue;
}
// saved, in case we would skip too much
CopyTo(match1, match0);
while (true)
{
if (Debugging.AssertsEnabled) Debugging.Assert(match1.start >= anchor);
if (match1.End() >= mfLimit || !ht.InsertAndFindWiderMatch(src, match1.End() - 2, match1.start + 1, matchLimit, match1.len, match2))
{
// no better match
EncodeSequence(src, anchor, match1.@ref, match1.start, match1.len, @out);
anchor = sOff = match1.End();
goto mainContinue;
}
if (match0.start < match1.start)
{
if (match2.start < match1.start + match0.len) // empirical
{
CopyTo(match0, match1);
}
}
if (Debugging.AssertsEnabled) Debugging.Assert(match2.start > match1.start);
if (match2.start - match1.start < 3) // First Match too small : removed
{
CopyTo(match2, match1);
goto search2Continue;
}
while (true)
{
if (match2.start - match1.start < OPTIMAL_ML)
{
int newMatchLen = match1.len;
if (newMatchLen > OPTIMAL_ML)
{
newMatchLen = OPTIMAL_ML;
}
if (match1.start + newMatchLen > match2.End() - MIN_MATCH)
{
newMatchLen = match2.start - match1.start + match2.len - MIN_MATCH;
}
int correction = newMatchLen - (match2.start - match1.start);
if (correction > 0)
{
match2.Fix(correction);
}
}
if (match2.start + match2.len >= mfLimit || !ht.InsertAndFindWiderMatch(src, match2.End() - 3, match2.start, matchLimit, match2.len, match3))
{
// no better match -> 2 sequences to encode
if (match2.start < match1.End())
{
match1.len = match2.start - match1.start;
}
// encode seq 1
EncodeSequence(src, anchor, match1.@ref, match1.start, match1.len, @out);
anchor = sOff = match1.End();
// encode seq 2
EncodeSequence(src, anchor, match2.@ref, match2.start, match2.len, @out);
anchor = sOff = match2.End();
goto mainContinue;
}
if (match3.start < match1.End() + 3) // Not enough space for match 2 : remove it
{
if (match3.start >= match1.End()) // // can write Seq1 immediately ==> Seq2 is removed, so Seq3 becomes Seq1
{
if (match2.start < match1.End())
{
int correction = match1.End() - match2.start;
match2.Fix(correction);
if (match2.len < MIN_MATCH)
{
CopyTo(match3, match2);
}
}
EncodeSequence(src, anchor, match1.@ref, match1.start, match1.len, @out);
anchor = sOff = match1.End();
CopyTo(match3, match1);
CopyTo(match2, match0);
goto search2Continue;
}
CopyTo(match3, match2);
goto search3Continue;
}
// OK, now we have 3 ascending matches; let's write at least the first one
if (match2.start < match1.End())
{
if (match2.start - match1.start < 0x0F)
{
if (match1.len > OPTIMAL_ML)
{
match1.len = OPTIMAL_ML;
}
if (match1.End() > match2.End() - MIN_MATCH)
{
match1.len = match2.End() - match1.start - MIN_MATCH;
}
int correction = match1.End() - match2.start;
match2.Fix(correction);
}
else
{
match1.len = match2.start - match1.start;
}
}
EncodeSequence(src, anchor, match1.@ref, match1.start, match1.len, @out);
anchor = sOff = match1.End();
CopyTo(match2, match1);
CopyTo(match3, match2);
goto search3Continue;
search3Continue: ;
}
//search3Break: ; // LUCENENET NOTE: Unreachable
search2Continue: ;
}
//search2Break: ; // LUCENENET NOTE: Not referenced
mainContinue: ;
}
//mainBreak: // LUCENENET NOTE: Not referenced
EncodeLastLiterals(src, anchor, srcEnd - anchor, @out);
}
}
}
| |
///////////////////////////////////////////////////////////////////
// Ported to C# by Martin Kraner <martinkraner@outlook.com> //
// from https://code.google.com/p/language-detection/ //
///////////////////////////////////////////////////////////////////
using System.Collections.Generic;
using Frost.SharpLanguageDetect.JDK;
using Frost.SharpLanguageDetect.Properties;
using StringBuilder = System.Text.StringBuilder;
namespace Frost.SharpLanguageDetect.Util {
/**
*
* Users don't use this class directly.
* @author Nakatani Shuyo
*/
public class NGram {
public const int N_GRAM = 3;
private static readonly string Latin1Excluded = Resources.NGram_LATIN1_EXCLUDE;
private static readonly Dictionary<char, char> CjkMap = new Dictionary<char, char>();
private bool _capitalword;
private StringBuilder _grams;
static NGram() {
foreach (string cjkList in CjkClass) {
char representative = cjkList[0];
foreach (char ch in cjkList) {
CjkMap.Add(ch, representative);
}
}
}
/**
*
*/
public NGram() {
_grams = new StringBuilder(" ");
_capitalword = false;
}
/**
* @param ch
*/
public void AddChar(char ch) {
ch = Normalize(ch);
char lastchar = _grams[_grams.Length - 1];
if (lastchar == ' ') {
_grams = new StringBuilder(" ");
_capitalword = false;
if (ch == ' ') {
return;
}
}
else if (_grams.Length >= N_GRAM) {
_grams.Remove(0, 1);
}
_grams.Append(ch);
if (char.IsUpper(ch)) {
if (char.IsUpper(lastchar)) {
_capitalword = true;
}
}
else {
_capitalword = false;
}
}
/**
* Get n-Gram
* @param n length of n-gram
* @return n-Gram string (null if it is invalid)
*/
public string this[int n] {
get {
if (_capitalword) {
return null;
}
int len = _grams.Length;
if (n < 1 || n > 3 || len < n) {
return null;
}
if (n == 1) {
char ch = _grams[len - 1];
return (ch == ' ')
? null
: char.ToString(ch);
}
return _grams.ToString().Substring(len - n, n);
}
}
/**
* char Normalization
* @param ch
* @return Normalized character
*/
public static char Normalize(char ch) {
UnicodeBlock block = UnicodeBlock.Of(ch);
//comparing by-ref is ok
if (block == UnicodeBlock.BASIC_LATIN) {
if (ch < 'A' || (ch < 'a' && ch > 'Z') || ch > 'z') {
ch = ' ';
}
}
else if (block == UnicodeBlock.LATIN_1_SUPPLEMENT) {
if (Latin1Excluded.IndexOf(ch) >= 0) {
ch = ' ';
}
}
else if (block == UnicodeBlock.GENERAL_PUNCTUATION) {
ch = ' ';
}
else if (block == UnicodeBlock.ARABIC) {
if (ch == '\u06cc') {
ch = '\u064a';
}
}
else if (block == UnicodeBlock.LATIN_EXTENDED_ADDITIONAL) {
if (ch >= '\u1ea0') {
ch = '\u1ec3';
}
}
else if (block == UnicodeBlock.HIRAGANA) {
ch = '\u3042';
}
else if (block == UnicodeBlock.KATAKANA) {
ch = '\u30a2';
}
else if (block == UnicodeBlock.BOPOMOFO || block == UnicodeBlock.BOPOMOFO_EXTENDED) {
ch = '\u3105';
}
else if (block == UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS) {
if (CjkMap.ContainsKey(ch)) {
ch = CjkMap[ch];
}
}
else if (block == UnicodeBlock.HANGUL_SYLLABLES) {
ch = '\uac00';
}
return ch;
}
#region CJK CJK Kanji Normalization Mapping
/**
* CJK Kanji Normalization Mapping
*/
private static readonly string[] CjkClass = {
Resources.NGram_KANJI_1_0,
Resources.NGram_KANJI_1_2,
Resources.NGram_KANJI_1_4,
Resources.NGram_KANJI_1_8,
Resources.NGram_KANJI_1_11,
Resources.NGram_KANJI_1_12,
Resources.NGram_KANJI_1_13,
Resources.NGram_KANJI_1_14,
Resources.NGram_KANJI_1_16,
Resources.NGram_KANJI_1_18,
Resources.NGram_KANJI_1_22,
Resources.NGram_KANJI_1_27,
Resources.NGram_KANJI_1_29,
Resources.NGram_KANJI_1_31,
Resources.NGram_KANJI_1_35,
Resources.NGram_KANJI_2_0,
Resources.NGram_KANJI_2_1,
Resources.NGram_KANJI_2_4,
Resources.NGram_KANJI_2_9,
Resources.NGram_KANJI_2_10,
Resources.NGram_KANJI_2_11,
Resources.NGram_KANJI_2_12,
Resources.NGram_KANJI_2_13,
Resources.NGram_KANJI_2_15,
Resources.NGram_KANJI_2_16,
Resources.NGram_KANJI_2_18,
Resources.NGram_KANJI_2_21,
Resources.NGram_KANJI_2_22,
Resources.NGram_KANJI_2_23,
Resources.NGram_KANJI_2_28,
Resources.NGram_KANJI_2_29,
Resources.NGram_KANJI_2_30,
Resources.NGram_KANJI_2_31,
Resources.NGram_KANJI_2_32,
Resources.NGram_KANJI_2_35,
Resources.NGram_KANJI_2_36,
Resources.NGram_KANJI_2_37,
Resources.NGram_KANJI_2_38,
Resources.NGram_KANJI_3_1,
Resources.NGram_KANJI_3_2,
Resources.NGram_KANJI_3_3,
Resources.NGram_KANJI_3_4,
Resources.NGram_KANJI_3_5,
Resources.NGram_KANJI_3_8,
Resources.NGram_KANJI_3_9,
Resources.NGram_KANJI_3_11,
Resources.NGram_KANJI_3_12,
Resources.NGram_KANJI_3_13,
Resources.NGram_KANJI_3_15,
Resources.NGram_KANJI_3_16,
Resources.NGram_KANJI_3_18,
Resources.NGram_KANJI_3_19,
Resources.NGram_KANJI_3_22,
Resources.NGram_KANJI_3_23,
Resources.NGram_KANJI_3_27,
Resources.NGram_KANJI_3_29,
Resources.NGram_KANJI_3_30,
Resources.NGram_KANJI_3_31,
Resources.NGram_KANJI_3_32,
Resources.NGram_KANJI_3_35,
Resources.NGram_KANJI_3_36,
Resources.NGram_KANJI_3_37,
Resources.NGram_KANJI_3_38,
Resources.NGram_KANJI_4_0,
Resources.NGram_KANJI_4_9,
Resources.NGram_KANJI_4_10,
Resources.NGram_KANJI_4_16,
Resources.NGram_KANJI_4_17,
Resources.NGram_KANJI_4_18,
Resources.NGram_KANJI_4_22,
Resources.NGram_KANJI_4_24,
Resources.NGram_KANJI_4_28,
Resources.NGram_KANJI_4_34,
Resources.NGram_KANJI_4_39,
Resources.NGram_KANJI_5_10,
Resources.NGram_KANJI_5_11,
Resources.NGram_KANJI_5_12,
Resources.NGram_KANJI_5_13,
Resources.NGram_KANJI_5_14,
Resources.NGram_KANJI_5_18,
Resources.NGram_KANJI_5_26,
Resources.NGram_KANJI_5_29,
Resources.NGram_KANJI_5_34,
Resources.NGram_KANJI_5_39,
Resources.NGram_KANJI_6_0,
Resources.NGram_KANJI_6_3,
Resources.NGram_KANJI_6_9,
Resources.NGram_KANJI_6_10,
Resources.NGram_KANJI_6_11,
Resources.NGram_KANJI_6_12,
Resources.NGram_KANJI_6_16,
Resources.NGram_KANJI_6_18,
Resources.NGram_KANJI_6_20,
Resources.NGram_KANJI_6_21,
Resources.NGram_KANJI_6_22,
Resources.NGram_KANJI_6_23,
Resources.NGram_KANJI_6_25,
Resources.NGram_KANJI_6_28,
Resources.NGram_KANJI_6_29,
Resources.NGram_KANJI_6_30,
Resources.NGram_KANJI_6_32,
Resources.NGram_KANJI_6_34,
Resources.NGram_KANJI_6_35,
Resources.NGram_KANJI_6_37,
Resources.NGram_KANJI_6_39,
Resources.NGram_KANJI_7_0,
Resources.NGram_KANJI_7_3,
Resources.NGram_KANJI_7_6,
Resources.NGram_KANJI_7_7,
Resources.NGram_KANJI_7_9,
Resources.NGram_KANJI_7_11,
Resources.NGram_KANJI_7_12,
Resources.NGram_KANJI_7_13,
Resources.NGram_KANJI_7_16,
Resources.NGram_KANJI_7_18,
Resources.NGram_KANJI_7_19,
Resources.NGram_KANJI_7_20,
Resources.NGram_KANJI_7_21,
Resources.NGram_KANJI_7_23,
Resources.NGram_KANJI_7_25,
Resources.NGram_KANJI_7_28,
Resources.NGram_KANJI_7_29,
Resources.NGram_KANJI_7_32,
Resources.NGram_KANJI_7_33,
Resources.NGram_KANJI_7_35,
Resources.NGram_KANJI_7_37,
};
#endregion
}
}
| |
////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011-2016 by Rob Jellinghaus. //
// All Rights Reserved. //
////////////////////////////////////////////////////////////////////////
using System;
using System.Diagnostics;
namespace Holofunk.Core
{
/// <summary>
/// Sample identifies Times based on audio sample counts.
/// </summary>
public class Sample
{
}
/// <summary>
/// Frame identifies Times based on video frame counts.
/// </summary>
public class Frame
{
}
/// <summary>
/// Time parameterized on some underlying measurement.
/// </summary>
public struct Time<TTime>
{
readonly long m_time;
public Time(long time)
{
m_time = time;
}
public override string ToString()
{
return "T[" + (long)this + "]";
}
public static Time<TTime> Min(Time<TTime> first, Time<TTime> second)
{
return new Time<TTime>(Math.Min(first, second));
}
public static Time<TTime> Max(Time<TTime> first, Time<TTime> second)
{
return new Time<TTime>(Math.Max(first, second));
}
public static implicit operator long(Time<TTime> time)
{
return time.m_time;
}
public static implicit operator Time<TTime>(long time)
{
return new Time<TTime>(time);
}
public static bool operator <(Time<TTime> first, Time<TTime> second)
{
return (long)first < (long)second;
}
public static bool operator >(Time<TTime> first, Time<TTime> second)
{
return (long)first > (long)second;
}
public static bool operator ==(Time<TTime> first, Time<TTime> second)
{
return (long)first == (long)second;
}
public override bool Equals(object obj)
{
return obj is Time<TTime>
&& ((Time<TTime>)obj) == this;
}
public override int GetHashCode()
{
return (int)m_time;
}
public static bool operator !=(Time<TTime> first, Time<TTime> second)
{
return (long)first != (long)second;
}
public static bool operator <=(Time<TTime> first, Time<TTime> second)
{
return (long)first <= (long)second;
}
public static bool operator >=(Time<TTime> first, Time<TTime> second)
{
return (long)first >= (long)second;
}
public static Duration<TTime> operator -(Time<TTime> first, Time<TTime> second)
{
return new Duration<TTime>((long)first - (long)second);
}
public static Time<TTime> operator -(Time<TTime> first, Duration<TTime> second)
{
return new Time<TTime>((long)first - (long)second);
}
}
/// <summary>
/// A distance between two Times.
/// </summary>
/// <typeparam name="TTime"></typeparam>
public struct Duration<TTime>
{
readonly long m_count;
public Duration(long count)
{
HoloDebug.Assert(count >= 0);
m_count = count;
}
public override string ToString()
{
return "D[" + (long)this + "]";
}
public static implicit operator long(Duration<TTime> offset)
{
return offset.m_count;
}
public static implicit operator Duration<TTime>(long value)
{
return new Duration<TTime>(value);
}
public static Duration<TTime> Min(Duration<TTime> first, Duration<TTime> second)
{
return new Duration<TTime>(Math.Min(first, second));
}
public static Duration<TTime> operator +(Duration<TTime> first, Duration<TTime> second)
{
return new Duration<TTime>((long)first + (long)second);
}
public static Duration<TTime> operator -(Duration<TTime> first, Duration<TTime> second)
{
return new Duration<TTime>((long)first - (long)second);
}
public static Duration<TTime> operator /(Duration<TTime> first, int second)
{
return new Duration<TTime>((long)first / second);
}
public static bool operator <(Duration<TTime> first, Duration<TTime> second)
{
return (long)first < (long)second;
}
public static bool operator >(Duration<TTime> first, Duration<TTime> second)
{
return (long)first > (long)second;
}
public static bool operator <=(Duration<TTime> first, Duration<TTime> second)
{
return (long)first <= (long)second;
}
public static bool operator >=(Duration<TTime> first, Duration<TTime> second)
{
return (long)first >= (long)second;
}
public static bool operator ==(Duration<TTime> first, Duration<TTime> second)
{
return (long)first == (long)second;
}
public static bool operator !=(Duration<TTime> first, Duration<TTime> second)
{
return (long)first != (long)second;
}
public static Time<TTime> operator +(Time<TTime> first, Duration<TTime> second)
{
return new Time<TTime>((long)first + (long)second);
}
public override bool Equals(object obj)
{
return obj is Duration<TTime>
&& ((Duration<TTime>)obj) == this;
}
public override int GetHashCode()
{
return (int)m_count;
}
}
/// <summary>
/// An interval, defined as a start time and a duration (aka length).
/// </summary>
/// <remarks>
/// Empty intervals semantically have no InitialTime, and no distinction should be made between empty
/// intervals based on InitialTime.</remarks>
/// <typeparam name="TTime"></typeparam>
public struct Interval<TTime>
{
public readonly Time<TTime> InitialTime;
public readonly Duration<TTime> Duration;
readonly bool m_isInitialized;
public Interval(Time<TTime> initialTime, Duration<TTime> duration)
{
HoloDebug.Assert(duration >= 0);
InitialTime = initialTime;
Duration = duration;
m_isInitialized = true;
}
public override string ToString()
{
return "I[" + InitialTime + ", " + Duration + "]";
}
public static Interval<TTime> Empty { get { return new Interval<TTime>(0, 0); } }
public bool IsInitialized { get { return m_isInitialized; } }
public bool IsEmpty
{
get { return Duration == 0; }
}
public Interval<TTime> SubintervalStartingAt(Duration<TTime> offset)
{
Debug.Assert(offset <= Duration);
return new Interval<TTime>(InitialTime + offset, Duration - offset);
}
public Interval<TTime> SubintervalOfDuration(Duration<TTime> duration)
{
Debug.Assert(duration <= Duration);
return new Interval<TTime>(InitialTime, duration);
}
public Interval<TTime> Intersect(Interval<TTime> other)
{
Time<TTime> intersectionStart = Time<TTime>.Max(InitialTime, other.InitialTime);
Time<TTime> intersectionEnd = Time<TTime>.Min(InitialTime + Duration, other.InitialTime + other.Duration);
if (intersectionEnd < intersectionStart) {
return Interval<TTime>.Empty;
}
else {
return new Interval<TTime>(intersectionStart, intersectionEnd - intersectionStart);
}
}
public bool Contains(Time<TTime> time)
{
if (IsEmpty) {
return false;
}
return InitialTime <= time
&& (InitialTime + Duration) > time;
}
}
}
| |
// 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 ExtendToVector256Int32()
{
var test = new GenericUnaryOpTest__ExtendToVector256Int32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class GenericUnaryOpTest__ExtendToVector256Int32
{
private struct TestStruct
{
public Vector128<Int32> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(GenericUnaryOpTest__ExtendToVector256Int32 testClass)
{
var result = Avx.ExtendToVector256<Int32>(_fld);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static Int32[] _data = new Int32[Op1ElementCount];
private static Vector128<Int32> _clsVar;
private Vector128<Int32> _fld;
private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable;
static GenericUnaryOpTest__ExtendToVector256Int32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public GenericUnaryOpTest__ExtendToVector256Int32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.ExtendToVector256<Int32>(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.ExtendToVector256<Int32>(
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.ExtendToVector256<Int32>(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.ExtendToVector256))
.MakeGenericMethod( new Type[] { typeof(Int32) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.ExtendToVector256))
.MakeGenericMethod( new Type[] { typeof(Int32) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.ExtendToVector256))
.MakeGenericMethod( new Type[] { typeof(Int32) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.ExtendToVector256<Int32>(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr);
var result = Avx.ExtendToVector256<Int32>(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr));
var result = Avx.ExtendToVector256<Int32>(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr));
var result = Avx.ExtendToVector256<Int32>(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new GenericUnaryOpTest__ExtendToVector256Int32();
var result = Avx.ExtendToVector256<Int32>(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.ExtendToVector256<Int32>(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.ExtendToVector256(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int32> firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
if (firstOp[0] != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((i < (RetElementCount / 2)) ? firstOp[i] : 0))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.ExtendToVector256)}<Int32>(Vector128<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.Drawing;
namespace fyiReporting.RDL
{
///<summary>
/// Pie chart definition and processing.
///</summary>
internal class ChartPie: ChartBase
{
internal ChartPie(Report r, Row row, Chart c, MatrixCellEntry[,] m, Expression showTooltips, Expression showTooltipsX,Expression _ToolTipYFormat, Expression _ToolTipXFormat)
: base(r, row, c, m, showTooltips, showTooltipsX, _ToolTipYFormat, _ToolTipXFormat)
{
}
override internal void Draw(Report rpt)
{
CreateSizedBitmap();
using (Graphics g1 = Graphics.FromImage(_bm))
{
_aStream = new System.IO.MemoryStream();
IntPtr HDC = g1.GetHdc();
_mf = new System.Drawing.Imaging.Metafile(_aStream, HDC, new RectangleF(0, 0, _bm.Width, _bm.Height), System.Drawing.Imaging.MetafileFrameUnit.Pixel);
g1.ReleaseHdc(HDC);
}
using (Graphics g = Graphics.FromImage(_mf))
{
// 06122007AJM Used to Force Higher Quality
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
// Adjust the top margin to depend on the title height
Size titleSize = DrawTitleMeasure(rpt, g, ChartDefn.Title);
Layout.TopMargin = titleSize.Height;
DrawChartStyle(rpt, g);
// Draw title; routine determines if necessary
DrawTitle(rpt, g, ChartDefn.Title, new System.Drawing.Rectangle(0, 0, _bm.Width, Layout.TopMargin));
// Draw legend
System.Drawing.Rectangle lRect = DrawLegend(rpt, g, false, true);
// Adjust the bottom margin to depend on the Category Axis
Size caSize = CategoryAxisSize(rpt, g);
Layout.BottomMargin = caSize.Height;
// 20022008 AJM GJL - Added required info
AdjustMargins(lRect,rpt,g); // Adjust margins based on legend.
// Draw Plot area
DrawPlotAreaStyle(rpt, g, lRect);
// Draw Category Axis
if (caSize.Height > 0)
DrawCategoryAxis(rpt, g,
new System.Drawing.Rectangle(Layout.LeftMargin, _bm.Height-Layout.BottomMargin, _bm.Width - Layout.LeftMargin - Layout.RightMargin, caSize.Height));
if (ChartDefn.Type == ChartTypeEnum.Doughnut)
DrawPlotAreaDoughnut(rpt, g);
else
DrawPlotAreaPie(rpt, g);
DrawLegend(rpt, g, false, false);
}
}
void DrawPlotAreaDoughnut(Report rpt, Graphics g)
{
// Draw Plot area data
int widthPie = Layout.PlotArea.Width;
int maxHeight = Layout.PlotArea.Height;
int maxPieSize = Math.Min(widthPie, maxHeight);
int doughWidth = maxPieSize / 4 / CategoryCount;
if (doughWidth < 2)
doughWidth = 2; // enforce minimum width
float startAngle;
float endAngle;
int pieLocX;
int pieLocY;
int pieSize;
// Go and draw the pies
int left = Layout.PlotArea.Left + (maxPieSize == widthPie? 0: (widthPie - maxPieSize) / 2);
int top = Layout.PlotArea.Top + (maxPieSize == maxHeight? 0: (maxHeight - maxPieSize) / 2);
for (int iRow=1; iRow <= CategoryCount; iRow++)
{
pieLocX= left + ((iRow-1) * doughWidth);
pieLocY= top + ((iRow-1) * doughWidth);
double total=0; // sum up for this category
for (int iCol=1; iCol <= SeriesCount; iCol++)
{
total += this.GetDataValue(rpt, iRow, iCol);
}
// Pie size decreases as we go in
startAngle=0.0f;
pieSize = maxPieSize - ((iRow - 1) * doughWidth * 2);
for (int iCol=1; iCol <= SeriesCount; iCol++)
{
double v = this.GetDataValue(rpt, iRow, iCol);
endAngle = (float) (startAngle + v / total * 360);
DrawPie(g, rpt, GetSeriesBrush(rpt, iRow, iCol),
new System.Drawing.Rectangle(pieLocX, pieLocY, pieSize, pieSize), iRow, iCol, startAngle, endAngle);
startAngle = endAngle;
}
}
// Now draw the center hole with the plot area style
if (ChartDefn.PlotArea == null || ChartDefn.PlotArea.Style == null)
return;
pieLocX= left + (CategoryCount * doughWidth);
pieLocY= top + (CategoryCount * doughWidth);
pieSize = maxPieSize - (CategoryCount * doughWidth * 2);
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(pieLocX, pieLocY, pieSize, pieSize);
Style s = ChartDefn.PlotArea.Style;
Rows cData = ChartDefn.ChartMatrix.GetMyData(rpt);
Row r = cData.Data[0];
s.DrawBackgroundCircle(rpt, g, r, rect);
}
void DrawPlotAreaPie(Report rpt, Graphics g)
{
int piesNeeded = CategoryCount;
int gapsNeeded = CategoryCount + 1;
int gapSize=13;
// Draw Plot area data
int widthPie = (int) ((Layout.PlotArea.Width - gapsNeeded*gapSize) / piesNeeded);
int maxHeight = (int) (Layout.PlotArea.Height);
int maxPieSize = Math.Min(widthPie, maxHeight);
int pieLocY = Layout.PlotArea.Top + (maxHeight - maxPieSize) / 2;
float startAngle;
float endAngle;
// calculate the size of the largest category
// all pie sizes will be relative to that maximum
double maxCategory=0;
for (int iRow=1; iRow <= CategoryCount; iRow++)
{
double total=0;
for (int iCol=1; iCol <= SeriesCount; iCol++)
{
total += this.GetDataValue(rpt, iRow, iCol);
}
if (total > maxCategory)
maxCategory = total;
}
// Go and draw the pies
for (int iRow=1; iRow <= CategoryCount; iRow++)
{
int pieLocX=(int) (Layout.PlotArea.Left + (iRow-1) * ((double) (Layout.PlotArea.Width) / CategoryCount));
pieLocX += gapSize; // space before series
double total=0;
for (int iCol=1; iCol <= SeriesCount; iCol++)
{
total += this.GetDataValue(rpt, iRow, iCol);
}
// Pie size is a ratio of the area of the pies (not the diameter)
startAngle=0.0f;
int pieSize = (int) (2 * Math.Sqrt(Math.PI * ((maxPieSize/2) * (maxPieSize/2) * total/maxCategory) / Math.PI));
for (int iCol=1; iCol <= SeriesCount; iCol++)
{
double v = this.GetDataValue(rpt, iRow, iCol);
endAngle = (float) (startAngle + v / total * 360);
DrawPie(g, rpt, GetSeriesBrush(rpt, iRow, iCol),
new System.Drawing.Rectangle(pieLocX, pieLocY, pieSize, pieSize), iRow, iCol, startAngle, endAngle);
startAngle = endAngle;
}
}
}
// Calculate the size of the category axis
protected Size CategoryAxisSize(Report rpt, Graphics g)
{
Size size=Size.Empty;
if (this.ChartDefn.CategoryAxis == null ||
this.ChartDefn.Type == ChartTypeEnum.Doughnut) // doughnut doesn't get this
return size;
Axis a = this.ChartDefn.CategoryAxis.Axis;
if (a == null)
return size;
Style s = a.Style;
// Measure the title
size = DrawTitleMeasure(rpt, g, a.Title);
if (!a.Visible) // don't need to calculate the height
return size;
// Calculate the tallest category name
TypeCode tc;
int maxHeight=0;
for (int iRow=1; iRow <= CategoryCount; iRow++)
{
object v = this.GetCategoryValue(rpt, iRow, out tc);
Size tSize;
if (s == null)
tSize = Style.MeasureStringDefaults(rpt, g, v, tc, null, int.MaxValue);
else
tSize =s.MeasureString(rpt, g, v, tc, null, int.MaxValue);
if (tSize.Height > maxHeight)
maxHeight = tSize.Height;
}
// Add on the tallest category name
size.Height += maxHeight;
return size;
}
// DrawCategoryAxis
protected void DrawCategoryAxis(Report rpt, Graphics g, System.Drawing.Rectangle rect)
{
if (this.ChartDefn.CategoryAxis == null)
return;
Axis a = this.ChartDefn.CategoryAxis.Axis;
if (a == null)
return;
Style s = a.Style;
Size tSize = DrawTitleMeasure(rpt, g, a.Title);
DrawTitle(rpt, g, a.Title, new System.Drawing.Rectangle(rect.Left, rect.Bottom-tSize.Height, rect.Width, tSize.Height));
int drawWidth = rect.Width / CategoryCount;
TypeCode tc;
for (int iRow=1; iRow <= CategoryCount; iRow++)
{
object v = this.GetCategoryValue(rpt, iRow, out tc);
int drawLoc=(int) (rect.Left + (iRow-1) * ((double) rect.Width / CategoryCount));
// Draw the category text
if (a.Visible)
{
System.Drawing.Rectangle drawRect = new System.Drawing.Rectangle(drawLoc, rect.Top, drawWidth, rect.Height-tSize.Height);
if (s == null)
Style.DrawStringDefaults(g, v, drawRect);
else
s.DrawString(rpt, g, v, tc, null, drawRect);
}
}
return;
}
void DrawPie(Graphics g, Report rpt, Brush brush, System.Drawing.Rectangle rect, int iRow, int iCol, float startAngle, float endAngle)
{
if ((ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.Exploded)
{
// Need to adjust the rectangle
int side = (int) (rect.Width * .75); // side needs to be smaller to account for exploded pies
int offset = (int) (side * .1); // we add a little to the left and top
int adjX, adjY;
adjX = adjY = (int) (side * .1);
float midAngle = startAngle + (endAngle - startAngle)/2;
if (midAngle < 90)
{
}
else if (midAngle < 180)
{
adjX = -adjX;
}
else if (midAngle < 270)
{
adjX = adjY = -adjX;
}
else
{
adjY = - adjY;
}
rect = new System.Drawing.Rectangle(rect.Left + adjX + offset, rect.Top + adjY + offset, side, side);
}
g.FillPie(brush, rect, startAngle, endAngle - startAngle);
g.DrawPie(Pens.Black, rect, startAngle, endAngle - startAngle);
return;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management;
using Microsoft.WindowsAzure.Management.Models;
namespace Microsoft.WindowsAzure.Management
{
/// <summary>
/// You can use management certificates, which are also known as
/// subscription certificates, to authenticate clients attempting to
/// connect to resources associated with your Azure subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj154124.aspx for
/// more information)
/// </summary>
internal partial class ManagementCertificateOperations : IServiceOperations<ManagementClient>, IManagementCertificateOperations
{
/// <summary>
/// Initializes a new instance of the ManagementCertificateOperations
/// class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ManagementCertificateOperations(ManagementClient client)
{
this._client = client;
}
private ManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.ManagementClient.
/// </summary>
public ManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// The Create Management Certificate operation adds a certificate to
/// the list of management certificates. Management certificates,
/// which are also known as subscription certificates, authenticate
/// clients attempting to connect to resources associated with your
/// Azure subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj154123.aspx
/// for more information)
/// </summary>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Management Certificate
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> CreateAsync(ManagementCertificateCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/certificates";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement subscriptionCertificateElement = new XElement(XName.Get("SubscriptionCertificate", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(subscriptionCertificateElement);
if (parameters.PublicKey != null)
{
XElement subscriptionCertificatePublicKeyElement = new XElement(XName.Get("SubscriptionCertificatePublicKey", "http://schemas.microsoft.com/windowsazure"));
subscriptionCertificatePublicKeyElement.Value = Convert.ToBase64String(parameters.PublicKey);
subscriptionCertificateElement.Add(subscriptionCertificatePublicKeyElement);
}
if (parameters.Thumbprint != null)
{
XElement subscriptionCertificateThumbprintElement = new XElement(XName.Get("SubscriptionCertificateThumbprint", "http://schemas.microsoft.com/windowsazure"));
subscriptionCertificateThumbprintElement.Value = parameters.Thumbprint;
subscriptionCertificateElement.Add(subscriptionCertificateThumbprintElement);
}
if (parameters.Data != null)
{
XElement subscriptionCertificateDataElement = new XElement(XName.Get("SubscriptionCertificateData", "http://schemas.microsoft.com/windowsazure"));
subscriptionCertificateDataElement.Value = Convert.ToBase64String(parameters.Data);
subscriptionCertificateElement.Add(subscriptionCertificateDataElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Delete Management Certificate operation deletes a certificate
/// from the list of management certificates. Management certificates,
/// which are also known as subscription certificates, authenticate
/// clients attempting to connect to resources associated with your
/// Azure subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj154127.aspx
/// for more information)
/// </summary>
/// <param name='thumbprint'>
/// Required. The thumbprint value of the certificate to delete.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string thumbprint, CancellationToken cancellationToken)
{
// Validate
if (thumbprint == null)
{
throw new ArgumentNullException("thumbprint");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("thumbprint", thumbprint);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/certificates/";
url = url + Uri.EscapeDataString(thumbprint);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NotFound)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Get Management Certificate operation retrieves information
/// about the management certificate with the specified thumbprint.
/// Management certificates, which are also known as subscription
/// certificates, authenticate clients attempting to connect to
/// resources associated with your Azure subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj154131.aspx
/// for more information)
/// </summary>
/// <param name='thumbprint'>
/// Required. The thumbprint value of the certificate to retrieve
/// information about.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get Management Certificate operation response.
/// </returns>
public async Task<ManagementCertificateGetResponse> GetAsync(string thumbprint, CancellationToken cancellationToken)
{
// Validate
if (thumbprint == null)
{
throw new ArgumentNullException("thumbprint");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("thumbprint", thumbprint);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/certificates/";
url = url + Uri.EscapeDataString(thumbprint);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ManagementCertificateGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ManagementCertificateGetResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement subscriptionCertificateElement = responseDoc.Element(XName.Get("SubscriptionCertificate", "http://schemas.microsoft.com/windowsazure"));
if (subscriptionCertificateElement != null)
{
XElement subscriptionCertificatePublicKeyElement = subscriptionCertificateElement.Element(XName.Get("SubscriptionCertificatePublicKey", "http://schemas.microsoft.com/windowsazure"));
if (subscriptionCertificatePublicKeyElement != null)
{
byte[] subscriptionCertificatePublicKeyInstance = Convert.FromBase64String(subscriptionCertificatePublicKeyElement.Value);
result.PublicKey = subscriptionCertificatePublicKeyInstance;
}
XElement subscriptionCertificateThumbprintElement = subscriptionCertificateElement.Element(XName.Get("SubscriptionCertificateThumbprint", "http://schemas.microsoft.com/windowsazure"));
if (subscriptionCertificateThumbprintElement != null)
{
string subscriptionCertificateThumbprintInstance = subscriptionCertificateThumbprintElement.Value;
result.Thumbprint = subscriptionCertificateThumbprintInstance;
}
XElement subscriptionCertificateDataElement = subscriptionCertificateElement.Element(XName.Get("SubscriptionCertificateData", "http://schemas.microsoft.com/windowsazure"));
if (subscriptionCertificateDataElement != null)
{
byte[] subscriptionCertificateDataInstance = Convert.FromBase64String(subscriptionCertificateDataElement.Value);
result.Data = subscriptionCertificateDataInstance;
}
XElement createdElement = subscriptionCertificateElement.Element(XName.Get("Created", "http://schemas.microsoft.com/windowsazure"));
if (createdElement != null)
{
DateTime createdInstance = DateTime.Parse(createdElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
result.Created = createdInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The List Management Certificates operation lists and returns basic
/// information about all of the management certificates associated
/// with the specified subscription. Management certificates, which
/// are also known as subscription certificates, authenticate clients
/// attempting to connect to resources associated with your Azure
/// subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx
/// for more information)
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Management Certificates operation response.
/// </returns>
public async Task<ManagementCertificateListResponse> ListAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/certificates";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ManagementCertificateListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ManagementCertificateListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement subscriptionCertificatesSequenceElement = responseDoc.Element(XName.Get("SubscriptionCertificates", "http://schemas.microsoft.com/windowsazure"));
if (subscriptionCertificatesSequenceElement != null)
{
foreach (XElement subscriptionCertificatesElement in subscriptionCertificatesSequenceElement.Elements(XName.Get("SubscriptionCertificate", "http://schemas.microsoft.com/windowsazure")))
{
ManagementCertificateListResponse.SubscriptionCertificate subscriptionCertificateInstance = new ManagementCertificateListResponse.SubscriptionCertificate();
result.SubscriptionCertificates.Add(subscriptionCertificateInstance);
XElement subscriptionCertificatePublicKeyElement = subscriptionCertificatesElement.Element(XName.Get("SubscriptionCertificatePublicKey", "http://schemas.microsoft.com/windowsazure"));
if (subscriptionCertificatePublicKeyElement != null)
{
byte[] subscriptionCertificatePublicKeyInstance = Convert.FromBase64String(subscriptionCertificatePublicKeyElement.Value);
subscriptionCertificateInstance.PublicKey = subscriptionCertificatePublicKeyInstance;
}
XElement subscriptionCertificateThumbprintElement = subscriptionCertificatesElement.Element(XName.Get("SubscriptionCertificateThumbprint", "http://schemas.microsoft.com/windowsazure"));
if (subscriptionCertificateThumbprintElement != null)
{
string subscriptionCertificateThumbprintInstance = subscriptionCertificateThumbprintElement.Value;
subscriptionCertificateInstance.Thumbprint = subscriptionCertificateThumbprintInstance;
}
XElement subscriptionCertificateDataElement = subscriptionCertificatesElement.Element(XName.Get("SubscriptionCertificateData", "http://schemas.microsoft.com/windowsazure"));
if (subscriptionCertificateDataElement != null)
{
byte[] subscriptionCertificateDataInstance = Convert.FromBase64String(subscriptionCertificateDataElement.Value);
subscriptionCertificateInstance.Data = subscriptionCertificateDataInstance;
}
XElement createdElement = subscriptionCertificatesElement.Element(XName.Get("Created", "http://schemas.microsoft.com/windowsazure"));
if (createdElement != null)
{
DateTime createdInstance = DateTime.Parse(createdElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
subscriptionCertificateInstance.Created = createdInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
namespace XenAdmin.SettingsPanels
{
partial class WlbAdvancedSettingsPage
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region 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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WlbAdvancedSettingsPage));
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.labelOptAgr = new System.Windows.Forms.Label();
this.labelHistData = new System.Windows.Forms.Label();
this.labelRepSub = new System.Windows.Forms.Label();
this.labelVmMigInt = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.labelRecSev = new System.Windows.Forms.Label();
this.panelVmMigInt = new System.Windows.Forms.FlowLayoutPanel();
this.numericUpDownRelocationInterval = new System.Windows.Forms.NumericUpDown();
this.labelRelocationUnit = new System.Windows.Forms.Label();
this.labelRelocationDefault = new System.Windows.Forms.Label();
this.labelRecCnt = new System.Windows.Forms.Label();
this.panelRecCnt = new System.Windows.Forms.FlowLayoutPanel();
this.numericUpDownPollInterval = new System.Windows.Forms.NumericUpDown();
this.labelRecommendationIntervalUnit = new System.Windows.Forms.Label();
this.labelRecommendationIntervalDefault = new System.Windows.Forms.Label();
this.panelRecSev = new System.Windows.Forms.FlowLayoutPanel();
this.comboBoxOptimizationSeverity = new System.Windows.Forms.ComboBox();
this.labelRecommendationSeverityDefault = new System.Windows.Forms.Label();
this.panelOptAgr = new System.Windows.Forms.FlowLayoutPanel();
this.comboBoxAutoBalanceAggressiveness = new System.Windows.Forms.ComboBox();
this.labelAutoBalanceAggressivenessDefault = new System.Windows.Forms.Label();
this.panelHistData = new System.Windows.Forms.FlowLayoutPanel();
this.numericUpDownGroomingPeriod = new System.Windows.Forms.NumericUpDown();
this.labelGroomingUnits = new System.Windows.Forms.Label();
this.labelGroomingDefault = new System.Windows.Forms.Label();
this.panelRepSub = new System.Windows.Forms.FlowLayoutPanel();
this.labelSMTPServer = new System.Windows.Forms.Label();
this.textBoxSMTPServer = new System.Windows.Forms.TextBox();
this.LabelSmtpPort = new System.Windows.Forms.Label();
this.TextBoxSMTPServerPort = new System.Windows.Forms.TextBox();
this.sectionHeaderLabelRepSub = new XenAdmin.Controls.SectionHeaderLabel();
this.sectionHeaderLabelHistData = new XenAdmin.Controls.SectionHeaderLabel();
this.sectionHeaderLabelOptAgr = new XenAdmin.Controls.SectionHeaderLabel();
this.sectionHeaderLabelRecSev = new XenAdmin.Controls.SectionHeaderLabel();
this.sectionHeaderLabelVmMigInt = new XenAdmin.Controls.SectionHeaderLabel();
this.sectionHeaderLabelRecCnt = new XenAdmin.Controls.SectionHeaderLabel();
this.labelAuditTrail = new System.Windows.Forms.Label();
this.sectionHeaderLabelAuditTrail = new XenAdmin.Controls.SectionHeaderLabel();
this.comboBoxPoolAuditTrailLevel = new System.Windows.Forms.ComboBox();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.auditTrailPanel = new System.Windows.Forms.FlowLayoutPanel();
this.poolAuditTrailNote = new System.Windows.Forms.Label();
this.tableLayoutPanel1.SuspendLayout();
this.panelVmMigInt.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownRelocationInterval)).BeginInit();
this.panelRecCnt.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownPollInterval)).BeginInit();
this.panelRecSev.SuspendLayout();
this.panelOptAgr.SuspendLayout();
this.panelHistData.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownGroomingPeriod)).BeginInit();
this.panelRepSub.SuspendLayout();
this.auditTrailPanel.SuspendLayout();
this.SuspendLayout();
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.labelAuditTrail, 0, 23);
this.tableLayoutPanel1.Controls.Add(this.sectionHeaderLabelAuditTrail, 0, 22);
this.tableLayoutPanel1.Controls.Add(this.label2, 0, 21);
this.tableLayoutPanel1.Controls.Add(this.sectionHeaderLabelRepSub, 0, 16);
this.tableLayoutPanel1.Controls.Add(this.sectionHeaderLabelHistData, 0, 13);
this.tableLayoutPanel1.Controls.Add(this.sectionHeaderLabelOptAgr, 0, 10);
this.tableLayoutPanel1.Controls.Add(this.labelOptAgr, 0, 11);
this.tableLayoutPanel1.Controls.Add(this.labelHistData, 0, 14);
this.tableLayoutPanel1.Controls.Add(this.sectionHeaderLabelRecSev, 0, 7);
this.tableLayoutPanel1.Controls.Add(this.labelRepSub, 0, 17);
this.tableLayoutPanel1.Controls.Add(this.sectionHeaderLabelVmMigInt, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.labelVmMigInt, 0, 2);
this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.labelRecSev, 0, 8);
this.tableLayoutPanel1.Controls.Add(this.panelVmMigInt, 0, 3);
this.tableLayoutPanel1.Controls.Add(this.sectionHeaderLabelRecCnt, 0, 4);
this.tableLayoutPanel1.Controls.Add(this.labelRecCnt, 0, 5);
this.tableLayoutPanel1.Controls.Add(this.panelRecCnt, 0, 6);
this.tableLayoutPanel1.Controls.Add(this.panelRecSev, 0, 9);
this.tableLayoutPanel1.Controls.Add(this.panelOptAgr, 0, 12);
this.tableLayoutPanel1.Controls.Add(this.panelHistData, 0, 15);
this.tableLayoutPanel1.Controls.Add(this.panelRepSub, 0, 18);
this.tableLayoutPanel1.Controls.Add(this.auditTrailPanel, 0, 24);
this.tableLayoutPanel1.Controls.Add(this.label3, 0, 20);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// labelAuditTrail
//
resources.ApplyResources(this.labelAuditTrail, "labelAuditTrail");
this.labelAuditTrail.BackColor = System.Drawing.Color.Transparent;
this.labelAuditTrail.Name = "labelAuditTrail";
//
// sectionHeaderLabelAuditTrail
//
resources.ApplyResources(this.sectionHeaderLabelAuditTrail, "sectionHeaderLabelAuditTrail");
this.sectionHeaderLabelAuditTrail.FocusControl = this.comboBoxPoolAuditTrailLevel;
this.sectionHeaderLabelAuditTrail.LineColor = System.Drawing.SystemColors.ActiveBorder;
this.sectionHeaderLabelAuditTrail.LineLocation = XenAdmin.Controls.SectionHeaderLabel.VerticalAlignment.Middle;
this.sectionHeaderLabelAuditTrail.Name = "sectionHeaderLabelAuditTrail";
//
// comboBoxPoolAuditTrailLevel
//
this.comboBoxPoolAuditTrailLevel.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxPoolAuditTrailLevel.FormattingEnabled = true;
this.comboBoxPoolAuditTrailLevel.Items.AddRange(new object[] {
resources.GetString("comboBoxPoolAuditTrailLevel.Items"),
resources.GetString("comboBoxPoolAuditTrailLevel.Items1"),
resources.GetString("comboBoxPoolAuditTrailLevel.Items2")});
resources.ApplyResources(this.comboBoxPoolAuditTrailLevel, "comboBoxPoolAuditTrailLevel");
this.comboBoxPoolAuditTrailLevel.Name = "comboBoxPoolAuditTrailLevel";
this.comboBoxPoolAuditTrailLevel.SelectedIndexChanged += new System.EventHandler(this.comboBoxPoolAuditTrailLevel_SelectedIndexChanged);
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// labelOptAgr
//
resources.ApplyResources(this.labelOptAgr, "labelOptAgr");
this.labelOptAgr.Name = "labelOptAgr";
//
// labelHistData
//
resources.ApplyResources(this.labelHistData, "labelHistData");
this.labelHistData.BackColor = System.Drawing.Color.Transparent;
this.labelHistData.MaximumSize = new System.Drawing.Size(533, 45);
this.labelHistData.Name = "labelHistData";
//
// labelRepSub
//
resources.ApplyResources(this.labelRepSub, "labelRepSub");
this.labelRepSub.BackColor = System.Drawing.Color.Transparent;
this.labelRepSub.Name = "labelRepSub";
//
// labelVmMigInt
//
resources.ApplyResources(this.labelVmMigInt, "labelVmMigInt");
this.labelVmMigInt.BackColor = System.Drawing.Color.Transparent;
this.labelVmMigInt.Name = "labelVmMigInt";
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// labelRecSev
//
resources.ApplyResources(this.labelRecSev, "labelRecSev");
this.labelRecSev.Name = "labelRecSev";
//
// panelVmMigInt
//
resources.ApplyResources(this.panelVmMigInt, "panelVmMigInt");
this.panelVmMigInt.Controls.Add(this.numericUpDownRelocationInterval);
this.panelVmMigInt.Controls.Add(this.labelRelocationUnit);
this.panelVmMigInt.Controls.Add(this.labelRelocationDefault);
this.panelVmMigInt.Name = "panelVmMigInt";
//
// numericUpDownRelocationInterval
//
resources.ApplyResources(this.numericUpDownRelocationInterval, "numericUpDownRelocationInterval");
this.numericUpDownRelocationInterval.Maximum = new decimal(new int[] {
260,
0,
0,
0});
this.numericUpDownRelocationInterval.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDownRelocationInterval.Name = "numericUpDownRelocationInterval";
this.numericUpDownRelocationInterval.Value = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDownRelocationInterval.ValueChanged += new System.EventHandler(this.numericUpDown_ValueChanged);
this.numericUpDownRelocationInterval.KeyUp += new System.Windows.Forms.KeyEventHandler(this.numericUpDownRelocationInterval_KeyUp);
//
// labelRelocationUnit
//
resources.ApplyResources(this.labelRelocationUnit, "labelRelocationUnit");
this.labelRelocationUnit.Name = "labelRelocationUnit";
//
// labelRelocationDefault
//
resources.ApplyResources(this.labelRelocationDefault, "labelRelocationDefault");
this.labelRelocationDefault.ForeColor = System.Drawing.Color.Gray;
this.labelRelocationDefault.Name = "labelRelocationDefault";
//
// labelRecCnt
//
resources.ApplyResources(this.labelRecCnt, "labelRecCnt");
this.labelRecCnt.Name = "labelRecCnt";
//
// panelRecCnt
//
resources.ApplyResources(this.panelRecCnt, "panelRecCnt");
this.panelRecCnt.Controls.Add(this.numericUpDownPollInterval);
this.panelRecCnt.Controls.Add(this.labelRecommendationIntervalUnit);
this.panelRecCnt.Controls.Add(this.labelRecommendationIntervalDefault);
this.panelRecCnt.Name = "panelRecCnt";
//
// numericUpDownPollInterval
//
resources.ApplyResources(this.numericUpDownPollInterval, "numericUpDownPollInterval");
this.numericUpDownPollInterval.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDownPollInterval.Name = "numericUpDownPollInterval";
this.numericUpDownPollInterval.Value = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDownPollInterval.ValueChanged += new System.EventHandler(this.numericUpDownPollInterval_ValueChanged);
//
// labelRecommendationIntervalUnit
//
resources.ApplyResources(this.labelRecommendationIntervalUnit, "labelRecommendationIntervalUnit");
this.labelRecommendationIntervalUnit.Name = "labelRecommendationIntervalUnit";
//
// labelRecommendationIntervalDefault
//
resources.ApplyResources(this.labelRecommendationIntervalDefault, "labelRecommendationIntervalDefault");
this.labelRecommendationIntervalDefault.ForeColor = System.Drawing.Color.Gray;
this.labelRecommendationIntervalDefault.Name = "labelRecommendationIntervalDefault";
//
// panelRecSev
//
resources.ApplyResources(this.panelRecSev, "panelRecSev");
this.panelRecSev.Controls.Add(this.comboBoxOptimizationSeverity);
this.panelRecSev.Controls.Add(this.labelRecommendationSeverityDefault);
this.panelRecSev.Name = "panelRecSev";
//
// comboBoxOptimizationSeverity
//
this.comboBoxOptimizationSeverity.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxOptimizationSeverity.FormattingEnabled = true;
this.comboBoxOptimizationSeverity.Items.AddRange(new object[] {
resources.GetString("comboBoxOptimizationSeverity.Items"),
resources.GetString("comboBoxOptimizationSeverity.Items1"),
resources.GetString("comboBoxOptimizationSeverity.Items2"),
resources.GetString("comboBoxOptimizationSeverity.Items3")});
resources.ApplyResources(this.comboBoxOptimizationSeverity, "comboBoxOptimizationSeverity");
this.comboBoxOptimizationSeverity.Name = "comboBoxOptimizationSeverity";
this.comboBoxOptimizationSeverity.SelectedIndexChanged += new System.EventHandler(this.comboBoxOptimizationSeverity_SelectedIndexChanged);
//
// labelRecommendationSeverityDefault
//
resources.ApplyResources(this.labelRecommendationSeverityDefault, "labelRecommendationSeverityDefault");
this.labelRecommendationSeverityDefault.ForeColor = System.Drawing.Color.Gray;
this.labelRecommendationSeverityDefault.Name = "labelRecommendationSeverityDefault";
//
// panelOptAgr
//
resources.ApplyResources(this.panelOptAgr, "panelOptAgr");
this.panelOptAgr.Controls.Add(this.comboBoxAutoBalanceAggressiveness);
this.panelOptAgr.Controls.Add(this.labelAutoBalanceAggressivenessDefault);
this.panelOptAgr.Name = "panelOptAgr";
//
// comboBoxAutoBalanceAggressiveness
//
this.comboBoxAutoBalanceAggressiveness.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxAutoBalanceAggressiveness.FormattingEnabled = true;
this.comboBoxAutoBalanceAggressiveness.Items.AddRange(new object[] {
resources.GetString("comboBoxAutoBalanceAggressiveness.Items"),
resources.GetString("comboBoxAutoBalanceAggressiveness.Items1"),
resources.GetString("comboBoxAutoBalanceAggressiveness.Items2")});
resources.ApplyResources(this.comboBoxAutoBalanceAggressiveness, "comboBoxAutoBalanceAggressiveness");
this.comboBoxAutoBalanceAggressiveness.Name = "comboBoxAutoBalanceAggressiveness";
this.comboBoxAutoBalanceAggressiveness.SelectedIndexChanged += new System.EventHandler(this.comboBoxAutoBalanceAggressiveness_SelectedIndexChanged);
//
// labelAutoBalanceAggressivenessDefault
//
resources.ApplyResources(this.labelAutoBalanceAggressivenessDefault, "labelAutoBalanceAggressivenessDefault");
this.labelAutoBalanceAggressivenessDefault.ForeColor = System.Drawing.Color.Gray;
this.labelAutoBalanceAggressivenessDefault.Name = "labelAutoBalanceAggressivenessDefault";
//
// panelHistData
//
resources.ApplyResources(this.panelHistData, "panelHistData");
this.panelHistData.Controls.Add(this.numericUpDownGroomingPeriod);
this.panelHistData.Controls.Add(this.labelGroomingUnits);
this.panelHistData.Controls.Add(this.labelGroomingDefault);
this.panelHistData.Name = "panelHistData";
//
// numericUpDownGroomingPeriod
//
resources.ApplyResources(this.numericUpDownGroomingPeriod, "numericUpDownGroomingPeriod");
this.numericUpDownGroomingPeriod.Maximum = new decimal(new int[] {
260,
0,
0,
0});
this.numericUpDownGroomingPeriod.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDownGroomingPeriod.Name = "numericUpDownGroomingPeriod";
this.numericUpDownGroomingPeriod.Value = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDownGroomingPeriod.ValueChanged += new System.EventHandler(this.numericUpDown_ValueChanged);
//
// labelGroomingUnits
//
resources.ApplyResources(this.labelGroomingUnits, "labelGroomingUnits");
this.labelGroomingUnits.Name = "labelGroomingUnits";
//
// labelGroomingDefault
//
resources.ApplyResources(this.labelGroomingDefault, "labelGroomingDefault");
this.labelGroomingDefault.ForeColor = System.Drawing.Color.Gray;
this.labelGroomingDefault.Name = "labelGroomingDefault";
//
// panelRepSub
//
resources.ApplyResources(this.panelRepSub, "panelRepSub");
this.panelRepSub.Controls.Add(this.labelSMTPServer);
this.panelRepSub.Controls.Add(this.textBoxSMTPServer);
this.panelRepSub.Controls.Add(this.LabelSmtpPort);
this.panelRepSub.Controls.Add(this.TextBoxSMTPServerPort);
this.panelRepSub.Name = "panelRepSub";
//
// labelSMTPServer
//
resources.ApplyResources(this.labelSMTPServer, "labelSMTPServer");
this.labelSMTPServer.Name = "labelSMTPServer";
//
// textBoxSMTPServer
//
resources.ApplyResources(this.textBoxSMTPServer, "textBoxSMTPServer");
this.textBoxSMTPServer.Name = "textBoxSMTPServer";
this.textBoxSMTPServer.TextChanged += new System.EventHandler(this.textBoxSMTPServer_TextChanged);
//
// LabelSmtpPort
//
resources.ApplyResources(this.LabelSmtpPort, "LabelSmtpPort");
this.LabelSmtpPort.Name = "LabelSmtpPort";
//
// TextBoxSMTPServerPort
//
resources.ApplyResources(this.TextBoxSMTPServerPort, "TextBoxSMTPServerPort");
this.TextBoxSMTPServerPort.Name = "TextBoxSMTPServerPort";
//
// sectionHeaderLabelRepSub
//
resources.ApplyResources(this.sectionHeaderLabelRepSub, "sectionHeaderLabelRepSub");
this.sectionHeaderLabelRepSub.FocusControl = this.textBoxSMTPServer;
this.sectionHeaderLabelRepSub.LineColor = System.Drawing.SystemColors.ActiveBorder;
this.sectionHeaderLabelRepSub.LineLocation = XenAdmin.Controls.SectionHeaderLabel.VerticalAlignment.Middle;
this.sectionHeaderLabelRepSub.MinimumSize = new System.Drawing.Size(0, 14);
this.sectionHeaderLabelRepSub.Name = "sectionHeaderLabelRepSub";
//
// sectionHeaderLabelHistData
//
resources.ApplyResources(this.sectionHeaderLabelHistData, "sectionHeaderLabelHistData");
this.sectionHeaderLabelHistData.FocusControl = this.numericUpDownGroomingPeriod;
this.sectionHeaderLabelHistData.LineColor = System.Drawing.SystemColors.ActiveBorder;
this.sectionHeaderLabelHistData.LineLocation = XenAdmin.Controls.SectionHeaderLabel.VerticalAlignment.Middle;
this.sectionHeaderLabelHistData.MinimumSize = new System.Drawing.Size(0, 14);
this.sectionHeaderLabelHistData.Name = "sectionHeaderLabelHistData";
//
// sectionHeaderLabelOptAgr
//
resources.ApplyResources(this.sectionHeaderLabelOptAgr, "sectionHeaderLabelOptAgr");
this.sectionHeaderLabelOptAgr.FocusControl = this.comboBoxAutoBalanceAggressiveness;
this.sectionHeaderLabelOptAgr.LineColor = System.Drawing.SystemColors.ActiveBorder;
this.sectionHeaderLabelOptAgr.LineLocation = XenAdmin.Controls.SectionHeaderLabel.VerticalAlignment.Middle;
this.sectionHeaderLabelOptAgr.MinimumSize = new System.Drawing.Size(0, 14);
this.sectionHeaderLabelOptAgr.Name = "sectionHeaderLabelOptAgr";
//
// sectionHeaderLabelRecSev
//
resources.ApplyResources(this.sectionHeaderLabelRecSev, "sectionHeaderLabelRecSev");
this.sectionHeaderLabelRecSev.FocusControl = this.comboBoxOptimizationSeverity;
this.sectionHeaderLabelRecSev.LineColor = System.Drawing.SystemColors.ActiveBorder;
this.sectionHeaderLabelRecSev.LineLocation = XenAdmin.Controls.SectionHeaderLabel.VerticalAlignment.Middle;
this.sectionHeaderLabelRecSev.MinimumSize = new System.Drawing.Size(0, 14);
this.sectionHeaderLabelRecSev.Name = "sectionHeaderLabelRecSev";
//
// sectionHeaderLabelVmMigInt
//
resources.ApplyResources(this.sectionHeaderLabelVmMigInt, "sectionHeaderLabelVmMigInt");
this.sectionHeaderLabelVmMigInt.FocusControl = this.numericUpDownRelocationInterval;
this.sectionHeaderLabelVmMigInt.LineColor = System.Drawing.SystemColors.ActiveBorder;
this.sectionHeaderLabelVmMigInt.LineLocation = XenAdmin.Controls.SectionHeaderLabel.VerticalAlignment.Middle;
this.sectionHeaderLabelVmMigInt.MinimumSize = new System.Drawing.Size(0, 14);
this.sectionHeaderLabelVmMigInt.Name = "sectionHeaderLabelVmMigInt";
//
// sectionHeaderLabelRecCnt
//
resources.ApplyResources(this.sectionHeaderLabelRecCnt, "sectionHeaderLabelRecCnt");
this.sectionHeaderLabelRecCnt.FocusControl = this.numericUpDownPollInterval;
this.sectionHeaderLabelRecCnt.LineColor = System.Drawing.SystemColors.ActiveBorder;
this.sectionHeaderLabelRecCnt.LineLocation = XenAdmin.Controls.SectionHeaderLabel.VerticalAlignment.Middle;
this.sectionHeaderLabelRecCnt.MinimumSize = new System.Drawing.Size(0, 14);
this.sectionHeaderLabelRecCnt.Name = "sectionHeaderLabelRecCnt";
//
// auditTrailPanel
//
this.auditTrailPanel.Controls.Add(this.comboBoxPoolAuditTrailLevel);
this.auditTrailPanel.Controls.Add(this.poolAuditTrailNote);
resources.ApplyResources(this.auditTrailPanel, "auditTrailPanel");
this.auditTrailPanel.Name = "auditTrailPanel";
//
// poolAuditTrailNote
//
resources.ApplyResources(this.poolAuditTrailNote, "poolAuditTrailNote");
this.poolAuditTrailNote.ForeColor = System.Drawing.Color.Gray;
this.poolAuditTrailNote.Name = "poolAuditTrailNote";
// label3
//
this.label3.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
resources.ApplyResources(this.label3, "label3");
this.label3.Name = "label3";
//
// WlbAdvancedSettingsPage
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.BackColor = System.Drawing.SystemColors.Window;
this.Controls.Add(this.tableLayoutPanel1);
this.MinimumSize = new System.Drawing.Size(560, 560);
this.Name = "WlbAdvancedSettingsPage";
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.panelVmMigInt.ResumeLayout(false);
this.panelVmMigInt.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownRelocationInterval)).EndInit();
this.panelRecCnt.ResumeLayout(false);
this.panelRecCnt.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownPollInterval)).EndInit();
this.panelRecSev.ResumeLayout(false);
this.panelRecSev.PerformLayout();
this.panelOptAgr.ResumeLayout(false);
this.panelOptAgr.PerformLayout();
this.panelHistData.ResumeLayout(false);
this.panelHistData.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownGroomingPeriod)).EndInit();
this.panelRepSub.ResumeLayout(false);
this.panelRepSub.PerformLayout();
this.auditTrailPanel.ResumeLayout(false);
this.auditTrailPanel.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label labelHistData;
private System.Windows.Forms.Label labelGroomingUnits;
private System.Windows.Forms.Label labelGroomingDefault;
private System.Windows.Forms.NumericUpDown numericUpDownGroomingPeriod;
private System.Windows.Forms.Label labelRepSub;
private System.Windows.Forms.Label labelSMTPServer;
private System.Windows.Forms.TextBox textBoxSMTPServer;
private System.Windows.Forms.ComboBox comboBoxOptimizationSeverity;
private System.Windows.Forms.ComboBox comboBoxAutoBalanceAggressiveness;
private System.Windows.Forms.Label labelRecSev;
private System.Windows.Forms.Label labelRecommendationIntervalUnit;
private System.Windows.Forms.NumericUpDown numericUpDownPollInterval;
private System.Windows.Forms.Label labelRecCnt;
private System.Windows.Forms.Label labelRecommendationSeverityDefault;
private System.Windows.Forms.Label labelRecommendationIntervalDefault;
private System.Windows.Forms.Label labelOptAgr;
private System.Windows.Forms.Label labelAutoBalanceAggressivenessDefault;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label LabelSmtpPort;
private System.Windows.Forms.TextBox TextBoxSMTPServerPort;
private System.Windows.Forms.FlowLayoutPanel panelVmMigInt;
private System.Windows.Forms.Label labelVmMigInt;
private System.Windows.Forms.NumericUpDown numericUpDownRelocationInterval;
private System.Windows.Forms.Label labelRelocationUnit;
private System.Windows.Forms.Label labelRelocationDefault;
private XenAdmin.Controls.SectionHeaderLabel sectionHeaderLabelVmMigInt;
private XenAdmin.Controls.SectionHeaderLabel sectionHeaderLabelRecCnt;
private XenAdmin.Controls.SectionHeaderLabel sectionHeaderLabelRecSev;
private System.Windows.Forms.FlowLayoutPanel panelRecCnt;
private System.Windows.Forms.FlowLayoutPanel panelRecSev;
private XenAdmin.Controls.SectionHeaderLabel sectionHeaderLabelOptAgr;
private System.Windows.Forms.FlowLayoutPanel panelOptAgr;
private XenAdmin.Controls.SectionHeaderLabel sectionHeaderLabelRepSub;
private XenAdmin.Controls.SectionHeaderLabel sectionHeaderLabelHistData;
private System.Windows.Forms.FlowLayoutPanel panelHistData;
private System.Windows.Forms.FlowLayoutPanel panelRepSub;
private System.Windows.Forms.Label labelAuditTrail;
private Controls.SectionHeaderLabel sectionHeaderLabelAuditTrail;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.FlowLayoutPanel auditTrailPanel;
private System.Windows.Forms.ComboBox comboBoxPoolAuditTrailLevel;
private System.Windows.Forms.Label poolAuditTrailNote;
private System.Windows.Forms.Label label3;
}
}
| |
using System;
using DataModel.ConfigurationModel.Factory;
using DataModel.ConfigurationModel;
using System.Collections.Generic;
using System.IO;
using DataModel.ConfigurationModel.Pages;
using DataModel.ConfigurationModel.Classes;
namespace DataAggregator
{
public static class ExampleConfigurations
{
public static PagesConfig ExamPresentation(){
PageFactory pageFactory = new PageFactory ();
int updateInterval = 2000;
string aggregatorHost= "192.168.0.74"; int aggregatorPort = 8080;
string realtimeHost02 = "syslab-02"; int realtimePort02 = 8080; // Diesel
string realtimeHost05 = "syslab-05"; int realtimePort05 = 8080; // Dumpload
string realtimeHost05Simul = "localhost"; int realtimePort05Simul = 8080; // Dumpload
string realtimeHost03 = "syslab-03"; int realtimePort03 = 8080; // Gaia
string realtimeHost07 = "syslab-07"; int realtimePort07 = 8080; // PV
string realtimeHost10 = "syslab-10"; int realtimePort10 = 8080; // PV
string realtimeHost12 = "syslab-12"; int realtimePort12 = 8080; // VRBBattery
string realtimeHost16 = "syslab-16"; int realtimePort16 = 8080; // mobileload
string realtimeHost18 = "syslab-18"; int realtimePort18 = 8080; // mobileload
string realtimeHost27 = "syslab-27"; int realtimePort27 = 8080; // dump
string realtimeHost08 = "syslab-08"; int realtimePort08 = 8085; // Flexhouse
VisualizationFactory VisFac = new VisualizationFactory ();
AbstractApplianceVisualizationFactory appliance =
VisFac.CreateApplianceVizualizationFactory (aggregatorHost, aggregatorPort); // Washing Machine Experiment
RealtimeVisualizationFactory realtime02 = new RealtimeVisualizationFactory (aggregatorHost, aggregatorPort, realtimeHost02, realtimePort02);
RealtimeVisualizationFactory realtime05 = new RealtimeVisualizationFactory (aggregatorHost, aggregatorPort, realtimeHost05, realtimePort05);
RealtimeVisualizationFactory realtime03 = new RealtimeVisualizationFactory (aggregatorHost, aggregatorPort,realtimeHost03, realtimePort03);
RealtimeVisualizationFactory realtime07 = new RealtimeVisualizationFactory (aggregatorHost, aggregatorPort, realtimeHost07, realtimePort07);
RealtimeVisualizationFactory realtime08 = new RealtimeVisualizationFactory (aggregatorHost, aggregatorPort, realtimeHost08, realtimePort08);
RealtimeVisualizationFactory realtime10 = new RealtimeVisualizationFactory (aggregatorHost, aggregatorPort, realtimeHost10, realtimePort10);
RealtimeVisualizationFactory realtime12 = new RealtimeVisualizationFactory (aggregatorHost, aggregatorPort, realtimeHost12, realtimePort12);
RealtimeVisualizationFactory realtime16 = new RealtimeVisualizationFactory (aggregatorHost, aggregatorPort, realtimeHost16, realtimePort16);
RealtimeVisualizationFactory realtime18 = new RealtimeVisualizationFactory (aggregatorHost, aggregatorPort, realtimeHost18, realtimePort18);
RealtimeVisualizationFactory realtime27 = new RealtimeVisualizationFactory (aggregatorHost, aggregatorPort, realtimeHost27, realtimePort27);
RealtimeVisualizationFactory realtime05Simul = new RealtimeVisualizationFactory (aggregatorHost, aggregatorPort, realtimeHost05Simul, realtimePort05Simul);
MAggregationVisualizationFactory multi = new MAggregationVisualizationFactory (aggregatorHost, aggregatorPort);
SAggregationVisualizationFactory single = new SAggregationVisualizationFactory (aggregatorHost, aggregatorPort);
// Page 1 Experiment of Dumpload, Gaia, Diesel, PV
List<ExperimentConfig> visualizations1 = new List<ExperimentConfig>{
realtime05.CreateExperiment (
RealtimeInterface.GenericLoadWS,
RealtimeData.ActivePower,
updateInterval,
"mW",
realtime05.CreateGraph (RealtimeInterface.GenericLoadWS, RealtimeData.ActivePower, updateInterval,
"ActivePower", -1, 1, 10, "mW"),
realtime05.CreateGraph(RealtimeInterface.GenericLoadWS,RealtimeData.ReactivePower,updateInterval,
"ReactivePower",-1,1,10,"mW")
)
,
realtime03.CreateExperiment (
RealtimeInterface.GaiaWindTurbineWS,
RealtimeData.ActivePower,
updateInterval,
"mW",
realtime03.CreateGraph (RealtimeInterface.GaiaWindTurbineWS, RealtimeData.ActivePower, updateInterval,
"ActivePower", -5, 15, 10, "mW"),
realtime03.CreateGraph(RealtimeInterface.GaiaWindTurbineWS,RealtimeData.GeneratorRPM,updateInterval,
"GeneratorRPM",0,1500,100,"mW")
),
realtime02.CreateExperiment (
RealtimeInterface.DEIFDieselGensetWS,
RealtimeData.ACActivePower,
updateInterval,
"mW",
realtime02.CreateGraph (RealtimeInterface.DEIFDieselGensetWS, RealtimeData.EngineRPM, updateInterval,
"Engine", 0, 1200, 10, "rpm"),
realtime02.CreateControl(RealtimeInterface.DEIFDieselGensetWS,"dieselControl")
),
realtime07.CreateExperiment (
RealtimeInterface.PVSystemWS,
RealtimeData.ActivePower,
updateInterval,
"mW",
realtime03.CreateGraph (RealtimeInterface.PVSystemWS, RealtimeData.ActivePower, updateInterval,
"ActivePower", 0, 1000, 10, "W"),
realtime03.CreateGraph(RealtimeInterface.PVSystemWS,RealtimeData.Frequency,updateInterval,
"GeneratorRPM",40,70,10,"Hz")
)
};
ExperimentPageConfig page1 = new ExperimentPageConfig (visualizations1, "Experiment",aggregatorHost,aggregatorPort);
// Page 2 // Washing Machine visualizatin
PageConfig page2 = pageFactory.Create3x3Page (new List<VisualizationConfig> (){
appliance.CreateBar(ApplianceData.Count,1000,"Count",0,5,"#"),
appliance.CreateBar(ApplianceData.AEC,1000,"AEC",0,400,"kWh"),
appliance.CreateBar(ApplianceData.Score, 1000,"Score",0,100,""),
appliance.CreatePie(ApplianceData.Count,1000,"Count"),
appliance.CreatePie(ApplianceData.EnergyCentroid,1000,"Energy"),
appliance.CreateTable(ApplianceData.Discovered, 1000,"Discovered Programs"),
},"Grid3x3");
// Page 3 PV 10 03 and VRBBatteryW 12
List<VisualizationConfig> visualizations3 = new List<VisualizationConfig>{
realtime10.CreateGraph(RealtimeInterface.PVSystemWS,RealtimeData.ACFrequency,updateInterval,"PV-10 ACFrequency",0,70,100,"Hz"),
realtime10.CreateGraph(RealtimeInterface.PVSystemWS,RealtimeData.ACReactivePower,updateInterval,"PV-10 ACReactivePower",0,2000,10,"W"),
realtime10.CreateUnit(3000),
realtime07.CreateGraph(RealtimeInterface.PVSystemWS,RealtimeData.ACFrequency,updateInterval,"PV-07 ACFrequency",40,70,100,"Hz"),
realtime07.CreateGraph(RealtimeInterface.PVSystemWS,RealtimeData.ACReactivePower,updateInterval,"PV-07 ACReactivePower",0,2000,10,"W"),
realtime07.CreateUnit(3000),
realtime12.CreateGraph(RealtimeInterface.VRBBatteryWS,RealtimeData.ACFrequency,updateInterval,"Battery-12 ACFrequency",40,70,10,"Hz"),
realtime12.CreateGraph(RealtimeInterface.VRBBatteryWS,RealtimeData.ACReactivePower,updateInterval,"Battery-12 ACReactivePower",-2000,2000,10,"W"),
realtime12.CreateUnit(3000)
};
PageConfig page3 = pageFactory.Create3x3Page (visualizations3,"Grid3x3");
// Page 4 PV 03
List<VisualizationConfig> visualizations4 = new List<VisualizationConfig>{
realtime07.CreateGraph(RealtimeInterface.PVSystemWS,RealtimeData.ACFrequency,updateInterval,"PV-07 ACFrequency",40,70,100,"Hz"),
realtime07.CreateGraph(RealtimeInterface.PVSystemWS,RealtimeData.ACReactivePower,updateInterval,"PV-07 ACReactivePower",0,2000,10,"W"),
realtime07.CreateUnit(3000)
};
PageConfig page4 = pageFactory.Create3x3Page (visualizations4,"Grid3x3");
// Page 5 VNR BAttery
List<VisualizationConfig> visualizations5 = new List<VisualizationConfig>{
realtime12.CreateGraph(RealtimeInterface.VRBBatteryWS,RealtimeData.ACFrequency,updateInterval,"Battery-12 ACFrequency",40,70,10,"Hz"),
realtime12.CreateGraph(RealtimeInterface.VRBBatteryWS,RealtimeData.ACReactivePower,updateInterval,"Battery-12 ACReactivePower",-2000,2000,10,"W"),
realtime12.CreateUnit(3000)
};
PageConfig page5 = pageFactory.Create3x3Page (visualizations5,"Grid3x3");
// Page 8: Gaia Visualization from report
List<VisualizationConfig> visualizations8 = new List<VisualizationConfig> (){
realtime03.CreateGauge(RealtimeInterface.GaiaWindTurbineWS, RealtimeData.InterphaseVoltages,1000,"Interphase Voltages",0,500,"U [V]",
new double[,]{{350,450}},null,new double[,]{{0,350},{450,500}}),
realtime03.CreateGauge(RealtimeInterface.GaiaWindTurbineWS, RealtimeData.ActivePower,1000,"Active Power",-5,20,"P [kW]",
new double[,]{{0,11}},new double[,]{{-5,0},{11,15}},new double[,]{{15,20}}),
realtime03.CreateGauge(RealtimeInterface.GaiaWindTurbineWS, RealtimeData.WindspeedOutsideNacelle,1000,"Windspeed",0,40,"v [m/s]",
new double[,]{{0,25}},new double[,]{{25,39}},new double[,]{{39,40}}),
realtime03.CreateGauge(RealtimeInterface.GaiaWindTurbineWS, RealtimeData.RotorRPM,1000,"Rotor RPM",0,100,"RPM0 [1/min]",
new double[,]{{0,62}},new double[,]{{62,70}},new double[,]{{70,100}}),
realtime03.CreateGauge(RealtimeInterface.GaiaWindTurbineWS, RealtimeData.GeneratorRPM,1000,"Generator RPM",0,1200,"RPM1 [1/min]",
new double[,]{{0,1040}},new double[,]{{1040,1100}},new double[,]{{1100,1200}}),
realtime03.CreateGraph(RealtimeInterface.GaiaWindTurbineWS, RealtimeData.InterphaseVoltages,1000,"Interphase Voltages",0,500,12,"U [V]"),
realtime03.CreateControl(RealtimeInterface.GaiaWindTurbineWS,"gaiaControl"),
realtime03.CreateUnit(30000)
};
PageConfig page8 = new PageConfig (visualizations8,"Grid3x3");
// Page 7 Diesel
List<VisualizationConfig> visualizations7 = new List<VisualizationConfig>{
realtime02.CreateGauge(RealtimeInterface.DEIFDieselGensetWS,RealtimeData.BusbarInterphaseVoltages,1000,"BusbarInterphaseVoltages",0,500, "U [v]",
new double[,]{{350,450}},new double[,]{},new double[,]{{0,350},{450,500}}),
realtime02.CreateGauge(RealtimeInterface.DEIFDieselGensetWS,RealtimeData.ActivePower,1000,"Active Power",0,60, "P [kW]",
new double[,]{{0,48}},new double[,]{{48,55}},new double[,]{{55,60}}),
realtime02.CreateGauge(RealtimeInterface.DEIFDieselGensetWS,RealtimeData.ReactivePower,1000,"Reactive Power",-80,80, "Q [kVAr]",
new double[,]{{-60,60}},new double[,]{{-65,-60},{60,65}},new double[,]{{-80,-65},{65,80}}),
realtime02.CreateGauge(RealtimeInterface.DEIFDieselGensetWS,RealtimeData.EngineRPM,1000,"Engine RPM",0,2000, "RPM [1/min]",
new double[,]{{0,1700}},new double[,]{{1700,1800}},new double[,]{{1800,2000}}),
realtime02.CreateGauge(RealtimeInterface.DEIFDieselGensetWS,RealtimeData.BusbarFrequency,1000,"Busbar Frequency",30,70, "f [Hz]",
new double[,]{{48,52}},new double[,]{{45,48},{52,55}},new double[,]{{30,45},{55,70}}),
realtime02.CreateControl(RealtimeInterface.DEIFDieselGensetWS,"dieselControl")
};
PageConfig page7 = new PageConfig (visualizations7,"Grid3x3");
PagesConfig pages = pageFactory.CreatePages (new List<MasterPageConfig> (){ page1, page2,page3,page7, page8});
string serializedGaiaConf = Newtonsoft.Json.JsonConvert.SerializeObject (pages);
File.Delete ("PageConfigurations/BigPres.json");
File.AppendAllText ("PageConfigurations/BigPres.json", serializedGaiaConf);
return pages;
}
public static PagesConfig Example1(){
PageFactory pageFactory = new PageFactory ();
RealtimeVisualizationFactory realtime = new RealtimeVisualizationFactory ("localhost", 9001, "localhost", 8080);
RealtimeVisualizationFactory realtime2 = new RealtimeVisualizationFactory ("localhost", 9001, "localhost", 8085);
MAggregationVisualizationFactory multi = new MAggregationVisualizationFactory ("localhost", 9001);
SAggregationVisualizationFactory single = new SAggregationVisualizationFactory ("localhost", 9001);
PagesConfig pages = pageFactory.Create3x3Pages (
new List<VisualizationConfig>{
realtime.CreateUnit (2000),realtime2.CreateUnit (2000),
realtime.CreateGauge(RealtimeInterface.GaiaWindTurbineWS,RealtimeData.ActivePower,2000,"8080 Power",-10,10,"mW",
new double[,]{{-10,-1}},new double[,]{{-1.0,1}},new double[,]{{1.0,10}}),
multi.CreateMultiGraph(new List<string>{"localhost","localhost"},new List<int>{8080,8085},
RealtimeInterface.GaiaWindTurbineWS,RealtimeData.ActivePower,
2000,"8080 and 8085 Power",0,12,10,"mW"),
single.CreateGraph(SingleAggregation.AvgActivePower,2000,"Realtime Avg Power",0,12,10,"mW"),
multi.CreateMultiGraph(new List<string>{"localhost","localhost","localhost"},new List<int>{8080,8085,8090},
RealtimeInterface.GaiaWindTurbineWS,RealtimeData.ActivePower,
2000,"8080 and 8085 Power",0,12,10,"mW"),
multi.CreateBar(new List<string>{"localhost","localhost"},new List<int>{8080,8085},RealtimeInterface.GaiaWindTurbineWS,RealtimeData.ActivePower,2000,"Active Power",0,12,"mW"),
multi.CreatePie(new List<string>{"localhost","localhost"},new List<int>{8080,8085},RealtimeInterface.GaiaWindTurbineWS,RealtimeData.ActivePower,2000,"Active Power"),
multi.CreatePie(new List<string>{"localhost","localhost","localhost"},new List<int>{8080,8085,8090},RealtimeInterface.GaiaWindTurbineWS,RealtimeData.ActivePower,2000,"Active Power"),
multi.CreateBar(new List<string>{"localhost","localhost","localhost"},new List<int>{8080,8085,8090},RealtimeInterface.GaiaWindTurbineWS,RealtimeData.ActivePower,2000,"Active Power",0,12,"mW"),
},"Grid3x3"
);
return pages;
}
public static PagesConfig WashingMachineExperiment(){
VisualizationFactory VisFac = new VisualizationFactory ();
AbstractRealtimeVisualizationFactory realtime8080 =
VisFac.CreateRealtimeVizualizationFactory ("localhost", 9001, "localhost", 8080);
AbstractApplianceVisualizationFactory appliance =
VisFac.CreateApplianceVizualizationFactory ("localhost", 9001);
PageFactory pageFactory = new PageFactory ();
PagesConfig washingExample = pageFactory.Create3x3Pages (new List<VisualizationConfig> (){
appliance.CreatePie(ApplianceData.Count,1000,"Count"),
appliance.CreatePie(ApplianceData.EnergyCentroid,1000,"Energy"),
appliance.CreateBar(ApplianceData.Count,1000,"Count",0,5,"#"),
appliance.CreateBar(ApplianceData.AEC,1000,"AEC",0,400,"kWh"),
appliance.CreateBar(ApplianceData.Score, 1000,"Score",0,100,""),
realtime8080.CreateGauge(RealtimeInterface.GenericLoadWS,RealtimeData.ActivePower,1000,"Power",0,3000000,"mW",
new double[,]{{0.0,2000000.0}},
new double[,]{{0.0,0.0}},new double[,]{{2000000.0,3000000.0}}),
realtime8080.CreateGraph(RealtimeInterface.GenericLoadWS, RealtimeData.ActivePower,1000,"Active Power",-5,5,7200,"mW"),
appliance.CreateTable(ApplianceData.Discovered, 1000,"Discovered Programs"),
},"Grid3x3");
return washingExample;
}
public static PagesConfig testGaia(){
VisualizationFactory VisFac = new VisualizationFactory ();
PageFactory pageFactory = new PageFactory ();
AbstractRealtimeVisualizationFactory realtime8080 =
VisFac.CreateRealtimeVizualizationFactory ("localhost", 9001, "localhost", 8080);
PagesConfig gaia= pageFactory.Create3x3Pages(new List<VisualizationConfig> (){
realtime8080.CreateGauge(RealtimeInterface.GaiaWindTurbineWS, RealtimeData.InterphaseVoltages,1000,"Interphase Voltages",0,500,"U [V]",
new double[,]{{350,450}},null,new double[,]{{0,350},{450,500}}),
realtime8080.CreateGauge(RealtimeInterface.GaiaWindTurbineWS, RealtimeData.ActivePower,1000,"Active Power",-5,20,"P [kW]",
new double[,]{{0,11}},new double[,]{{-5,0},{11,15}},new double[,]{{15,20}}),
realtime8080.CreateGauge(RealtimeInterface.GaiaWindTurbineWS, RealtimeData.WindspeedOutsideNacelle,1000,"Windspeed",0,40,"v [m/s]",
new double[,]{{0,25}},new double[,]{{25,39}},new double[,]{{39,40}}),
realtime8080.CreateGauge(RealtimeInterface.GaiaWindTurbineWS, RealtimeData.RotorRPM,1000,"Rotor RPM",0,100,"RPM0 [1/min]",
new double[,]{{0,62}},new double[,]{{62,70}},new double[,]{{70,100}}),
realtime8080.CreateGauge(RealtimeInterface.GaiaWindTurbineWS, RealtimeData.GeneratorRPM,1000,"Generator RPM",0,1200,"RPM1 [1/min]",
new double[,]{{0,1040}},new double[,]{{1040,1100}},new double[,]{{1100,1200}}),
realtime8080.CreateGraph(RealtimeInterface.GaiaWindTurbineWS, RealtimeData.InterphaseVoltages,1000,"Interphase Voltages",0,500,12,"U [V]"),
realtime8080.CreateControl(RealtimeInterface.GaiaWindTurbineWS,"gaiaControl"),
realtime8080.CreateUnit(30000)
},"Grid3x3");
string serializedGaiaConf = Newtonsoft.Json.JsonConvert.SerializeObject (gaia);
File.Delete ("PageConfigurations/gaia.json");
File.AppendAllText ("PageConfigurations/gaia.json", serializedGaiaConf);
return gaia;
}
public static PagesConfig testMultiGaiaWashing(){
VisualizationFactory VisFac = new VisualizationFactory ();
PageFactory pageFactory = new PageFactory ();
AbstractRealtimeVisualizationFactory realtime8080 =
VisFac.CreateRealtimeVizualizationFactory ("192.168.1.4", 9001, "localhost", 8080);
AbstractApplianceVisualizationFactory appliance =
VisFac.CreateApplianceVizualizationFactory ("192.168.1.4", 9001);
PagesConfig gaia= pageFactory.Create3x3Pages(new List<VisualizationConfig> (){
appliance.CreatePie(ApplianceData.Count,2000,"Count"),
appliance.CreatePie(ApplianceData.PowerCentroid,2000,"Power"),
appliance.CreatePie(ApplianceData.EnergyCentroid,2000,"Energy"),
appliance.CreateBar(ApplianceData.Count,2000,"Count",0,10,"#"),
appliance.CreateBar(ApplianceData.AEC,2000,"AEC",0,400,"kWh"),
appliance.CreateBar(ApplianceData.Score, 2000,"Score",0,100,""),
realtime8080.CreateGauge(RealtimeInterface.GenericLoadWS,RealtimeData.ActivePower,2000,"Power",-5,5,"mW",
new double[,]{{-5.0,1}},
new double[,]{{1.0,2.0}},new double[,]{{2.0,5.0}}),
realtime8080.CreateGraph(RealtimeInterface.GenericLoadWS, RealtimeData.ActivePower,2000,"Active Power",-5,5,7200,"mW"),
appliance.CreateTable(ApplianceData.Discovered, 2000,"Discovered Programs"),
realtime8080.CreateGauge(RealtimeInterface.GaiaWindTurbineWS, RealtimeData.InterphaseVoltages,1000,"Interphase Voltages",0,500,"U [V]",
new double[,]{{350,450}},null,new double[,]{{0,350},{450,500}}),
realtime8080.CreateGauge(RealtimeInterface.GaiaWindTurbineWS, RealtimeData.ActivePower,1000,"Active Power",-5,20,"P [kW]",
new double[,]{{0,11}},new double[,]{{-5,0},{11,15}},new double[,]{{15,20}}),
realtime8080.CreateGauge(RealtimeInterface.GaiaWindTurbineWS, RealtimeData.WindspeedOutsideNacelle,1000,"Windspeed",0,40,"v [m/s]",
new double[,]{{0,25}},new double[,]{{25,39}},new double[,]{{39,40}}),
realtime8080.CreateGauge(RealtimeInterface.GaiaWindTurbineWS, RealtimeData.RotorRPM,1000,"Rotor RPM",0,100,"RPM0 [1/min]",
new double[,]{{0,62}},new double[,]{{62,70}},new double[,]{{70,100}}),
realtime8080.CreateGauge(RealtimeInterface.GaiaWindTurbineWS, RealtimeData.GeneratorRPM,1000,"Generator RPM",0,1200,"RPM1 [1/min]",
new double[,]{{0,1040}},new double[,]{{1040,1100}},new double[,]{{1100,1200}}),
realtime8080.CreateGraph(RealtimeInterface.GaiaWindTurbineWS, RealtimeData.InterphaseVoltages,1000,"Interphase Voltages",0,500,12,"U [V]"),
realtime8080.CreateControl(RealtimeInterface.GaiaWindTurbineWS,"gaiaControl"),
realtime8080.CreateUnit(30000)
},"Grid3x3");
string serializedGaiaConf = Newtonsoft.Json.JsonConvert.SerializeObject (gaia);
File.Delete ("PageConfigurations/testMultiGaiaWashing.json");
File.AppendAllText ("PageConfigurations/testMultiGaiaWashing.json", serializedGaiaConf);
return gaia;
}
public static PagesConfig testEmpty(){
VisualizationFactory VisFac = new VisualizationFactory ();
PageFactory pageFactory = new PageFactory ();
PagesConfig gaia= pageFactory.Create3x3Pages(new List<VisualizationConfig> (){
},"Grid3x3");
return gaia;
}
public static PagesConfig Experiement(){
PageFactory pageFactory = new PageFactory ();
RealtimeVisualizationFactory realtime = new RealtimeVisualizationFactory ("127.0.0.1", 9001, "localhost", 8080);
RealtimeVisualizationFactory realtime2 = new RealtimeVisualizationFactory ("127.0.0.1", 9001, "localhost", 8085);
RealtimeVisualizationFactory realtime3 = new RealtimeVisualizationFactory ("127.0.0.1", 9001, "localhost", 8090);
List<ExperimentConfig> experiments = new List<ExperimentConfig>{
new ExperimentConfig(
"127.0.0.1",
8080,
"GenericLoadWS",
"getActivePower"
,5000,
"mW",
realtime.CreateGraph(RealtimeInterface.GenericLoadWS,RealtimeData.ActivePower,3000,"Power",-10,10,10,"mW"),
realtime.CreateGraph(RealtimeInterface.GenericLoadWS,RealtimeData.ReactivePower,3000,"Power",-10,10,10,"mW")
)
,
new ExperimentConfig(
"127.0.0.1",
8085,
"GaiaWindTurbineWS",
"getActivePower"
,5000,
"mW",
realtime2.CreateGraph(RealtimeInterface.GaiaWindTurbineWS,RealtimeData.RotorRPM,3000,"Power",-10,10,10,"mW"),
realtime2.CreateGraph(RealtimeInterface.GaiaWindTurbineWS,RealtimeData.ActivePower,3000,"Power",-10,10,10,"mW")
)
,
new ExperimentConfig(
"127.0.0.1",
8090,
"LithiumBatteryWS",
"getSOC"
,5000,
"mW",
realtime3.CreateGraph(RealtimeInterface.LithiumBatteryWS,RealtimeData.SOC,3000,"Power",-10,10,10,"mW"),
realtime3.CreateGraph(RealtimeInterface.LithiumBatteryWS,RealtimeData.Temperature,3000,"Power",-10,10,10,"mW")
)
};
ExperimentPageConfig b = new ExperimentPageConfig (experiments, "Experiment","127.0.0.1",9001);
return pageFactory.CreatePages (new List<MasterPageConfig> (){ b });
}
public static PagesConfig ExperiementAndWashingMachine(){
PageFactory pageFactory = new PageFactory ();
RealtimeVisualizationFactory realtime = new RealtimeVisualizationFactory ("127.0.0.1", 9001, "127.0.0.1", 8080);
RealtimeVisualizationFactory realtime2 = new RealtimeVisualizationFactory ("127.0.0.1", 9001, "127.0.0.1", 8085);
RealtimeVisualizationFactory realtime3 = new RealtimeVisualizationFactory ("127.0.0.1", 9001, "127.0.0.1", 8090);
List<ExperimentConfig> experiments = new List<ExperimentConfig>{
realtime.CreateExperiment (
RealtimeInterface.GenericLoadWS,
RealtimeData.ActivePower,
5000,
"mW",
realtime.CreateGraph (RealtimeInterface.GenericLoadWS, RealtimeData.ActivePower, 6000, "ActivePower", -1, 1, 10, "mW"),
realtime.CreateGraph(RealtimeInterface.GenericLoadWS,RealtimeData.ReactivePower,6000,"ReactivePower",-1,1,10,"mW")
)
,
realtime2.CreateExperiment (
RealtimeInterface.GaiaWindTurbineWS,
RealtimeData.ActivePower,
5000,
"mW",
realtime2.CreateGraph (RealtimeInterface.GaiaWindTurbineWS, RealtimeData.ActivePower, 6000, "ActivePower", -5, 15, 10, "mW"),
realtime2.CreateGraph(RealtimeInterface.GaiaWindTurbineWS,RealtimeData.GeneratorRPM,6000,"GeneratorRPM",1000,1050,10,"mW")
),
realtime3.CreateExperiment (
RealtimeInterface.LithiumBatteryWS,
RealtimeData.SOC,
5000,
"mW",
realtime3.CreateGraph (RealtimeInterface.LithiumBatteryWS, RealtimeData.SOC, 6000, "SOC", 0, 100, 10, "mW"),
realtime3.CreateGraph(RealtimeInterface.LithiumBatteryWS,RealtimeData.Temperature,6000,"Temperature",0,100,10,"mW")
),
realtime2.CreateExperiment (
RealtimeInterface.GaiaWindTurbineWS,
RealtimeData.ActivePower,
5000,
"mW",
realtime2.CreateGraph (RealtimeInterface.GaiaWindTurbineWS, RealtimeData.ActivePower, 6000, "ActivePower", -5, 15, 10, "mW"),
realtime2.CreateGraph(RealtimeInterface.GaiaWindTurbineWS,RealtimeData.GeneratorRPM,6000,"GeneratorRPM",1000,1050,10,"mW")
),
realtime3.CreateExperiment (
RealtimeInterface.LithiumBatteryWS,
RealtimeData.SOC,
5000,
"mW",
realtime3.CreateGraph (RealtimeInterface.LithiumBatteryWS, RealtimeData.SOC, 6000, "SOC", 0, 100, 10, "mW"),
realtime3.CreateGraph(RealtimeInterface.LithiumBatteryWS,RealtimeData.Temperature,6000,"Temperature",0,100,10,"mW")
)
};
ExperimentPageConfig b = new ExperimentPageConfig (experiments, "Experiment","127.0.0.1",9001);
PagesConfig c = WashingMachineExperiment ();
return pageFactory.CreatePages (new List<MasterPageConfig> (){ b, c.Pages[0] });
}
/*
public static PagesConfig BatteryPage(){
PageFactory pageFactory = new PageFactory ();
RealtimeVisualizationFactory realtime3 = new RealtimeVisualizationFactory ("127.0.0.1", 9001, "127.0.0.1", 8090);
MAggregationVisualizationFactory multi = new MAggregationVisualizationFactory ("127.0.0.1", 9001);
List<VisualizationConfig> visualizations = new List<VisualizationConfig>{
realtime3.CreateUnit(3000),
realtime3.CreateGraph(RealtimeInterface.LithiumBatteryWS,RealtimeData.ActiveEnergyExport,3000,"Export",0,10,10,"W"),
realtime3.CreateGraph(RealtimeInterface.LithiumBatteryWS,RealtimeData.ActiveEnergyImport,3000,"Import",0,10,10,"W"),
realtime3.CreateGraph(RealtimeInterface.LithiumBatteryWS,RealtimeData.ACReactivePower,3000,"AC Reactive Power",0,10,10,"W"),
realtime3.CreateGraph(RealtimeInterface.LithiumBatteryWS,RealtimeData.ACFrequency,3000,"AC Frequency",0,10,10,"W"),
realtime3.CreateGraph(RealtimeInterface.LithiumBatteryWS,RealtimeData.ACActivePower,3000,"AC Active Power",0,10,10,"W"),
realtime3.CreateControl(RealtimeInterface.LithiumBatteryWS,"Control Battery")
};
ExperimentPageConfig b = new ExperimentPageConfig (visualizations, "Experiment","127.0.0.1",9001);
PagesConfig c = WashingMachineExperiment ();
return pageFactory.CreatePages (new List<MasterPageConfig> (){ b, c.Pages[0] });
}
*/
}
}
| |
/* */
/* File: BigIntegerTestGenerator.cs */
/* Function: Generates result tables for a set of big integers and the */
/* math operations on them, as an include file for the */
/* BigIntegerTest.dpr program, called BigIntegerTestData.inc. */
/* Language: C# 4.0 or above */
/* Author: Rudy Velthuis */
/* Copyright: (c) 2015 Rudy Velthuis */
/* Notes: Can be compiled with the freely available Microsoft C# */
/* Express IDE. */
/* See http://rvelthuis.de/programs/bigintegers.html */
/* */
/* License: 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. */
/* */
/* Disclaimer: THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" */
/* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */
/* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND */
/* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO */
/* EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE */
/* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, */
/* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, */
/* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, */
/* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED */
/* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT */
/* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) */
/* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF */
/* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;
using System.Globalization;
namespace TestBigIntegers
{
class ResultGenerator
{
const int DefaultStringWidth = 40;
public enum TestResultInfo
{
Ok,
DivideByZero,
ArgumentNull,
ArgumentRange,
Format,
Overflow
}
public struct TestResult
{
public TestResultInfo info;
public string val;
}
static void Main(string[] args)
{
DoubleConverter.SpecialValues[0] = "Infinity"; // "+INF";
DoubleConverter.SpecialValues[1] = "NegInfinity"; // "-INF";
DoubleConverter.SpecialValues[2] = "NaN"; // "NAN";
using (StreamWriter sw = NewWriter("BigIntegerTestResults.inc.inc"))
{
WriteDate(sw);
WriteTypes(sw);
WriteData(sw);
}
using (StreamWriter sw = NewWriter("BigIntegerArithmeticResults.inc.inc"))
{
GenerateAddResults(sw);
GenerateSubtractResults(sw);
GenerateMultiplyResults(sw);
GenerateDivisionResults(sw);
GenerateModulusResults(sw);
}
using (StreamWriter sw = NewWriter("BigIntegerBitwiseResults.inc.inc"))
{
GenerateBitwiseAndResults(sw);
GenerateBitwiseOrResults(sw);
GenerateBitwiseXorResults(sw);
GenerateNegationResults(sw);
GenerateLogicalNotResults(sw);
GenerateLeftShiftResults(sw);
GenerateRightShiftResults(sw);
}
using (StreamWriter sw = NewWriter("BigIntegerMathResults.inc.inc"))
{
GenerateLnResults(sw);
GeneratePowerResults(sw);
GenerateModPowResults(sw);
GenerateComparisonResults(sw);
GenerateGCDResults(sw);
GenerateMinResults(sw);
GenerateMaxResults(sw);
}
using (StreamWriter sw = NewWriter("BigIntegerConvertResults.inc.inc"))
{
GenerateByteArrayResults(sw);
GenerateHexResults(sw);
GenerateAsIntegerResults(sw);
GenerateAsCardinalResults(sw);
GenerateAsInt64Results(sw);
GenerateAsUInt64Results(sw);
GenerateFromDoubleResults(sw);
GenerateDoubleResults(sw);
}
Console.WriteLine();
Console.Write("Press any key...");
Console.ReadKey();
}
static StreamWriter NewWriter(string fileName)
{
return new StreamWriter("..\\..\\..\\..\\..\\..\\Tests\\BigIntegers\\" + fileName);
}
static string[] SplitString(string s, int width)
{
List<string> results = new List<string>();
if (s == null || s.Length == 0)
return new String[] { "" };
while (s.Length > 0)
{
results.Add(s.Substring(0, s.Length > width ? width : s.Length));
s = s.Substring(s.Length > width ? width : s.Length);
}
return results.ToArray<string>();
}
static void WriteDate(TextWriter tw)
{
DateTime dt = DateTime.Now;
tw.WriteLine("// {0,-95} //", "");
tw.WriteLine("// {0,-95} //", String.Format("Test data for BigIntegers.pas, generated {0}", dt));
tw.WriteLine("// {0,-95} //", "");
tw.WriteLine("// {0,-95} //", "Do not modify the generated data in this file. Modify the data in the generator source file.");
tw.WriteLine("// {0,-95} //", "The source file for the generator is BigIntegerTestGenerator.cs, in the Test subdirectory.");
tw.WriteLine("// {0,-95} //", "");
tw.WriteLine("// {0,-95} //", "The generator was written in C#, using Microsoft Visual C# 2010 Express");
tw.WriteLine("// {0,-95} //", "");
tw.WriteLine();
Console.WriteLine("Test data generator for BigIntegers.pas");
Console.WriteLine("---------------------------------------");
Console.WriteLine();
Console.WriteLine("This program generates the include file BigIntegerTestResults.inc,");
Console.WriteLine("which is used by the test programs for BigIntegers.pas");
Console.WriteLine();
Console.WriteLine("You'll see a list of errors. This is expected. The generated errors are");
Console.WriteLine("registered and written to the test data include file generated by this program");
Console.WriteLine();
Console.Write("Press any key...");
Console.ReadKey();
Console.WriteLine();
}
static void WriteTypes(TextWriter tw)
{
TestResultInfo[] infos = (TestResultInfo[])Enum.GetValues(typeof(TestResultInfo));
tw.WriteLine("type");
tw.WriteLine(" TTestResultInfo =");
tw.WriteLine(" (");
foreach (TestResultInfo info in infos)
tw.WriteLine(" tri{0}{1}", info, info != infos[infos.Length - 1] ? "," : " ");
tw.WriteLine(" );");
tw.WriteLine();
tw.WriteLine(" TTestResult = record");
tw.WriteLine(" info: TTestResultInfo;");
tw.WriteLine(" val: string;");
tw.WriteLine(" end;");
tw.WriteLine();
tw.WriteLine(" TComparisonResult = (crGreater, crGreaterEqual, crEqual, crLessEqual, crLess, crNotEqual);");
tw.WriteLine();
}
static void WriteData(TextWriter tw)
{
int count = testData.Length;
int shiftCount = bitShifts.Length;
tw.WriteLine("const");
tw.WriteLine(" TestCount = {0};", count);
tw.WriteLine(" ShiftCount = {0};", bitShifts.Length);
tw.WriteLine(" DoubleCount = {0};", doubles.Length);
tw.WriteLine();
// Arguments array
tw.WriteLine(" Arguments: array[0..TestCount - 1] of string =");
tw.WriteLine(" (");
for (int i = 0; i < count; ++i)
{
bool isLast = (i == count - 1);
string[] parts = SplitString(testData[i], DefaultStringWidth);
for (int j = 0; j < parts.Length; j++)
{
string s = parts[j];
tw.Write(" {0,-43}", "'" + s + ((i < count - 1) && (j == parts.Length - 1) ? "'," : "' "));
if (j < parts.Length - 1)
tw.WriteLine("+ ");
else
tw.WriteLine(" // {1}", i < count - 1 ? "," : " ", i);
}
}
tw.WriteLine(" );");
tw.WriteLine();
// BitShifts array
tw.WriteLine(" BitShifts: array[0..ShiftCount - 1] of Integer =");
tw.Write(" (");
for (int i = 0; i < shiftCount; ++i)
{
if ((i % 8) == 0)
{
tw.WriteLine();
tw.Write(" ");
}
tw.Write("{0,4}{1}", bitShifts[i], (i < shiftCount - 1) ? "," : " ");
}
//if (shiftCount % 8 != 0)
tw.WriteLine();
tw.WriteLine(" );");
// Doubles array
tw.WriteLine();
tw.WriteLine(" Doubles: array[0..DoubleCount - 1] of Double =");
tw.WriteLine(" (");
for (int i = 0; i < doubles.Length; i++)
{
tw.WriteLine(" {0}{1}", doubles[i].ToString(CultureInfo.InvariantCulture), i == (doubles.Length - 1) ? "" : ",");
}
tw.WriteLine(" );");
tw.WriteLine();
}
static void FormatResult(TextWriter tw, TestResult result, bool isLast, string comment)
{
string info = String.Format("tri{0};", result.info);
string[] values = SplitString(result.val, DefaultStringWidth);
for (int k = 0; k < values.Count(); k++)
{
if (k == 0)
tw.Write(" (info: {0,-17} val: '{1}'", info, values[k]);
else
tw.Write("{0,34}'{1}'", ' ', values[k]);
if (k < values.Count() - 1)
tw.WriteLine(" + ");
else
{
string lineEnd = ")" + (isLast ? "" : ",");
tw.WriteLine(lineEnd + new String(' ', 44 - lineEnd.Length - values[k].Length) + "// {0}", comment);
}
}
}
static void WriteMonadicResults(TextWriter tw, string ArrayName, TestResult[] results, int count, string prefix, string suffix)
{
tw.WriteLine(" {0}: array[0.. TestCount - 1] of TTestResult =", ArrayName);
tw.WriteLine(" (");
for (int i = 0; i < count; ++i)
FormatResult(tw, results[i], (i == count - 1), String.Format("{0}Arguments[{1}]{2}", prefix, i, suffix));
tw.WriteLine(" );");
tw.WriteLine();
}
static void WriteDyadicResults(TextWriter tw, string ArrayName, TestResult[] results, int count, string op)
{
// This routine goes out of its way to nicely indent and format the strings into 40 character portions.
// There may be a better way to achieve this, but hey, it works.
tw.WriteLine(" {0}: array[0..TestCount * TestCount - 1] of TTestResult =", ArrayName);
tw.WriteLine(" (");
int n = 0;
for (int i = 0; i < count; ++i)
for (int j = 0; j < count; ++j, ++n)
FormatResult(tw, results[n], (i == count - 1 && j == count - 1), String.Format("{3,4}: Arguments[{0}] {1} Arguments[{2}]", i, op, j, n));
tw.WriteLine(" );");
tw.WriteLine();
}
static void WriteDyadicResults(TextWriter tw, string ArrayName, TestResult[] results, int count, string op, string counter, string origin)
{
// This routine goes out of its way to nicely indent and format the strings into 40 character portions.
// There may be a better way to achieve this, but hey, it works.
tw.WriteLine(" {0}: array[0..{1} * {1} - 1] of TTestResult =", ArrayName, counter);
tw.WriteLine(" (");
int n = 0;
for (int i = 0; i < count; ++i)
for (int j = 0; j < count; ++j, ++n)
FormatResult(tw, results[n], (i == count - 1 && j == count - 1), String.Format("{3}[{0}] {1} {3}[{2}]", i, op, j, origin));
tw.WriteLine(" );");
tw.WriteLine();
}
static void WriteShiftResults(TextWriter tw, string ArrayName, TestResult[] results, int count, int shiftCount, string op)
{
// This routine goes out of its way to nicely indent and format the strings into 40 character portions.
// There may be a better way to achieve this, but hey, it works.
int high = results.Length - 1;
tw.WriteLine(" {0}: array[0..TestCount * ShiftCount - 1] of TTestResult =", ArrayName);
tw.WriteLine(" (");
int n = 0;
for (int i = 0; i < count; ++i)
for (int j = 0; j < shiftCount; ++j, ++n)
FormatResult(tw, results[n], (n == high), String.Format("Arguments[{0}] {1} {2}", i, op, bitShifts[j]));
tw.WriteLine(" );");
tw.WriteLine();
}
static void GenerateAddResults(TextWriter tw)
{
string[] data = testData;
int count = data.Length;
TestResult[] results = new TestResult[count * count];
TestResult tr;
int n = 0;
for (int i = 0; i < count; ++i)
{
BigInteger d1 = BigInteger.Parse(data[i]);
for (int j = 0; j < count; ++j, ++n)
{
// Test operation.
BigInteger d2 = BigInteger.Parse(data[j]);
BigInteger d3 = 0;
BigInteger d4 = 0;
tr.info = TestResultInfo.Ok;
d3 = d1 + d2;
tr.val = d3.ToString();
results[n] = tr;
}
}
WriteDyadicResults(tw, "AddResults", results, count, "+");
}
static void GenerateSubtractResults(TextWriter tw)
{
string[] data = testData;
int count = data.Length;
TestResult[] results = new TestResult[count * count];
TestResult tr;
int n = 0;
for (int i = 0; i < count; ++i)
{
BigInteger d1 = BigInteger.Parse(data[i]);
for (int j = 0; j < count; ++j, ++n)
{
// Test operation.
BigInteger d2 = BigInteger.Parse(data[j]);
BigInteger d3 = 0;
BigInteger d4 = 0;
tr.info = TestResultInfo.Ok;
d3 = d1 - d2;
tr.val = d3.ToString();
results[n] = tr;
}
}
WriteDyadicResults(tw, "SubtractResults", results, count, "-");
}
static void GenerateMultiplyResults(TextWriter tw)
{
string[] data = testData;
int count = data.Length;
TestResult[] results = new TestResult[count * count];
TestResult tr;
int n = 0;
for (int i = 0; i < count; ++i)
{
BigInteger d1 = BigInteger.Parse(data[i]);
for (int j = 0; j < count; ++j, ++n)
{
// Test operation.
BigInteger d2 = BigInteger.Parse(data[j]);
BigInteger d3 = 0;
BigInteger d4 = 0;
tr.info = TestResultInfo.Ok;
d3 = d1 * d2;
tr.val = d3.ToString();
results[n] = tr;
}
}
WriteDyadicResults(tw, "MultiplyResults", results, count, "*");
}
static void GenerateDivisionResults(TextWriter tw)
{
string[] data = testData;
int count = data.Length;
TestResult[] results = new TestResult[count * count];
TestResult tr;
int n = 0;
for (int i = 0; i < count; ++i)
{
BigInteger d1 = BigInteger.Parse(data[i]);
for (int j = 0; j < count; ++j, ++n)
{
// Test operation.
BigInteger d2 = BigInteger.Parse(data[j]);
BigInteger d3 = 0;
BigInteger d4 = 0;
tr.info = TestResultInfo.Ok;
try
{
d3 = d1 / d2;
tr.val = d3.ToString();
}
catch (DivideByZeroException e)
{
tr.info = TestResultInfo.DivideByZero;
tr.val = e.Message;
Console.WriteLine("{0,2},{1,2} -- Division error: {2}", i, j, e.Message);
}
// No need to do the reverse, right? e.g. d4 = d3 * d2 + d1 % d2, check if d4 = d1, and if not, reverseDivision
// This could be useful for DivMod, but not for this routine.
results[n] = tr;
}
}
WriteDyadicResults(tw, "DivisionResults", results, count, "div");
}
static void GenerateModulusResults(TextWriter tw)
{
string[] data = testData;
int count = data.Length;
TestResult[] results = new TestResult[count * count];
TestResult tr;
int n = 0;
for (int i = 0; i < count; ++i)
{
BigInteger d1 = BigInteger.Parse(data[i]);
for (int j = 0; j < count; ++j, ++n)
{
// Test operation.
BigInteger d2 = BigInteger.Parse(data[j]);
BigInteger d3 = 0;
BigInteger d4 = 0;
tr.info = TestResultInfo.Ok;
try
{
d3 = d1 % d2;
tr.val = d3.ToString();
}
catch (DivideByZeroException e)
{
tr.info = TestResultInfo.DivideByZero;
tr.val = e.Message;
Console.WriteLine("{0,2},{1,2} -- Modulus error: {2}", i, j, e.Message);
}
// No need to do the reverse, right? e.g. d4 = d3 * d2 + d1 % d2, check if d4 = d1, and if not, reverseDivision
// This could be useful for DivMod, but not for this routine.
results[n] = tr;
}
}
WriteDyadicResults(tw, "ModulusResults", results, count, "mod");
}
static void GenerateBitwiseAndResults(TextWriter tw)
{
string[] data = testData;
int count = data.Length;
TestResult[] results = new TestResult[count * count];
TestResult tr;
int n = 0;
for (int i = 0; i < count; ++i)
{
BigInteger d1 = BigInteger.Parse(data[i]);
for (int j = 0; j < count; ++j, ++n)
{
// Test operation.
BigInteger d2 = BigInteger.Parse(data[j]);
BigInteger d3 = 0;
BigInteger d4 = 0;
tr.info = TestResultInfo.Ok;
d3 = d1 & d2;
tr.val = d3.ToString();
results[n] = tr;
}
}
WriteDyadicResults(tw, "BitwiseAndResults", results, count, "and");
}
static void GenerateBitwiseOrResults(TextWriter tw)
{
string[] data = testData;
int count = data.Length;
TestResult[] results = new TestResult[count * count];
TestResult tr;
int n = 0;
for (int i = 0; i < count; ++i)
{
BigInteger d1 = BigInteger.Parse(data[i]);
for (int j = 0; j < count; ++j, ++n)
{
// Test operation.
BigInteger d2 = BigInteger.Parse(data[j]);
BigInteger d3 = 0;
BigInteger d4 = 0;
tr.info = TestResultInfo.Ok;
d3 = d1 | d2;
tr.val = d3.ToString();
results[n] = tr;
}
}
WriteDyadicResults(tw, "BitwiseOrResults", results, count, "or");
}
static void GenerateBitwiseXorResults(TextWriter tw)
{
string[] data = testData;
int count = data.Length;
TestResult[] results = new TestResult[count * count];
TestResult tr;
int n = 0;
for (int i = 0; i < count; ++i)
{
BigInteger d1 = BigInteger.Parse(data[i]);
for (int j = 0; j < count; ++j, ++n)
{
// Test operation.
BigInteger d2 = BigInteger.Parse(data[j]);
BigInteger d3 = 0;
BigInteger d4 = 0;
tr.info = TestResultInfo.Ok;
d3 = d1 ^ d2;
tr.val = d3.ToString();
results[n] = tr;
}
}
WriteDyadicResults(tw, "BitwiseXorResults", results, count, "xor");
}
static void GenerateNegationResults(TextWriter tw)
{
string[] data = testData;
int count = data.Length;
TestResult[] results = new TestResult[count];
TestResult tr;
for (int i = 0; i < count; ++i)
{
BigInteger d1 = BigInteger.Parse(data[i]);
BigInteger d2 = -d1;
tr.info = TestResultInfo.Ok;
tr.val = d2.ToString();
results[i] = tr;
}
WriteMonadicResults(tw, "NegationResults", results, count, "Negate(", ")");
}
static void GenerateLogicalNotResults(TextWriter tw)
{
string[] data = testData;
int count = data.Length;
TestResult[] results = new TestResult[count];
TestResult tr;
for (int i = 0; i < count; ++i)
{
BigInteger d1 = BigInteger.Parse(data[i]);
BigInteger d2 = ~d1;
tr.info = TestResultInfo.Ok;
tr.val = d2.ToString();
results[i] = tr;
}
WriteMonadicResults(tw, "LogicalNotResults", results, count, "not ", "");
}
static void GenerateLeftShiftResults(TextWriter tw)
{
int count = testData.Length;
int shiftCount = bitShifts.Length;
TestResult[] results = new TestResult[count * shiftCount];
TestResult tr;
int n = 0;
for (int i = 0; i < count; ++i)
{
BigInteger d1 = BigInteger.Parse(testData[i]);
for (int j = 0; j < shiftCount; ++j, n++)
{
int d2 = bitShifts[j];
BigInteger d3 = d1 << d2;
tr.info = TestResultInfo.Ok;
tr.val = d3.ToString();
results[n] = tr;
}
}
WriteShiftResults(tw, "LeftShiftResults", results, count, shiftCount, "shl");
}
static void GenerateRightShiftResults(TextWriter tw)
{
int count = testData.Length;
int shiftCount = bitShifts.Length;
TestResult[] results = new TestResult[count * shiftCount];
TestResult tr;
int n = 0;
for (int i = 0; i < count; ++i)
{
BigInteger d1 = BigInteger.Parse(testData[i]);
for (int j = 0; j < shiftCount; ++j, n++)
{
int d2 = bitShifts[j];
BigInteger d3 = d1 >> d2;
tr.info = TestResultInfo.Ok;
tr.val = d3.ToString();
results[n] = tr;
}
}
WriteShiftResults(tw, "RightShiftResults", results, count, shiftCount, "shr");
}
static void WriteDoubleResults(TextWriter tw, string arrayName, double[] results, int count, string func)
{
tw.WriteLine(" {0}: array[0.. TestCount - 1] of Double =", arrayName);
tw.WriteLine(" (");
for (int i = 0; i < count; ++i)
{
double d = results[i];
string result = DoubleConverter.ToExactString(d);
result = (i < count - 1) ? result + "," : result;
tw.WriteLine(" {0,-76}// {1}(Arguments[{2}])", result, func, i);
}
tw.WriteLine(" );");
tw.WriteLine();
}
static void GenerateLnResults(TextWriter tw)
{
int count = testData.Length;
double[] results = new double[count];
for (int i = 0; i < count; ++i)
{
BigInteger b1 = BigInteger.Parse(testData[i]);
results[i] = BigInteger.Log(b1);
}
WriteDoubleResults(tw, "LnResults", results, count, "Ln");
BigInteger b = BigInteger.Pow(1000, 1000);
double d1 = BigInteger.Log(b);
double d2 = BigInteger.Log10(b);
double d3 = BigInteger.Log(b, 2.0);
tw.WriteLine(" Ln_1000_1000 = {0};", DoubleConverter.ToExactString(d1));
tw.WriteLine(" Log10_1000_1000 = {0};", DoubleConverter.ToExactString(d2));
tw.WriteLine(" Log2_1000_1000 = {0};", DoubleConverter.ToExactString(d3));
tw.WriteLine();
}
static void GenerateDoubleResults(TextWriter tw)
{
int count = testData.Length;
double[] results = new double[count];
for (int i = 0; i < count; ++i)
{
BigInteger d1 = BigInteger.Parse(testData[i]);
results[i] = (double)d1;
}
WriteDoubleResults(tw, "DoubleResults", results, count, "Double");
}
static void GeneratePowerResults(TextWriter tw)
{
int count = bitShifts.Length;
TestResult[] results = new TestResult[count * count];
int n = 0;
for (int i = 0; i < count; ++i)
{
BigInteger d1 = new BigInteger(bitShifts[i]);
for (int j = 0; j < count; ++j, ++n)
{
int d2 = bitShifts[j];
results[n].val = BigInteger.Pow(d1, d2).ToString();
results[n].info = TestResultInfo.Ok;
}
}
WriteDyadicResults(tw, "PowerResults", results, count, "^", "ShiftCount", "BitShifts");
}
static void GenerateComparisonResults(TextWriter tw)
{
int count = testData.Length;
bool[,] results = new bool[count * count, 6];
tw.WriteLine(" ComparisonResults: array[0..TestCount * TestCount - 1, TComparisonResult] of Boolean =");
tw.WriteLine(" (");
int n = 0;
for (int i = 0; i < count; i++)
{
BigInteger b1 = BigInteger.Parse(testData[i]);
for (int j = 0; j < count; j++, n++)
{
BigInteger b2 = BigInteger.Parse(testData[j]);
tw.WriteLine(" ({0,5}, {1,5}, {2,5}, {3,5}, {4,5}, {5,5}){6} // Arguments[{7}] <-> Arguments[{8}]", b1 > b2, b1 >= b2, b1 == b2, b1 <= b2, b1 < b2, b1 != b2, (n < count * count - 1) ? "," : " ", i, j);
}
}
tw.WriteLine(" );");
tw.WriteLine();
}
static void GenerateGCDResults(TextWriter tw)
{
int count = testData.Length;
TestResult[] results = new TestResult[count * count];
int n = 0;
for (int i = 0; i < count; i++)
{
BigInteger b1 = BigInteger.Parse(testData[i]);
for (int j = 0; j < count; j++, n++)
{
BigInteger b2 = BigInteger.Parse(testData[j]);
BigInteger b3 = BigInteger.GreatestCommonDivisor(b1, b2);
results[n].val = b3.ToString();
results[n].info = TestResultInfo.Ok;
}
}
WriteDyadicResults(tw, "GCDResults", results, count, "gcd");
}
static void GenerateByteArrayResults(TextWriter tw)
{
int count = testData.Length;
TestResult[] results = new TestResult[count];
for (int i = 0; i < count; i++)
{
BigInteger b = BigInteger.Parse(testData[i]);
byte[] bArray = b.ToByteArray();
int bArrayLength = bArray.Length;
StringBuilder sb = new StringBuilder(bArray.Length);
for (int j = 0; j < bArrayLength; j++)
sb.AppendFormat("{0:X2}", bArray[j]);
results[i].val = sb.ToString();
results[i].info = TestResultInfo.Ok;
}
WriteMonadicResults(tw, "ByteArrayResults", results, count, "", ".ToByteArray");
}
static void GenerateHexResults(TextWriter tw)
{
int count = testData.Length;
TestResult[] results = new TestResult[count];
for (int i = 0; i < count; i++)
{
// This could be so easy, if not .NET would add a "0" in front of some values and if
// it displayed negative values as negative, just like in decimal mode.
BigInteger b = BigInteger.Parse(testData[i]);
results[i].info = TestResultInfo.Ok;
string s = BigInteger.Abs(b).ToString("X");
if (s.Length > 1 && s[0] == '0')
s = s.Substring(1); // get rid of leading 0
if (b < 0)
s = "-" + s; // if negative, show it
results[i].val = s;
}
WriteMonadicResults(tw, "HexResults", results, count, "", ".ToString(16)");
}
static void GenerateAsIntegerResults(TextWriter tw)
{
int count = testData.Length;
TestResult[] results = new TestResult[count];
for (int i = 0; i < count; i++)
{
BigInteger b = BigInteger.Parse(testData[i]);
TestResult tr;
tr.info = TestResultInfo.Ok;
try
{
int bi = (int)b;
tr.val = String.Format("{0}", bi);
}
catch (OverflowException e)
{
Console.WriteLine("Error: {0} ({1})", e.Message, b);
tr.info = TestResultInfo.Overflow;
tr.val = "";
}
results[i] = tr;
}
WriteMonadicResults(tw, "AsIntegerResults", results, count, "", ".AsInteger");
}
static void GenerateAsCardinalResults(TextWriter tw)
{
int count = testData.Length;
TestResult[] results = new TestResult[count];
for (int i = 0; i < count; i++)
{
BigInteger b = BigInteger.Parse(testData[i]);
TestResult tr;
tr.info = TestResultInfo.Ok;
try
{
UInt32 bi = (UInt32)b;
tr.val = bi.ToString();
}
catch (OverflowException e)
{
Console.WriteLine("Error: {0} ({1})", e.Message, b);
tr.info = TestResultInfo.Overflow;
tr.val = "";
}
results[i] = tr;
}
WriteMonadicResults(tw, "AsCardinalResults", results, count, "", ".AsCardinal");
}
static void GenerateAsInt64Results(TextWriter tw)
{
int count = testData.Length;
TestResult[] results = new TestResult[count];
for (int i = 0; i < count; i++)
{
BigInteger b = BigInteger.Parse(testData[i]);
TestResult tr;
tr.info = TestResultInfo.Ok;
try
{
Int64 bi = (Int64)b;
tr.val = bi.ToString();
}
catch (OverflowException e)
{
Console.WriteLine("Error: {0} ({1})", e.Message, b);
tr.info = TestResultInfo.Overflow;
tr.val = "";
}
results[i] = tr;
}
WriteMonadicResults(tw, "AsInt64Results", results, count, "", ".AsInt64");
}
static void GenerateAsUInt64Results(TextWriter tw)
{
int count = testData.Length;
TestResult[] results = new TestResult[count];
for (int i = 0; i < count; i++)
{
BigInteger b = BigInteger.Parse(testData[i]);
TestResult tr;
tr.info = TestResultInfo.Ok;
try
{
UInt64 bi = (UInt64)b;
tr.val = bi.ToString();
}
catch (OverflowException e)
{
Console.WriteLine("Error: {0} ({1})", e.Message, b);
tr.info = TestResultInfo.Overflow;
tr.val = "";
}
results[i] = tr;
}
WriteMonadicResults(tw, "AsUInt64Results", results, count, "", ".AsUInt64");
}
static void GenerateMinResults(TextWriter tw)
{
int count = testData.Length;
TestResult[] results = new TestResult[count * count];
int n = 0;
for (int i = 0; i < count; i++)
{
BigInteger b1 = BigInteger.Parse(testData[i]);
for (int j = 0; j < count; j++, n++)
{
BigInteger b2 = BigInteger.Parse(testData[j]);
BigInteger b3 = BigInteger.Min(b1, b2);
results[n].info = TestResultInfo.Ok;
results[n].val = b3.ToString();
}
}
WriteDyadicResults(tw, "MinResults", results, count, "min");
}
static void GenerateMaxResults(TextWriter tw)
{
int count = testData.Length;
TestResult[] results = new TestResult[count * count];
int n = 0;
for (int i = 0; i < count; i++)
{
BigInteger b1 = BigInteger.Parse(testData[i]);
for (int j = 0; j < count; j++, n++)
{
BigInteger b2 = BigInteger.Parse(testData[j]);
BigInteger b3 = BigInteger.Max(b1, b2);
results[n].info = TestResultInfo.Ok;
results[n].val = b3.ToString();
}
}
WriteDyadicResults(tw, "MaxResults", results, count, "min");
}
static void GenerateFromDoubleResults(TextWriter tw)
{
int count = doubles.Length;
TestResult[] results = new TestResult[count];
for (int i = 0; i < count; i++)
{
BigInteger b = new BigInteger(doubles[i]);
results[i].info = TestResultInfo.Ok;
results[i].val = b.ToString();
}
tw.WriteLine();
tw.WriteLine(" {0}: array[0..DoubleCount - 1] of TTestResult =", "CreateDoubleResults");
tw.WriteLine(" (");
for (int i = 0; i < count; ++i)
FormatResult(tw, results[i], (i == count - 1), String.Format("BigInteger.Create({0})", doubles[i].ToString(CultureInfo.InvariantCulture)));
tw.WriteLine(" );");
tw.WriteLine();
}
// Experimental, to get debug info:
static BigInteger MyModPow(BigInteger abase, BigInteger exponent, BigInteger modulus)
{
if (modulus.IsOne)
return BigInteger.Zero;
BigInteger result = BigInteger.One;
abase = abase % modulus;
while (exponent > 0)
{
if (!exponent.IsEven)
result = (result * abase) % modulus;
exponent >>= 1;
abase = (abase * abase) % modulus;
}
return result;
}
static void GenerateModPowResults(TextWriter tw)
{
int count = testData.Length;
int num = count / 5 + 1;
int total = num * num * num;
tw.WriteLine(" ModPowResultsCount = {0}; // using MyModPow()", total);
tw.WriteLine(" ModPowResults: array[0..ModPowResultsCount - 1] of TTestResult =");
tw.WriteLine(" (");
int n = 0;
// Starting at 2, 0, 1 resp. produces a few exceptions, as desired.
for (int i = 2; i < count; i += 5)
{
BigInteger d1 = BigInteger.Abs(BigInteger.Parse(testData[i]));
for (int j = 0; j < count; j += 5)
{
BigInteger d2 = BigInteger.Abs(BigInteger.Parse(testData[j]));
for (int k = 1; k < count; k += 5, ++n)
{
BigInteger d3 = BigInteger.Abs(BigInteger.Parse(testData[k]));
TestResult tr;
try
{
BigInteger d4 = MyModPow(d1, d2, d3);
tr.val = d4.ToString();
tr.info = TestResultInfo.Ok;
}
catch (Exception e)
{
Console.WriteLine("({0},{1},{2},{3}): ModPow error: %s", i, j, k, n, e.Message);
tr.val = e.Message;
tr.info = TestResultInfo.DivideByZero;
}
FormatResult(tw, tr, n == total - 1, String.Format("({0}): ModPow(Arguments[{1}], Arguments[{2}], Arguments[{3}])", n, i, j, k));
}
}
}
tw.WriteLine(" );");
tw.WriteLine();
}
#region Data
static string[] testData = new string[]
{
"-1585715829851573239739325670632039865384960", // -0x1234 00000000 00000000 00000000 00000000
"-18034965446809738563558854193883715207167", // -0x34 FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF
"-779879232593610263927748006161",
"-82261793876695338192268955270",
"-8840587743209014991486176890",
"-499680576774082292410113726",
"-7096499840976817344578600",
"-74287305190053403856772",
"-13416290973509623768074",
"-8271324858169862655834",
"-1673271581108184934182",
"-100000",
"-45808",
"-10000",
"-1000",
"-100",
"-56",
"-10",
"-7",
"-2",
"-1",
"0",
"1",
"2",
"7",
"10",
"100",
"409",
"818",
"1000",
"10000",
"100000",
"1000000",
"4234575746049986044",
"5387241703157997895",
"9223372041149612032",
"172872415652910937156",
"977677435906606235647", // 0x34 FFFFFFFF FFFFFFFF
"1673271581108184934182",
"8271324858169862655834",
"13416290973509623768074",
"74287305190053403856772",
"85961827383486510530560",
"7096499840976817344578600",
"499680576774082292410113726",
"1243478184157339114435077574",
"8840587743209014991486176890",
"19807040619342712359383728129",
"63733365657267277460012361609",
"82261793876695338192268955270",
"779879232593610263927748006161",
"113110558780721284166510605813",
"4847586039315419829807005894255429",
"90612345123875509091827560007100099",
"85070591730234615847396907784232501249", // 0x3FFFFFFF FFFFFFFF 00000000 00000001
"85070591730234615847396907784232501250",
"680564693277057719623408366969033850880",
"18034965446809738563558854193883715207167", // 0x34 FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF
"1585715829851573239739325670632039865384960", // 0x1234 00000000 00000000 00000000 00000000
"1234567890123456789012345678901234567890123456789012345678901234567890", // 0x2D CAEC4C2D F4268937 664439BA 2F162FC2 D76998CB ACCFF196 CE3F0AD2
// Add your own data between this and the following comment
"343597383679999999999999999995663191310057982263970188796520233154296875",
"3435973836799999999999999999956631913100579822639701887965202331542968750000000000000",
"10000000000000",
"1000000000000000000000000000000000000000000000000000000000"
};
static int[] bitShifts = new int[]
{
1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 20,
25, 30, 31, 32, 33, 35, 40, 50,
60, 70, 71, 72, 73, 74, 75, 90,
100, 110, 159, 160, 161, 162, 163, 164,
};
static double[] doubles = new double[]
{
-6.0E20,
-1.0E20,
-3.51,
-3.5,
-3.49,
-2.51,
-2.5,
-2.49,
-2.0E-100,
0.0,
7.0E-8,
0.0001,
0.1,
0.2,
0.3,
0.4,
0.49999999999999,
0.5,
0.50000001,
0.7,
0.9,
1.0,
1.00000000000001,
1.1,
1.49999999999999,
1.5,
1.50000000000001,
1.9999,
2.0,
2.49,
2.5,
2.51,
3.0,
3.49,
3.5,
3.51,
4.0,
4.1,
4.2,
4.4,
4.5,
4.6,
4.9999,
5.0,
6.0,
7.0,
8.0,
9.0,
10.0,
15.0,
22.0,
44.0,
85.0,
128.0,
256.0,
256.1,
256.5,
256.7,
300.0,
876.543210987654,
645000.0,
1000000.49999999999999,
1000000.5,
1000000.50000000000001,
1048576.1,
1048576.5,
10000000000.0,
14900000000.0,
15000000000.0,
15100000000.0,
31415920000.0,
100000000000.0,
1000000000000.0,
10000000000000.0,
100000000000000.0,
1.0E15,
2.0E15,
4.0E15,
4.9E15,
8.0E15,
1.0E16,
2.0E16,
4.0E16,
5.0E16,
1.0E17,
1.0E18,
1.0E19,
1.23456789012346E19,
1.0E20,
1.0E14 + 1.0,
1.0E14 + 2.0,
1.0E14 + 4.0,
1.0E14 + 8.0,
1.0E14 + 16.0,
1.0E14 + 32.0,
1.0E14 + 64.0,
1.0E14 + 128.0,
1.0E14 + 256.0,
1.0E14 + 512.0,
1.0E80
};
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Net.HttpListenerRequest
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo.mono@gmail.com)
// Marek Safar (marek.safar@gmail.com)
//
// Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
// Copyright (c) 2011-2012 Xamarin, Inc. (http://xamarin.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.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Net.WebSockets;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace System.Net
{
public sealed partial class HttpListenerRequest
{
private class Context : TransportContext
{
public override ChannelBinding GetChannelBinding(ChannelBindingKind kind)
{
throw new NotImplementedException();
}
}
private string[] _acceptTypes;
private Encoding _contentEncoding;
private long _contentLength;
private bool _clSet;
private CookieCollection _cookies;
private WebHeaderCollection _headers;
private string _method;
private Stream _inputStream;
private Version _version;
private NameValueCollection _queryString; // check if null is ok, check if read-only, check case-sensitiveness
private string _rawUrl;
private Uri _url;
private Uri _referrer;
private string[] _userLanguages;
private HttpListenerContext _context;
private bool _isChunked;
private bool _kaSet;
private bool _keepAlive;
private static byte[] s_100continue = Encoding.ASCII.GetBytes("HTTP/1.1 100 Continue\r\n\r\n");
internal HttpListenerRequest(HttpListenerContext context)
{
_context = context;
_headers = new WebHeaderCollection();
_version = HttpVersion.Version10;
}
private static char[] s_separators = new char[] { ' ' };
internal void SetRequestLine(string req)
{
string[] parts = req.Split(s_separators, 3);
if (parts.Length != 3)
{
_context.ErrorMessage = "Invalid request line (parts).";
return;
}
_method = parts[0];
foreach (char c in _method)
{
int ic = (int)c;
if ((ic >= 'A' && ic <= 'Z') ||
(ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
continue;
_context.ErrorMessage = "(Invalid verb)";
return;
}
_rawUrl = parts[1];
if (parts[2].Length != 8 || !parts[2].StartsWith("HTTP/"))
{
_context.ErrorMessage = "Invalid request line (version).";
return;
}
try
{
_version = new Version(parts[2].Substring(5));
if (_version.Major < 1)
throw new Exception();
}
catch
{
_context.ErrorMessage = "Invalid request line (version).";
return;
}
}
private void CreateQueryString(string query)
{
if (query == null || query.Length == 0)
{
_queryString = new NameValueCollection(1);
return;
}
_queryString = new NameValueCollection();
if (query[0] == '?')
query = query.Substring(1);
string[] components = query.Split('&');
foreach (string kv in components)
{
int pos = kv.IndexOf('=');
if (pos == -1)
{
_queryString.Add(null, WebUtility.UrlDecode(kv));
}
else
{
string key = WebUtility.UrlDecode(kv.Substring(0, pos));
string val = WebUtility.UrlDecode(kv.Substring(pos + 1));
_queryString.Add(key, val);
}
}
}
private static bool MaybeUri(string s)
{
int p = s.IndexOf(':');
if (p == -1)
return false;
if (p >= 10)
return false;
return IsPredefinedScheme(s.Substring(0, p));
}
private static bool IsPredefinedScheme(string scheme)
{
if (scheme == null || scheme.Length < 3)
return false;
char c = scheme[0];
if (c == 'h')
return (scheme == "http" || scheme == "https");
if (c == 'f')
return (scheme == "file" || scheme == "ftp");
if (c == 'n')
{
c = scheme[1];
if (c == 'e')
return (scheme == "news" || scheme == "net.pipe" || scheme == "net.tcp");
if (scheme == "nntp")
return true;
return false;
}
if ((c == 'g' && scheme == "gopher") || (c == 'm' && scheme == "mailto"))
return true;
return false;
}
internal void FinishInitialization()
{
string host = UserHostName;
if (_version > HttpVersion.Version10 && (host == null || host.Length == 0))
{
_context.ErrorMessage = "Invalid host name";
return;
}
string path;
Uri raw_uri = null;
if (MaybeUri(_rawUrl.ToLowerInvariant()) && Uri.TryCreate(_rawUrl, UriKind.Absolute, out raw_uri))
path = raw_uri.PathAndQuery;
else
path = _rawUrl;
if ((host == null || host.Length == 0))
host = UserHostAddress;
if (raw_uri != null)
host = raw_uri.Host;
int colon = host.IndexOf(':');
if (colon >= 0)
host = host.Substring(0, colon);
string base_uri = String.Format("{0}://{1}:{2}",
(IsSecureConnection) ? "https" : "http",
host, LocalEndPoint.Port);
if (!Uri.TryCreate(base_uri + path, UriKind.Absolute, out _url))
{
_context.ErrorMessage = WebUtility.HtmlEncode("Invalid url: " + base_uri + path);
return;
}
CreateQueryString(_url.Query);
_url = HttpListenerRequestUriBuilder.GetRequestUri(_rawUrl, _url.Scheme,
_url.Authority, _url.LocalPath, _url.Query);
if (_version >= HttpVersion.Version11)
{
string t_encoding = Headers["Transfer-Encoding"];
_isChunked = (t_encoding != null && string.Equals(t_encoding, "chunked", StringComparison.OrdinalIgnoreCase));
// 'identity' is not valid!
if (t_encoding != null && !_isChunked)
{
_context.Connection.SendError(null, 501);
return;
}
}
if (!_isChunked && !_clSet)
{
if (string.Equals(_method, "POST", StringComparison.OrdinalIgnoreCase) ||
string.Equals(_method, "PUT", StringComparison.OrdinalIgnoreCase))
{
_context.Connection.SendError(null, 411);
return;
}
}
if (String.Compare(Headers["Expect"], "100-continue", StringComparison.OrdinalIgnoreCase) == 0)
{
HttpResponseStream output = _context.Connection.GetResponseStream();
output.InternalWrite(s_100continue, 0, s_100continue.Length);
}
}
internal static string Unquote(String str)
{
int start = str.IndexOf('\"');
int end = str.LastIndexOf('\"');
if (start >= 0 && end >= 0)
str = str.Substring(start + 1, end - 1);
return str.Trim();
}
internal void AddHeader(string header)
{
int colon = header.IndexOf(':');
if (colon == -1 || colon == 0)
{
_context.ErrorMessage = HttpStatusDescription.Get(400);
_context.ErrorStatus = 400;
return;
}
string name = header.Substring(0, colon).Trim();
string val = header.Substring(colon + 1).Trim();
string lower = name.ToLower(CultureInfo.InvariantCulture);
_headers.Set(name, val);
switch (lower)
{
case "accept-language":
_userLanguages = val.Split(','); // yes, only split with a ','
break;
case "accept":
_acceptTypes = val.Split(','); // yes, only split with a ','
break;
case "content-length":
try
{
_contentLength = long.Parse(val.Trim());
if (_contentLength < 0)
_context.ErrorMessage = "Invalid Content-Length.";
_clSet = true;
}
catch
{
_context.ErrorMessage = "Invalid Content-Length.";
}
break;
case "referer":
try
{
_referrer = new Uri(val);
}
catch
{
_referrer = null;
}
break;
case "cookie":
if (_cookies == null)
_cookies = new CookieCollection();
string[] cookieStrings = val.Split(new char[] { ',', ';' });
Cookie current = null;
int version = 0;
foreach (string cookieString in cookieStrings)
{
string str = cookieString.Trim();
if (str.Length == 0)
continue;
if (str.StartsWith("$Version"))
{
version = Int32.Parse(Unquote(str.Substring(str.IndexOf('=') + 1)));
}
else if (str.StartsWith("$Path"))
{
if (current != null)
current.Path = str.Substring(str.IndexOf('=') + 1).Trim();
}
else if (str.StartsWith("$Domain"))
{
if (current != null)
current.Domain = str.Substring(str.IndexOf('=') + 1).Trim();
}
else if (str.StartsWith("$Port"))
{
if (current != null)
current.Port = str.Substring(str.IndexOf('=') + 1).Trim();
}
else
{
if (current != null)
{
_cookies.Add(current);
}
current = new Cookie();
int idx = str.IndexOf('=');
if (idx > 0)
{
current.Name = str.Substring(0, idx).Trim();
current.Value = str.Substring(idx + 1).Trim();
}
else
{
current.Name = str.Trim();
current.Value = String.Empty;
}
current.Version = version;
}
}
if (current != null)
{
_cookies.Add(current);
}
break;
}
}
// returns true is the stream could be reused.
internal bool FlushInput()
{
if (!HasEntityBody)
return true;
int length = 2048;
if (_contentLength > 0)
length = (int)Math.Min(_contentLength, (long)length);
byte[] bytes = new byte[length];
while (true)
{
try
{
IAsyncResult ares = InputStream.BeginRead(bytes, 0, length, null, null);
if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne(1000))
return false;
if (InputStream.EndRead(ares) <= 0)
return true;
}
catch (ObjectDisposedException)
{
_inputStream = null;
return true;
}
catch
{
return false;
}
}
}
public string[] AcceptTypes
{
get { return _acceptTypes; }
}
public int ClientCertificateError
{
get
{
HttpConnection cnc = _context.Connection;
if (cnc.ClientCertificate == null)
throw new InvalidOperationException(SR.net_no_client_certificate);
int[] errors = cnc.ClientCertificateErrors;
if (errors != null && errors.Length > 0)
return errors[0];
return 0;
}
}
public Encoding ContentEncoding
{
get
{
if (_contentEncoding == null)
_contentEncoding = Encoding.Default;
return _contentEncoding;
}
}
public long ContentLength64
{
get
{
if (_isChunked)
_contentLength = -1;
return _contentLength;
}
}
public string ContentType
{
get { return _headers["content-type"]; }
}
public CookieCollection Cookies
{
get
{
if (_cookies == null)
_cookies = new CookieCollection();
return _cookies;
}
}
public bool HasEntityBody
{
get { return (_contentLength > 0 || _isChunked); }
}
public NameValueCollection Headers
{
get { return _headers; }
}
public string HttpMethod
{
get { return _method; }
}
public Stream InputStream
{
get
{
if (_inputStream == null)
{
if (_isChunked || _contentLength > 0)
_inputStream = _context.Connection.GetRequestStream(_isChunked, _contentLength);
else
_inputStream = Stream.Null;
}
return _inputStream;
}
}
public bool IsAuthenticated
{
get { return false; }
}
public bool IsLocal
{
get { return LocalEndPoint.Address.Equals(RemoteEndPoint.Address); }
}
public bool IsSecureConnection
{
get { return _context.Connection.IsSecure; }
}
public bool KeepAlive
{
get
{
if (_kaSet)
return _keepAlive;
_kaSet = true;
// 1. Connection header
// 2. Protocol (1.1 == keep-alive by default)
// 3. Keep-Alive header
string cnc = _headers["Connection"];
if (!String.IsNullOrEmpty(cnc))
{
_keepAlive = (0 == String.Compare(cnc, "keep-alive", StringComparison.OrdinalIgnoreCase));
}
else if (_version == HttpVersion.Version11)
{
_keepAlive = true;
}
else
{
cnc = _headers["keep-alive"];
if (!String.IsNullOrEmpty(cnc))
_keepAlive = (0 != String.Compare(cnc, "closed", StringComparison.OrdinalIgnoreCase));
}
return _keepAlive;
}
}
public IPEndPoint LocalEndPoint
{
get { return _context.Connection.LocalEndPoint; }
}
public Version ProtocolVersion
{
get { return _version; }
}
public NameValueCollection QueryString
{
get { return _queryString; }
}
public string RawUrl
{
get { return _rawUrl; }
}
public IPEndPoint RemoteEndPoint
{
get { return _context.Connection.RemoteEndPoint; }
}
public Guid RequestTraceIdentifier
{
get { return Guid.Empty; }
}
public Uri Url
{
get { return _url; }
}
public Uri UrlReferrer
{
get { return _referrer; }
}
public string UserAgent
{
get { return _headers["user-agent"]; }
}
public string UserHostAddress
{
get { return LocalEndPoint.ToString(); }
}
public string UserHostName
{
get { return _headers["host"]; }
}
public string[] UserLanguages
{
get { return _userLanguages; }
}
public IAsyncResult BeginGetClientCertificate(AsyncCallback requestCallback, object state)
{
Task<X509Certificate2> getClientCertificate = new Task<X509Certificate2>(() => GetClientCertificate());
return TaskToApm.Begin(getClientCertificate, requestCallback, state);
}
public X509Certificate2 EndGetClientCertificate(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
return TaskToApm.End<X509Certificate2>(asyncResult);
}
public X509Certificate2 GetClientCertificate()
{
return _context.Connection.ClientCertificate;
}
public string ServiceName
{
get
{
return null;
}
}
public TransportContext TransportContext
{
get
{
return new Context();
}
}
public bool IsWebSocketRequest
{
get
{
if (string.IsNullOrEmpty(Headers[HttpKnownHeaderNames.Connection]) || string.IsNullOrEmpty(Headers[HttpKnownHeaderNames.Upgrade]))
{
return false;
}
bool foundConnectionUpgradeHeader = false;
foreach (string connection in Headers.GetValues(HttpKnownHeaderNames.Connection))
{
if (string.Equals(connection, HttpKnownHeaderNames.Upgrade, StringComparison.OrdinalIgnoreCase))
{
foundConnectionUpgradeHeader = true;
break;
}
}
if (!foundConnectionUpgradeHeader)
{
return false;
}
foreach (string upgrade in Headers.GetValues(HttpKnownHeaderNames.Upgrade))
{
if (string.Equals(upgrade, HttpWebSocket.WebSocketUpgradeToken, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
}
public Task<X509Certificate2> GetClientCertificateAsync()
{
return Task<X509Certificate2>.Factory.FromAsync(BeginGetClientCertificate, EndGetClientCertificate, null);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Jint.Collections;
using Jint.Native.Array;
using Jint.Native.ArrayBuffer;
using Jint.Native.Iterator;
using Jint.Native.Number;
using Jint.Native.Object;
using Jint.Native.Symbol;
using Jint.Pooling;
using Jint.Runtime;
using Jint.Runtime.Descriptors;
using Jint.Runtime.Interop;
namespace Jint.Native.TypedArray
{
/// <summary>
/// https://tc39.es/ecma262/#sec-properties-of-the-%typedarrayprototype%-object
/// </summary>
internal sealed class IntrinsicTypedArrayPrototype : ObjectInstance
{
private readonly Realm _realm;
private readonly IntrinsicTypedArrayConstructor _constructor;
private ClrFunctionInstance _originalIteratorFunction;
internal IntrinsicTypedArrayPrototype(
Engine engine,
Realm realm,
ObjectInstance objectPrototype,
IntrinsicTypedArrayConstructor constructor) : base(engine)
{
_prototype = objectPrototype;
_realm = realm;
_constructor = constructor;
}
protected override void Initialize()
{
const PropertyFlag lengthFlags = PropertyFlag.Configurable;
const PropertyFlag propertyFlags = PropertyFlag.Writable | PropertyFlag.Configurable;
var properties = new PropertyDictionary(33, false)
{
["buffer"] = new GetSetPropertyDescriptor(new ClrFunctionInstance(_engine, "get buffer", Buffer, 0, lengthFlags), Undefined, PropertyFlag.Configurable),
["byteLength"] = new GetSetPropertyDescriptor(new ClrFunctionInstance(_engine, "get byteLength", ByteLength, 0, lengthFlags), Undefined, PropertyFlag.Configurable),
["byteOffset"] = new GetSetPropertyDescriptor(new ClrFunctionInstance(Engine, "get byteOffset", ByteOffset, 0, lengthFlags), Undefined, PropertyFlag.Configurable),
["length"] = new GetSetPropertyDescriptor(new ClrFunctionInstance(Engine, "get length", GetLength, 0, lengthFlags), Undefined, PropertyFlag.Configurable),
["constructor"] = new(_constructor, PropertyFlag.NonEnumerable),
["copyWithin"] = new(new ClrFunctionInstance(Engine, "copyWithin", CopyWithin, 2, PropertyFlag.Configurable), propertyFlags),
["entries"] = new(new ClrFunctionInstance(Engine, "entries", Entries, 0, PropertyFlag.Configurable), propertyFlags),
["every"] = new(new ClrFunctionInstance(Engine, "every", Every, 1, PropertyFlag.Configurable), propertyFlags),
["fill"] = new(new ClrFunctionInstance(Engine, "fill", Fill, 1, PropertyFlag.Configurable), propertyFlags),
["filter"] = new(new ClrFunctionInstance(Engine, "filter", Filter, 1, PropertyFlag.Configurable), propertyFlags),
["find"] = new(new ClrFunctionInstance(Engine, "find", Find, 1, PropertyFlag.Configurable), propertyFlags),
["findIndex"] = new(new ClrFunctionInstance(Engine, "findIndex", FindIndex, 1, PropertyFlag.Configurable), propertyFlags),
["findLast"] = new(new ClrFunctionInstance(Engine, "findLast", FindLast, 1, PropertyFlag.Configurable), propertyFlags),
["findLastIndex"] = new(new ClrFunctionInstance(Engine, "findLastIndex", FindLastIndex, 1, PropertyFlag.Configurable), propertyFlags),
["forEach"] = new(new ClrFunctionInstance(Engine, "forEach", ForEach, 1, PropertyFlag.Configurable), propertyFlags),
["includes"] = new(new ClrFunctionInstance(Engine, "includes", Includes, 1, PropertyFlag.Configurable), propertyFlags),
["indexOf"] = new(new ClrFunctionInstance(Engine, "indexOf", IndexOf, 1, PropertyFlag.Configurable), propertyFlags),
["join"] = new(new ClrFunctionInstance(Engine, "join", Join, 1, PropertyFlag.Configurable), propertyFlags),
["keys"] = new(new ClrFunctionInstance(Engine, "keys", Keys, 0, PropertyFlag.Configurable), propertyFlags),
["lastIndexOf"] = new(new ClrFunctionInstance(Engine, "lastIndexOf", LastIndexOf, 1, PropertyFlag.Configurable), propertyFlags),
["map"] = new(new ClrFunctionInstance(Engine, "map", Map, 1, PropertyFlag.Configurable), propertyFlags),
["reduce"] = new(new ClrFunctionInstance(Engine, "reduce", Reduce, 1, PropertyFlag.Configurable), propertyFlags),
["reduceRight"] = new(new ClrFunctionInstance(Engine, "reduceRight", ReduceRight, 1, PropertyFlag.Configurable), propertyFlags),
["reverse"] = new(new ClrFunctionInstance(Engine, "reverse", Reverse, 0, PropertyFlag.Configurable), propertyFlags),
["set"] = new(new ClrFunctionInstance(Engine, "set", Set, 1, PropertyFlag.Configurable), propertyFlags),
["slice"] = new(new ClrFunctionInstance(Engine, "slice", Slice, 2, PropertyFlag.Configurable), propertyFlags),
["some"] = new(new ClrFunctionInstance(Engine, "some", Some, 1, PropertyFlag.Configurable), propertyFlags),
["sort"] = new(new ClrFunctionInstance(Engine, "sort", Sort, 1, PropertyFlag.Configurable), propertyFlags),
["subarray"] = new(new ClrFunctionInstance(Engine, "subarray", Subarray, 2, PropertyFlag.Configurable), propertyFlags),
["toLocaleString"] = new(new ClrFunctionInstance(Engine, "toLocaleString", ToLocaleString, 0, PropertyFlag.Configurable), propertyFlags),
["toString"] = new(new ClrFunctionInstance(Engine, "toLocaleString", _realm.Intrinsics.Array.PrototypeObject.ToString, 0, PropertyFlag.Configurable), propertyFlags),
["values"] = new(new ClrFunctionInstance(Engine, "values", Values, 0, PropertyFlag.Configurable), propertyFlags),
["at"] = new(new ClrFunctionInstance(Engine, "at", At, 1, PropertyFlag.Configurable), propertyFlags),
};
SetProperties(properties);
_originalIteratorFunction = new ClrFunctionInstance(Engine, "iterator", Values, 1);
var symbols = new SymbolDictionary(2)
{
[GlobalSymbolRegistry.Iterator] = new(_originalIteratorFunction, propertyFlags),
[GlobalSymbolRegistry.ToStringTag] = new GetSetPropertyDescriptor(
new ClrFunctionInstance(Engine, "get [Symbol.toStringTag]", ToStringTag, 0, PropertyFlag.Configurable),
Undefined,
PropertyFlag.Configurable)
};
SetSymbols(symbols);
}
/// <summary>
/// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype.buffer
/// </summary>
private JsValue Buffer(JsValue thisObj, JsValue[] arguments)
{
var o = thisObj as TypedArrayInstance;
if (o is null)
{
ExceptionHelper.ThrowTypeError(_realm);
}
return o._viewedArrayBuffer;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype.bytelength
/// </summary>
private JsValue ByteLength(JsValue thisObj, JsValue[] arguments)
{
var o = thisObj as TypedArrayInstance;
if (o is null)
{
ExceptionHelper.ThrowTypeError(_realm);
}
if (o._viewedArrayBuffer.IsDetachedBuffer)
{
return JsNumber.PositiveZero;
}
return JsNumber.Create(o._byteLength);
}
/// <summary>
/// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype.byteoffset
/// </summary>
private JsValue ByteOffset(JsValue thisObj, JsValue[] arguments)
{
var o = thisObj as TypedArrayInstance;
if (o is null)
{
ExceptionHelper.ThrowTypeError(_realm);
}
if (o._viewedArrayBuffer.IsDetachedBuffer)
{
return JsNumber.PositiveZero;
}
return JsNumber.Create(o._byteOffset);
}
/// <summary>
/// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype.length
/// </summary>
private JsValue GetLength(JsValue thisObj, JsValue[] arguments)
{
var o = thisObj as TypedArrayInstance;
if (o is null)
{
ExceptionHelper.ThrowTypeError(_realm);
}
var buffer = o._viewedArrayBuffer;
if (buffer.IsDetachedBuffer)
{
return JsNumber.PositiveZero;
}
return JsNumber.Create(o.Length);
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.copywithin
/// </summary>
private JsValue CopyWithin(JsValue thisObj, JsValue[] arguments)
{
var o = thisObj.ValidateTypedArray(_realm);
var target = arguments.At(0);
var start = arguments.At(1);
var end = arguments.At(2);
long len = o.Length;
var relativeTarget = TypeConverter.ToIntegerOrInfinity(target);
long to;
if (double.IsNegativeInfinity(relativeTarget))
{
to = 0;
}
else if (relativeTarget < 0)
{
to = (long) System.Math.Max(len + relativeTarget, 0);
}
else
{
to = (long) System.Math.Min(relativeTarget, len);
}
var relativeStart = TypeConverter.ToIntegerOrInfinity(start);
long from;
if (double.IsNegativeInfinity(relativeStart))
{
from = 0;
}
else if (relativeStart < 0)
{
from = (long) System.Math.Max(len + relativeStart, 0);
}
else
{
from = (long) System.Math.Min(relativeStart, len);
}
var relativeEnd = end.IsUndefined()
? len
: TypeConverter.ToIntegerOrInfinity(end);
long final;
if (double.IsNegativeInfinity(relativeEnd))
{
final = 0;
}
else if (relativeEnd < 0)
{
final = (long) System.Math.Max(len + relativeEnd, 0);
}
else
{
final = (long) System.Math.Min(relativeEnd, len);
}
var count = System.Math.Min(final - from, len - to);
if (count > 0)
{
var buffer = o._viewedArrayBuffer;
buffer.AssertNotDetached();
var elementSize = o._arrayElementType.GetElementSize();
var byteOffset = o._byteOffset;
var toByteIndex = to * elementSize + byteOffset;
var fromByteIndex = from * elementSize + byteOffset;
var countBytes = count * elementSize;
int direction;
if (fromByteIndex < toByteIndex && toByteIndex < fromByteIndex + countBytes)
{
direction = -1;
fromByteIndex = fromByteIndex + countBytes - 1;
toByteIndex = toByteIndex + countBytes - 1;
}
else
{
direction = 1;
}
while (countBytes > 0)
{
var value = buffer.GetValueFromBuffer((int) fromByteIndex, TypedArrayElementType.Uint8, true, ArrayBufferOrder.Unordered);
buffer.SetValueInBuffer((int) toByteIndex, TypedArrayElementType.Uint8, value, true, ArrayBufferOrder.Unordered);
fromByteIndex += direction;
toByteIndex += direction;
countBytes--;
}
}
return o;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.entries
/// </summary>
private JsValue Entries(JsValue thisObj, JsValue[] arguments)
{
var o = thisObj.ValidateTypedArray(_realm);
return _realm.Intrinsics.ArrayIteratorPrototype.Construct(o, ArrayIteratorType.KeyAndValue);
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.every
/// </summary>
private JsValue Every(JsValue thisObj, JsValue[] arguments)
{
var o = thisObj.ValidateTypedArray(_realm);
var len = o.Length;
if (len == 0)
{
return JsBoolean.True;
}
var predicate = GetCallable(arguments.At(0));
var thisArg = arguments.At(1);
var args = _engine._jsValueArrayPool.RentArray(3);
args[2] = o;
for (var k = 0; k < len; k++)
{
args[0] = o[k];
args[1] = k;
if (!TypeConverter.ToBoolean(predicate.Call(thisArg, args)))
{
return JsBoolean.False;
}
}
_engine._jsValueArrayPool.ReturnArray(args);
return JsBoolean.True;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.fill
/// </summary>
private JsValue Fill(JsValue thisObj, JsValue[] arguments)
{
var o = thisObj.ValidateTypedArray(_realm);
var jsValue = arguments.At(0);
var start = arguments.At(1);
var end = arguments.At(2);
JsValue value;
if (o._contentType == TypedArrayContentType.BigInt)
{
value = JsBigInt.Create(jsValue.ToBigInteger(_engine));
}
else
{
value = JsNumber.Create(jsValue);
}
var len = o.Length;
int k;
var relativeStart = TypeConverter.ToIntegerOrInfinity(start);
if (double.IsNegativeInfinity(relativeStart))
{
k = 0;
}
else if (relativeStart < 0)
{
k = (int) System.Math.Max(len + relativeStart, 0);
}
else
{
k = (int) System.Math.Min(relativeStart, len);
}
uint final;
var relativeEnd = end.IsUndefined() ? len : TypeConverter.ToIntegerOrInfinity(end);
if (double.IsNegativeInfinity(relativeEnd))
{
final = 0;
}
else if (relativeEnd < 0)
{
final = (uint) System.Math.Max(len + relativeEnd, 0);
}
else
{
final = (uint) System.Math.Min(relativeEnd, len);
}
o._viewedArrayBuffer.AssertNotDetached();
for (var i = k; i < final; ++i)
{
o[i] = value;
}
return thisObj;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.filter
/// </summary>
private JsValue Filter(JsValue thisObj, JsValue[] arguments)
{
var callbackfn = GetCallable(arguments.At(0));
var thisArg = arguments.At(1);
var o = thisObj.ValidateTypedArray(_realm);
var len = o.Length;
var kept = new List<JsValue>();
var captured = 0;
var args = _engine._jsValueArrayPool.RentArray(3);
args[2] = o;
for (var k = 0; k < len; k++)
{
var kValue = o[k];
args[0] = kValue;
args[1] = k;
var selected = callbackfn.Call(thisArg, args);
if (TypeConverter.ToBoolean(selected))
{
kept.Add(kValue);
captured++;
}
}
_engine._jsValueArrayPool.ReturnArray(args);
var a = _realm.Intrinsics.TypedArray.TypedArraySpeciesCreate(o, new JsValue[] { captured });
for (var n = 0; n < captured; ++n)
{
a[n] = kept[n];
}
return a;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.find
/// </summary>
private JsValue Find(JsValue thisObj, JsValue[] arguments)
{
return DoFind(thisObj, arguments).Value;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.findindex
/// </summary>
private JsValue FindIndex(JsValue thisObj, JsValue[] arguments)
{
return DoFind(thisObj, arguments).Key;
}
private JsValue FindLast(JsValue thisObj, JsValue[] arguments)
{
return DoFind(thisObj, arguments, fromEnd: true).Value;
}
private JsValue FindLastIndex(JsValue thisObj, JsValue[] arguments)
{
return DoFind(thisObj, arguments, fromEnd: true).Key;
}
private KeyValuePair<JsValue, JsValue> DoFind(JsValue thisObj, JsValue[] arguments, bool fromEnd = false)
{
var o = thisObj.ValidateTypedArray(_realm);
var len = (int) o.Length;
var predicate = GetCallable(arguments.At(0));
var thisArg = arguments.At(1);
var args = _engine._jsValueArrayPool.RentArray(3);
args[2] = o;
if (!fromEnd)
{
for (var k = 0; k < len; k++)
{
var kNumber = JsNumber.Create(k);
var kValue = o[k];
args[0] = kValue;
args[1] = kNumber;
if (TypeConverter.ToBoolean(predicate.Call(thisArg, args)))
{
return new KeyValuePair<JsValue, JsValue>(kNumber, kValue);
}
}
}
else
{
for (var k = len - 1; k >= 0; k--)
{
var kNumber = JsNumber.Create(k);
var kValue = o[k];
args[0] = kValue;
args[1] = kNumber;
if (TypeConverter.ToBoolean(predicate.Call(thisArg, args)))
{
return new KeyValuePair<JsValue, JsValue>(kNumber, kValue);
}
}
}
return new KeyValuePair<JsValue, JsValue>(JsNumber.IntegerNegativeOne, Undefined);
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.foreach
/// </summary>
private JsValue ForEach(JsValue thisObj, JsValue[] arguments)
{
var callbackfn = GetCallable(arguments.At(0));
var thisArg = arguments.At(1);
var o = thisObj.ValidateTypedArray(_realm);
var len = o.Length;
var args = _engine._jsValueArrayPool.RentArray(3);
args[2] = o;
for (var k = 0; k < len; k++)
{
var kValue = o[k];
args[0] = kValue;
args[1] = k;
callbackfn.Call(thisArg, args);
}
_engine._jsValueArrayPool.ReturnArray(args);
return Undefined;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.includes
/// </summary>
private JsValue Includes(JsValue thisObj, JsValue[] arguments)
{
var o = thisObj.ValidateTypedArray(_realm);
var len = o.Length;
if (len == 0)
{
return false;
}
var searchElement = arguments.At(0);
var fromIndex = arguments.At(1, 0);
var n = TypeConverter.ToIntegerOrInfinity(fromIndex);
if (double.IsPositiveInfinity(n))
{
return JsBoolean.False;
}
else if (double.IsNegativeInfinity(n))
{
n = 0;
}
long k;
if (n >= 0)
{
k = (long) n;
}
else
{
k = (long) (len + n);
if (k < 0)
{
k = 0;
}
}
while (k < len)
{
var value = o[(int) k];
if (SameValueZeroComparer.Equals(value, searchElement))
{
return JsBoolean.True;
}
k++;
}
return JsBoolean.False;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.indexof
/// </summary>
private JsValue IndexOf(JsValue thisObj, JsValue[] arguments)
{
var searchElement = arguments.At(0);
var fromIndex = arguments.At(1);
var o = thisObj.ValidateTypedArray(_realm);
var len = o.Length;
if (len == 0)
{
return JsNumber.IntegerNegativeOne;
}
var n = TypeConverter.ToIntegerOrInfinity(fromIndex);
if (double.IsPositiveInfinity(n))
{
return JsNumber.IntegerNegativeOne;
}
else if (double.IsNegativeInfinity(n))
{
n = 0;
}
long k;
if (n >= 0)
{
k = (long) n;
}
else
{
k = (long) (len + n);
if (k < 0)
{
k = 0;
}
}
for (; k < len; k++)
{
var kPresent = o.HasProperty(k);
if (kPresent)
{
var elementK = o[(int) k];
if (elementK == searchElement)
{
return k;
}
}
}
return JsNumber.IntegerNegativeOne;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.join
/// </summary>
private JsValue Join(JsValue thisObj, JsValue[] arguments)
{
var o = thisObj.ValidateTypedArray(_realm);
var separator = arguments.At(0);
var len = o.Length;
var sep = TypeConverter.ToString(separator.IsUndefined() ? JsString.CommaString : separator);
// as per the spec, this has to be called after ToString(separator)
if (len == 0)
{
return JsString.Empty;
}
static string StringFromJsValue(JsValue value)
{
return value.IsUndefined()
? ""
: TypeConverter.ToString(value);
}
var s = StringFromJsValue(o[0]);
if (len == 1)
{
return s;
}
using var sb = StringBuilderPool.Rent();
sb.Builder.Append(s);
for (var k = 1; k < len; k++)
{
sb.Builder.Append(sep);
sb.Builder.Append(StringFromJsValue(o[k]));
}
return sb.ToString();
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.keys
/// </summary>
private JsValue Keys(JsValue thisObj, JsValue[] arguments)
{
var o = thisObj.ValidateTypedArray(_realm);
return _realm.Intrinsics.ArrayIteratorPrototype.Construct(o, ArrayIteratorType.Key);
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.lastindexof
/// </summary>
private JsValue LastIndexOf(JsValue thisObj, JsValue[] arguments)
{
var searchElement = arguments.At(0);
var o = thisObj.ValidateTypedArray(_realm);
var len = o.Length;
if (len == 0)
{
return JsNumber.IntegerNegativeOne;
}
var fromIndex = arguments.At(1, len - 1);
var n = TypeConverter.ToIntegerOrInfinity(fromIndex);
if (double.IsNegativeInfinity(n))
{
return JsNumber.IntegerNegativeOne;
}
long k;
if (n >= 0)
{
k = (long) System.Math.Min(n, len - 1);
}
else
{
k = (long) (len + n);
}
for (; k >= 0; k--)
{
var kPresent = o.HasProperty(k);
if (kPresent)
{
var elementK = o[(int) k];
if (elementK == searchElement)
{
return k;
}
}
}
return JsNumber.IntegerNegativeOne;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.map
/// </summary>
private ObjectInstance Map(JsValue thisObj, JsValue[] arguments)
{
var o = thisObj.ValidateTypedArray(_realm);
var len = o.Length;
var thisArg = arguments.At(1);
var callable = GetCallable(arguments.At(0));
var a = _realm.Intrinsics.TypedArray.TypedArraySpeciesCreate(o, new JsValue[] { len });
var args = _engine._jsValueArrayPool.RentArray(3);
args[2] = o;
for (var k = 0; k < len; k++)
{
args[0] = o[k];
args[1] = k;
var mappedValue = callable.Call(thisArg, args);
a[k] = mappedValue;
}
_engine._jsValueArrayPool.ReturnArray(args);
return a;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.reduce
/// </summary>
private JsValue Reduce(JsValue thisObj, JsValue[] arguments)
{
var callbackfn = GetCallable(arguments.At(0));
var initialValue = arguments.At(1);
var o = thisObj.ValidateTypedArray(_realm);
var len = o.Length;
if (len == 0 && arguments.Length < 2)
{
ExceptionHelper.ThrowTypeError(_realm);
}
var k = 0;
var accumulator = Undefined;
if (!initialValue.IsUndefined())
{
accumulator = initialValue;
}
else
{
accumulator = o[k];
k++;
}
var args = _engine._jsValueArrayPool.RentArray(4);
args[3] = o;
while (k < len)
{
var kValue = o[k];
args[0] = accumulator;
args[1] = kValue;
args[2] = k;
accumulator = callbackfn.Call(Undefined, args);
k++;
}
_engine._jsValueArrayPool.ReturnArray(args);
return accumulator;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.reduceright
/// </summary>
private JsValue ReduceRight(JsValue thisObj, JsValue[] arguments)
{
var callbackfn = GetCallable(arguments.At(0));
var initialValue = arguments.At(1);
var o = thisObj.ValidateTypedArray(_realm);
var len = (int) o.Length;
if (len == 0 && arguments.Length < 2)
{
ExceptionHelper.ThrowTypeError(_realm);
}
var k = len - 1;
JsValue accumulator;
if (arguments.Length > 1)
{
accumulator = initialValue;
}
else
{
accumulator = o[k];
k--;
}
var jsValues = _engine._jsValueArrayPool.RentArray(4);
jsValues[3] = o;
for (; k >= 0; k--)
{
jsValues[0] = accumulator;
jsValues[1] = o[k];
jsValues[2] = k;
accumulator = callbackfn.Call(Undefined, jsValues);
}
_engine._jsValueArrayPool.ReturnArray(jsValues);
return accumulator;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.reverse
/// </summary>
private ObjectInstance Reverse(JsValue thisObj, JsValue[] arguments)
{
var o = thisObj.ValidateTypedArray(_realm);
var len = (int) o.Length;
var middle = (int) System.Math.Floor(len / 2.0);
var lower = 0;
while (lower != middle)
{
var upper = len - lower - 1;
var lowerValue = o[lower];
var upperValue = o[upper];
o[lower] = upperValue;
o[upper] = lowerValue;
lower++;
}
return o;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.set
/// </summary>
private JsValue Set(JsValue thisObj, JsValue[] arguments)
{
var target = thisObj as TypedArrayInstance;
if (target is null)
{
ExceptionHelper.ThrowTypeError(_realm);
}
var source = arguments.At(0);
var offset = arguments.At(1);
var targetOffset = TypeConverter.ToIntegerOrInfinity(offset);
if (targetOffset < 0)
{
ExceptionHelper.ThrowRangeError(_realm, "Invalid offset");
}
if (source is TypedArrayInstance typedArrayInstance)
{
SetTypedArrayFromTypedArray(target, targetOffset, typedArrayInstance);
}
else
{
SetTypedArrayFromArrayLike(target, targetOffset, source);
}
return Undefined;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-settypedarrayfromtypedarray
/// </summary>
private void SetTypedArrayFromTypedArray(TypedArrayInstance target, double targetOffset, TypedArrayInstance source)
{
var targetBuffer = target._viewedArrayBuffer;
targetBuffer.AssertNotDetached();
var targetLength = target._arrayLength;
var srcBuffer = source._viewedArrayBuffer;
srcBuffer.AssertNotDetached();
var targetType = target._arrayElementType;
var targetElementSize = targetType.GetElementSize();
var targetByteOffset = target._byteOffset;
var srcType = source._arrayElementType;
var srcElementSize = srcType.GetElementSize();
var srcLength = source._arrayLength;
var srcByteOffset = source._byteOffset;
if (double.IsNegativeInfinity(targetOffset))
{
ExceptionHelper.ThrowRangeError(_realm, "Invalid target offset");
}
if (srcLength + targetOffset > targetLength)
{
ExceptionHelper.ThrowRangeError(_realm, "Invalid target offset");
}
if (target._contentType != source._contentType)
{
ExceptionHelper.ThrowTypeError(_realm, "Content type mismatch");
}
bool same;
if (srcBuffer.IsSharedArrayBuffer && targetBuffer.IsSharedArrayBuffer)
{
// a. If srcBuffer.[[ArrayBufferData]] and targetBuffer.[[ArrayBufferData]] are the same Shared Data Block values, let same be true; else let same be false.
ExceptionHelper.ThrowNotImplementedException("SharedBuffer not implemented");
same = false;
}
else
{
same = SameValue(srcBuffer, targetBuffer);
}
int srcByteIndex;
if (same)
{
var srcByteLength = source._byteLength;
srcBuffer = srcBuffer.CloneArrayBuffer(_realm.Intrinsics.ArrayBuffer, srcByteOffset, srcByteLength, _realm.Intrinsics.ArrayBuffer);
// %ArrayBuffer% is used to clone srcBuffer because is it known to not have any observable side-effects.
srcByteIndex = 0;
}
else
{
srcByteIndex = srcByteOffset;
}
var targetByteIndex = (int) (targetOffset * targetElementSize + targetByteOffset);
var limit = targetByteIndex + targetElementSize * srcLength;
if (srcType == targetType)
{
// NOTE: If srcType and targetType are the same, the transfer must be performed in a manner that preserves the bit-level encoding of the source data.
while (targetByteIndex < limit)
{
var value = srcBuffer.GetValueFromBuffer(srcByteIndex, TypedArrayElementType.Uint8, true, ArrayBufferOrder.Unordered);
targetBuffer.SetValueInBuffer(targetByteIndex, TypedArrayElementType.Uint8, value, true, ArrayBufferOrder.Unordered);
srcByteIndex += 1;
targetByteIndex += 1;
}
}
else
{
while (targetByteIndex < limit)
{
var value = srcBuffer.GetValueFromBuffer(srcByteIndex, srcType, true, ArrayBufferOrder.Unordered);
targetBuffer.SetValueInBuffer(targetByteIndex, targetType, value, true, ArrayBufferOrder.Unordered);
srcByteIndex += srcElementSize;
targetByteIndex += targetElementSize;
}
}
}
/// <summary>
/// https://tc39.es/ecma262/#sec-settypedarrayfromarraylike
/// </summary>
private void SetTypedArrayFromArrayLike(TypedArrayInstance target, double targetOffset, JsValue source)
{
var targetBuffer = target._viewedArrayBuffer;
targetBuffer.AssertNotDetached();
var targetLength = target._arrayLength;
var targetElementSize = target._arrayElementType.GetElementSize();
var targetType = target._arrayElementType;
var targetByteOffset = target._byteOffset;
var src = ArrayOperations.For(TypeConverter.ToObject(_realm, source));
var srcLength = src.GetLength();
if (double.IsNegativeInfinity(targetOffset))
{
ExceptionHelper.ThrowRangeError(_realm, "Invalid target offset");
}
if (srcLength + targetOffset > targetLength)
{
ExceptionHelper.ThrowRangeError(_realm, "Invalid target offset");
}
var targetByteIndex = targetOffset * targetElementSize + targetByteOffset;
ulong k = 0;
var limit = targetByteIndex + targetElementSize * srcLength;
while (targetByteIndex < limit)
{
if (target._contentType == TypedArrayContentType.BigInt)
{
var value = src.Get(k).ToBigInteger(_engine);
targetBuffer.AssertNotDetached();
targetBuffer.SetValueInBuffer((int) targetByteIndex, targetType, value, true, ArrayBufferOrder.Unordered);
}
else
{
var value = TypeConverter.ToNumber(src.Get(k));
targetBuffer.AssertNotDetached();
targetBuffer.SetValueInBuffer((int) targetByteIndex, targetType, value, true, ArrayBufferOrder.Unordered);
}
k++;
targetByteIndex += targetElementSize;
}
}
/// <summary>
/// https://tc39.es/proposal-relative-indexing-method/#sec-%typedarray.prototype%-additions
/// </summary>
private JsValue At(JsValue thisObj, JsValue[] arguments)
{
var start = arguments.At(0);
var o = thisObj.ValidateTypedArray(_realm);
long len = o.Length;
var relativeStart = TypeConverter.ToInteger(start);
int k;
if (relativeStart < 0)
{
k = (int) (len + relativeStart);
}
else
{
k = (int) relativeStart;
}
if(k < 0 || k >= len)
{
return Undefined;
}
return o.Get(k);
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.slice
/// </summary>
private JsValue Slice(JsValue thisObj, JsValue[] arguments)
{
var start = arguments.At(0);
var end = arguments.At(1);
var o = thisObj.ValidateTypedArray(_realm);
long len = o.Length;
var relativeStart = TypeConverter.ToIntegerOrInfinity(start);
int k;
if (double.IsNegativeInfinity(relativeStart))
{
k = 0;
}
else if (relativeStart < 0)
{
k = (int) System.Math.Max(len + relativeStart, 0);
}
else
{
k = (int) System.Math.Min(relativeStart, len);
}
var relativeEnd = end.IsUndefined()
? len
: TypeConverter.ToIntegerOrInfinity(end);
long final;
if (double.IsNegativeInfinity(relativeEnd))
{
final = 0;
}
else if (relativeEnd < 0)
{
final = (long) System.Math.Max(len + relativeEnd, 0);
}
else
{
final = (long) System.Math.Min(relativeEnd, len);
}
var count = System.Math.Max(final - k, 0);
var a = _realm.Intrinsics.TypedArray.TypedArraySpeciesCreate(o, new JsValue[] { count });
if (count > 0)
{
o._viewedArrayBuffer.AssertNotDetached();
var srcType = o._arrayElementType;
var targetType = a._arrayElementType;
if (srcType != targetType)
{
var n = 0;
while (k < final)
{
var kValue = o[k];
a[n] = kValue;
k++;
n++;
}
}
else
{
var srcBuffer = o._viewedArrayBuffer;
var targetBuffer = a._viewedArrayBuffer;
var elementSize = srcType.GetElementSize();
var srcByteOffset = o._byteOffset;
var targetByteIndex = a._byteOffset;
var srcByteIndex = (int) k * elementSize + srcByteOffset;
var limit = targetByteIndex + count * elementSize;
while (targetByteIndex < limit)
{
var value = srcBuffer.GetValueFromBuffer(srcByteIndex, TypedArrayElementType.Uint8, true, ArrayBufferOrder.Unordered);
targetBuffer.SetValueInBuffer(targetByteIndex, TypedArrayElementType.Uint8, value, true, ArrayBufferOrder.Unordered);
srcByteIndex++;
targetByteIndex++;
}
}
}
return a;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.some
/// </summary>
private JsValue Some(JsValue thisObj, JsValue[] arguments)
{
var o = thisObj.ValidateTypedArray(_realm);
var len = o.Length;
var callbackfn = GetCallable(arguments.At(0));
var thisArg = arguments.At(1);
var args = _engine._jsValueArrayPool.RentArray(3);
args[2] = o;
for (var k = 0; k < len; k++)
{
args[0] = o[k];
args[1] = k;
if (TypeConverter.ToBoolean(callbackfn.Call(thisArg, args)))
{
return JsBoolean.True;
}
}
_engine._jsValueArrayPool.ReturnArray(args);
return JsBoolean.False;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.sort
/// </summary>
private JsValue Sort(JsValue thisObj, JsValue[] arguments)
{
/*
* %TypedArray%.prototype.sort is a distinct function that, except as described below,
* implements the same requirements as those of Array.prototype.sort as defined in 23.1.3.27.
* The implementation of the %TypedArray%.prototype.sort specification may be optimized with the knowledge that the this value is
* an object that has a fixed length and whose integer-indexed properties are not sparse.
*/
var obj = thisObj.ValidateTypedArray(_realm);
var buffer = obj._viewedArrayBuffer;
var len = obj.Length;
var compareArg = arguments.At(0);
ICallable compareFn = null;
if (!compareArg.IsUndefined())
{
compareFn = GetCallable(compareArg);
}
if (len <= 1)
{
return obj;
}
JsValue[] array;
try
{
var comparer = TypedArrayComparer.WithFunction(buffer, compareFn);
var operations = ArrayOperations.For(obj);
array = operations
.OrderBy(x => x, comparer)
.ToArray();
}
catch (InvalidOperationException e)
{
throw e.InnerException ?? e;
}
for (var i = 0; i < (uint) array.Length; ++i)
{
obj[i] = array[i];
}
return obj;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.subarray
/// </summary>
private JsValue Subarray(JsValue thisObj, JsValue[] arguments)
{
var o = thisObj as TypedArrayInstance;
if (o is null)
{
ExceptionHelper.ThrowTypeError(_realm);
}
var begin = arguments.At(0);
var end = arguments.At(1);
var buffer = o._viewedArrayBuffer;
var srcLength = o.Length;
var relativeBegin = TypeConverter.ToIntegerOrInfinity(begin);
double beginIndex;
if (double.IsNegativeInfinity(relativeBegin))
{
beginIndex = 0;
}
else if (relativeBegin < 0)
{
beginIndex = System.Math.Max(srcLength + relativeBegin, 0);
}
else
{
beginIndex = System.Math.Min(relativeBegin, srcLength);
}
double relativeEnd;
if (end.IsUndefined())
{
relativeEnd = srcLength;
}
else
{
relativeEnd = TypeConverter.ToIntegerOrInfinity(end);
}
double endIndex;
if (double.IsNegativeInfinity(relativeEnd))
{
endIndex = 0;
}
else if (relativeEnd < 0)
{
endIndex = System.Math.Max(srcLength + relativeEnd, 0);
}
else
{
endIndex = System.Math.Min(relativeEnd, srcLength);
}
var newLength = System.Math.Max(endIndex - beginIndex, 0);
var elementSize = o._arrayElementType.GetElementSize();
var srcByteOffset = o._byteOffset;
var beginByteOffset = srcByteOffset + beginIndex * elementSize;
var argumentsList = new JsValue[] { buffer, beginByteOffset, newLength };
return _realm.Intrinsics.TypedArray.TypedArraySpeciesCreate(o, argumentsList);
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.tolocalestring
/// </summary>
private JsValue ToLocaleString(JsValue thisObj, JsValue[] arguments)
{
/*
* %TypedArray%.prototype.toLocaleString is a distinct function that implements the same algorithm as Array.prototype.toLocaleString
* as defined in 23.1.3.29 except that the this value's [[ArrayLength]] internal slot is accessed in place of performing
* a [[Get]] of "length". The implementation of the algorithm may be optimized with the knowledge that the this value is an object
* that has a fixed length and whose integer-indexed properties are not sparse. However, such optimization must not introduce
* any observable changes in the specified behaviour of the algorithm.
*/
var array = thisObj.ValidateTypedArray(_realm);
var len = array.Length;
const string separator = ",";
if (len == 0)
{
return JsString.Empty;
}
JsValue r;
if (!array.TryGetValue(0, out var firstElement) || firstElement.IsNull() || firstElement.IsUndefined())
{
r = JsString.Empty;
}
else
{
var elementObj = TypeConverter.ToObject(_realm, firstElement);
var func = elementObj.Get("toLocaleString", elementObj) as ICallable;
if (func is null)
{
ExceptionHelper.ThrowTypeError(_realm);
}
r = func.Call(elementObj, Arguments.Empty);
}
for (var k = 1; k < len; k++)
{
var s = r + separator;
var elementObj = TypeConverter.ToObject(_realm, array[k]);
var func = elementObj.Get("toLocaleString", elementObj) as ICallable;
if (func is null)
{
ExceptionHelper.ThrowTypeError(_realm);
}
r = func.Call(elementObj, Arguments.Empty);
r = s + r;
}
return r;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-%typedarray%.prototype.values
/// </summary>
private JsValue Values(JsValue thisObj, JsValue[] arguments)
{
var o = thisObj.ValidateTypedArray(_realm);
return _realm.Intrinsics.ArrayIteratorPrototype.Construct(o, ArrayIteratorType.Value);
}
/// <summary>
/// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype-@@tostringtag
/// </summary>
private static JsValue ToStringTag(JsValue thisObj, JsValue[] arguments)
{
if (thisObj is not TypedArrayInstance o)
{
return Undefined;
}
return o._arrayElementType.GetTypedArrayName();
}
private sealed class TypedArrayComparer : IComparer<JsValue>
{
public static TypedArrayComparer WithFunction(ArrayBufferInstance buffer, ICallable compare)
{
return new TypedArrayComparer(buffer, compare);
}
private readonly ArrayBufferInstance _buffer;
private readonly ICallable _compare;
private readonly JsValue[] _comparableArray = new JsValue[2];
private TypedArrayComparer(ArrayBufferInstance buffer, ICallable compare)
{
_buffer = buffer;
_compare = compare;
}
public int Compare(JsValue x, JsValue y)
{
if (_compare is not null)
{
_comparableArray[0] = x;
_comparableArray[1] = y;
var v = TypeConverter.ToNumber(_compare.Call(Undefined, _comparableArray));
_buffer.AssertNotDetached();
if (double.IsNaN(v))
{
return 0;
}
return (int) v;
}
if (x.Type == Types.BigInt || y.Type == Types.BigInt)
{
var xBigInt = TypeConverter.ToBigInt(x);
var yBigInt = TypeConverter.ToBigInt(y);
return xBigInt.CompareTo(yBigInt);
}
var xValue = x.AsNumber();
var yValue = y.AsNumber();
if (double.IsNaN(xValue) && double.IsNaN(yValue))
{
return 0;
}
if (double.IsNaN(xValue))
{
return 1;
}
if (double.IsNaN(yValue))
{
return -1;
}
if (xValue < yValue)
{
return -1;
}
if (xValue > yValue)
{
return 1;
}
if (NumberInstance.IsNegativeZero(xValue) && yValue == 0)
{
return -1;
}
if (xValue == 0 && NumberInstance.IsNegativeZero(yValue))
{
return 1;
}
return 0;
}
}
}
}
| |
// MIT License
//
// Copyright (c) 2009-2017 Luca Piccioni
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// This file is automatically generated
#pragma warning disable 649, 1572, 1573
// ReSharper disable RedundantUsingDirective
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Khronos;
// ReSharper disable CheckNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable JoinDeclarationAndInitializer
namespace OpenGL
{
public partial class Gl
{
/// <summary>
/// [GL] Value of GL_PACK_SKIP_VOLUMES_SGIS symbol.
/// </summary>
[RequiredByFeature("GL_SGIS_texture4D")]
public const int PACK_SKIP_VOLUMES_SGIS = 0x8130;
/// <summary>
/// [GL] Value of GL_PACK_IMAGE_DEPTH_SGIS symbol.
/// </summary>
[RequiredByFeature("GL_SGIS_texture4D")]
public const int PACK_IMAGE_DEPTH_SGIS = 0x8131;
/// <summary>
/// [GL] Value of GL_UNPACK_SKIP_VOLUMES_SGIS symbol.
/// </summary>
[RequiredByFeature("GL_SGIS_texture4D")]
public const int UNPACK_SKIP_VOLUMES_SGIS = 0x8132;
/// <summary>
/// [GL] Value of GL_UNPACK_IMAGE_DEPTH_SGIS symbol.
/// </summary>
[RequiredByFeature("GL_SGIS_texture4D")]
public const int UNPACK_IMAGE_DEPTH_SGIS = 0x8133;
/// <summary>
/// [GL] Value of GL_TEXTURE_4D_SGIS symbol.
/// </summary>
[RequiredByFeature("GL_SGIS_texture4D")]
public const int TEXTURE_4D_SGIS = 0x8134;
/// <summary>
/// [GL] Value of GL_PROXY_TEXTURE_4D_SGIS symbol.
/// </summary>
[RequiredByFeature("GL_SGIS_texture4D")]
public const int PROXY_TEXTURE_4D_SGIS = 0x8135;
/// <summary>
/// [GL] Value of GL_TEXTURE_4DSIZE_SGIS symbol.
/// </summary>
[RequiredByFeature("GL_SGIS_texture4D")]
public const int TEXTURE_4DSIZE_SGIS = 0x8136;
/// <summary>
/// [GL] Value of GL_TEXTURE_WRAP_Q_SGIS symbol.
/// </summary>
[RequiredByFeature("GL_SGIS_texture4D")]
public const int TEXTURE_WRAP_Q_SGIS = 0x8137;
/// <summary>
/// [GL] Value of GL_MAX_4D_TEXTURE_SIZE_SGIS symbol.
/// </summary>
[RequiredByFeature("GL_SGIS_texture4D")]
public const int MAX_4D_TEXTURE_SIZE_SGIS = 0x8138;
/// <summary>
/// [GL] Value of GL_TEXTURE_4D_BINDING_SGIS symbol.
/// </summary>
[RequiredByFeature("GL_SGIS_texture4D")]
public const int TEXTURE_4D_BINDING_SGIS = 0x814F;
/// <summary>
/// [GL] glTexImage4DSGIS: Binding for glTexImage4DSGIS.
/// </summary>
/// <param name="target">
/// A <see cref="T:TextureTarget"/>.
/// </param>
/// <param name="level">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="internalformat">
/// A <see cref="T:InternalFormat"/>.
/// </param>
/// <param name="width">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="height">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="depth">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="size4d">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="border">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="format">
/// A <see cref="T:PixelFormat"/>.
/// </param>
/// <param name="type">
/// A <see cref="T:PixelType"/>.
/// </param>
/// <param name="pixels">
/// A <see cref="T:IntPtr"/>.
/// </param>
[RequiredByFeature("GL_SGIS_texture4D")]
public static void TexImage4DSGIS(TextureTarget target, int level, InternalFormat internalformat, int width, int height, int depth, int size4d, int border, PixelFormat format, PixelType type, IntPtr pixels)
{
Debug.Assert(Delegates.pglTexImage4DSGIS != null, "pglTexImage4DSGIS not implemented");
Delegates.pglTexImage4DSGIS((int)target, level, (int)internalformat, width, height, depth, size4d, border, (int)format, (int)type, pixels);
LogCommand("glTexImage4DSGIS", null, target, level, internalformat, width, height, depth, size4d, border, format, type, pixels );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glTexImage4DSGIS: Binding for glTexImage4DSGIS.
/// </summary>
/// <param name="target">
/// A <see cref="T:TextureTarget"/>.
/// </param>
/// <param name="level">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="internalformat">
/// A <see cref="T:InternalFormat"/>.
/// </param>
/// <param name="width">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="height">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="depth">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="size4d">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="border">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="format">
/// A <see cref="T:PixelFormat"/>.
/// </param>
/// <param name="type">
/// A <see cref="T:PixelType"/>.
/// </param>
/// <param name="pixels">
/// A <see cref="T:object"/>.
/// </param>
[RequiredByFeature("GL_SGIS_texture4D")]
public static void TexImage4DSGIS(TextureTarget target, int level, InternalFormat internalformat, int width, int height, int depth, int size4d, int border, PixelFormat format, PixelType type, object pixels)
{
GCHandle pin_pixels = GCHandle.Alloc(pixels, GCHandleType.Pinned);
try {
TexImage4DSGIS(target, level, internalformat, width, height, depth, size4d, border, format, type, pin_pixels.AddrOfPinnedObject());
} finally {
pin_pixels.Free();
}
}
/// <summary>
/// [GL] glTexSubImage4DSGIS: Binding for glTexSubImage4DSGIS.
/// </summary>
/// <param name="target">
/// A <see cref="T:TextureTarget"/>.
/// </param>
/// <param name="level">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="xoffset">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="yoffset">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="zoffset">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="woffset">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="width">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="height">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="depth">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="size4d">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="format">
/// A <see cref="T:PixelFormat"/>.
/// </param>
/// <param name="type">
/// A <see cref="T:PixelType"/>.
/// </param>
/// <param name="pixels">
/// A <see cref="T:IntPtr"/>.
/// </param>
[RequiredByFeature("GL_SGIS_texture4D")]
public static void TexSubImage4DSGIS(TextureTarget target, int level, int xoffset, int yoffset, int zoffset, int woffset, int width, int height, int depth, int size4d, PixelFormat format, PixelType type, IntPtr pixels)
{
Debug.Assert(Delegates.pglTexSubImage4DSGIS != null, "pglTexSubImage4DSGIS not implemented");
Delegates.pglTexSubImage4DSGIS((int)target, level, xoffset, yoffset, zoffset, woffset, width, height, depth, size4d, (int)format, (int)type, pixels);
LogCommand("glTexSubImage4DSGIS", null, target, level, xoffset, yoffset, zoffset, woffset, width, height, depth, size4d, format, type, pixels );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glTexSubImage4DSGIS: Binding for glTexSubImage4DSGIS.
/// </summary>
/// <param name="target">
/// A <see cref="T:TextureTarget"/>.
/// </param>
/// <param name="level">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="xoffset">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="yoffset">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="zoffset">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="woffset">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="width">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="height">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="depth">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="size4d">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="format">
/// A <see cref="T:PixelFormat"/>.
/// </param>
/// <param name="type">
/// A <see cref="T:PixelType"/>.
/// </param>
/// <param name="pixels">
/// A <see cref="T:object"/>.
/// </param>
[RequiredByFeature("GL_SGIS_texture4D")]
public static void TexSubImage4DSGIS(TextureTarget target, int level, int xoffset, int yoffset, int zoffset, int woffset, int width, int height, int depth, int size4d, PixelFormat format, PixelType type, object pixels)
{
GCHandle pin_pixels = GCHandle.Alloc(pixels, GCHandleType.Pinned);
try {
TexSubImage4DSGIS(target, level, xoffset, yoffset, zoffset, woffset, width, height, depth, size4d, format, type, pin_pixels.AddrOfPinnedObject());
} finally {
pin_pixels.Free();
}
}
internal static unsafe partial class Delegates
{
[RequiredByFeature("GL_SGIS_texture4D")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glTexImage4DSGIS(int target, int level, int internalformat, int width, int height, int depth, int size4d, int border, int format, int type, IntPtr pixels);
[RequiredByFeature("GL_SGIS_texture4D")]
[ThreadStatic]
internal static glTexImage4DSGIS pglTexImage4DSGIS;
[RequiredByFeature("GL_SGIS_texture4D")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glTexSubImage4DSGIS(int target, int level, int xoffset, int yoffset, int zoffset, int woffset, int width, int height, int depth, int size4d, int format, int type, IntPtr pixels);
[RequiredByFeature("GL_SGIS_texture4D")]
[ThreadStatic]
internal static glTexSubImage4DSGIS pglTexSubImage4DSGIS;
}
}
}
| |
using System;
using System.Diagnostics;
namespace Lucene.Net.Util.Packed
{
using Lucene.Net.Support;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using DataInput = Lucene.Net.Store.DataInput;
/// <summary>
/// Space optimized random access capable array of values with a fixed number of
/// bits/value. Values are packed contiguously.
/// </p><p>
/// The implementation strives to perform af fast as possible under the
/// constraint of contiguous bits, by avoiding expensive operations. this comes
/// at the cost of code clarity.
/// </p><p>
/// Technical details: this implementation is a refinement of a non-branching
/// version. The non-branching get and set methods meant that 2 or 4 atomics in
/// the underlying array were always accessed, even for the cases where only
/// 1 or 2 were needed. Even with caching, this had a detrimental effect on
/// performance.
/// Related to this issue, the old implementation used lookup tables for shifts
/// and masks, which also proved to be a bit slower than calculating the shifts
/// and masks on the fly.
/// See https://issues.apache.org/jira/browse/LUCENE-4062 for details.
///
/// </summary>
public class Packed64 : PackedInts.MutableImpl
{
internal const int BLOCK_SIZE = 64; // 32 = int, 64 = long
internal const int BLOCK_BITS = 6; // The #bits representing BLOCK_SIZE
internal static readonly int MOD_MASK = BLOCK_SIZE - 1; // x % BLOCK_SIZE
/// <summary>
/// Values are stores contiguously in the blocks array.
/// </summary>
private readonly long[] Blocks;
/// <summary>
/// A right-aligned mask of width BitsPerValue used by <seealso cref="#get(int)"/>.
/// </summary>
private readonly long MaskRight;
/// <summary>
/// Optimization: Saves one lookup in <seealso cref="#get(int)"/>.
/// </summary>
private readonly int BpvMinusBlockSize;
/// <summary>
/// Creates an array with the internal structures adjusted for the given
/// limits and initialized to 0. </summary>
/// <param name="valueCount"> the number of elements. </param>
/// <param name="bitsPerValue"> the number of bits available for any given value. </param>
public Packed64(int valueCount, int bitsPerValue)
: base(valueCount, bitsPerValue)
{
PackedInts.Format format = PackedInts.Format.PACKED;
int longCount = format.LongCount(PackedInts.VERSION_CURRENT, valueCount, bitsPerValue);
this.Blocks = new long[longCount];
// MaskRight = ~0L << (int)((uint)(BLOCK_SIZE - bitsPerValue) >> (BLOCK_SIZE - bitsPerValue)); //original
// MaskRight = (uint)(~0L << (BLOCK_SIZE - bitsPerValue)) >> (BLOCK_SIZE - bitsPerValue); //mod
/*var a = ~0L << (int)((uint)(BLOCK_SIZE - bitsPerValue) >> (BLOCK_SIZE - bitsPerValue)); //original
var b = (uint)(~0L << (BLOCK_SIZE - bitsPerValue)) >> (BLOCK_SIZE - bitsPerValue); //mod
Debug.Assert(a == b, "a: " + a, ", b: " + b);*/
MaskRight = (long)((ulong)(~0L << (BLOCK_SIZE - bitsPerValue)) >> (BLOCK_SIZE - bitsPerValue)); //mod
//Debug.Assert((long)((ulong)(~0L << (BLOCK_SIZE - bitsPerValue)) >> (BLOCK_SIZE - bitsPerValue)) == (uint)(~0L << (BLOCK_SIZE - bitsPerValue)) >> (BLOCK_SIZE - bitsPerValue));
BpvMinusBlockSize = bitsPerValue - BLOCK_SIZE;
}
/// <summary>
/// Creates an array with content retrieved from the given DataInput. </summary>
/// <param name="in"> a DataInput, positioned at the start of Packed64-content. </param>
/// <param name="valueCount"> the number of elements. </param>
/// <param name="bitsPerValue"> the number of bits available for any given value. </param>
/// <exception cref="java.io.IOException"> if the values for the backing array could not
/// be retrieved. </exception>
public Packed64(int packedIntsVersion, DataInput @in, int valueCount, int bitsPerValue)
: base(valueCount, bitsPerValue)
{
PackedInts.Format format = PackedInts.Format.PACKED;
long byteCount = format.ByteCount(packedIntsVersion, valueCount, bitsPerValue); // to know how much to read
int longCount = format.LongCount(PackedInts.VERSION_CURRENT, valueCount, bitsPerValue); // to size the array
Blocks = new long[longCount];
// read as many longs as we can
for (int i = 0; i < byteCount / 8; ++i)
{
Blocks[i] = @in.ReadLong();
}
int remaining = (int)(byteCount % 8);
if (remaining != 0)
{
// read the last bytes
long lastLong = 0;
for (int i = 0; i < remaining; ++i)
{
lastLong |= (@in.ReadByte() & 0xFFL) << (56 - i * 8);
}
Blocks[Blocks.Length - 1] = lastLong;
}
MaskRight = (long)((ulong)(~0L << (BLOCK_SIZE - bitsPerValue)) >> (BLOCK_SIZE - bitsPerValue));
BpvMinusBlockSize = bitsPerValue - BLOCK_SIZE;
}
/// <param name="index"> the position of the value. </param>
/// <returns> the value at the given index. </returns>
public override long Get(int index)
{
// The abstract index in a bit stream
long majorBitPos = (long)index * bitsPerValue;
// The index in the backing long-array
int elementPos = (int)(((ulong)majorBitPos) >> BLOCK_BITS);
//int elementPos = (int)((long)((ulong)majorBitPos >> BLOCK_BITS));
// The number of value-bits in the second long
long endBits = (majorBitPos & MOD_MASK) + BpvMinusBlockSize;
if (endBits <= 0) // Single block
{
return ((long)((ulong)Blocks[elementPos] >> (int)-endBits)) & MaskRight;
}
// Two blocks
return ((Blocks[elementPos] << (int)endBits) | ((long)((ulong)Blocks[elementPos + 1] >> (int)(BLOCK_SIZE - endBits)))) & MaskRight;
}
/*/// <param name="index"> the position of the value. </param>
/// <returns> the value at the given index. </returns>
public override long Get(int index)
{
// The abstract index in a bit stream
long majorBitPos = (long)index * bitsPerValue;
// The index in the backing long-array
int elementPos = (int)((long)((ulong)majorBitPos >> BLOCK_BITS));
// The number of value-bits in the second long
long endBits = (majorBitPos & MOD_MASK) + BpvMinusBlockSize;
if (endBits <= 0) // Single block
{
var mod = (long) ((ulong) (Blocks[elementPos]) >> (int) (-endBits)) & MaskRight;
var og = ((long) ((ulong) Blocks[elementPos] >> (int) -endBits)) & MaskRight;
Debug.Assert(mod == og);
//return (long)((ulong)(Blocks[elementPos]) >> (int)(-endBits)) & MaskRight;
return ((long)((ulong)Blocks[elementPos] >> (int)-endBits)) & MaskRight;
}
// Two blocks
var a = (((Blocks[elementPos] << (int)endBits) | (long)(((ulong)(Blocks[elementPos + 1])) >> (int)(BLOCK_SIZE - endBits))) & MaskRight);
var b = ((Blocks[elementPos] << (int)endBits) | ((long)((ulong)Blocks[elementPos + 1] >> (int)(BLOCK_SIZE - endBits)))) & MaskRight;
Debug.Assert(a == b);
//return (((Blocks[elementPos] << (int)endBits) | (long)(((ulong)(Blocks[elementPos + 1])) >> (int)(BLOCK_SIZE - endBits))) & MaskRight);
return ((Blocks[elementPos] << (int)endBits) | ((long)((ulong)Blocks[elementPos + 1] >> (int)(BLOCK_SIZE - endBits)))) & MaskRight;
}*/
public override int Get(int index, long[] arr, int off, int len)
{
Debug.Assert(len > 0, "len must be > 0 (got " + len + ")");
Debug.Assert(index >= 0 && index < valueCount);
len = Math.Min(len, valueCount - index);
Debug.Assert(off + len <= arr.Length);
int originalIndex = index;
PackedInts.Decoder decoder = BulkOperation.Of(PackedInts.Format.PACKED, bitsPerValue);
// go to the next block where the value does not span across two blocks
int offsetInBlocks = index % decoder.LongValueCount();
if (offsetInBlocks != 0)
{
for (int i = offsetInBlocks; i < decoder.LongValueCount() && len > 0; ++i)
{
arr[off++] = Get(index++);
--len;
}
if (len == 0)
{
return index - originalIndex;
}
}
// bulk get
Debug.Assert(index % decoder.LongValueCount() == 0);
int blockIndex = (int)((ulong)((long)index * bitsPerValue) >> BLOCK_BITS);
Debug.Assert((((long)index * bitsPerValue) & MOD_MASK) == 0);
int iterations = len / decoder.LongValueCount();
decoder.Decode(Blocks, blockIndex, arr, off, iterations);
int gotValues = iterations * decoder.LongValueCount();
index += gotValues;
len -= gotValues;
Debug.Assert(len >= 0);
if (index > originalIndex)
{
// stay at the block boundary
return index - originalIndex;
}
else
{
// no progress so far => already at a block boundary but no full block to get
Debug.Assert(index == originalIndex);
return base.Get(index, arr, off, len);
}
}
public override void Set(int index, long value)
{
// The abstract index in a contiguous bit stream
long majorBitPos = (long)index * bitsPerValue;
// The index in the backing long-array
int elementPos = (int)((long)((ulong)majorBitPos >> BLOCK_BITS)); // / BLOCK_SIZE
// The number of value-bits in the second long
long endBits = (majorBitPos & MOD_MASK) + BpvMinusBlockSize;
if (endBits <= 0) // Single block
{
Blocks[elementPos] = Blocks[elementPos] & ~(MaskRight << (int)-endBits) | (value << (int)-endBits);
return;
}
// Two blocks
Blocks[elementPos] = Blocks[elementPos] & ~((long)((ulong)MaskRight >> (int)endBits)) | ((long)((ulong)value >> (int)endBits));
Blocks[elementPos + 1] = Blocks[elementPos + 1] & ((long)(unchecked((ulong)~0L) >> (int)endBits)) | (value << (int)(BLOCK_SIZE - endBits));
}
public override int Set(int index, long[] arr, int off, int len)
{
Debug.Assert(len > 0, "len must be > 0 (got " + len + ")");
Debug.Assert(index >= 0 && index < valueCount);
len = Math.Min(len, valueCount - index);
Debug.Assert(off + len <= arr.Length);
int originalIndex = index;
PackedInts.Encoder encoder = BulkOperation.Of(PackedInts.Format.PACKED, bitsPerValue);
// go to the next block where the value does not span across two blocks
int offsetInBlocks = index % encoder.LongValueCount();
if (offsetInBlocks != 0)
{
for (int i = offsetInBlocks; i < encoder.LongValueCount() && len > 0; ++i)
{
Set(index++, arr[off++]);
--len;
}
if (len == 0)
{
return index - originalIndex;
}
}
// bulk set
Debug.Assert(index % encoder.LongValueCount() == 0);
int blockIndex = (int)((ulong)((long)index * bitsPerValue) >> BLOCK_BITS);
Debug.Assert((((long)index * bitsPerValue) & MOD_MASK) == 0);
int iterations = len / encoder.LongValueCount();
encoder.Encode(arr, off, Blocks, blockIndex, iterations);
int setValues = iterations * encoder.LongValueCount();
index += setValues;
len -= setValues;
Debug.Assert(len >= 0);
if (index > originalIndex)
{
// stay at the block boundary
return index - originalIndex;
}
else
{
// no progress so far => already at a block boundary but no full block to get
Debug.Assert(index == originalIndex);
return base.Set(index, arr, off, len);
}
}
public override string ToString()
{
return "Packed64(bitsPerValue=" + bitsPerValue + ", size=" + Size() + ", elements.length=" + Blocks.Length + ")";
}
public override long RamBytesUsed()
{
return RamUsageEstimator.AlignObjectSize(RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + 3 * RamUsageEstimator.NUM_BYTES_INT + RamUsageEstimator.NUM_BYTES_LONG + RamUsageEstimator.NUM_BYTES_OBJECT_REF) + RamUsageEstimator.SizeOf(Blocks); // blocks ref - maskRight - bpvMinusBlockSize,valueCount,bitsPerValue
}
public override void Fill(int fromIndex, int toIndex, long val)
{
Debug.Assert(PackedInts.BitsRequired(val) <= BitsPerValue);
Debug.Assert(fromIndex <= toIndex);
// minimum number of values that use an exact number of full blocks
int nAlignedValues = 64 / Gcd(64, bitsPerValue);
int span = toIndex - fromIndex;
if (span <= 3 * nAlignedValues)
{
// there needs be at least 2 * nAlignedValues aligned values for the
// block approach to be worth trying
base.Fill(fromIndex, toIndex, val);
return;
}
// fill the first values naively until the next block start
int fromIndexModNAlignedValues = fromIndex % nAlignedValues;
if (fromIndexModNAlignedValues != 0)
{
for (int i = fromIndexModNAlignedValues; i < nAlignedValues; ++i)
{
Set(fromIndex++, val);
}
}
Debug.Assert(fromIndex % nAlignedValues == 0);
// compute the long[] blocks for nAlignedValues consecutive values and
// use them to set as many values as possible without applying any mask
// or shift
int nAlignedBlocks = (nAlignedValues * bitsPerValue) >> 6;
long[] nAlignedValuesBlocks;
{
Packed64 values = new Packed64(nAlignedValues, bitsPerValue);
for (int i = 0; i < nAlignedValues; ++i)
{
values.Set(i, val);
}
nAlignedValuesBlocks = values.Blocks;
Debug.Assert(nAlignedBlocks <= nAlignedValuesBlocks.Length);
}
int startBlock = (int)((ulong)((long)fromIndex * bitsPerValue) >> 6);
int endBlock = (int)((ulong)((long)toIndex * bitsPerValue) >> 6);
for (int block = startBlock; block < endBlock; ++block)
{
long blockValue = nAlignedValuesBlocks[block % nAlignedBlocks];
Blocks[block] = blockValue;
}
// fill the gap
for (int i = (int)(((long)endBlock << 6) / bitsPerValue); i < toIndex; ++i)
{
Set(i, val);
}
}
private static int Gcd(int a, int b)
{
if (a < b)
{
return Gcd(b, a);
}
else if (b == 0)
{
return a;
}
else
{
return Gcd(b, a % b);
}
}
public override void Clear()
{
Arrays.Fill(Blocks, 0L);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.