context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Pathfinding;
namespace Pathfinding {
/** A path which searches from one point to a number of different targets in one search or from a number of different start points to a single target.
* \ingroup paths
* \astarpro
* \see Seeker.StartMultiTargetPath
* \see \ref MultiTargetPathExample.cs "Example of how to use multi-target-paths" */
public class MultiTargetPath : ABPath {
//public Node startNode;
public OnPathDelegate[] callbacks; /**< Callbacks to call for each individual path */
public GraphNode[] targetNodes; /**< Nearest nodes to the #targetPoints */
protected int targetNodeCount;
public bool[] targetsFound; /**< Indicates if the target has been found. Also true if the target cannot be reached (is in another area) */
public Vector3[] targetPoints; /**< Target points specified when creating the path. These are snapped to the nearest nodes */
public Vector3[] originalTargetPoints; /**< Target points specified when creating the path. These are not snapped to the nearest nodes */
public List<Vector3>[] vectorPaths; /**< Stores all vector paths to the targets. Elements are null if no path was found */
public List<GraphNode>[] nodePaths; /**< Stores all paths to the targets. Elements are null if no path was found */
public int endsFound = 0;
public bool pathsForAll = true; /**< If true, a path to all targets will be returned, otherwise just the one to the closest one */
public int chosenTarget = -1; /**< The closest target (if any was found) when #pathsForAll is false */
public int sequentialTarget = 0; /** Current target for Sequential #heuristicMode. Refers to an item in the targetPoints array */
/** How to calculate the heuristic. The \link #hTarget heuristic target point \endlink can be calculated in different ways, by taking the Average position of all targets, or taking the mid point of them (i.e center of the AABB encapsulating all targets).\n
* The one which works best seems to be Sequential though, it sets #hTarget to the first target, and when that target is found, it moves on to the next one.\n
* Some modes have the option to be 'moving' (e.g 'MovingAverage'), that means that it is updated every time a target is found.\n
* The H score is calculated according to AstarPath.heuristic */
public HeuristicMode heuristicMode = HeuristicMode.Sequential;
public enum HeuristicMode {
None,
Average,
MovingAverage,
Midpoint,
MovingMidpoint,
Sequential
}
/** False if the path goes from one point to multiple targets. True if it goes from multiple start points to one target point */
public bool inverted = true;
public MultiTargetPath () {}
[System.ObsoleteAttribute ("Please use the Construct method instead")]
public MultiTargetPath (Vector3[] startPoints, Vector3 target, OnPathDelegate[] callbackDelegates, OnPathDelegate callbackDelegate = null) : this (target,startPoints,callbackDelegates, callbackDelegate) {
inverted = true;
}
[System.ObsoleteAttribute ("Please use the Construct method instead")]
public MultiTargetPath (Vector3 start, Vector3[] targets, OnPathDelegate[] callbackDelegates, OnPathDelegate callbackDelegate = null) {
}
public static MultiTargetPath Construct (Vector3[] startPoints, Vector3 target, OnPathDelegate[] callbackDelegates, OnPathDelegate callback = null) {
MultiTargetPath p = Construct (target, startPoints, callbackDelegates, callback);
p.inverted = true;
return p;
}
public static MultiTargetPath Construct (Vector3 start, Vector3[] targets, OnPathDelegate[] callbackDelegates, OnPathDelegate callback = null) {
MultiTargetPath p = PathPool<MultiTargetPath>.GetPath ();
p.Setup (start,targets,callbackDelegates,callback);
return p;
}
protected void Setup (Vector3 start, Vector3[] targets, OnPathDelegate[] callbackDelegates, OnPathDelegate callback) {
inverted = false;
this.callback = callback;
callbacks = callbackDelegates;
targetPoints = targets;
originalStartPoint = start;
//originalEndPoint = end;
startPoint = start;
startIntPoint = (Int3)start;
if (targets.Length == 0) {
Error ();
LogError ("No targets were assigned to the MultiTargetPath");
return;
}
endPoint = targets[0];
originalTargetPoints = new Vector3[targetPoints.Length];
for (int i=0;i<targetPoints.Length;i++) {
originalTargetPoints[i] = targetPoints[i];
}
}
protected override void Recycle () {
PathPool<MultiTargetPath>.Recycle (this);
}
public override void OnEnterPool () {
if (vectorPaths != null)
for (int i=0;i<vectorPaths.Length;i++)
if (vectorPaths[i] != null) Util.ListPool<Vector3>.Release (vectorPaths[i]);
vectorPaths = null;
vectorPath = null;
if (nodePaths != null)
for (int i=0;i<nodePaths.Length;i++)
if (nodePaths[i] != null) Util.ListPool<GraphNode>.Release (nodePaths[i]);
nodePaths = null;
path = null;
base.OnEnterPool ();
}
public override void ReturnPath () {
if (error) {
if (callbacks != null) {
for (int i=0;i<callbacks.Length;i++)
if (callbacks[i] != null) callbacks[i] (this);
}
if (callback != null) callback(this);
return;
}
bool anySucceded = false;
Vector3 _originalStartPoint = originalStartPoint;
Vector3 _startPoint = startPoint;
GraphNode _startNode = startNode;
for (int i=0;i<nodePaths.Length;i++) {
path = nodePaths[i];
if (path != null) {
CompleteState = PathCompleteState.Complete;
anySucceded = true;
} else {
CompleteState = PathCompleteState.Error;
}
if (callbacks != null && callbacks[i] != null) {
vectorPath = vectorPaths[i];
//=== SEGMENT - should be identical to the one a few rows below (except "i")
if (inverted) {
endPoint = _startPoint;
endNode = _startNode;//path[0];
startNode = targetNodes[i];//path[path.Length-1];
startPoint = targetPoints[i];
originalEndPoint = _originalStartPoint;
originalStartPoint = originalTargetPoints[i];
} else {
endPoint = targetPoints[i];
originalEndPoint = originalTargetPoints[i];
endNode = targetNodes[i];//path[path.Length-1];
}
callbacks[i] (this);
//In case a modifier changed the vectorPath, update the array of all vectorPaths
vectorPaths[i] = vectorPath;
}
}
if (anySucceded) {
CompleteState = PathCompleteState.Complete;
if (!pathsForAll) {
path = nodePaths[chosenTarget];
vectorPath = vectorPaths[chosenTarget];
//=== SEGMENT - should be identical to the one a few rows above (except "chosenTarget")
if (inverted) {
endPoint = _startPoint;
endNode = _startNode;
startNode = targetNodes[chosenTarget];
startPoint = targetPoints[chosenTarget];
originalEndPoint = _originalStartPoint;
originalStartPoint = originalTargetPoints[chosenTarget];
} else {
endPoint = targetPoints[chosenTarget];
originalEndPoint = originalTargetPoints[chosenTarget];
endNode = targetNodes[chosenTarget];
}
}
} else {
CompleteState = PathCompleteState.Error;
}
if (callback != null) {
callback (this);
}
}
public void FoundTarget (PathNode nodeR, int i) {
nodeR.flag1 = false;//Reset bit 8
Trace (nodeR);
vectorPaths[i] = vectorPath;
nodePaths[i] = path;
vectorPath = Util.ListPool<Vector3>.Claim ();
path = Util.ListPool<GraphNode>.Claim ();
targetsFound[i] = true;
targetNodeCount--;
if (!pathsForAll) {
CompleteState = PathCompleteState.Complete;
chosenTarget = i; //Mark which path was found
targetNodeCount = 0;
return;
}
//If there are no more targets to find, return here and avoid calculating a new hTarget
if (targetNodeCount <= 0) {
CompleteState = PathCompleteState.Complete;
return;
}
//No need to check for if pathsForAll is true since the function would have returned by now then
if (heuristicMode == HeuristicMode.MovingAverage) {
Vector3 avg = Vector3.zero;
int count = 0;
for (int j=0;j<targetPoints.Length;j++) {
if (!targetsFound[j]) {
avg += (Vector3)targetNodes[j].position;
count++;
}
}
if (count > 0) {
avg /= count;
}
hTarget = (Int3)avg;
RebuildOpenList ();
} else if (heuristicMode == HeuristicMode.MovingMidpoint) {
Vector3 min = Vector3.zero;
Vector3 max = Vector3.zero;
bool set = false;
for (int j=0;j<targetPoints.Length;j++) {
if (!targetsFound[j]) {
if (!set) {
min = (Vector3)targetNodes[j].position;
max = (Vector3)targetNodes[j].position;
set = true;
} else {
min = Vector3.Min ((Vector3)targetNodes[j].position,min);
max = Vector3.Max ((Vector3)targetNodes[j].position,max);
}
}
}
Int3 midpoint = (Int3)((min+max)*0.5F);
hTarget = (Int3)midpoint;
RebuildOpenList ();
} else if (heuristicMode == HeuristicMode.Sequential) {
//If this was the target hTarget was set to at the moment
if (sequentialTarget == i) {
//Pick a new hTarget
float dist = 0;
for (int j=0;j<targetPoints.Length;j++) {
if (!targetsFound[j]) {
float d = (targetNodes[j].position-startNode.position).sqrMagnitude;
if (d > dist) {
dist = d;
hTarget = (Int3)targetPoints[j];
sequentialTarget = j;
}
}
}
RebuildOpenList ();
}
}
}
protected void RebuildOpenList () {
BinaryHeapM heap = pathHandler.GetHeap();
for (int j=0;j<heap.numberOfItems;j++) {
PathNode nodeR = heap.GetNode(j);
nodeR.H = this.CalculateHScore (nodeR.node);
}
pathHandler.RebuildHeap();
}
public override void Prepare () {
nnConstraint.tags = enabledTags;
NNInfo startNNInfo = AstarPath.active.GetNearest (startPoint,nnConstraint, startHint);
startNode = startNNInfo.node;
if (startNode == null) {
LogError ("Could not find start node for multi target path");
Error ();
return;
}
if (!startNode.Walkable) {
LogError ("Nearest node to the start point is not walkable");
Error ();
return;
}
//Tell the NNConstraint which node was found as the start node if it is a PathNNConstraint and not a normal NNConstraint
PathNNConstraint pathNNConstraint = nnConstraint as PathNNConstraint;
if (pathNNConstraint != null) {
pathNNConstraint.SetStart (startNNInfo.node);
}
vectorPaths = new List<Vector3>[targetPoints.Length];
nodePaths = new List<GraphNode>[targetPoints.Length];
targetNodes = new GraphNode[targetPoints.Length];
targetsFound = new bool[targetPoints.Length];
targetNodeCount = targetPoints.Length;
bool anyWalkable = false;
bool anySameArea = false;
bool anyNotNull = false;
for (int i=0;i<targetPoints.Length;i++) {
NNInfo endNNInfo = AstarPath.active.GetNearest (targetPoints[i],nnConstraint);
targetNodes[i] = endNNInfo.node;
//Debug.DrawLine (targetPoints[i],targetNodes[i].position,Color.red);
targetPoints[i] = endNNInfo.clampedPosition;
if (targetNodes[i] != null) {
anyNotNull = true;
endNode = targetNodes[i];
}
bool notReachable = false;
if (endNNInfo.node != null && endNNInfo.node.Walkable) {
anyWalkable = true;
} else {
notReachable = true;
}
if (endNNInfo.node != null && endNNInfo.node.Area == startNode.Area) {
anySameArea = true;
} else {
notReachable = true;
}
if (notReachable) {
targetsFound[i] = true; //Signal that the pathfinder should not look for this node
targetNodeCount--;
}
}
startPoint = startNNInfo.clampedPosition;
startIntPoint = (Int3)startPoint;
//hTarget = (Int3)endPoint;
#if ASTARDEBUG
Debug.DrawLine (startNode.position,startPoint,Color.blue);
//Debug.DrawLine (endNode.position,endPoint,Color.blue);
#endif
if (startNode == null || !anyNotNull) {
LogError ("Couldn't find close nodes to either the start or the end (start = "+(startNode != null ? "found":"not found")+" end = "+(anyNotNull?"at least one found":"none found")+")");
Error ();
return;
}
if (!startNode.Walkable) {
LogError ("The node closest to the start point is not walkable");
Error ();
return;
}
if (!anyWalkable) {
LogError ("No target nodes were walkable");
Error ();
return;
}
if (!anySameArea) {
LogError ("There are no valid paths to the targets");
Error ();
return;
}
//=== Calcuate hTarget ===
if (pathsForAll) {
if (heuristicMode == HeuristicMode.None) {
heuristic = Heuristic.None;
heuristicScale = 0F;
} else if (heuristicMode == HeuristicMode.Average || heuristicMode == HeuristicMode.MovingAverage) {
Vector3 avg = Vector3.zero;
for (int i=0;i<targetNodes.Length;i++) {
avg += (Vector3)targetNodes[i].position;
}
avg /= targetNodes.Length;
hTarget = (Int3)avg;
} else if (heuristicMode == HeuristicMode.Midpoint || heuristicMode == HeuristicMode.MovingMidpoint) {
Vector3 min = Vector3.zero;
Vector3 max = Vector3.zero;
bool set = false;
for (int j=0;j<targetPoints.Length;j++) {
if (!targetsFound[j]) {
if (!set) {
min = (Vector3)targetNodes[j].position;
max = (Vector3)targetNodes[j].position;
set = true;
} else {
min = Vector3.Min ((Vector3)targetNodes[j].position,min);
max = Vector3.Max ((Vector3)targetNodes[j].position,max);
}
}
}
Vector3 midpoint = (min+max)*0.5F;
hTarget = (Int3)midpoint;
} else if (heuristicMode == HeuristicMode.Sequential) {
float dist = 0;
for (int j=0;j<targetNodes.Length;j++) {
if (!targetsFound[j]) {
float d = (targetNodes[j].position-startNode.position).sqrMagnitude;
if (d > dist) {
dist = d;
hTarget = (Int3)targetPoints[j];
sequentialTarget = j;
}
}
}
}
} else {
heuristic = Heuristic.None;
heuristicScale = 0.0F;
}
}
public override void Initialize () {
for (int j=0;j < targetNodes.Length;j++) {
if (startNode == targetNodes[j]) {
PathNode r = pathHandler.GetPathNode(startNode);
FoundTarget (r, j);
} else if (targetNodes[j] != null) {
pathHandler.GetPathNode (targetNodes[j]).flag1 = true;
}
}
//Reset flag1 on all nodes after the pathfinding has completed (no matter if an error occurs or if the path is canceled)
AstarPath.OnPathPostSearch += ResetFlags;
//If all paths have either been invalidated or found already because they were at the same node as the start node
if (targetNodeCount <= 0) {
CompleteState = PathCompleteState.Complete;
return;
}
PathNode startRNode = pathHandler.GetPathNode(startNode);
startRNode.node = startNode;
startRNode.pathID = pathID;
startRNode.parent = null;
startRNode.cost = 0;
startRNode.G = GetTraversalCost (startNode);
startRNode.H = CalculateHScore (startNode);
//if (recalcStartEndCosts) {
// startNode.InitialOpen (open,hTarget,startIntPoint,this,true);
//} else {
startNode.Open (this,startRNode,pathHandler);
//}
searchedNodes++;
//any nodes left to search?
if (pathHandler.HeapEmpty ()) {
LogError ("No open points, the start node didn't open any nodes");
Error();
return;
}
currentR = pathHandler.PopNode ();
}
public void ResetFlags (Path p) {
AstarPath.OnPathPostSearch -= ResetFlags;
if (p != this) {
Debug.LogError ("This should have been cleared after it was called on 'this' path. Was it not called? Or did the delegate reset not work?");
}
// Reset all flags
for ( int i = 0; i < targetNodes.Length; i++ ) {
if (targetNodes[i] != null) pathHandler.GetPathNode (targetNodes[i]).flag1 = false;
}
}
public override void CalculateStep (long targetTick) {
int counter = 0;
//Continue to search while there hasn't ocurred an error and the end hasn't been found
while (CompleteState == PathCompleteState.NotCalculated) {
//@Performance Just for debug info
searchedNodes++;
if (currentR.flag1) {
//Close the current node, if the current node is the target node then the path is finnished
for (int i=0;i<targetNodes.Length;i++) {
if (!targetsFound[i] && currentR.node == targetNodes[i]) {
FoundTarget (currentR, i);
if (CompleteState != PathCompleteState.NotCalculated) {
break;
}
}
}
if (targetNodeCount <= 0) {
CompleteState = PathCompleteState.Complete;
break;
}
}
//Loop through all walkable neighbours of the node and add them to the open list.
currentR.node.Open (this,currentR,pathHandler);
//any nodes left to search?
if (pathHandler.HeapEmpty()) {
CompleteState = PathCompleteState.Complete;
break;
}
//Select the node with the lowest F score and remove it from the open list
AstarProfiler.StartFastProfile (7);
currentR = pathHandler.PopNode ();
AstarProfiler.EndFastProfile (7);
//Check for time every 500 nodes, roughly every 0.5 ms usually
if (counter > 500) {
//Have we exceded the maxFrameTime, if so we should wait one frame before continuing the search since we don't want the game to lag
if (System.DateTime.UtcNow.Ticks >= targetTick) {
//Return instead of yield'ing, a separate function handles the yield (CalculatePaths)
return;
}
counter = 0;
}
counter++;
}
}
protected override void Trace (PathNode node) {
base.Trace (node);
if (inverted) {
//Invert the paths
int half = path.Count/2;
for (int i=0;i<half;i++) {
GraphNode tmp = path[i];
path[i] = path[path.Count-i-1];
path[path.Count-i-1] = tmp;
}
for (int i=0;i<half;i++) {
Vector3 tmp = vectorPath[i];
vectorPath[i] = vectorPath[vectorPath.Count-i-1];
vectorPath[vectorPath.Count-i-1] = tmp;
}
}
}
public override string DebugString (PathLog logMode) {
if (logMode == PathLog.None || (!error && logMode == PathLog.OnlyErrors)) {
return "";
}
System.Text.StringBuilder text = pathHandler.DebugStringBuilder;
text.Length = 0;
text.Append (error ? "Path Failed : " : "Path Completed : ");
text.Append ("Computation Time ");
text.Append ((duration).ToString (logMode == PathLog.Heavy ? "0.000" : "0.00"));
text.Append (" ms Searched Nodes ");
text.Append (searchedNodes);
if (!error) {
text.Append ("\nLast Found Path Length ");
text.Append (path == null ? "Null" : path.Count.ToString ());
if (logMode == PathLog.Heavy) {
text.Append ("\nSearch Iterations "+searchIterations);
text.Append ("\nPaths (").Append (targetsFound.Length).Append ("):");
for (int i=0;i<targetsFound.Length;i++) {
text.Append ("\n\n Path "+i).Append (" Found: ").Append (targetsFound[i]);
GraphNode node = nodePaths[i] == null ? null : nodePaths[i][nodePaths[i].Count-1];
text.Append ("\n Length: ");
text.Append (nodePaths[i].Count);
if (node != null) {
PathNode nodeR = pathHandler.GetPathNode (endNode);
if (nodeR != null) {
text.Append ("\n End Node");
text.Append ("\n G: ");
text.Append (nodeR.G);
text.Append ("\n H: ");
text.Append (nodeR.H);
text.Append ("\n F: ");
text.Append (nodeR.F);
text.Append ("\n Point: ");
text.Append (((Vector3)endPoint).ToString ());
text.Append ("\n Graph: ");
text.Append (endNode.GraphIndex);
} else {
text.Append ("\n End Node: Null");
}
}
}
text.Append ("\nStart Node");
text.Append ("\n Point: ");
text.Append (((Vector3)endPoint).ToString ());
text.Append ("\n Graph: ");
text.Append (startNode.GraphIndex);
text.Append ("\nBinary Heap size at completion: ");
text.AppendLine (pathHandler.GetHeap() == null ? "Null" : (pathHandler.GetHeap().numberOfItems-2).ToString ());// -2 because numberOfItems includes the next item to be added and item zero is not used
}
}
if (error) {
text.Append ("\nError: ");
text.Append (errorLog);
text.AppendLine();
}
if (logMode == PathLog.Heavy && !AstarPath.IsUsingMultithreading ) {
text.Append ("\nCallback references ");
if (callback != null) text.Append(callback.Target.GetType().FullName).AppendLine();
else text.AppendLine ("NULL");
}
text.Append ("\nPath Number ");
text.Append (pathID);
return text.ToString ();
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace WebApplication2
{
/// <summary>
/// Summary description for frmAddProcedure.
/// </summary>
public partial class frmUpdTimetable : System.Web.UI.Page
{
private static string strURL =
System.Configuration.ConfigurationSettings.AppSettings["local_url"];
private static string strDB =
System.Configuration.ConfigurationSettings.AppSettings["local_db"];
public SqlConnection epsDbConn=new SqlConnection(strDB);
private int GetIndexOfStatus (string s)
{
switch(s)
{
case "Planned":
return 0;
case "Active":
return 1;
case "Completed":
return 2;
case "Cancelled":
return 3;
default:
return 0;
}
}
protected void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
if (Session["MgrName"] == null)
{
lblMgr.Text=Session["OrgName"].ToString();
}
else
{
lblMgr.Text=Session["MgrName"].ToString()
;
}
lblService.Text="Service: " + Session["ServiceName"].ToString();
lblLocation.Text="Location: " + Session["LocName"].ToString();
lblProj.Text=Session["PJNameS"].ToString()
+ ": " + Session["ProjName"].ToString();
lblTask.Text="Task Name: "
+ Session["ProcName"].ToString();
lblContents1.Text = "Please enter dates in form mm/dd/yyyy)";
loadData();
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
#endregion
private void loadData()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.Connection=this.epsDbConn;
cmd.CommandText="wms_RetrieveTimetable";
cmd.Parameters.Add ("@PSEPId",SqlDbType.Int);
cmd.Parameters["@PSEPId"].Value=Session["PSEPId"].ToString();
cmd.Parameters.Add ("@ProjectId",SqlDbType.Int);
cmd.Parameters["@ProjectId"].Value=Session["ProjectId"].ToString();
cmd.Parameters.Add ("@OrgId",SqlDbType.Int);
cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString();
cmd.Parameters.Add("@LocationsId", SqlDbType.Int);
cmd.Parameters["@LocationsId"].Value = Session["LocationsId"].ToString();
/*cmd.Parameters.Add ("@OLPProjectsId",SqlDbType.Int);
cmd.Parameters["@OLPProjectsId"].Value=Session["OLPProjectsId"].ToString();*/
/*
cmd.Parameters.Add ("@PSEPID",SqlDbType.Int);
cmd.Parameters["@PSEPID"].Value=Session["PSEPID"].ToString();
cmd.Parameters.Add ("@OrgLocId",SqlDbType.Int);
cmd.Parameters["@OrgLocId"].Value=Session["OrgLocId"].ToString();*/
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(ds,"Timetables");
if (ds.Tables["Timetables"].Rows.Count == 0)
{
DataGrid1.Visible=false;
lblContents1.Text="Note: There are no timetable steps related to this task"
+ " that need to be monitored.";
/*lblOrg.Text="PTPId: "+Session["ProjTypesPSEPId"].ToString()+
" ProjectId: "+ Session["ProjectId"].ToString()+
" OrgLocId: " + Session["OrgLocId"].ToString();*/
}
Session["ds"] = ds;
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
refreshGrid();
}
private void refreshGrid()
{
foreach (DataGridItem i in DataGrid1.Items)
{
TextBox tbDate = (TextBox)(i.Cells[6].FindControl("txtCompletionDate"));
CheckBox cbStatus = (CheckBox)(i.Cells[7].FindControl("cbxStatus"));
if (i.Cells[0].Text.StartsWith("&") == false)
{
if (i.Cells[4].Text.StartsWith("&") == true)
{
tbDate.Text="";
}
else
{
tbDate.Text= i.Cells[4].Text;
}
if (i.Cells[5].Text == "Actual")
{
cbStatus.Checked=true;
}
}
else
{
tbDate.Text="";
}
}
}
protected void btnAction_Click(object sender, System.EventArgs e)
{
updateTimetable();
Done();
}
private void updateTimetable()
{
foreach (DataGridItem i in DataGrid1.Items)
{
if (i.Cells[0].Text.StartsWith("&") == false)
{
TextBox tbDate = (TextBox)(i.Cells[6].FindControl("txtCompletionDate"));
CheckBox cbStatus = (CheckBox)(i.Cells[7].FindControl("cbxStatus"));
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="wms_UpdateTimetable";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add ("@Id",SqlDbType.Int);
cmd.Parameters["@Id"].Value=Int32.Parse(i.Cells[0].Text);
cmd.Parameters.Add ("@CompletionDate",SqlDbType.SmallDateTime);
if (tbDate.Text != "")
{
cmd.Parameters["@CompletionDate"].Value=tbDate.Text;
}
else
{
cmd.Parameters["@CompletionDate"].Value = null;
}
cmd.Parameters.Add ("@Status",SqlDbType.NVarChar);
if (cbStatus.Checked)
{
cmd.Parameters["@Status"].Value="Actual";
}
else
{
cmd.Parameters["@Status"].Value="Plan";
}
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
else
{
TextBox tbDate = (TextBox)(i.Cells[6].FindControl("txtCompletionDate"));
CheckBox cbStatus = (CheckBox)(i.Cells[7].FindControl("cbxStatus"));
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="wms_AddTimetable";
cmd.Connection=this.epsDbConn;
//cmd.Parameters.Add ("@OLPProjectsId",SqlDbType.Int);
//cmd.Parameters["@OLPProjectsId"].Value=Session["OLPProjectsId"].ToString();
cmd.Parameters.Add ("@ProjectId",SqlDbType.Int);
cmd.Parameters["@ProjectId"].Value=Session["ProjectId"].ToString();
cmd.Parameters.Add ("@PSEPID",SqlDbType.Int);
cmd.Parameters["@PSEPID"].Value=Session["PSEPId"].ToString();
cmd.Parameters.Add("@OrgId", SqlDbType.Int);
cmd.Parameters["@OrgId"].Value = Int32.Parse(Session["OrgId"].ToString());
cmd.Parameters.Add("@LocationsId", SqlDbType.Int);
cmd.Parameters["@LocationsId"].Value = Int32.Parse(Session["LocationsId"].ToString());
cmd.Parameters.Add ("@CompletionDate",SqlDbType.SmallDateTime);
if (tbDate.Text != "")
{
cmd.Parameters["@CompletionDate"].Value=tbDate.Text;
}
else
{
cmd.Parameters["@CompletionDate"].Value = null;
}
cmd.Parameters.Add ("@Status",SqlDbType.NVarChar);
cmd.Parameters.Add ("@PSEPStepsId",SqlDbType.Int);
cmd.Parameters["@PSEPStepsId"].Value=i.Cells[2].Text;
if (cbStatus.Checked)
{
cmd.Parameters["@Status"].Value="Actual";
}
else
{
cmd.Parameters["@Status"].Value="Plan";
}
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
}
private void Done()
{
Response.Redirect (strURL + Session["CUpdTT"].ToString() + ".aspx?");
}
protected void btnCancel_Click(object sender, System.EventArgs e)
{
Done();
}
/*private void addTimetable()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.Connection=this.epsDbConn;
cmd.CommandText="wms_RetrieveProjectStepsNew";
cmd.Parameters.Add ("@PSEPID",SqlDbType.Int);
cmd.Parameters["@PSEPID"].Value=Session["PSEPID"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(ds,"Timetables");
if (ds.Tables["Timetables"].Rows.Count == 0)
{
DataGrid1.Visible=false;
lblContents1.ForeColor=System.Drawing.Color.Maroon;
lblContents1.Text="Note: No timetable steps available."
+ "Please contact your system administrator and request creation of timetable steps.";
}
Session["ds"] = ds;
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
refreshGrid();
}*/
/*private void createTimetable()
{
foreach (DataGridItem i in DataGrid1.Items)
{
TextBox tbDate = (TextBox)(i.Cells[5].FindControl("txtCompletionDate"));
CheckBox cbStatus = (CheckBox)(i.Cells[6].FindControl("cbxStatus"));
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="wms_AddTimetable";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add ("@ProjectsId",SqlDbType.Int);
cmd.Parameters["@ProjectsId"].Value=Session["ProjectId"].ToString();
cmd.Parameters.Add ("@CompletionDate",SqlDbType.SmallDateTime);
if (tbDate.Text != "")
{
cmd.Parameters["@CompletionDate"].Value=tbDate.Text;
}
else
{
cmd.Parameters["@CompletionDate"].Value = null;
}
cmd.Parameters.Add ("@Status",SqlDbType.NVarChar);
cmd.Parameters.Add ("@ProfileSEPStepsId",SqlDbType.Int);
cmd.Parameters["@ProfileSEPStepsId"].Value=Int32.Parse(i.Cells[2].Text);
if (cbStatus.Checked)
{
cmd.Parameters["@Status"].Value="Actual";
}
else
{
cmd.Parameters["@Status"].Value="Plan";
}
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}*/
/* private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if (e.CommandName == "Staff")
{
Session["PSEPSId"]=e.Item.Cells[1].Text;
Session["StepName"]=e.Item.Cells[2].Text;
Session["CPStaff"]="frmUpdProject";
Response.Redirect (strURL + "frmProjStepStaff.aspx?");
}
else if (e.CommandName == "Resources")
{
Session["PSEPSId"]=e.Item.Cells[1].Text;
Session["ProfileSEPSName"]=e.Item.Cells[2].Text;
Session["CSEPResTypes"]="frmOLPSEPSteps";
Response.Redirect (strURL + "frmOLPSEPSRes.aspx?");
}
else if (e.CommandName == "Services")
{
Session["PSEPSId"]=e.Item.Cells[1].Text;
Session["ProfileSEPSName"]=e.Item.Cells[2].Text;
Session["CSEPServices"]="frmOLPSEPSteps";
Response.Redirect (strURL + "frmOLPSEPSSer.aspx?");
}
}
*/
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.IO;
using System.Reflection;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Management.Automation;
using System.Management.Automation.Provider;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.WSMan.Management
{
#region Test-WSMAN
/// <summary>
/// Issues an operation against the remote machine to ensure that the wsman
/// service is running.
/// </summary>
[Cmdlet(VerbsDiagnostic.Test, "WSMan", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=141464")]
public class TestWSManCommand : AuthenticatingWSManCommand, IDisposable
{
/// <summary>
/// The following is the definition of the input parameter "ComputerName".
/// Executes the management operation on the specified computer. The default is
/// the local computer. Type the fully qualified domain name, NETBIOS name or IP
/// address to indicate the remote host.
/// </summary>
[Parameter(Position = 0, ValueFromPipeline = true)]
[Alias("cn")]
public string ComputerName
{
get { return computername; }
set
{
computername = value;
if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.OrdinalIgnoreCase)))
{
computername = "localhost";
}
}
}
private string computername = null;
/// <summary>
/// The following is the definition of the input parameter "Authentication".
/// This parameter takes a set of authentication methods the user can select
/// from. The available method are an enum called AuthenticationMechanism in the
/// System.Management.Automation.Runspaces namespace. The available options
/// should be as follows:
/// - Default : Use the default authentication (ad defined by the underlying
/// protocol) for establishing a remote connection.
/// - Negotiate
/// - Kerberos
/// - Basic: Use basic authentication for establishing a remote connection.
/// -CredSSP: Use CredSSP authentication for establishing a remote connection
/// which will enable the user to perform credential delegation. (i.e. second
/// hop)
/// </summary>
/// <remarks>
/// Overriding to use a different default than the one in AuthenticatingWSManCommand base class
/// </remarks>
[Parameter]
[ValidateNotNullOrEmpty]
[Alias("auth", "am")]
public override AuthenticationMechanism Authentication
{
get { return authentication; }
set
{
authentication = value;
ValidateSpecifiedAuthentication();
}
}
private AuthenticationMechanism authentication = AuthenticationMechanism.None;
/// <summary>
/// The following is the definition of the input parameter "Port".
/// Specifies the port to be used when connecting to the ws management service.
/// </summary>
[Parameter(ParameterSetName = "ComputerName")]
[ValidateNotNullOrEmpty]
[ValidateRange(1, Int32.MaxValue)]
public Int32 Port
{
get { return port; }
set { port = value; }
}
private Int32 port = 0;
/// <summary>
/// The following is the definition of the input parameter "UseSSL".
/// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to
/// the remote computer. If SSL is not available on the port specified by the
/// Port parameter, the command fails.
/// </summary>
[Parameter(ParameterSetName = "ComputerName")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")]
public SwitchParameter UseSSL
{
get { return usessl; }
set { usessl = value; }
}
private SwitchParameter usessl;
/// <summary>
/// The following is the definition of the input parameter "ApplicationName".
/// ApplicationName identifies the remote endpoint.
/// </summary>
[Parameter(ParameterSetName = "ComputerName")]
[ValidateNotNullOrEmpty]
public string ApplicationName
{
get { return applicationname; }
set { applicationname = value; }
}
private string applicationname = null;
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
WSManHelper helper = new WSManHelper(this);
IWSManEx wsmanObject = (IWSManEx)new WSManClass();
string connectionStr = string.Empty;
connectionStr = helper.CreateConnectionString(null, port, computername, applicationname);
IWSManSession m_SessionObj = null;
try
{
m_SessionObj = helper.CreateSessionObject(wsmanObject, Authentication, null, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent);
m_SessionObj.Timeout = 1000; // 1 sec. we are putting this low so that Test-WSMan can return promptly if the server goes unresponsive.
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(m_SessionObj.Identify(0));
WriteObject(xmldoc.DocumentElement);
}
catch(Exception)
{
try
{
if (!string.IsNullOrEmpty(m_SessionObj.Error))
{
XmlDocument ErrorDoc = new XmlDocument();
ErrorDoc.LoadXml(m_SessionObj.Error);
InvalidOperationException ex = new InvalidOperationException(ErrorDoc.OuterXml);
ErrorRecord er = new ErrorRecord(ex, "WsManError", ErrorCategory.InvalidOperation, computername);
this.WriteError(er);
}
}
catch(Exception)
{}
}
finally
{
if (m_SessionObj != null)
Dispose(m_SessionObj);
}
}
#region IDisposable Members
/// <summary>
/// Public dispose method.
/// </summary>
public
void
Dispose()
{
// CleanUp();
GC.SuppressFinalize(this);
}
/// <summary>
/// Public dispose method.
/// </summary>
public
void
Dispose(IWSManSession sessionObject)
{
sessionObject = null;
this.Dispose();
}
#endregion IDisposable Members
}
#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 TestCases.SS.UserModel
{
using System;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.Util;
using NUnit.Framework;
/**
* Common superclass for testing implementatiosn of
* {@link Comment}
*/
public class BaseTestCellComment
{
private ITestDataProvider _testDataProvider;
public BaseTestCellComment()
: this(TestCases.HSSF.HSSFITestDataProvider.Instance)
{}
protected BaseTestCellComment(ITestDataProvider testDataProvider) {
_testDataProvider = testDataProvider;
}
[Test]
public void Find()
{
IWorkbook book = _testDataProvider.CreateWorkbook();
ISheet sheet = book.CreateSheet();
Assert.IsNull(sheet.GetCellComment(new CellAddress(0, 0)));
IRow row = sheet.CreateRow(0);
ICell cell = row.CreateCell(0);
Assert.IsNull(sheet.GetCellComment(new CellAddress(0, 0)));
Assert.IsNull(cell.CellComment);
book.Close();
}
[Test]
public void Create()
{
String cellText = "Hello, World";
String commentText = "We can set comments in POI";
String commentAuthor = "Apache Software Foundation";
int cellRow = 3;
int cellColumn = 1;
IWorkbook wb1 = _testDataProvider.CreateWorkbook();
ICreationHelper factory = wb1.GetCreationHelper();
ISheet sheet = wb1.CreateSheet();
Assert.IsNull(sheet.GetCellComment(new CellAddress(cellRow, cellColumn)));
ICell cell = sheet.CreateRow(cellRow).CreateCell(cellColumn);
cell.SetCellValue(factory.CreateRichTextString(cellText));
Assert.IsNull(cell.CellComment);
Assert.IsNull(sheet.GetCellComment(new CellAddress(cellRow, cellColumn)));
IDrawing patr = sheet.CreateDrawingPatriarch();
IClientAnchor anchor = factory.CreateClientAnchor();
anchor.Col1=(2);
anchor.Col2=(5);
anchor.Row1=(1);
anchor.Row2=(2);
IComment comment = patr.CreateCellComment(anchor);
Assert.IsFalse(comment.Visible);
comment.Visible = (true);
Assert.IsTrue(comment.Visible);
IRichTextString string1 = factory.CreateRichTextString(commentText);
comment.String=(string1);
comment.Author=(commentAuthor);
cell.CellComment=(comment);
Assert.IsNotNull(cell.CellComment);
Assert.IsNotNull(sheet.GetCellComment(new CellAddress(cellRow, cellColumn)));
//verify our Settings
Assert.AreEqual(commentAuthor, comment.Author);
Assert.AreEqual(commentText, comment.String.String);
Assert.AreEqual(cellRow, comment.Row);
Assert.AreEqual(cellColumn, comment.Column);
IWorkbook wb2 = _testDataProvider.WriteOutAndReadBack(wb1);
wb1.Close();
sheet = wb2.GetSheetAt(0);
cell = sheet.GetRow(cellRow).GetCell(cellColumn);
comment = cell.CellComment;
Assert.IsNotNull(comment);
Assert.AreEqual(commentAuthor, comment.Author);
Assert.AreEqual(commentText, comment.String.String);
Assert.AreEqual(cellRow, comment.Row);
Assert.AreEqual(cellColumn, comment.Column);
Assert.IsTrue(comment.Visible);
// Change slightly, and re-test
comment.String = (factory.CreateRichTextString("New Comment Text"));
comment.Visible = (false);
IWorkbook wb3 = _testDataProvider.WriteOutAndReadBack(wb2);
wb2.Close();
sheet = wb3.GetSheetAt(0);
cell = sheet.GetRow(cellRow).GetCell(cellColumn);
comment = cell.CellComment;
Assert.IsNotNull(comment);
Assert.AreEqual(commentAuthor, comment.Author);
Assert.AreEqual("New Comment Text", comment.String.String);
Assert.AreEqual(cellRow, comment.Row);
Assert.AreEqual(cellColumn, comment.Column);
Assert.IsFalse(comment.Visible);
// Test Comment.equals and Comment.hashCode
Assert.AreEqual(comment, cell.CellComment);
Assert.AreEqual(comment.GetHashCode(), cell.CellComment.GetHashCode());
wb3.Close();
}
/**
* test that we can read cell comments from an existing workbook.
*/
[Test]
public void ReadComments()
{
IWorkbook wb = _testDataProvider.OpenSampleWorkbook("SimpleWithComments." + _testDataProvider.StandardFileNameExtension);
ISheet sheet = wb.GetSheetAt(0);
ICell cell;
IRow row;
IComment comment;
for (int rownum = 0; rownum < 3; rownum++)
{
row = sheet.GetRow(rownum);
cell = row.GetCell(0);
comment = cell.CellComment;
Assert.IsNull(comment, "Cells in the first column are not commented");
Assert.IsNull(sheet.GetCellComment(new CellAddress(rownum, 0)));
}
for (int rownum = 0; rownum < 3; rownum++)
{
row = sheet.GetRow(rownum);
cell = row.GetCell(1);
comment = cell.CellComment;
Assert.IsNotNull(comment, "Cells in the second column have comments");
Assert.IsNotNull(sheet.GetCellComment(new CellAddress(rownum, 1)), "Cells in the second column have comments");
Assert.AreEqual("Yegor Kozlov", comment.Author);
Assert.IsFalse(comment.String.String == string.Empty, "cells in the second column have not empyy notes");
Assert.AreEqual(rownum, comment.Row);
Assert.AreEqual(cell.ColumnIndex, comment.Column);
}
wb.Close();
}
/**
* test that we can modify existing cell comments
*/
[Test]
public void ModifyComments()
{
IWorkbook wb1 = _testDataProvider.OpenSampleWorkbook("SimpleWithComments." + _testDataProvider.StandardFileNameExtension);
ICreationHelper factory = wb1.GetCreationHelper();
ISheet sheet = wb1.GetSheetAt(0);
ICell cell;
IRow row;
IComment comment;
for (int rownum = 0; rownum < 3; rownum++)
{
row = sheet.GetRow(rownum);
cell = row.GetCell(1);
comment = cell.CellComment;
comment.Author = ("Mofified[" + rownum + "] by Yegor");
comment.String = (factory.CreateRichTextString("Modified comment at row " + rownum));
}
IWorkbook wb2 = _testDataProvider.WriteOutAndReadBack(wb1);
wb1.Close();
sheet = wb2.GetSheetAt(0);
for (int rownum = 0; rownum < 3; rownum++)
{
row = sheet.GetRow(rownum);
cell = row.GetCell(1);
comment = cell.CellComment;
Assert.AreEqual("Mofified[" + rownum + "] by Yegor", comment.Author);
Assert.AreEqual("Modified comment at row " + rownum, comment.String.String);
}
wb2.Close();
}
[Test]
public void DeleteComments()
{
IWorkbook wb1 = _testDataProvider.OpenSampleWorkbook("SimpleWithComments." + _testDataProvider.StandardFileNameExtension);
ISheet sheet = wb1.GetSheetAt(0);
// Zap from rows 1 and 3
Assert.IsNotNull(sheet.GetRow(0).GetCell(1).CellComment);
Assert.IsNotNull(sheet.GetRow(1).GetCell(1).CellComment);
Assert.IsNotNull(sheet.GetRow(2).GetCell(1).CellComment);
sheet.GetRow(0).GetCell(1).RemoveCellComment();
sheet.GetRow(2).GetCell(1).CellComment = (null);
// Check gone so far
Assert.IsNull(sheet.GetRow(0).GetCell(1).CellComment);
Assert.IsNotNull(sheet.GetRow(1).GetCell(1).CellComment);
Assert.IsNull(sheet.GetRow(2).GetCell(1).CellComment);
// Save and re-load
IWorkbook wb2 = _testDataProvider.WriteOutAndReadBack(wb1);
wb1.Close();
sheet = wb2.GetSheetAt(0);
// Check
Assert.IsNull(sheet.GetRow(0).GetCell(1).CellComment);
Assert.IsNotNull(sheet.GetRow(1).GetCell(1).CellComment);
Assert.IsNull(sheet.GetRow(2).GetCell(1).CellComment);
wb2.Close();
}
/**
* code from the quick guide
*/
[Test]
public void QuickGuide()
{
IWorkbook wb1 = _testDataProvider.CreateWorkbook();
ICreationHelper factory = wb1.GetCreationHelper();
ISheet sheet = wb1.CreateSheet();
ICell cell = sheet.CreateRow(3).CreateCell(5);
cell.SetCellValue("F4");
IDrawing drawing = sheet.CreateDrawingPatriarch();
IClientAnchor anchor = factory.CreateClientAnchor();
IComment comment = drawing.CreateCellComment(anchor);
IRichTextString str = factory.CreateRichTextString("Hello, World!");
comment.String = (str);
comment.Author = ("Apache POI");
//assign the comment to the cell
cell.CellComment = (comment);
IWorkbook wb2 = _testDataProvider.WriteOutAndReadBack(wb1);
wb1.Close();
sheet = wb2.GetSheetAt(0);
cell = sheet.GetRow(3).GetCell(5);
comment = cell.CellComment;
Assert.IsNotNull(comment);
Assert.AreEqual("Hello, World!", comment.String.String);
Assert.AreEqual("Apache POI", comment.Author);
Assert.AreEqual(3, comment.Row);
Assert.AreEqual(5, comment.Column);
wb2.Close();
}
[Test]
public void GetClientAnchor()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet sheet = wb.CreateSheet();
IRow row = sheet.CreateRow(10);
ICell cell = row.CreateCell(5);
ICreationHelper factory = wb.GetCreationHelper();
IDrawing Drawing = sheet.CreateDrawingPatriarch();
double r_mul, c_mul;
if (sheet is HSSFSheet)
{
double rowheight = Units.ToEMU(row.HeightInPoints) / Units.EMU_PER_PIXEL;
r_mul = 256.0 / rowheight;
double colwidth = sheet.GetColumnWidthInPixels(2);
c_mul = 1024.0 / colwidth;
}
else
{
r_mul = c_mul = Units.EMU_PER_PIXEL;
}
int dx1 = (int)Math.Round(10 * c_mul);
int dy1 = (int)Math.Round(10 * r_mul);
int dx2 = (int)Math.Round(3 * c_mul);
int dy2 = (int)Math.Round(4 * r_mul);
int col1 = cell.ColumnIndex + 1;
int row1 = row.RowNum;
int col2 = cell.ColumnIndex + 2;
int row2 = row.RowNum + 1;
IClientAnchor anchor = Drawing.CreateAnchor(dx1, dy1, dx2, dy2, col1, row1, col2, row2);
IComment comment = Drawing.CreateCellComment(anchor);
comment.Visible = (/*setter*/true);
cell.CellComment = (/*setter*/comment);
anchor = comment.ClientAnchor;
Assert.AreEqual(dx1, anchor.Dx1);
Assert.AreEqual(dy1, anchor.Dy1);
Assert.AreEqual(dx2, anchor.Dx2);
Assert.AreEqual(dy2, anchor.Dy2);
Assert.AreEqual(col1, anchor.Col1);
Assert.AreEqual(row1, anchor.Row1);
Assert.AreEqual(col2, anchor.Col2);
Assert.AreEqual(row2, anchor.Row2);
anchor = factory.CreateClientAnchor();
comment = Drawing.CreateCellComment(anchor);
cell.CellComment = (/*setter*/comment);
anchor = comment.ClientAnchor;
if (sheet is HSSFSheet)
{
Assert.AreEqual(0, anchor.Col1);
Assert.AreEqual(0, anchor.Dx1);
Assert.AreEqual(0, anchor.Row1);
Assert.AreEqual(0, anchor.Dy1);
Assert.AreEqual(0, anchor.Col2);
Assert.AreEqual(0, anchor.Dx2);
Assert.AreEqual(0, anchor.Row2);
Assert.AreEqual(0, anchor.Dy2);
}
else
{
// when anchor is Initialized without parameters, the comment anchor attributes default to
// "1, 15, 0, 2, 3, 15, 3, 16" ... see XSSFVMLDrawing.NewCommentShape()
Assert.AreEqual(1, anchor.Col1);
Assert.AreEqual(15 * Units.EMU_PER_PIXEL, anchor.Dx1);
Assert.AreEqual(0, anchor.Row1);
Assert.AreEqual(2 * Units.EMU_PER_PIXEL, anchor.Dy1);
Assert.AreEqual(3, anchor.Col2);
Assert.AreEqual(15 * Units.EMU_PER_PIXEL, anchor.Dx2);
Assert.AreEqual(3, anchor.Row2);
Assert.AreEqual(16 * Units.EMU_PER_PIXEL, anchor.Dy2);
}
wb.Close();
}
[Test]
public void AttemptToSave2CommentsWithSameCoordinates()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet sh = wb.CreateSheet();
ICreationHelper factory = wb.GetCreationHelper();
IDrawing patriarch = sh.CreateDrawingPatriarch();
patriarch.CreateCellComment(factory.CreateClientAnchor());
try
{
patriarch.CreateCellComment(factory.CreateClientAnchor());
_testDataProvider.WriteOutAndReadBack(wb);
Assert.Fail("Expected InvalidOperationException(found multiple cell comments for cell $A$1");
}
catch (InvalidOperationException e)
{
// HSSFWorkbooks fail when writing out workbook
Assert.AreEqual(e.Message, "found multiple cell comments for cell A1");
}
catch (ArgumentException e)
{
// XSSFWorkbooks fail when creating and setting the cell address of the comment
Assert.AreEqual(e.Message, "Multiple cell comments in one cell are not allowed, cell: A1");
}
finally
{
wb.Close();
}
}
[Test]
public void GetAddress()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet sh = wb.CreateSheet();
ICreationHelper factory = wb.GetCreationHelper();
IDrawing patriarch = sh.CreateDrawingPatriarch();
IComment comment = patriarch.CreateCellComment(factory.CreateClientAnchor());
Assert.AreEqual(CellAddress.A1, comment.Address);
ICell C2 = sh.CreateRow(1).CreateCell(2);
C2.CellComment = comment;
Assert.AreEqual(new CellAddress("C2"), comment.Address);
}
[Test]
public void SetAddress()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet sh = wb.CreateSheet();
ICreationHelper factory = wb.GetCreationHelper();
IDrawing patriarch = sh.CreateDrawingPatriarch();
IComment comment = patriarch.CreateCellComment(factory.CreateClientAnchor());
Assert.AreEqual(CellAddress.A1, comment.Address);
CellAddress C2 = new CellAddress("C2");
Assert.AreEqual("C2", C2.FormatAsString());
comment.Address = C2;
Assert.AreEqual(C2, comment.Address);
CellAddress E10 = new CellAddress(9, 4);
Assert.AreEqual("E10", E10.FormatAsString());
comment.SetAddress(9, 4);
Assert.AreEqual(E10, comment.Address);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
using System.Windows.Forms.Design;
using System.ComponentModel;
namespace FileHelpers.WizardApp
{
[Designer(typeof (FileBrowser.FileBrowserDesigner))]
public class FileBrowser : ScrollableControl
{
private class FileBrowserDesigner : ControlDesigner
{
protected override void PostFilterProperties(System.Collections.IDictionary properties)
{
base.PostFilterProperties(properties);
properties.Remove("Font");
}
}
public FileBrowser()
{
mColumns.AddRange(new ColumnInfo[] {
new ColumnInfo(11),
new ColumnInfo(38),
new ColumnInfo(72 - 50),
new ColumnInfo(110 - 72),
new ColumnInfo(151 - 110),
new ColumnInfo(169 - 151),
new ColumnInfo(15)
});
PenEvenRule = new Pen(ColorEvenRule);
PenOddRule = new Pen(ColorOddRule);
PenOverRule = new Pen(ColorOverRule);
this.Font = new System.Drawing.Font("Courier New",
mFontSize,
System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Pixel,
((byte) (0)));
this.VerticalScroll.Enabled = true;
this.DoubleBuffered = true;
}
private int mTextTop = 25;
private int mFontSize = 16;
public int FontSize
{
get { return mFontSize; }
set
{
mFontSize = value;
mCharWidth = -1;
this.Font = new System.Drawing.Font("Courier New", mFontSize, System.Drawing.FontStyle.Regular);
this.Invalidate();
}
}
public int TextTop
{
get { return mTextTop; }
set
{
mTextTop = value;
this.Invalidate();
}
}
private int mTextLeft = 10;
public int TextLeft
{
get { return mTextLeft; }
set
{
mTextLeft = value;
this.Invalidate();
}
}
private List<ColumnInfo> mColumns = new List<ColumnInfo>();
public List<ColumnInfo> Columns
{
get { return mColumns; }
}
private Color ColorEvenRule = Color.DarkOrange;
private Color ColorOddRule = Color.RoyalBlue;
private Color ColorOverRule = Color.Black;
private Color ColorOverColumn = Color.LightGoldenrodYellow;
private Pen PenEvenRule;
private Pen PenOddRule;
private Pen PenOverRule;
private int mCharWidth = -1;
private int mOverColumn = -1;
protected override void OnPaint(PaintEventArgs e)
{
if (mCharWidth == -1)
mCharWidth = (int) TextRenderer.MeasureText("m", this.Font).Width - 5;
int width;
int left = mTextLeft;
int rulesTop = mTextTop - 2;
int rulesNumberTop = rulesTop - 13;
bool even = true;
for (int i = 0; i < mColumns.Count; i++) {
width = mCharWidth*mColumns[i].Width;
Brush backBrush;
if (i == mOverColumn)
backBrush = new SolidBrush(ColorOverColumn);
else
backBrush = new SolidBrush(mColumns[i].Color);
e.Graphics.FillRectangle(backBrush, left, 0, width, this.Height - 1);
backBrush.Dispose();
Pen rulePen;
rulePen = even
? PenEvenRule
: PenOddRule;
even = !even;
if (i == mOverColumn)
rulePen = PenOverRule;
e.Graphics.DrawLine(rulePen, left + 1, rulesTop, left + width - 1, rulesTop);
Brush widthBrush;
if (i == mOverColumn)
widthBrush = new SolidBrush(Color.Black);
else
widthBrush = Brushes.DarkRed;
e.Graphics.DrawString(mColumns[i].Width.ToString(),
this.Font,
widthBrush,
left + width/2 - 10,
rulesNumberTop);
left += width;
}
Brush b = new SolidBrush(this.ForeColor);
e.Graphics.DrawString(Text, this.Font, b, mTextLeft, mTextTop);
b.Dispose();
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
int oldCol = mOverColumn;
mOverColumn = CalculateColumn(e.X);
if (oldCol != mOverColumn)
this.Invalidate();
}
private int CalculateColumn(int x)
{
if (x < mTextLeft)
return -1;
int left = mTextLeft;
for (int i = 0; i < mColumns.Count; i++) {
left += mCharWidth*mColumns[i].Width;
if (x < left)
return i;
}
return -1;
}
protected override void OnFontChanged(EventArgs e)
{
base.OnFontChanged(e);
mCharWidth = -1;
}
public class ColumnInfo
{
private int mWidth;
public int Width
{
get { return mWidth; }
set { mWidth = value; }
}
private Color mColor;
public Color Color
{
get { return mColor; }
set { mColor = value; }
}
public static bool even = false;
public ColumnInfo()
{
if (even)
Color = Color.AliceBlue;
else
Color = Color.White;
even = !even;
}
public ColumnInfo(int width)
: this()
{
this.Width = width;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests.LegacyTests
{
public class LastOrDefaultTests
{
private static IEnumerable<int> NumList(int start, int count)
{
for (int i = 0; i < count; i++)
yield return start + i;
}
private static IEnumerable<T> ForceNotCollection<T>(IEnumerable<T> source)
{
foreach (T item in source) yield return item;
}
private static bool IsEven(int num)
{
return num % 2 == 0;
}
[Fact]
public void SameResultsRepeatCallsIntQuery()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
Assert.Equal(q.LastOrDefault(), q.LastOrDefault());
}
[Fact]
public void SameResultsRepeatCallsStringQuery()
{
var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty }
where !String.IsNullOrEmpty(x)
select x;
Assert.Equal(q.LastOrDefault(), q.LastOrDefault());
}
private static void TestEmptyIList<T>()
{
T[] source = { };
T expected = default(T);
Assert.IsAssignableFrom<IList<T>>(source);
Assert.Equal(expected, source.LastOrDefault());
}
[Fact]
public void EmptyIListT()
{
TestEmptyIList<int>();
TestEmptyIList<string>();
TestEmptyIList<DateTime>();
TestEmptyIList<LastOrDefaultTests>();
}
[Fact]
public void IListTOneElement()
{
int[] source = { 5 };
int expected = 5;
Assert.IsAssignableFrom<IList<int>>(source);
Assert.Equal(expected, source.LastOrDefault());
}
[Fact]
public void IListTManyELementsLastIsDefault()
{
int?[] source = { -10, 2, 4, 3, 0, 2, null };
int? expected = null;
Assert.IsAssignableFrom<IList<int?>>(source);
Assert.Equal(expected, source.LastOrDefault());
}
[Fact]
public void IListTManyELementsLastIsNotDefault()
{
int?[] source = { -10, 2, 4, 3, 0, 2, null, 19 };
int? expected = 19;
Assert.IsAssignableFrom<IList<int?>>(source);
Assert.Equal(expected, source.LastOrDefault());
}
private static IEnumerable<T> EmptySource<T>()
{
yield break;
}
private static void TestEmptyNotIList<T>()
{
var source = EmptySource<T>();
T expected = default(T);
Assert.Null(source as IList<T>);
Assert.Equal(expected, source.LastOrDefault());
}
[Fact]
public void EmptyNotIListT()
{
TestEmptyNotIList<int>();
TestEmptyNotIList<string>();
TestEmptyNotIList<DateTime>();
TestEmptyNotIList<LastOrDefaultTests>();
}
[Fact]
public void OneElementNotIListT()
{
IEnumerable<int> source = NumList(-5, 1);
int expected = -5;
Assert.Null(source as IList<int>);
Assert.Equal(expected, source.LastOrDefault());
}
[Fact]
public void ManyElementsNotIListT()
{
IEnumerable<int> source = NumList(3, 10);
int expected = 12;
Assert.Null(source as IList<int>);
Assert.Equal(expected, source.LastOrDefault());
}
[Fact]
public void EmptyIListSource()
{
int?[] source = { };
Assert.Null(source.LastOrDefault(x => true));
Assert.Null(source.LastOrDefault(x => false));
}
[Fact]
public void OneElementIListTruePredicate()
{
int[] source = { 4 };
Func<int, bool> predicate = IsEven;
int expected = 4;
Assert.Equal(expected, source.LastOrDefault(predicate));
}
[Fact]
public void ManyElementsIListPredicateFalseForAll()
{
int[] source = { 9, 5, 1, 3, 17, 21 };
Func<int, bool> predicate = IsEven;
int expected = default(int);
Assert.Equal(expected, source.LastOrDefault(predicate));
}
[Fact]
public void IListPredicateTrueOnlyForLast()
{
int[] source = { 9, 5, 1, 3, 17, 21, 50 };
Func<int, bool> predicate = IsEven;
int expected = 50;
Assert.Equal(expected, source.LastOrDefault(predicate));
}
[Fact]
public void IListPredicateTrueForSome()
{
int[] source = { 3, 7, 10, 7, 9, 2, 11, 18, 13, 9 };
Func<int, bool> predicate = IsEven;
int expected = 18;
Assert.Equal(expected, source.LastOrDefault(predicate));
}
[Fact]
public void EmptyNotIListSource()
{
IEnumerable<int?> source = Enumerable.Repeat((int?)4, 0);
Assert.Null(source.LastOrDefault(x => true));
Assert.Null(source.LastOrDefault(x => false));
}
[Fact]
public void OneElementNotIListTruePredicate()
{
IEnumerable<int> source = ForceNotCollection(new[] { 4 });
Func<int, bool> predicate = IsEven;
int expected = 4;
Assert.Equal(expected, source.LastOrDefault(predicate));
}
[Fact]
public void ManyElementsNotIListPredicateFalseForAll()
{
IEnumerable<int> source = ForceNotCollection(new int[] { 9, 5, 1, 3, 17, 21 });
Func<int, bool> predicate = IsEven;
int expected = default(int);
Assert.Equal(expected, source.LastOrDefault(predicate));
}
[Fact]
public void NotIListPredicateTrueOnlyForLast()
{
IEnumerable<int> source = ForceNotCollection(new int[] { 9, 5, 1, 3, 17, 21, 50 });
Func<int, bool> predicate = IsEven;
int expected = 50;
Assert.Equal(expected, source.LastOrDefault(predicate));
}
[Fact]
public void NotIListPredicateTrueForSome()
{
IEnumerable<int> source = ForceNotCollection(new int[] { 3, 7, 10, 7, 9, 2, 11, 18, 13, 9 });
Func<int, bool> predicate = IsEven;
int expected = 18;
Assert.Equal(expected, source.LastOrDefault(predicate));
}
}
}
| |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Chutzpah.FrameworkDefinitions;
using Chutzpah.Models;
using Chutzpah.Wrappers;
using Moq;
using Xunit;
namespace Chutzpah.Facts
{
public class ReferenceProcessorFacts
{
private class TestableReferenceProcessor : Testable<ReferenceProcessor>
{
public IFrameworkDefinition FrameworkDefinition { get; set; }
public TestableReferenceProcessor()
{
var frameworkMock = Mock<IFrameworkDefinition>();
frameworkMock.Setup(x => x.FileUsesFramework(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<PathType>())).Returns(true);
frameworkMock.Setup(x => x.FrameworkKey).Returns("qunit");
frameworkMock.Setup(x => x.GetTestRunner(It.IsAny<ChutzpahTestSettingsFile>())).Returns("qunitRunner.js");
frameworkMock.Setup(x => x.GetTestHarness(It.IsAny<ChutzpahTestSettingsFile>())).Returns("qunit.html");
frameworkMock.Setup(x => x.GetFileDependencies(It.IsAny<ChutzpahTestSettingsFile>())).Returns(new[] { "qunit.js", "qunit.css" });
FrameworkDefinition = frameworkMock.Object;
Mock<IFileProbe>().Setup(x => x.FindFilePath(It.IsAny<string>())).Returns<string>(x => x);
Mock<IFileSystemWrapper>().Setup(x => x.GetText(It.IsAny<string>())).Returns(string.Empty);
}
}
public class SetupAmdFilePaths
{
[Fact]
public void Will_set_amd_path_for_reference_path()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\path";
var referencedFile = new ReferencedFile {Path = @"C:\some\path\code\test.js"};
var referenceFiles = new List<ReferencedFile> { referencedFile };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles,testHarnessDirectory, new ChutzpahTestSettingsFile().InheritFromDefault());
Assert.Equal("code/test",referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_make_amd_path_relative_to_amdbaseurl_if_no_amdappdirectory_if_given()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\path";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
var settings = new ChutzpahTestSettingsFile { AMDBaseUrl = @"C:\some\other" };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, settings);
Assert.Equal("../path/code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_make_amd_path_relative_to_amdappdirectory_if_given()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\path";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
var settings = new ChutzpahTestSettingsFile { AMDAppDirectory = @"C:\some\other" };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, settings);
Assert.Equal("../path/code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_make_amd_path_relative_to_amdbasepath_with_legacy_setting()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\path";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
var settings = new ChutzpahTestSettingsFile {AMDBasePath = @"C:\some\other"};
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, settings);
Assert.Equal("../path/code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_make_amd_path_relative_to_testHarnessLocation()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\src\folder";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
var settings = new ChutzpahTestSettingsFile { };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, settings);
Assert.Equal("../../path/code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_make_amd_path_relative_to_testHarnessLocation_and_amdbasepath()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\path\subFolder";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
var settings = new ChutzpahTestSettingsFile { AMDBasePath = @"C:\some\other" };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, settings);
Assert.Equal("../path/subFolder/../code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_set_amd_path_ignoring_the_case()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"C:\Some\Path";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, new ChutzpahTestSettingsFile().InheritFromDefault());
Assert.Equal("code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_set_amd_path_for_reference_path_and_generated_path()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"C:\some\path";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.ts", GeneratedFilePath = @"C:\some\path\code\_Chutzpah.1.test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, new ChutzpahTestSettingsFile().InheritFromDefault());
Assert.Equal("code/test", referencedFile.AmdFilePath);
}
}
public class GetReferencedFiles
{
[Fact]
public void Will_add_reference_file_to_referenced_files()
{
var processor = new TestableReferenceProcessor();
var settings = new ChutzpahTestSettingsFile { }.InheritFromDefault();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var text = (@"/// <reference path=""lib.js"" />
some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\lib.js" && x.IncludeInTestHarness));
}
[Fact]
public void Will_handle_multiple_test_files()
{
var processor = new TestableReferenceProcessor();
var settings = new ChutzpahTestSettingsFile { }.InheritFromDefault();
var referenceFiles = new List<ReferencedFile> {
new ReferencedFile { IsFileUnderTest = true, Path = @"path\test1.js", ExpandReferenceComments = true },
new ReferencedFile { IsFileUnderTest = true, Path = @"path\test2.js", ExpandReferenceComments = true }};
var text = (@"/// <reference path=""lib.js"" />
some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test1.js")).Returns(text);
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test2.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.Equal(2, referenceFiles.Count(x => x.IsFileUnderTest));
}
[Fact]
public void Will_exclude_reference_from_harness_in_amd_mode()
{
var processor = new TestableReferenceProcessor();
var settings = new ChutzpahTestSettingsFile { }.InheritFromDefault();
settings.TestHarnessReferenceMode = TestHarnessReferenceMode.AMD;
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var text = (@"/// <reference path=""lib.js"" />
some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\lib.js" && !x.IncludeInTestHarness));
}
[Fact]
public void Will_change_path_root_given_SettingsFileDirectory_RootReferencePathMode()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path1\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile
{
RootReferencePathMode = RootReferencePathMode.SettingsFileDirectory,
SettingsFileDirectory = @"C:\root"
};
var text = @"/// <reference path=""/this/file.js"" />
some javascript code
";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path1\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path.Equals(@"C:\root/this/file.js")));
}
[Fact]
public void Will_change_path_root_given_even_if_has_tilde()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path1\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile
{
RootReferencePathMode = RootReferencePathMode.SettingsFileDirectory,
SettingsFileDirectory = @"C:\root"
};
var text = @"/// <reference path=""~/this/file.js"" />
some javascript code
";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path1\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path.Equals(@"C:\root/this/file.js")));
}
[Fact]
public void Will_not_change_path_root_given_SettingsFileDirectory_RootReferencePathMode()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path1\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {RootReferencePathMode = RootReferencePathMode.DriveRoot, SettingsFileDirectory = @"C:\root"};
var text = @"/// <reference path=""/this/file.js"" />
some javascript code
";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path1\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path.Equals(@"/this/file.js")));
}
[Fact]
public void Will_change_path_root_given_SettingsFileDirectory_RootReferencePathMode_for_html_file()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path1\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile
{
RootReferencePathMode = RootReferencePathMode.SettingsFileDirectory,
SettingsFileDirectory = @"C:\root"
};
var text = @"/// <reference path=""/this/file.html"" />
some javascript code
";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path1\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path.Equals(@"C:\root/this/file.html")));
}
[Fact]
public void Will_not_add_referenced_file_if_it_is_excluded()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path1\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
var text = @"/// <reference path=""lib.js"" />
/// <reference path=""../../js/excluded.js"" chutzpah-exclude=""true"" />
/// <reference path=""../../js/doublenegative.js"" chutzpah-exclude=""false"" />
/// <reference path=""../../js/excluded.js"" chutzpahExclude=""true"" />
/// <reference path=""../../js/doublenegative.js"" chutzpahExclude=""false"" />
some javascript code
";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path1\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.False(referenceFiles.Any(x => x.Path.EndsWith("excluded.js")), "Test context contains excluded reference.");
Assert.True(referenceFiles.Any(x => x.Path.EndsWith("doublenegative.js")), "Test context does not contain negatively excluded reference.");
}
[Fact]
public void Will_put_recursively_referenced_files_before_parent_file()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileProbe>()
.Setup(x => x.FindFilePath(Path.Combine(@"path\", @"../../js/references.js")))
.Returns(@"path\references.js");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetText(@"path\references.js"))
.Returns(@"/// <reference path=""lib.js"" />");
string text = @"/// <reference path=""../../js/references.js"" />
some javascript code
";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
var ref1 = referenceFiles.First(x => x.Path == @"path\lib.js");
var ref2 = referenceFiles.First(x => x.Path == @"path\references.js");
var pos1 = referenceFiles.IndexOf(ref1);
var pos2 = referenceFiles.IndexOf(ref2);
Assert.True(pos1 < pos2);
}
[Fact(Timeout = 5000)]
public void Will_stop_infinite_loop_when_processing_referenced_files()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
var text = @"/// <reference path=""../../js/references.js"" />
some javascript code
";
var loopText = @"/// <reference path=""../../js/references.js"" />";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetText(@"path\references.js"))
.Returns(loopText);
processor.Mock<IFileProbe>()
.Setup(x => x.FindFilePath(Path.Combine(@"path\", @"../../js/references.js")))
.Returns(@"path\references.js");
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\references.js"));
}
[Fact]
public void Will_process_all_files_in_folder_references()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileProbe>()
.Setup(x => x.FindFilePath(Path.Combine(@"path\", @"../../js/somefolder")))
.Returns((string) null);
processor.Mock<IFileProbe>()
.Setup(x => x.FindFolderPath(Path.Combine(@"path\", @"../../js/somefolder")))
.Returns(@"path\someFolder");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"path\someFolder", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\subFile.js"});
var text = @"/// <reference path=""../../js/somefolder"" />
some javascript code
";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
}
[Fact]
public void Will_skip_chutzpah_temporary_files_in_folder_references()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileProbe>()
.Setup(x => x.FindFilePath(Path.Combine(@"path\", @"../../js/somefolder")))
.Returns((string) null);
processor.Mock<IFileProbe>()
.Setup(x => x.FindFolderPath(Path.Combine(@"path\", @"../../js/somefolder")))
.Returns(@"path\someFolder");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"path\someFolder", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\subFile.js"});
var text = @"/// <reference path=""../../js/somefolder"" />
some javascript code
";
processor.Mock<IFileProbe>().Setup(x => x.IsTemporaryChutzpahFile(It.IsAny<string>())).Returns(true);
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.False(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
}
[Fact]
public void Will_only_include_one_reference_with_mulitple_references_in_html_template()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
var text = (@"/// <template path=""../../templates/file.html"" />
/// <template path=""../../templates/file.html"" />
some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.Equal(1, referenceFiles.Count(x => x.Path.EndsWith("file.html")));
}
[Fact]
public void Will_parse_html_template_in_script_mode()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile { };
var text = (@"/// <template mode=""script"" id=""my.Id"" path=""../../templates/file.html"" type=""My/Type""/>
some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
var file = referenceFiles.FirstOrDefault(x => x.Path.EndsWith("file.html"));
Assert.NotNull(file);
Assert.Equal(TemplateMode.Script, file.TemplateOptions.Mode);
Assert.Equal("my.Id", file.TemplateOptions.Id);
Assert.Equal("My/Type", file.TemplateOptions.Type);
}
[Fact]
public void Will_parse_html_template_in_raw_mode()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile { };
var text = (@"/// <template path=""../../templates/file.html"" />
some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
var file = referenceFiles.FirstOrDefault(x => x.Path.EndsWith("file.html"));
Assert.NotNull(file);
Assert.Equal(TemplateMode.Raw, file.TemplateOptions.Mode);
Assert.Null(file.TemplateOptions.Id);
Assert.Null(file.TemplateOptions.Type);
}
[Fact]
public void Will_add_reference_url_to_referenced_files()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
var text = (@"/// <reference path=""http://a.com/lib.js"" />
some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == "http://a.com/lib.js"));
}
[Fact]
public void Will_add_chutzpah_reference_to_referenced_files()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
var text = (@"/// <chutzpah_reference path=""lib.js"" />
some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path.EndsWith("lib.js")));
}
[Fact]
public void Will_add_file_from_settings_referenced_files()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here.js",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"c:\dir\here.js" && x.IncludeInTestHarness));
}
[Fact]
public void Will_default_path_to_settings_folder_when_adding_from_settings_references()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile().InheritFromDefault();
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\settingsDir")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\settingsDir")).Returns(@"c:\settingsDir");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\settingsDir", "*.*", SearchOption.AllDirectories))
.Returns(new[] { @"settingsDir\subFile.js", @"settingsDir\newFile.js", @"other\subFile.js" });
settings.SettingsFileDirectory = @"c:\settingsDir";
settings.References.Add(
new SettingsFileReference
{
Path = null,
Include = "*subFile.js",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"settingsDir\subFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\newFile.js"));
}
[Fact]
public void Will_exclude_from_test_harness_given_setting()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
settings.SettingsFileDirectory = @"c:\dir";
settings.TestHarnessReferenceMode = TestHarnessReferenceMode.AMD;
settings.References.Add(
new SettingsFileReference
{
Path = "here.js",
IncludeInTestHarness = true,
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"c:\dir\here.js" && x.IncludeInTestHarness));
}
[Fact]
public void Will_add_files_from_folder_from_settings_referenced_files()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\subFile.js", @"path\newFile.js"});
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
Assert.True(referenceFiles.Any(x => x.Path == @"path\newFile.js"));
}
[Fact]
public void Will_exclude_files_from_folder_from_settings_referenced_files_if_match_exclude_path()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\subFile.js", @"path\newFile.js"});
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
Exclude = @"*path\sub*",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\newFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
}
[Fact]
public void Will_exclude_files_from_folder_from_settings_referenced_files_if_they_dont_match_include_path()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\subFile.js", @"path\newFile.js"});
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
Include = @"*path\sub*",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.False(referenceFiles.Any(x => x.Path == @"path\newFile.js"));
Assert.True(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
}
[Fact]
public void Will_exclude_files_from_folder_from_settings_referenced_files_if_match_exclude_path_and_dont_match_include()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\parentFile.js", @"other\newFile.js", @"path\sub\childFile.js"});
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
Include = @"path\*",
Exclude = @"*path\pare*",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\sub\childFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\parentFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"other\newFile.js"));
}
[Fact]
public void Will_exclude_files_from_folder_from_settings_referenced_files_if_match_excludes_path_and_dont_match_include()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile { };
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] { @"path\parentFile.js", @"other\newFile.js", @"path\sub\childFile.js" });
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
Includes = new[] { @"path\*", @"other\*", },
Excludes = new []{ @"*path\pare*", @"other\new*" },
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\sub\childFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\parentFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"other\newFile.js"));
}
[Fact]
public void Will_normlize_paths_for_case_and_slashes_for_path_include_exclude()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile { };
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] { @"pAth/parentFile.js", @"Other/newFile.js", @"path\sub\childFile.js" });
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
Include = @"PATH/*",
Exclude = @"*paTh/pAre*",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\sub\childFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\parentFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"other\newFile.js"));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using FortuneCookies;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Samples.Chirper.GrainInterfaces;
using Orleans.Samples.Chirper.Network.Loader;
namespace Orleans.Samples.Chirper.Network.Driver
{
class ChirperNetworkDriver : IDisposable
{
private AsyncPipeline pipeline;
private readonly List<SimulatedUser> activeUsers;
public FileInfo GraphDataFile { get; internal set; }
public double LoggedInUserRate { get; set; }
public double ShouldRechirpRate { get; set; }
public int ChirpPublishTimebase { get; set; }
public bool ChirpPublishTimeRandom { get; set; }
public bool Verbose { get; set; }
public int LinksPerUser { get; set; }
public int PipelineLength { get; set; }
private ChirperNetworkLoader loader;
private readonly Fortune fortune;
private ChirperPerformanceCounters perfCounters;
public ChirperNetworkDriver()
{
this.LinksPerUser = 27;
this.LoggedInUserRate = 0.001;
this.ShouldRechirpRate = 0.0;
this.ChirpPublishTimebase = 0;
this.ChirpPublishTimeRandom = true;
this.activeUsers = new List<SimulatedUser>();
this.PipelineLength = 500;
this.fortune = new Fortune("fortune.txt");
if (!GrainClient.IsInitialized)
{
var config = ClientConfiguration.LocalhostSilo();
GrainClient.Initialize(config);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification="This method creates SimulatedUser objects which will not be disposed until the Stop method")]
public int Run()
{
this.perfCounters = new ChirperPerformanceCounters(this.GraphDataFile.FullName);
perfCounters.ChirpsPerSecond.RawValue = 0;
pipeline = new AsyncPipeline(PipelineLength);
loader = new ChirperNetworkLoader(pipeline);
//if (this.Verbose) loader.SetVerbose();
Console.WriteLine("Loading Chirper network data file " + this.GraphDataFile.FullName);
loader.FileToLoad = this.GraphDataFile;
loader.LoadData();
loader.CreateUserNodes(); // Connect/create users
Console.WriteLine(
"Starting Chirper network traffic simulation for {0} users.\n"
+ "Chirp publication time base = {1}\n"
+ "Random time distribution = {2}\n"
+ "Rechirp rate = {3}",
loader.Users.Count, this.ChirpPublishTimebase, this.ChirpPublishTimeRandom, this.ShouldRechirpRate);
ForEachUser(user =>
{
SimulatedUser u = new SimulatedUser(user);
u.ShouldRechirpRate = this.ShouldRechirpRate;
u.ChirpPublishTimebase = this.ChirpPublishTimebase;
u.ChirpPublishTimeRandom = this.ChirpPublishTimeRandom;
u.Verbose = this.Verbose;
lock (activeUsers)
{
activeUsers.Add(u);
}
u.Start();
});
Console.WriteLine("Starting sending chirps...");
Random rand = new Random();
int count = 0;
Stopwatch stopwatch = Stopwatch.StartNew();
do
{
int i = rand.Next(activeUsers.Count);
SimulatedUser u = activeUsers[i];
if (u == null)
{
Console.WriteLine("User {0} not found.", i);
return -1;
}
string msg = fortune.GetFortune();
pipeline.Add(u.PublishMessage(msg));
count++;
if (count % 10000 == 0)
{
Console.WriteLine("{0:0.#}/sec: {1} in {2}ms. Pipeline contains {3} items.",
((float)10000 / stopwatch.ElapsedMilliseconds) * 1000, count, stopwatch.ElapsedMilliseconds, pipeline.Count);
perfCounters.ChirpsPerSecond.RawValue = (int) (((float) 10000 / stopwatch.ElapsedMilliseconds) * 1000);
stopwatch.Restart();
}
if (ChirpPublishTimebase > 0)
{
Thread.Sleep(ChirpPublishTimebase * 1000);
}
} while (true);
}
public void Stop()
{
activeUsers.ForEach(u => u.Dispose());
activeUsers.Clear();
}
public bool ParseArguments(string[] args)
{
bool ok = true;
int argPos = 1;
for (int i = 0; i < args.Length; i++)
{
string a = args[i];
if (a.StartsWith("-") || a.StartsWith("/"))
{
a = a.ToLowerInvariant().Substring(1);
switch (a)
{
case "verbose":
case "v":
this.Verbose = true;
break;
case "norandom":
this.ChirpPublishTimeRandom = false;
break;
case "time":
this.ChirpPublishTimebase = Int32.Parse(args[++i]);
break;
case "rechirp":
this.ShouldRechirpRate = Double.Parse(args[++i]);
break;
case "links":
this.LinksPerUser = Int32.Parse(args[++i]);
break;
case "pipeline":
this.PipelineLength = Int32.Parse(args[++i]);
break;
case "?":
case "help":
default:
ok = false;
break;
}
}
// unqualified arguments below
else if (argPos == 1)
{
this.GraphDataFile = new FileInfo(a);
argPos++;
if (!GraphDataFile.Exists)
{
Console.WriteLine("Cannot find data file: " + this.GraphDataFile.FullName);
ok = false;
}
}
else
{
// Too many command line arguments
Console.WriteLine("Too many command line arguments supplied: " + a);
return false;
}
}
if (GraphDataFile == null)
{
Console.WriteLine("No graph data file supplied -- driver cannot run.");
return false;
}
return ok;
}
public void PrintUsage()
{
using (StringWriter usageStr = new StringWriter())
{
usageStr.WriteLine(Assembly.GetExecutingAssembly().GetName().Name + ".exe [options] {file}");
usageStr.WriteLine("Where:");
usageStr.WriteLine(" {file} = GraphML file for network to simulate");
usageStr.WriteLine(" /create = Create the network graph in Orleans before running simulation");
usageStr.WriteLine(" /time {t} = Base chirp publication time (integer)");
usageStr.WriteLine(" /rechirp {r} = Rechirp rate (decimal 0.0 - 1.0)");
usageStr.WriteLine(" /norandom = Use constant chirp publication time intervals, rather than random");
usageStr.WriteLine(" /create = Create the network graph in Orleans before running simulation");
usageStr.WriteLine(" /v = Verbose output");
Console.WriteLine(usageStr.ToString());
}
}
private void ForEachUser(Action<IChirperAccount> action)
{
List<Task> promises = new List<Task>();
foreach (long userId in loader.Users.Keys)
{
IChirperAccount user = loader.Users[userId];
Task p = Task.Factory.StartNew(() => action(user));
pipeline.Add(p);
promises.Add(p);
}
pipeline.Wait();
Task.WhenAll(promises).Wait();
}
#region IDisposable Members
public void Dispose()
{
//loader.Dispose();
}
#endregion
}
}
| |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org.
// ****************************************************************
namespace NUnit.Core
{
using System;
using System.Collections;
using System.Runtime.Remoting.Messaging;
using System.Threading;
using System.Text;
using System.Text.RegularExpressions;
using System.Reflection;
/// <summary>
/// The TestMethod class represents a Test implemented as a method.
///
/// Because of how exceptions are handled internally, this class
/// must incorporate processing of expected exceptions. A change to
/// the Test interface might make it easier to process exceptions
/// in an object that aggregates a TestMethod in the future.
/// </summary>
public abstract class TestMethod : Test
{
static Logger log = InternalTrace.GetLogger(typeof(TestMethod));
static ContextDictionary context;
#region Fields
/// <summary>
/// The test method
/// </summary>
internal MethodInfo method;
/// <summary>
/// The SetUp method.
/// </summary>
protected MethodInfo[] setUpMethods;
/// <summary>
/// The teardown method
/// </summary>
protected MethodInfo[] tearDownMethods;
/// <summary>
/// The ExpectedExceptionProcessor for this test, if any
/// </summary>
internal ExpectedExceptionProcessor exceptionProcessor;
/// <summary>
/// Arguments to be used in invoking the method
/// </summary>
internal object[] arguments;
/// <summary>
/// The expected result of the method return value
/// </summary>
internal object expectedResult;
/// <summary>
/// Indicates whether expectedResult was set - thereby allowing null as a value
/// </summary>
internal bool hasExpectedResult;
/// <summary>
/// The fixture object, if it has been created
/// </summary>
private object fixture;
private Exception builderException;
#endregion
#region Constructors
public TestMethod( MethodInfo method )
: base( method.ReflectedType.FullName, method.Name )
{
if( method.DeclaringType != method.ReflectedType)
this.TestName.Name = method.DeclaringType.Name + "." + method.Name;
this.method = method;
}
#endregion
#region Static Properties
private static ContextDictionary Context
{
get
{
if (context==null)
{
context = new ContextDictionary();
}
return context;
}
}
#endregion
#region Properties
public override string TestType
{
get { return "TestMethod"; }
}
public MethodInfo Method
{
get { return method; }
}
public override Type FixtureType
{
get { return method.ReflectedType; }
}
public ExpectedExceptionProcessor ExceptionProcessor
{
get { return exceptionProcessor; }
set { exceptionProcessor = value; }
}
public bool ExceptionExpected
{
get { return exceptionProcessor != null; }
}
public override object Fixture
{
get { return fixture; }
set { fixture = value; }
}
public int Timeout
{
get
{
return Properties.Contains("Timeout")
? (int)Properties["Timeout"]
: TestExecutionContext.CurrentContext.TestCaseTimeout;
}
}
protected override bool ShouldRunOnOwnThread
{
get
{
return base.ShouldRunOnOwnThread || Timeout > 0;
}
}
public Exception BuilderException
{
get { return builderException; }
set { builderException = value; }
}
#endregion
#region Run Methods
public override TestResult Run(EventListener listener, ITestFilter filter)
{
log.Debug("Test Starting: " + this.TestName.FullName);
listener.TestStarted(this.TestName);
long startTime = DateTime.Now.Ticks;
TestResult testResult = this.RunState == RunState.Runnable || this.RunState == RunState.Explicit
? RunTestInContext() : SkipTest();
log.Debug("Test result = " + testResult.ResultState);
long stopTime = DateTime.Now.Ticks;
double time = ((double)(stopTime - startTime)) / (double)TimeSpan.TicksPerSecond;
testResult.Time = time;
listener.TestFinished(testResult);
return testResult;
}
private TestResult SkipTest()
{
TestResult testResult = new TestResult(this);
switch (this.RunState)
{
case RunState.Skipped:
default:
testResult.Skip(IgnoreReason);
break;
case RunState.NotRunnable:
if (BuilderException != null)
testResult.Invalid(BuilderException);
else
testResult.Invalid(IgnoreReason);
break;
case RunState.Ignored:
testResult.Ignore(IgnoreReason);
break;
}
return testResult;
}
private TestResult RunTestInContext()
{
TestExecutionContext.Save();
TestExecutionContext.CurrentContext.CurrentTest = this;
ContextDictionary context = Context;
context._ec = TestExecutionContext.CurrentContext;
CallContext.SetData("NUnit.Framework.TestContext", context);
if (this.Parent != null)
{
this.Fixture = this.Parent.Fixture;
TestSuite suite = this.Parent as TestSuite;
if (suite != null)
{
this.setUpMethods = suite.GetSetUpMethods();
this.tearDownMethods = suite.GetTearDownMethods();
}
}
try
{
// Temporary... to allow for tests that directly execute a test case
if (Fixture == null && !method.IsStatic)
Fixture = Reflect.Construct(this.FixtureType);
if (this.Properties["_SETCULTURE"] != null)
TestExecutionContext.CurrentContext.CurrentCulture =
new System.Globalization.CultureInfo((string)Properties["_SETCULTURE"]);
if (this.Properties["_SETUICULTURE"] != null)
TestExecutionContext.CurrentContext.CurrentUICulture =
new System.Globalization.CultureInfo((string)Properties["_SETUICULTURE"]);
return RunRepeatedTest();
}
catch (Exception ex)
{
log.Debug("TestMethod: Caught " + ex.GetType().Name);
if (ex is ThreadAbortException)
Thread.ResetAbort();
TestResult testResult = new TestResult(this);
RecordException(ex, testResult, FailureSite.Test);
return testResult;
}
finally
{
Fixture = null;
CallContext.FreeNamedDataSlot("NUnit.Framework.TestContext");
TestExecutionContext.Restore();
}
}
// TODO: Repeated tests need to be implemented as separate tests
// in the tree of tests. Once that is done, this method will no
// longer be needed and RunTest can be called directly.
private TestResult RunRepeatedTest()
{
TestResult testResult = null;
int repeatCount = this.Properties.Contains("Repeat")
? (int)this.Properties["Repeat"] : 1;
while (repeatCount-- > 0)
{
testResult = ShouldRunOnOwnThread
? new TestMethodThread(this).Run(NullListener.NULL, TestFilter.Empty)
: RunTest();
if (testResult.ResultState == ResultState.Failure ||
testResult.ResultState == ResultState.Error ||
testResult.ResultState == ResultState.Cancelled)
{
break;
}
}
return testResult;
}
/// <summary>
/// The doRun method is used to run a test internally.
/// It assumes that the caller is taking care of any
/// TestFixtureSetUp and TestFixtureTearDown needed.
/// </summary>
/// <param name="testResult">The result in which to record success or failure</param>
public virtual TestResult RunTest()
{
DateTime start = DateTime.Now;
TestResult testResult = new TestResult(this);
TestExecutionContext.CurrentContext.CurrentResult = testResult;
try
{
RunSetUp();
RunTestCase( testResult );
}
catch(Exception ex)
{
// doTestCase handles its own exceptions so
// if we're here it's a setup exception
if (ex is ThreadAbortException)
Thread.ResetAbort();
RecordException(ex, testResult, FailureSite.SetUp);
}
finally
{
RunTearDown( testResult );
DateTime stop = DateTime.Now;
TimeSpan span = stop.Subtract(start);
testResult.Time = (double)span.Ticks / (double)TimeSpan.TicksPerSecond;
if (testResult.IsSuccess)
{
if (this.Properties.Contains("MaxTime"))
{
int elapsedTime = (int)Math.Round(testResult.Time * 1000.0);
int maxTime = (int)this.Properties["MaxTime"];
if (maxTime > 0 && elapsedTime > maxTime)
testResult.Failure(
string.Format("Elapsed time of {0}ms exceeds maximum of {1}ms",
elapsedTime, maxTime),
null);
}
if (testResult.IsSuccess && testResult.Message == null &&
Environment.CurrentDirectory != TestExecutionContext.CurrentContext.prior.CurrentDirectory)
{
// TODO: Introduce a warning result state in NUnit 3.0
testResult.SetResult(ResultState.Success, "Warning: Test changed the CurrentDirectory", null);
}
}
}
log.Debug("Test result = " + testResult.ResultState);
return testResult;
}
#endregion
#region Invoke Methods by Reflection, Recording Errors
private void RunSetUp()
{
if (setUpMethods != null)
foreach( MethodInfo setUpMethod in setUpMethods )
Reflect.InvokeMethod(setUpMethod, setUpMethod.IsStatic ? null : this.Fixture);
}
private void RunTearDown( TestResult testResult )
{
try
{
if (tearDownMethods != null)
{
int index = tearDownMethods.Length;
while (--index >= 0)
Reflect.InvokeMethod(tearDownMethods[index], tearDownMethods[index].IsStatic ? null : this.Fixture);
}
}
catch(Exception ex)
{
if ( ex is NUnitException )
ex = ex.InnerException;
// TODO: What about ignore exceptions in teardown?
testResult.Error( ex,FailureSite.TearDown );
}
}
private void RunTestCase( TestResult testResult )
{
try
{
RunTestMethod(testResult);
if (testResult.IsSuccess && exceptionProcessor != null)
exceptionProcessor.ProcessNoException(testResult);
}
catch (Exception ex)
{
if (ex is ThreadAbortException)
Thread.ResetAbort();
if (exceptionProcessor == null)
RecordException(ex, testResult, FailureSite.Test);
else
exceptionProcessor.ProcessException(ex, testResult);
}
}
private void RunTestMethod(TestResult testResult)
{
object fixture = this.method.IsStatic ? null : this.Fixture;
object result = Reflect.InvokeMethod( this.method, fixture, this.arguments );
if (this.hasExpectedResult)
NUnitFramework.Assert.AreEqual(expectedResult, result);
testResult.Success();
}
#endregion
#region Record Info About An Exception
protected virtual void RecordException( Exception exception, TestResult testResult, FailureSite failureSite )
{
if (exception is NUnitException)
exception = exception.InnerException;
testResult.SetResult(NUnitFramework.GetResultState(exception), exception, failureSite);
}
#endregion
#region Inner Classes
public class ContextDictionary : Hashtable
{
internal TestExecutionContext _ec;
public override object this[object key]
{
get
{
// Get Result values dynamically, since
// they may change as execution proceeds
switch (key as string)
{
case "Test.Name":
return _ec.CurrentTest.TestName.Name;
case "Test.FullName":
return _ec.CurrentTest.TestName.FullName;
case "Test.Properties":
return _ec.CurrentTest.Properties;
case "Result.State":
return (int)_ec.CurrentResult.ResultState;
case "TestDirectory":
return AssemblyHelper.GetDirectoryName(_ec.CurrentTest.FixtureType.Assembly);
default:
return base[key];
}
}
set
{
base[key] = value;
}
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: Attributes for debugger
**
**
===========================================================*/
namespace System.Diagnostics {
using System;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
[Serializable]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
[ComVisible(true)]
public sealed class DebuggerStepThroughAttribute : Attribute
{
public DebuggerStepThroughAttribute () {}
}
[Serializable]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
[ComVisible(true)]
public sealed class DebuggerStepperBoundaryAttribute : Attribute
{
public DebuggerStepperBoundaryAttribute () {}
}
[Serializable]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)]
[ComVisible(true)]
public sealed class DebuggerHiddenAttribute : Attribute
{
public DebuggerHiddenAttribute () {}
}
[Serializable]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor |AttributeTargets.Struct, Inherited = false)]
[ComVisible(true)]
public sealed class DebuggerNonUserCodeAttribute : Attribute
{
public DebuggerNonUserCodeAttribute () {}
}
// Attribute class used by the compiler to mark modules.
// If present, then debugging information for everything in the
// assembly was generated by the compiler, and will be preserved
// by the Runtime so that the debugger can provide full functionality
// in the case of JIT attach. If not present, then the compiler may
// or may not have included debugging information, and the Runtime
// won't preserve the debugging info, which will make debugging after
// a JIT attach difficult.
[AttributeUsage(AttributeTargets.Assembly|AttributeTargets.Module, AllowMultiple = false)]
[ComVisible(true)]
public sealed class DebuggableAttribute : Attribute
{
[Flags]
[ComVisible(true)]
public enum DebuggingModes
{
None = 0x0,
Default = 0x1,
DisableOptimizations = 0x100,
IgnoreSymbolStoreSequencePoints = 0x2,
EnableEditAndContinue = 0x4
}
private DebuggingModes m_debuggingModes;
public DebuggableAttribute(bool isJITTrackingEnabled,
bool isJITOptimizerDisabled)
{
m_debuggingModes = 0;
if (isJITTrackingEnabled)
{
m_debuggingModes |= DebuggingModes.Default;
}
if (isJITOptimizerDisabled)
{
m_debuggingModes |= DebuggingModes.DisableOptimizations;
}
}
public DebuggableAttribute(DebuggingModes modes)
{
m_debuggingModes = modes;
}
public bool IsJITTrackingEnabled
{
get { return ((m_debuggingModes & DebuggingModes.Default) != 0); }
}
public bool IsJITOptimizerDisabled
{
get { return ((m_debuggingModes & DebuggingModes.DisableOptimizations) != 0); }
}
public DebuggingModes DebuggingFlags
{
get { return m_debuggingModes; }
}
}
// DebuggerBrowsableState states are defined as follows:
// Never never show this element
// Expanded expansion of the class is done, so that all visible internal members are shown
// Collapsed expansion of the class is not performed. Internal visible members are hidden
// RootHidden The target element itself should not be shown, but should instead be
// automatically expanded to have its members displayed.
// Default value is collapsed
// Please also change the code which validates DebuggerBrowsableState variable (in this file)
// if you change this enum.
[ComVisible(true)]
public enum DebuggerBrowsableState
{
Never = 0,
//Expanded is not supported in this release
//Expanded = 1,
Collapsed = 2,
RootHidden = 3
}
// the one currently supported with the csee.dat
// (mcee.dat, autoexp.dat) file.
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
[ComVisible(true)]
public sealed class DebuggerBrowsableAttribute: Attribute
{
private DebuggerBrowsableState state;
public DebuggerBrowsableAttribute(DebuggerBrowsableState state)
{
if( state < DebuggerBrowsableState.Never || state > DebuggerBrowsableState.RootHidden)
throw new ArgumentOutOfRangeException(nameof(state));
Contract.EndContractBlock();
this.state = state;
}
public DebuggerBrowsableState State
{
get { return state; }
}
}
// DebuggerTypeProxyAttribute
[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)]
[ComVisible(true)]
public sealed class DebuggerTypeProxyAttribute: Attribute
{
private string typeName;
private string targetName;
private Type target;
public DebuggerTypeProxyAttribute(Type type)
{
if (type == null) {
throw new ArgumentNullException(nameof(type));
}
Contract.EndContractBlock();
this.typeName = type.AssemblyQualifiedName;
}
public DebuggerTypeProxyAttribute(string typeName)
{
this.typeName = typeName;
}
public string ProxyTypeName
{
get { return typeName; }
}
public Type Target
{
set {
if( value == null) {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
targetName = value.AssemblyQualifiedName;
target = value;
}
get { return target; }
}
public string TargetTypeName
{
get { return targetName; }
set { targetName = value; }
}
}
// This attribute is used to control what is displayed for the given class or field
// in the data windows in the debugger. The single argument to this attribute is
// the string that will be displayed in the value column for instances of the type.
// This string can include text between { and } which can be either a field,
// property or method (as will be documented in mscorlib). In the C# case,
// a general expression will be allowed which only has implicit access to the this pointer
// for the current instance of the target type. The expression will be limited,
// however: there is no access to aliases, locals, or pointers.
// In addition, attributes on properties referenced in the expression are not processed.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Delegate | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Assembly, AllowMultiple = true)]
[ComVisible(true)]
public sealed class DebuggerDisplayAttribute : Attribute
{
private string name;
private string value;
private string type;
private string targetName;
private Type target;
public DebuggerDisplayAttribute(string value)
{
if( value == null ) {
this.value = "";
}
else {
this.value = value;
}
name = "";
type = "";
}
public string Value
{
get { return this.value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Type
{
get { return type; }
set { type = value; }
}
public Type Target
{
set {
if( value == null) {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
targetName = value.AssemblyQualifiedName;
target = value;
}
get { return target; }
}
public string TargetTypeName
{
get { return targetName; }
set { targetName = value; }
}
}
/// <summary>
/// Signifies that the attributed type has a visualizer which is pointed
/// to by the parameter type name strings.
/// </summary>
[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)]
[ComVisible(true)]
public sealed class DebuggerVisualizerAttribute: Attribute
{
private string visualizerObjectSourceName;
private string visualizerName;
private string description;
private string targetName;
private Type target;
public DebuggerVisualizerAttribute(string visualizerTypeName)
{
this.visualizerName = visualizerTypeName;
}
public DebuggerVisualizerAttribute(string visualizerTypeName, string visualizerObjectSourceTypeName)
{
this.visualizerName = visualizerTypeName;
this.visualizerObjectSourceName = visualizerObjectSourceTypeName;
}
public DebuggerVisualizerAttribute(string visualizerTypeName, Type visualizerObjectSource)
{
if (visualizerObjectSource == null) {
throw new ArgumentNullException(nameof(visualizerObjectSource));
}
Contract.EndContractBlock();
this.visualizerName = visualizerTypeName;
this.visualizerObjectSourceName = visualizerObjectSource.AssemblyQualifiedName;
}
public DebuggerVisualizerAttribute(Type visualizer)
{
if (visualizer == null) {
throw new ArgumentNullException(nameof(visualizer));
}
Contract.EndContractBlock();
this.visualizerName = visualizer.AssemblyQualifiedName;
}
public DebuggerVisualizerAttribute(Type visualizer, Type visualizerObjectSource)
{
if (visualizer == null) {
throw new ArgumentNullException(nameof(visualizer));
}
if (visualizerObjectSource == null) {
throw new ArgumentNullException(nameof(visualizerObjectSource));
}
Contract.EndContractBlock();
this.visualizerName = visualizer.AssemblyQualifiedName;
this.visualizerObjectSourceName = visualizerObjectSource.AssemblyQualifiedName;
}
public DebuggerVisualizerAttribute(Type visualizer, string visualizerObjectSourceTypeName)
{
if (visualizer == null) {
throw new ArgumentNullException(nameof(visualizer));
}
Contract.EndContractBlock();
this.visualizerName = visualizer.AssemblyQualifiedName;
this.visualizerObjectSourceName = visualizerObjectSourceTypeName;
}
public string VisualizerObjectSourceTypeName
{
get { return visualizerObjectSourceName; }
}
public string VisualizerTypeName
{
get { return visualizerName; }
}
public string Description
{
get { return description; }
set { description = value; }
}
public Type Target
{
set {
if( value == null) {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
targetName = value.AssemblyQualifiedName;
target = value;
}
get { return target; }
}
public string TargetTypeName
{
set { targetName = value; }
get { return targetName; }
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using Microsoft.Protocols.TestTools.StackSdk;
using Microsoft.Protocols.TestTools.StackSdk.Transport;
using Microsoft.Protocols.TestTools.ExtendedLogging;
namespace Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpbcgr
{
/// <summary>
/// Decode stack packet from the received message bytes.
/// </summary>
/// <param name="endPoint">the endpoint from which the message bytes are received.</param>
/// <param name="messageBytes">the received message bytes to be decoded.</param>
/// <param name="consumedLength">the length of message bytes consumed by decoder.</param>
/// <param name="expectedLength">the length of message bytes the decoder expects to receive.</param>
/// <returns>the stack packets decoded from the received message bytes.</returns>
public delegate StackPacket[] DecodePacketCallback(
object endPoint,
byte[] messageBytes,
out int consumedLength,
out int expectedLength);
/// <summary>
/// When enhanced security is used, a new ssl stream should be used to send and receive data.
/// </summary>
public enum SecurityStreamType
{
None,
Ssl,
CredSsp
}
/// <summary>
/// the status of transport returned from receiving method.
/// </summary>
public enum ReceiveStatus : int
{
/// <summary>
/// All transport should use this value to notify the caller that the transport has received
/// valid data from the remote host.
/// </summary>
Success,
/// <summary>
/// All transport should use this value to notify the caller that the transport is disconnected
/// by the remost host.
/// </summary>
Disconnected,
}
/// <summary>
/// Stores the configurable parameters used by transport.
/// </summary>
public class RdpcbgrServerTransportConfig
{
#region Field members
private int maxConnections;
private SecurityStreamType streamType;
private int bufferSize;
private IPAddress localIpAddress;
private int localIpPort;
private IPAddress remoteIpAddress;
private int remoteIpPort;
#endregion
#region Properties
/// <summary>
/// The size of buffer used for receiving data.
/// </summary>
public int BufferSize
{
get
{
return this.bufferSize;
}
set
{
this.bufferSize = value;
}
}
/// <summary>
/// The max number of connections.
/// </summary>
public int MaxConnections
{
get
{
return maxConnections;
}
set
{
maxConnections = value;
}
}
/// <summary>
/// Ssl stream or normal network stream.
/// </summary>
public SecurityStreamType StreamType
{
get
{
return streamType;
}
set
{
streamType = value;
}
}
/// <summary>
/// The local IPAddress.
/// </summary>
public IPAddress LocalIpAddress
{
get
{
return this.localIpAddress;
}
set
{
this.localIpAddress = value;
}
}
/// <summary>
/// The local IP port.
/// </summary>
public int LocalIpPort
{
get
{
return this.localIpPort;
}
set
{
this.localIpPort = value;
}
}
/// <summary>
/// The remote IPAddress.
/// </summary>
public IPAddress RemoteIpAddress
{
get
{
return this.remoteIpAddress;
}
set
{
this.remoteIpAddress = value;
}
}
/// <summary>
/// The remote IP port.
/// </summary>
public int RemoteIpPort
{
get
{
return this.remoteIpPort;
}
set
{
this.remoteIpPort = value;
}
}
#endregion
#region Constructors
/// <summary>
/// Constructor. Initialize member variables.
/// </summary>
/// <param name="sType">The type of security stream.</param>
/// <param name="ip">The server ip.</param>
/// <param name="port">The service port.</param>
public RdpcbgrServerTransportConfig(
SecurityStreamType sType,
IPAddress ip,
int port)
{
int ti = ConstValue.MAXCONNECTIONS;
maxConnections = ti;
streamType = sType;
bufferSize = ConstValue.BUFFERSIZE;
this.localIpAddress = ip;
this.localIpPort = port;
}
#endregion
}
/// <summary>
/// Ugly Code.
/// ETW Stream wrapping NetworkStream for ETW Provider to dump message
/// </summary>
class ETWStream : Stream
{
Stream stream;
List<byte> sentBuffer;
int sentBufferIndex;
List<byte> receivedBuffer;
int receivedBufferIndex;
const int lengthHigh = 3;
const int lengthLow = 4;
const int headerLength = 5;
public ETWStream(Stream stream)
{
this.stream = stream;
sentBuffer = new List<byte>();
receivedBuffer = new List<byte>();
sentBufferIndex = 0;
receivedBufferIndex = 0;
}
public override bool CanRead
{
get { return stream.CanRead; }
}
public override bool CanSeek
{
get { return stream.CanSeek; }
}
public override bool CanWrite
{
get { return stream.CanWrite; }
}
public override void Flush()
{
stream.Flush();
}
public override long Length
{
get { return stream.Length; }
}
public override long Position
{
get
{
return stream.Position;
}
set
{
stream.Position = value;
}
}
public override int Read(byte[] buffer, int offset, int count)
{
int readcount = stream.Read(buffer, offset, count);
// ETW Provider Dump Message and Reassembly
string messageName = "RDPBCGR:TLSReceived";
byte[] readBytes = new byte[readcount];
Array.Copy(buffer, offset, readBytes, 0, readcount);
receivedBuffer.AddRange(readBytes);
if (receivedBufferIndex + lengthHigh < receivedBuffer.Count && receivedBufferIndex + lengthLow < receivedBuffer.Count)
{
int length = (receivedBuffer[receivedBufferIndex + lengthHigh] << 8) + receivedBuffer[receivedBufferIndex + lengthLow];
while (receivedBufferIndex + headerLength + length < receivedBuffer.Count)
{
receivedBufferIndex = receivedBufferIndex + headerLength + length;
length = (receivedBuffer[receivedBufferIndex + lengthHigh] << 8) + receivedBuffer[receivedBufferIndex + lengthLow];
}
if (receivedBufferIndex + headerLength + length == receivedBuffer.Count)
{
ExtendedLogger.DumpMessage(messageName, RdpbcgrUtility.DumpLevel_LayerTLS, "TLS Received Data", receivedBuffer.ToArray());
receivedBuffer.Clear();
receivedBufferIndex = 0;
}
}
return readcount;
}
public override long Seek(long offset, SeekOrigin origin)
{
return stream.Seek(offset, origin);
}
public override void SetLength(long value)
{
stream.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
stream.Write(buffer, offset, count);
// ETW Provider Dump Message and Reassembly
string messageName = "RDPBCGR:TLSSent";
byte[] sentBytes = new byte[count];
Array.Copy(buffer, offset, sentBytes, 0, count);
sentBuffer.AddRange(sentBytes);
if (sentBufferIndex + lengthHigh < sentBuffer.Count && sentBufferIndex + lengthLow < sentBuffer.Count)
{
int length = (sentBuffer[sentBufferIndex + lengthHigh] << 8) + sentBuffer[sentBufferIndex + lengthLow];
while (sentBufferIndex + headerLength + length < sentBuffer.Count)
{
sentBufferIndex = sentBufferIndex + headerLength + length;
length = (sentBuffer[sentBufferIndex + lengthHigh] << 8) + sentBuffer[sentBufferIndex + lengthLow];
}
if (sentBufferIndex + headerLength + length == sentBuffer.Count)
{
ExtendedLogger.DumpMessage(messageName, RdpbcgrUtility.DumpLevel_LayerTLS, "TLS Sent Data", sentBuffer.ToArray());
sentBuffer.Clear();
sentBufferIndex = 0;
}
}
}
}
/// <summary>
/// Contains fields and methods to provide tcp connection and relative functions.
/// </summary>
internal class RdpbcgrServerTransportStack : IDisposable
{
#region Field members
private SecurityStreamType streamType;
private bool disposed;
private RdpcbgrServerTransportConfig config;
private DecodePacketCallback decoder;
private QueueManager packetQueue;
private Dictionary<Socket, RdpbcgrReceiveThread> receivingStreams;
private Socket listenSock;
private Thread acceptThread;
private bool isTcpServerTransportStarted;
private volatile bool exitLoop;
private RdpbcgrServer rdpbcgrServer;
//private string certName;
private X509Certificate2 cert;
#endregion
#region Properties
/// <summary>
/// The packetQueue.
/// </summary>
public QueueManager PacketQueue
{
get
{
return packetQueue;
}
}
/// <summary>
/// The receivingStreams.
/// </summary>
public ReadOnlyDictionary<Socket, RdpbcgrReceiveThread> ReceivingStreams
{
get
{
return new ReadOnlyDictionary<Socket, RdpbcgrReceiveThread>(receivingStreams);
}
}
#endregion
#region Constructor and Dispose
/// <summary>
/// Constructor. Initialize member variables.
/// </summary>
/// <param name="transportConfig">Provides the transport parameters.</param>
/// <param name="decodePacketCallback">Callback of decoding packet.</param>
public RdpbcgrServerTransportStack(
RdpbcgrServer rdpbcgrServer,
RdpcbgrServerTransportConfig transportConfig,
DecodePacketCallback decodePacketCallback)
{
this.rdpbcgrServer = rdpbcgrServer;
this.config = transportConfig;
if (this.config == null)
{
throw new System.InvalidCastException("TcpServerTransport needs SocketTransportConfig.");
}
this.decoder = decodePacketCallback;
this.packetQueue = new QueueManager();
this.listenSock = new Socket(transportConfig.LocalIpAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
this.streamType = config.StreamType;
IPEndPoint endPoint = new IPEndPoint(config.LocalIpAddress, config.LocalIpPort);
this.listenSock.Bind(endPoint);
this.listenSock.Listen(config.MaxConnections);
this.acceptThread = new Thread(new ThreadStart(AcceptLoop));
this.receivingStreams = new Dictionary<Socket, RdpbcgrReceiveThread>();
}
/// <summary>
/// Constructor. Initialize member variables.
/// </summary>
/// <param name="transportConfig">Provides the transport parameters.</param>
/// <param name="decodePacketCallback">Callback of decoding packet.</param>
/// <param name="certificate">X509 certificate.</param>
public RdpbcgrServerTransportStack(
RdpbcgrServer rdpbcgrServer,
RdpcbgrServerTransportConfig transportConfig,
DecodePacketCallback decodePacketCallback,
X509Certificate2 certificate)
{
this.rdpbcgrServer = rdpbcgrServer;
this.config = transportConfig;
if (this.config == null)
{
throw new System.InvalidCastException("TcpServerTransport needs SocketTransportConfig.");
}
this.decoder = decodePacketCallback;
this.packetQueue = new QueueManager();
this.listenSock = new Socket(transportConfig.LocalIpAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
this.streamType = transportConfig.StreamType;
IPEndPoint endPoint = new IPEndPoint(config.LocalIpAddress, config.LocalIpPort);
this.listenSock.Bind(endPoint);
this.listenSock.Listen(config.MaxConnections);
this.acceptThread = new Thread(new ThreadStart(AcceptLoop));
this.receivingStreams = new Dictionary<Socket, RdpbcgrReceiveThread>();
this.cert = certificate;
}
/// <summary>
/// Close specific end point stream.
/// </summary>
public void CloseStream(object endPoint)
{
lock (this.receivingStreams)
{
if (this.receivingStreams != null)
{
foreach (KeyValuePair<Socket, RdpbcgrReceiveThread> kvp in this.receivingStreams)
{
if (kvp.Key.RemoteEndPoint == endPoint)
{
this.receivingStreams.Remove(kvp.Key);
kvp.Key.Close();
kvp.Value.Dispose();
break;
}
}
}
}
}
/// <summary>
/// Release the managed and unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
//Take this object out of the finalization queue of the GC:
GC.SuppressFinalize(this);
}
/// <summary>
/// Release resources.
/// </summary>
/// <param name="disposing">If disposing equals true, Managed and unmanaged resources are disposed.
/// if false, Only unmanaged resources can be disposed.</param>
private void Dispose(bool disposing)
{
if (!this.disposed)
{
exitLoop = true;
// If disposing equals true, dispose all managed and unmanaged resources.
if (disposing)
{
if (this.listenSock != null)
{
this.listenSock.Close();
this.listenSock = null;
}
lock (this.receivingStreams)
{
if (this.receivingStreams != null)
{
foreach (KeyValuePair<Socket, RdpbcgrReceiveThread> kvp in this.receivingStreams)
{
kvp.Key.Close();
kvp.Value.Dispose();
}
this.receivingStreams = null;
}
}
if (this.packetQueue != null)
{
this.packetQueue.Dispose();
this.packetQueue = null;
}
if (this.acceptThread != null && this.acceptThread.ThreadState != ThreadState.Unstarted)
{
this.acceptThread.Join();
}
}
this.disposed = true;
}
}
/// <summary>
/// This destructor will get called only from the finalization queue.
/// </summary>
~RdpbcgrServerTransportStack()
{
this.Dispose(false);
}
#endregion
#region User interface
/// <summary>
/// Start the server.
/// </summary>
public void Start()
{
this.acceptThread.Start();
this.isTcpServerTransportStarted = true;
}
/// <summary>
/// Disconnect from all remote hosts.
/// </summary>
public void Disconnect()
{
lock (this.receivingStreams)
{
foreach (KeyValuePair<Socket, RdpbcgrReceiveThread> kvp in this.receivingStreams)
{
kvp.Value.Abort();
kvp.Key.Close();
}
this.receivingStreams.Clear();
}
}
/// <summary>
/// Disconnect from the remote host according to the given endPoint.
/// </summary>
/// <param name="endPoint">Endpoint to be disconnected.</param>
public void Disconnect(object endPoint)
{
IPEndPoint ipEndPoint = endPoint as IPEndPoint;
if (ipEndPoint == null)
{
throw new ArgumentException("The endPoint is not an IPEndPoint.", "endPoint");
}
lock (this.receivingStreams)
{
Socket socket = null;
foreach (Socket sock in this.receivingStreams.Keys)
{
IPEndPoint endPointTmp = (IPEndPoint)sock.RemoteEndPoint;
if (ipEndPoint.Address.ToString().CompareTo(endPointTmp.Address.ToString()) == 0 && (ipEndPoint.Port == endPointTmp.Port))
{
socket = sock;
}
}
this.receivingStreams[socket].Abort();
socket.Close();
this.receivingStreams.Remove(socket);
}
}
/// <summary>
/// Send a packet to a special remote host.
/// </summary>
/// <param name="endPoint">The remote host to which the packet will be sent.</param>
/// <param name="packet">The packet to be sent.</param>
public void SendPacket(object endPoint, StackPacket packet)
{
ValidServerHasStarted();
IPEndPoint ipEndPoint = endPoint as IPEndPoint;
if (ipEndPoint == null)
{
throw new ArgumentException("The endPoint is not an IPEndPoint.", "endPoint");
}
// If we use raw bytes to construct the packet, we send the raw bytes out directly,
// otherwise we convert the packet to bytes and send it out.
byte[] writeBytes = (packet.PacketBytes == null) ? packet.ToBytes() : packet.PacketBytes;
Stream stream = GetStream(ipEndPoint.Address, ipEndPoint.Port);
if (stream == null)
{
throw new InvalidOperationException("The endPoint is not in the connect list.");
}
stream.Write(writeBytes, 0, writeBytes.Length);
}
/// <summary>
/// Send arbitrary message to a special remote host.
/// </summary>
/// <param name="endpoint">The remote host to which the packet will be sent.</param>
/// <param name="message">The message to be sent.</param>
public void SendBytes(object endpoint, byte[] message)
{
IPEndPoint ipEndPoint = endpoint as IPEndPoint;
Stream stream = GetStream(ipEndPoint.Address, ipEndPoint.Port);
stream.Write(message, 0, message.Length);
}
/// <summary>
/// Add transport event to transport, TSD can invoke ExpectTransportEvent to get it.
/// </summary>
/// <param name="transportEvent">
/// a TransportEvent object that contains the event to add to the queue
/// </param>
public void AddEvent(TransportEvent transportEvent)
{
this.packetQueue.AddObject(transportEvent);
}
/// <summary>
/// Expect transport event from transport.
/// if event arrived and packet data buffer is empty, return event directly.
/// decode packet from packet data buffer, return packet if arrived, otherwise, return event.
/// </summary>
/// <param name="timeout">
/// TimeSpan struct that specifies the timeout of waiting for a packet or event from the transport.
/// </param>
/// <returns>
/// TransportEvent object that contains the expected event from transport.
/// </returns>
/// <exception cref="ObjectDisposedException">
/// Thrown when this object is disposed.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Thrown when the under layer transport is null! the config for TransportStack is invalid.
/// </exception>
public TransportEvent ExpectTransportEvent(TimeSpan timeout)
{
TransportEvent eventPacket = this.packetQueue.GetObject(ref timeout) as TransportEvent;
if (eventPacket == null)
{
throw new InvalidOperationException("Invalid object are cached in the queue.");
}
if (eventPacket.EventType == EventType.ReceivedPacket)
{
StackPacket packet = eventPacket.EventObject as StackPacket;
}
else if (eventPacket.EventType == EventType.Exception)
{
throw new InvalidOperationException(
"There's an exception thrown when receiving a packet.",
(Exception)eventPacket.EventObject);
}
return eventPacket;
}
/// <summary>
/// Update the config of transport at runtime.
/// </summary>
/// <param name="type">The type of transport stream.</param>
internal void UpdateConfig(SecurityStreamType type)
{
foreach (Socket sock in this.receivingStreams.Keys)
{
if (receivingStreams[sock].ReceiveStream is SslStream || receivingStreams[sock].ReceiveStream is RdpbcgrServerCredSspStream)
{
//Skip the connections which already were updated to SSL or CredSSP.
continue;
}
else
{
NetworkStream netStream = (NetworkStream)receivingStreams[sock].ReceiveStream;
if (type == SecurityStreamType.Ssl)
{
SslStream sslStream = new SslStream(new ETWStream(netStream));
((SslStream)sslStream).AuthenticateAsServer(this.cert);
receivingStreams[sock].ReceiveStream = sslStream;
}
else if (type == SecurityStreamType.CredSsp)
{
string targetSPN = ConstValue.CREDSSP_SERVER_NAME_PREFIX + config.LocalIpAddress;
RdpbcgrServerCredSspStream credSspStream = new RdpbcgrServerCredSspStream(new ETWStream(netStream), targetSPN);
receivingStreams[sock].ReceiveStream = credSspStream;
credSspStream.Authenticate(cert);
}
}
}
}
/// <summary>
/// Close the transport and release resources.
/// </summary>
public void Release()
{
this.Dispose();
}
#endregion
#region Private methods
/// <summary>
/// Creates a new Socket for a newly created connection and a new thread to receive packet in the loop.
/// </summary>
private void AcceptLoop()
{
while (!exitLoop)
{
if (this.receivingStreams.Count >= config.MaxConnections)
{
// not listen untill the current connections are less than the max value.
// the interval to query is 1 seconds:
Thread.Sleep(1000);
continue;
}
Socket socket = null;
try
{
socket = this.listenSock.Accept();
}
catch (SocketException)
{
exitLoop = true;
continue;
}
TransportEvent connectEvent;
Stream receiveStream = null;
Stream baseStream = new NetworkStream(socket);
switch (streamType)
{
case SecurityStreamType.None:
receiveStream = baseStream;
break;
case SecurityStreamType.Ssl:
receiveStream = new SslStream(
new ETWStream(
baseStream),
false
);
((SslStream)receiveStream).AuthenticateAsServer(cert);
break;
case SecurityStreamType.CredSsp:
string targetSPN = ConstValue.CREDSSP_SERVER_NAME_PREFIX + config.LocalIpAddress;
RdpbcgrServerCredSspStream credSspStream = new RdpbcgrServerCredSspStream(new ETWStream(baseStream), targetSPN);
credSspStream.Authenticate(cert);
receiveStream = credSspStream;
break;
default:
receiveStream = baseStream;
break;
}
RdpbcgrReceiveThread receiveThread = new RdpbcgrReceiveThread(
socket.RemoteEndPoint,
this.packetQueue,
this.decoder,
receiveStream,
this.config.BufferSize,
this.rdpbcgrServer);
connectEvent = new TransportEvent(EventType.Connected, socket.RemoteEndPoint, null);
RdpbcgrServerSessionContext session = new RdpbcgrServerSessionContext();
session.Identity = connectEvent.EndPoint;
session.Server = this.rdpbcgrServer;
session.LocalIdentity = socket.LocalEndPoint;
session.IsClientToServerEncrypted = this.rdpbcgrServer.IsClientToServerEncrypted;
this.rdpbcgrServer.ServerContext.AddSession(session);
this.packetQueue.AddObject(connectEvent);
lock (this.receivingStreams)
{
this.receivingStreams.Add(socket, receiveThread);
}
receiveThread.Start();
}
}
/// <summary>
/// Add the given stack packets to the QueueManager object.
/// </summary>
/// <param name="endPoint">The endpoint of the packets</param>
/// <param name="packets">Decoded packets</param>
private void AddPacketToQueueManager(object endPoint, StackPacket[] packets)
{
if (packets == null)
{
return;
}
foreach (StackPacket packet in packets)
{
TransportEvent packetEvent = new TransportEvent(EventType.ReceivedPacket, endPoint, packet);
this.packetQueue.AddObject(packetEvent);
}
}
/// <summary>
/// Confirm the server is started
/// </summary>
/// <exception cref="ObjectDisposedException">
/// Thrown when transport is not started.
/// </exception>
private void ValidServerHasStarted()
{
if (!this.isTcpServerTransportStarted)
{
throw new InvalidOperationException(
"the server is not started! please call Start() to start the server first.");
}
}
/// <summary>
/// Get an existed stream object in the socket list through the ip address and port.
/// </summary>
/// <param name="address">The IP address of the remote host.</param>
/// <param name="port">The port of the remote host.</param>
/// <returns>
/// Return the existed stream if it exists in the remoteSockets list.
/// Otherwise return null.
/// </returns>
private Stream GetStream(IPAddress address, int port)
{
foreach (Socket sock in this.receivingStreams.Keys)
{
IPEndPoint endPoint = (IPEndPoint)sock.RemoteEndPoint;
if ((address == endPoint.Address) && (port == endPoint.Port))
{
return receivingStreams[sock].ReceiveStream;
}
}
return null;
}
/// <summary>
/// Get an existed thread object in the socket list through the ip address and port.
/// </summary>
/// <param name="address">The IP address of the remote host.</param>
/// <param name="port">The port of the remote host.</param>
/// <returns>
/// Return the existed stream if it exists in the remoteSockets list.
/// Otherwise return null.
/// </returns>
public RdpbcgrReceiveThread GetThread(object endPoint)
{
foreach (Socket sock in this.receivingStreams.Keys)
{
if (endPoint == sock.RemoteEndPoint)
{
return receivingStreams[sock];
}
}
return null;
}
#endregion
}
/// <summary>
/// RdpbcgrReceiveThread is a new thread class used to receive data.
/// </summary>
internal sealed class RdpbcgrReceiveThread : IDisposable
{
#region Field members
private bool disposed;
private QueueManager packetQueue;
private DecodePacketCallback decoder;
private object endPointIdentity;
private Thread receivingThread;
private Stream receiveStream;
private int maxBufferSize;
private volatile bool exitLoop;
// Give RdpbcgrReceiveThread object a reference of RdpbcgrServer, so that it can access necessary variable
private RdpbcgrServer rdpbcgrServer;
#endregion
#region Properties
/// <summary>
/// The receiving thread.
/// </summary>
public Thread ReceivingThread
{
get
{
return receivingThread;
}
}
/// <summary>
/// The receive stream responded for data receiving.
/// </summary>
public Stream ReceiveStream
{
get
{
return receiveStream;
}
set
{
receiveStream = value;
}
}
#endregion
#region Constructor and Dispose
/// <summary>
/// Create a new thread to receive the data from remote host.
/// </summary>
/// <param name="packetQueueManager">Store all event packets generated in receiving loop.</param>
/// <param name="decodePacketCallback">Callback of packet decode.</param>
/// <param name="stream">The stream used to receive data.</param>
/// <param name="bufferSize">Buffer size used in receiving data.</param>
public RdpbcgrReceiveThread(
object endPoint,
QueueManager packetQueueManager,
DecodePacketCallback decodePacketCallback,
Stream stream,
int bufferSize,
RdpbcgrServer rdpbcgrServer)
{
if (packetQueueManager == null)
{
throw new ArgumentNullException("packetQueueManager");
}
if (decodePacketCallback == null)
{
throw new ArgumentNullException("decodePacketCallback");
}
// Initialize variable.
this.endPointIdentity = endPoint;
this.packetQueue = packetQueueManager;
this.decoder = decodePacketCallback;
this.receiveStream = stream;
this.maxBufferSize = bufferSize;
this.rdpbcgrServer = rdpbcgrServer;
this.receivingThread = new Thread((new ThreadStart(ReceiveLoop)));
}
/// <summary>
/// Release the managed and unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
//Take this object out of the finalization queue of the GC:
GC.SuppressFinalize(this);
}
/// <summary>
/// Release resources.
/// </summary>
/// <param name="disposing">If disposing equals true, Managed and unmanaged resources are disposed.
/// if false, Only unmanaged resources can be disposed.</param>
private void Dispose(bool disposing)
{
if (!this.disposed)
{
// If disposing equals true, dispose all managed and unmanaged resources.
if (disposing)
{
// Free managed resources & other reference types:
if (this.receivingThread != null)
{
this.Abort();
this.receivingThread = null;
}
}
this.disposed = true;
}
}
/// <summary>
/// This destructor will get called only from the finalization queue.
/// </summary>
~RdpbcgrReceiveThread()
{
this.Dispose(false);
}
#endregion
#region User interface
/// <summary>
/// Start the receiving thread.
/// </summary>
public void Start()
{
this.receivingThread.Start();
}
/// <summary>
/// Abort the receiving thread.
/// </summary>
public void Abort()
{
this.exitLoop = true;
this.receiveStream.Close();
if (this.receivingThread.ThreadState != ThreadState.Unstarted)
{
this.receivingThread.Abort();
this.receivingThread.Join();
}
}
/// <summary>
/// Receive data, decode Packet and add them to QueueManager in the loop.
/// </summary>
private void ReceiveLoop()
{
StackPacket[] packets = null;
ReceiveStatus receiveStatus = ReceiveStatus.Success;
//object endPoint = null;
int bytesRecv = 0;
int leftCount = 0;
int expectedLength = this.maxBufferSize;
byte[] receivedCaches = new byte[0];
while (!exitLoop)
{
if (expectedLength <= 0)
{
expectedLength = this.maxBufferSize;
}
byte[] receivingBuffer = new byte[expectedLength];
try
{
bytesRecv = this.receiveStream.Read(receivingBuffer, 0, receivingBuffer.Length);
if (bytesRecv == 0)
{
receiveStatus = ReceiveStatus.Disconnected;
}
else
{
receiveStatus = ReceiveStatus.Success;
}
}
catch (System.IO.IOException)
{
// If this is an IOException, treat it as a disconnection.
if (!exitLoop)
{
if (this.packetQueue != null)
{
TransportEvent exceptionEvent = new TransportEvent(EventType.Disconnected, this.endPointIdentity, null);
this.packetQueue.AddObject(exceptionEvent);
break;
}
else
{
throw;
}
}
}
catch (Exception e)
{
if (!exitLoop)
{
if (this.packetQueue != null)
{
TransportEvent exceptionEvent = new TransportEvent(EventType.Exception, this.endPointIdentity, e);
this.packetQueue.AddObject(exceptionEvent);
break;
}
else
{
throw;
}
}
}
if (receiveStatus == ReceiveStatus.Success)
{
byte[] data = new byte[bytesRecv + receivedCaches.Length];
Array.Copy(receivedCaches, data, receivedCaches.Length);
Array.Copy(receivingBuffer, 0, data, receivedCaches.Length, bytesRecv);
while (true)
{
int consumedLength;
try
{
packets = this.decoder(this.endPointIdentity, data, out consumedLength, out expectedLength);
}
catch (Exception e)
{
TransportEvent exceptionEvent = new TransportEvent(EventType.Exception, this.endPointIdentity, e);
this.packetQueue.AddObject(exceptionEvent);
// If decoder throw exception, we think decoder will throw exception again when it decode
// subsequent received data So here we terminate the receive thread.
return;
}
if (consumedLength > 0)
{
//add packet to queue
if (packets != null && packets.Length > 0)
{
AddPacketToQueueManager(this.endPointIdentity, packets);
bytesRecv = 0;
foreach (StackPacket pdu in packets)
{
if (pdu.GetType() == typeof(Client_X_224_Connection_Request_Pdu))
{
// Block the thread if received a Client X224 Connection Request PDU
// the main thread will resume the thread after it send X224 Connection confirm PDU and other necessary process, such as TLS Handshake
rdpbcgrServer.ReceiveThreadControlEvent.WaitOne();
}
}
}
//check if continue the decoding
leftCount = data.Length - consumedLength;
if (leftCount <= 0)
{
receivedCaches = new byte[0];
data = new byte[0];
break;
}
else
{
// Update caches contents to the bytes which is not consumed
receivedCaches = new byte[leftCount];
Array.Copy(data, consumedLength, receivedCaches, 0, leftCount);
data = new byte[receivedCaches.Length];
Array.Copy(receivedCaches, data, data.Length);
}
}
else
{
//if no data consumed, it means the left data cannot be decoded separately, so cache it and jump out.
receivedCaches = new byte[data.Length];
Array.Copy(data, receivedCaches, receivedCaches.Length);
break;
}
}
}
else if (receiveStatus == ReceiveStatus.Disconnected)
{
if (this.packetQueue != null)
{
TransportEvent disconnectEvent = new TransportEvent(EventType.Disconnected, this.endPointIdentity, null);
this.packetQueue.AddObject(disconnectEvent);
break;
}
else
{
throw new InvalidOperationException("The transport is disconnected by remote host.");
}
}
else
{
throw new InvalidOperationException("Unknown status returned from receiving method.");
}
}
}
/// <summary>
/// Add the given stack packets to the QueueManager object if packet type not in filters or Customize filter.
/// </summary>
/// <param name="endPoint">the endpoint of the packets</param>
/// <param name="packets">decoded packets</param>
private void AddPacketToQueueManager(object endPoint, StackPacket[] packets)
{
if (packets == null)
{
return;
}
foreach (StackPacket packet in packets)
{
TransportEvent packetEvent = new TransportEvent(EventType.ReceivedPacket, endPoint, packet);
this.packetQueue.AddObject(packetEvent);
}
}
#endregion
}
}
| |
using System;
using Microsoft.Xna.Framework;
using Cocos2D;
namespace AngryNinjas
{
public class TheMenu : CCLayer
{
CCMenu VoiceFXMenu;
CCMenu SoundFXMenu;
CCMenu AmbientFXMenu;
CCPoint VoiceFXMenuLocation;
CCPoint SoundFXMenuLocation;
CCPoint AmbientFXMenuLocation;
string menuBackgroundName;
string lvlButtonName1;
string lvlLockedButtonName1;
string lvlButtonName2;
string lvlLockedButtonName2;
string lvlButtonName3;
string lvlLockedButtonName3;
string lvlButtonName4;
string lvlLockedButtonName4;
string lvlButtonName5;
string lvlLockedButtonName5;
string lvlButtonName6;
string lvlLockedButtonName6;
string lvlButtonName7;
string lvlLockedButtonName7;
string lvlButtonName8;
string lvlLockedButtonName8;
string lvlButtonName9;
string lvlLockedButtonName9;
string lvlButtonName10;
string lvlLockedButtonName10;
string voiceButtonName;
string voiceButtonNameDim;
string soundButtonName;
string soundButtonNameDim;
string ambientButtonName;
string ambientButtonNameDim;
public TheMenu ()
{
var screenSize = CCDirector.SharedDirector.WinSize;
CCPoint menu1Position;
CCPoint menu2Position;
menuBackgroundName = "menu_background.png";
//will use "menu_background.png" for non-Retina Phones
//will use "menu_background-hd.png"; for retina phones
//will use "menu_background-ipad.png";
//same goes for images below..
lvlButtonName1 = "levelButton1.png";
lvlLockedButtonName1 = "levelButton1_locked.png";
lvlButtonName2 = "levelButton2.png";
lvlLockedButtonName2 = "levelButton2_locked.png";
lvlButtonName3 = "levelButton3.png";
lvlLockedButtonName3 = "levelButton3_locked.png";
lvlButtonName4 = "levelButton4.png";
lvlLockedButtonName4 = "levelButton4_locked.png";
lvlButtonName5 = "levelButton5.png";
lvlLockedButtonName5 = "levelButton5_locked.png";
lvlButtonName6 = "levelButton6.png";
lvlLockedButtonName6 = "levelButton6_locked.png";
lvlButtonName7 = "levelButton7.png";
lvlLockedButtonName7 = "levelButton7_locked.png";
lvlButtonName8 = "levelButton8.png";
lvlLockedButtonName8 = "levelButton8_locked.png";
lvlButtonName9 = "levelButton9.png";
lvlLockedButtonName9 = "levelButton9_locked.png";
lvlButtonName10 = "levelButton10.png";
lvlLockedButtonName10 = "levelButton10_locked.png";
voiceButtonName = "voiceFX.png";
voiceButtonNameDim = "voiceFX_dim.png";
soundButtonName = "soundFX.png";
soundButtonNameDim = "soundFX_dim.png";
ambientButtonName = "ambientFX.png";
ambientButtonNameDim = "ambientFX_dim.png";
if (TheLevel.SharedLevel.IS_IPAD) { //iPADs..
menu1Position = new CCPoint(screenSize.Width / 2, 430 );
menu2Position = new CCPoint(screenSize.Width / 2, 290 );
SoundFXMenuLocation = new CCPoint( 240, 170 );
VoiceFXMenuLocation = new CCPoint( 480, 170 );
AmbientFXMenuLocation = new CCPoint(750, 170 );
//if( ! CCDirector.SharedDirector.enableRetinaDisplay ) {
CCLog.Log("must be iPad 1 or 2");
//change nothing
//} else {
CCLog.Log("retina display is on-must be iPAd 3");
//change files names for iPad 3
menuBackgroundName = "menu_background-ipad.png"; //will use @"menu_background-ipad-hd.png";
lvlButtonName1 = "levelButton1-ipad.png";
lvlLockedButtonName1 = "levelButton1_locked-ipad.png";
lvlButtonName2 = "levelButton2-ipad.png";
lvlLockedButtonName2 = "levelButton2_locked-ipad.png";
lvlButtonName3 = "levelButton3-ipad.png";
lvlLockedButtonName3 = "levelButton3_locked-ipad.png";
lvlButtonName4 = "levelButton4-ipad.png";
lvlLockedButtonName4 = "levelButton4_locked-ipad.png";
lvlButtonName5 = "levelButton5-ipad.png";
lvlLockedButtonName5 = "levelButton5_locked-ipad.png";
lvlButtonName6 = "levelButton6-ipad.png";
lvlLockedButtonName6 = "levelButton6_locked-ipad.png";
lvlButtonName7 = "levelButton7-ipad.png";
lvlLockedButtonName7 = "levelButton7_locked-ipad.png";
lvlButtonName8 = "levelButton8-ipad.png";
lvlLockedButtonName8 = "levelButton8_locked-ipad.png";
lvlButtonName9 = "levelButton9-ipad.png";
lvlLockedButtonName9 = "levelButton9_locked-ipad.png";
lvlButtonName10 = "levelButton10-ipad.png";
lvlLockedButtonName10 = "levelButton10_locked-ipad.png";
voiceButtonName = "voiceFX-ipad.png";
voiceButtonNameDim = "voiceFX_dim-ipad.png";
soundButtonName = "soundFX-ipad.png";
soundButtonNameDim = "soundFX_dim-ipad.png";
ambientButtonName = "ambientFX-ipad.png";
ambientButtonNameDim = "ambientFX_dim-ipad.png";
//}
} else { //IPHONES..
menu1Position = new CCPoint(screenSize.Width / 2, 185 );
menu2Position = new CCPoint(screenSize.Width / 2, 115 );
SoundFXMenuLocation = new CCPoint( 110, 55 );
VoiceFXMenuLocation = new CCPoint( 230, 55 );
AmbientFXMenuLocation = new CCPoint(355, 55 );
}
var theBackground = new CCSprite(menuBackgroundName);
theBackground.Position = new CCPoint(screenSize.Width / 2 , screenSize.Height / 2);
AddChild(theBackground,0);
TouchEnabled = true;
CCMenuItem button1;
CCMenuItem button2;
CCMenuItem button3;
CCMenuItem button4;
CCMenuItem button5;
CCMenuItem button6;
CCMenuItem button7;
CCMenuItem button8;
CCMenuItem button9;
CCMenuItem button10;
button1 = new CCMenuItemImage(lvlButtonName1, lvlButtonName1, GoToFirstLevelSection1);
if ( GameData.SharedData.CanYouGoToTheFirstLevelOfThisSection(2) == false ) {
button2 = new CCMenuItemImage(lvlLockedButtonName2, lvlLockedButtonName2, PlayNegativeSound);
} else {
button2 = new CCMenuItemImage(lvlButtonName2, lvlButtonName2, GoToFirstLevelSection2);
}
if ( GameData.SharedData.CanYouGoToTheFirstLevelOfThisSection(3) == false ) {
button3 = new CCMenuItemImage(lvlLockedButtonName3, lvlLockedButtonName3, PlayNegativeSound);
} else {
button3 = new CCMenuItemImage(lvlButtonName3, lvlButtonName3, GoToFirstLevelSection3);
}
if ( GameData.SharedData.CanYouGoToTheFirstLevelOfThisSection(4) == false ) {
button4 = new CCMenuItemImage(lvlLockedButtonName4, lvlLockedButtonName4, PlayNegativeSound);
} else {
button4 = new CCMenuItemImage(lvlButtonName4, lvlButtonName4, GoToFirstLevelSection4);
}
if ( GameData.SharedData.CanYouGoToTheFirstLevelOfThisSection(5) == false ) {
button5 = new CCMenuItemImage(lvlLockedButtonName5, lvlLockedButtonName5, PlayNegativeSound);
} else {
button5 = new CCMenuItemImage(lvlButtonName5, lvlButtonName5, GoToFirstLevelSection5);
}
if ( GameData.SharedData.CanYouGoToTheFirstLevelOfThisSection(6) == false ) {
button6 = new CCMenuItemImage(lvlLockedButtonName6, lvlLockedButtonName6, PlayNegativeSound);
} else {
button6 = new CCMenuItemImage(lvlButtonName6, lvlButtonName6, GoToFirstLevelSection6);
}
if ( GameData.SharedData.CanYouGoToTheFirstLevelOfThisSection(7) == false ) {
button7 = new CCMenuItemImage(lvlLockedButtonName7, lvlLockedButtonName7, PlayNegativeSound);
} else {
button7 = new CCMenuItemImage(lvlButtonName7, lvlButtonName7, GoToFirstLevelSection7);
}
if ( GameData.SharedData.CanYouGoToTheFirstLevelOfThisSection(8) == false ) {
button8 = new CCMenuItemImage(lvlLockedButtonName8, lvlLockedButtonName8, PlayNegativeSound);
} else {
button8 = new CCMenuItemImage(lvlButtonName8, lvlButtonName8, GoToFirstLevelSection8);
}
if ( GameData.SharedData.CanYouGoToTheFirstLevelOfThisSection(9) == false ) {
button9 = new CCMenuItemImage(lvlLockedButtonName9, lvlLockedButtonName9, PlayNegativeSound);
} else {
button9 = new CCMenuItemImage(lvlButtonName9, lvlButtonName9, GoToFirstLevelSection9);
}
if ( GameData.SharedData.CanYouGoToTheFirstLevelOfThisSection(10) == false ) {
button10 = new CCMenuItemImage(lvlLockedButtonName10, lvlLockedButtonName10, PlayNegativeSound);
} else {
button10 = new CCMenuItemImage(lvlButtonName10, lvlButtonName10, GoToFirstLevelSection10);
}
CCMenu Menu = new CCMenu(button1, button2, button3, button4, button5);
Menu.Position = menu1Position;
Menu.AlignItemsHorizontallyWithPadding(10);
AddChild(Menu, 1);
CCMenu Menu2 = new CCMenu(button6, button7, button8, button9, button10);
Menu2.Position = menu2Position;
Menu2.AlignItemsHorizontallyWithPadding(10);
AddChild(Menu2,1);
IsSoundFXMenuItemActive = !GameData.SharedData.AreSoundFXMuted;
IsVoiceFXMenuActive = !GameData.SharedData.AreVoiceFXMuted;
IsAmbientFXMenuActive = !GameData.SharedData.AreAmbientFXMuted;
}
void PlayNegativeSound (object sender)
{
//play a sound indicating this level isn't available
GameSounds.SharedGameSounds.PlaySoundFX("bloop.mp3");
}
public static CCScene Scene
{
get {
// 'scene' is an autorelease object.
CCScene scene = new CCScene();
// 'layer' is an autorelease object.
TheMenu layer = new TheMenu();
// add layer as a child to scene
scene.AddChild(layer);
// return the scene
return scene;
}
}
#region SECTION BUTTONS
void GoToFirstLevelSection1(object sender)
{
GameData.SharedData.ChangeLevelToFirstInThisSection(1);
PopAndTransition();
}
void GoToFirstLevelSection2(object sender)
{
if ( GameData.SharedData.CanYouGoToTheFirstLevelOfThisSection(2) )
{
GameData.SharedData.ChangeLevelToFirstInThisSection(2);
PopAndTransition();
}
}
void GoToFirstLevelSection3(object sender)
{
if ( GameData.SharedData.CanYouGoToTheFirstLevelOfThisSection(3) )
{
GameData.SharedData.ChangeLevelToFirstInThisSection(3);
PopAndTransition();
}
}
void GoToFirstLevelSection4(object sender)
{
if ( GameData.SharedData.CanYouGoToTheFirstLevelOfThisSection(4) )
{
GameData.SharedData.ChangeLevelToFirstInThisSection(4);
PopAndTransition();
}
}
void GoToFirstLevelSection5(object sender)
{
if ( GameData.SharedData.CanYouGoToTheFirstLevelOfThisSection(5) )
{
GameData.SharedData.ChangeLevelToFirstInThisSection(5);
PopAndTransition();
}
}
void GoToFirstLevelSection6(object sender)
{
if ( GameData.SharedData.CanYouGoToTheFirstLevelOfThisSection(6) )
{
GameData.SharedData.ChangeLevelToFirstInThisSection(6);
PopAndTransition();
}
}
void GoToFirstLevelSection7(object sender)
{
if ( GameData.SharedData.CanYouGoToTheFirstLevelOfThisSection(7) )
{
GameData.SharedData.ChangeLevelToFirstInThisSection(7);
PopAndTransition();
}
}
void GoToFirstLevelSection8(object sender)
{
if ( GameData.SharedData.CanYouGoToTheFirstLevelOfThisSection(8) )
{
GameData.SharedData.ChangeLevelToFirstInThisSection(8);
PopAndTransition();
}
}
void GoToFirstLevelSection9(object sender)
{
if ( GameData.SharedData.CanYouGoToTheFirstLevelOfThisSection(9) )
{
GameData.SharedData.ChangeLevelToFirstInThisSection(9);
PopAndTransition();
}
}
void GoToFirstLevelSection10(object sender)
{
if ( GameData.SharedData.CanYouGoToTheFirstLevelOfThisSection(10) )
{
GameData.SharedData.ChangeLevelToFirstInThisSection(10);
PopAndTransition();
}
}
#endregion
#region POP (remove) SCENE and Transition to new level
void PopAndTransition()
{
CCDirector.SharedDirector.PopScene();
//when TheLevel scene reloads it will start with a new level
TheLevel.SharedLevel.TransitionAfterMenuPop();
}
#endregion
#region POP (remove) SCENE and continue playing current level
public override void TouchesBegan (System.Collections.Generic.List<CCTouch> touches)
{
CCDirector.SharedDirector.PopScene();
}
#endregion
#region VOICE FX
bool IsVoiceFXMenuActive
{
set
{
RemoveChild(VoiceFXMenu, true);
CCMenuItem button1;
if (!value)
{
button1 = new CCMenuItemImage(voiceButtonNameDim, voiceButtonNameDim, TurnVoiceFXOn);
}
else
{
button1 = new CCMenuItemImage(voiceButtonName, voiceButtonName, TurnVoiceFXOff);
}
VoiceFXMenu = new CCMenu(button1);
VoiceFXMenu.Position= VoiceFXMenuLocation;
AddChild(VoiceFXMenu, 10);
}
}
void TurnVoiceFXOn(object sender)
{
GameData.SharedData.AreVoiceFXMuted = false;
GameSounds.SharedGameSounds.AreVoiceFXMuted = false;
IsVoiceFXMenuActive = true;
}
void TurnVoiceFXOff(object sender)
{
GameData.SharedData.AreVoiceFXMuted = true;
GameSounds.SharedGameSounds.AreVoiceFXMuted = true;
IsVoiceFXMenuActive = false;
}
#endregion
#region Sound FX
bool IsSoundFXMenuItemActive
{
set
{
RemoveChild(SoundFXMenu, true);
CCMenuItem button1;
if (!value)
{
button1 = new CCMenuItemImage(soundButtonNameDim, soundButtonNameDim, TurnSoundFXOn);
}
else
{
button1 = new CCMenuItemImage(soundButtonName,soundButtonName, TurnSoundFXOff);
}
SoundFXMenu = new CCMenu(button1);
SoundFXMenu.Position= SoundFXMenuLocation;
AddChild(SoundFXMenu, 10);
}
}
void TurnSoundFXOn(object sender)
{
GameData.SharedData.AreSoundFXMuted = false;
GameSounds.SharedGameSounds.AreSoundFXMuted = false;
IsSoundFXMenuItemActive = true;
}
void TurnSoundFXOff (object sender)
{
GameData.SharedData.AreSoundFXMuted = true;
GameSounds.SharedGameSounds.AreSoundFXMuted = true;
IsSoundFXMenuItemActive = false;
}
#endregion
#region Ambient FX
bool IsAmbientFXMenuActive
{
set
{
RemoveChild(AmbientFXMenu, true);
CCMenuItem button1;
if (!value)
{
button1 = new CCMenuItemImage( ambientButtonNameDim, ambientButtonNameDim, TurnAmbientFXOn);
}
else
{
button1 = new CCMenuItemImage( ambientButtonName,ambientButtonName,TurnAmbientFXOff);
}
AmbientFXMenu = new CCMenu(button1);
AmbientFXMenu.Position= AmbientFXMenuLocation;
AddChild(AmbientFXMenu, 10 );
}
}
void TurnAmbientFXOn (object sender) {
GameData.SharedData.AreAmbientFXMuted = true;
GameSounds.SharedGameSounds.RestartBackgroundMusic();
IsAmbientFXMenuActive = true;
}
void TurnAmbientFXOff (object sender) {
GameData.SharedData.AreAmbientFXMuted = false;
GameSounds.SharedGameSounds.StopBackgroundMusic();
IsAmbientFXMenuActive = false;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using Xunit;
namespace System.Net.Tests
{
public class WebProxyTest
{
public static IEnumerable<object[]> Ctor_ExpectedPropertyValues_MemberData()
{
yield return new object[] { new WebProxy(), null, false, false, Array.Empty<string>(), null };
yield return new object[] { new WebProxy("http://anything"), new Uri("http://anything"), false, false, Array.Empty<string>(), null };
yield return new object[] { new WebProxy("anything", 42), new Uri("http://anything:42"), false, false, Array.Empty<string>(), null };
yield return new object[] { new WebProxy(new Uri("http://anything")), new Uri("http://anything"), false, false, Array.Empty<string>(), null };
yield return new object[] { new WebProxy("http://anything", true), new Uri("http://anything"), false, true, Array.Empty<string>(), null };
yield return new object[] { new WebProxy(new Uri("http://anything"), true), new Uri("http://anything"), false, true, Array.Empty<string>(), null };
yield return new object[] { new WebProxy("http://anything.com", true, new[] { ".*.com" }), new Uri("http://anything.com"), false, true, new[] { ".*.com" }, null };
yield return new object[] { new WebProxy(new Uri("http://anything.com"), true, new[] { ".*.com" }), new Uri("http://anything.com"), false, true, new[] { ".*.com" }, null };
var c = new DummyCredentials();
yield return new object[] { new WebProxy("http://anything.com", true, new[] { ".*.com" }, c), new Uri("http://anything.com"), false, true, new[] { ".*.com" }, c };
yield return new object[] { new WebProxy(new Uri("http://anything.com"), true, new[] { ".*.com" }, c), new Uri("http://anything.com"), false, true, new[] { ".*.com" }, c };
}
[Theory]
[MemberData(nameof(Ctor_ExpectedPropertyValues_MemberData))]
public static void Ctor_ExpectedPropertyValues(
WebProxy p, Uri address, bool useDefaultCredentials, bool bypassLocal, string[] bypassedAddresses, ICredentials creds)
{
Assert.Equal(address, p.Address);
Assert.Equal(useDefaultCredentials, p.UseDefaultCredentials);
Assert.Equal(bypassLocal, p.BypassProxyOnLocal);
Assert.Equal(bypassedAddresses, p.BypassList);
Assert.Equal(bypassedAddresses, (string[])p.BypassArrayList.ToArray(typeof(string)));
Assert.Equal(creds, p.Credentials);
}
[Fact]
public static void BypassList_Roundtrip()
{
var p = new WebProxy();
Assert.Empty(p.BypassList);
Assert.Empty(p.BypassArrayList);
string[] strings;
strings = new string[] { "hello", "world" };
p.BypassList = strings;
Assert.Equal(strings, p.BypassList);
Assert.Equal(strings, (string[])p.BypassArrayList.ToArray(typeof(string)));
strings = new string[] { "hello" };
p.BypassList = strings;
Assert.Equal(strings, p.BypassList);
Assert.Equal(strings, (string[])p.BypassArrayList.ToArray(typeof(string)));
}
[Fact]
public static void UseDefaultCredentials_Roundtrip()
{
var p = new WebProxy();
Assert.False(p.UseDefaultCredentials);
Assert.Null(p.Credentials);
p.UseDefaultCredentials = true;
Assert.True(p.UseDefaultCredentials);
Assert.NotNull(p.Credentials);
p.UseDefaultCredentials = false;
Assert.False(p.UseDefaultCredentials);
Assert.Null(p.Credentials);
}
[Fact]
public static void BypassProxyOnLocal_Roundtrip()
{
var p = new WebProxy();
Assert.False(p.BypassProxyOnLocal);
p.BypassProxyOnLocal = true;
Assert.True(p.BypassProxyOnLocal);
p.BypassProxyOnLocal = false;
Assert.False(p.BypassProxyOnLocal);
}
[Fact]
public static void Address_Roundtrip()
{
var p = new WebProxy();
Assert.Null(p.Address);
p.Address = new Uri("http://hello");
Assert.Equal(new Uri("http://hello"), p.Address);
p.Address = null;
Assert.Null(p.Address);
}
[Fact]
public static void InvalidArgs_Throws()
{
var p = new WebProxy();
Assert.Throws<ArgumentNullException>("destination", () => p.GetProxy(null));
Assert.Throws<ArgumentNullException>("host", () => p.IsBypassed(null));
Assert.Throws<ArgumentNullException>("c", () => p.BypassList = null);
Assert.Throws<ArgumentException>(() => p.BypassList = new string[] { "*.com" });
}
[Fact]
public static void InvalidBypassUrl_AddedDirectlyToList_SilentlyEaten()
{
var p = new WebProxy("http://bing.com");
p.BypassArrayList.Add("*.com");
p.IsBypassed(new Uri("http://microsoft.com")); // exception should be silently eaten
}
[Fact]
public static void BypassList_DoesntContainUrl_NotBypassed()
{
var p = new WebProxy("http://microsoft.com");
Assert.Equal(new Uri("http://microsoft.com"), p.GetProxy(new Uri("http://bing.com")));
}
[Fact]
public static void BypassList_ContainsUrl_IsBypassed()
{
var p = new WebProxy("http://microsoft.com", false, new[] { "hello", "bing.*", "world" });
Assert.Equal(new Uri("http://bing.com"), p.GetProxy(new Uri("http://bing.com")));
}
public static IEnumerable<object[]> BypassOnLocal_MemberData()
{
// Local
yield return new object[] { new Uri($"http://nodotinhostname"), true };
yield return new object[] { new Uri($"http://{Guid.NewGuid().ToString("N")}"), true };
foreach (IPAddress address in Dns.GetHostEntryAsync(Dns.GetHostName()).GetAwaiter().GetResult().AddressList)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
{
Uri uri;
try { uri = new Uri($"http://{address}"); }
catch (UriFormatException) { continue; }
yield return new object[] { uri, true };
}
}
string domain = IPGlobalProperties.GetIPGlobalProperties().DomainName;
if (!string.IsNullOrWhiteSpace(domain))
{
Uri uri = null;
try { new Uri($"http://{Guid.NewGuid().ToString("N")}.{domain}"); }
catch (UriFormatException) { }
if (uri != null)
{
yield return new object[] { uri, true };
}
}
// Non-local
yield return new object[] { new Uri($"http://{Guid.NewGuid().ToString("N")}.com"), false };
yield return new object[] { new Uri($"http://{IPAddress.None}"), false };
}
[Theory]
[MemberData(nameof(BypassOnLocal_MemberData))]
public static void BypassOnLocal_MatchesExpected(Uri destination, bool isLocal)
{
Uri proxyUri = new Uri("http://microsoft.com");
Assert.Equal(isLocal, new WebProxy(proxyUri, true).IsBypassed(destination));
Assert.False(new WebProxy(proxyUri, false).IsBypassed(destination));
Assert.Equal(isLocal ? destination : proxyUri, new WebProxy(proxyUri, true).GetProxy(destination));
Assert.Equal(proxyUri, new WebProxy(proxyUri, false).GetProxy(destination));
}
[Fact]
public static void BypassOnLocal_SpecialCases()
{
Assert.True(new WebProxy().IsBypassed(new Uri("http://anything.com")));
Assert.True(new WebProxy((string)null).IsBypassed(new Uri("http://anything.com")));
Assert.True(new WebProxy((Uri)null).IsBypassed(new Uri("http://anything.com")));
Assert.True(new WebProxy("microsoft", true).IsBypassed(new Uri($"http://{IPAddress.Loopback}")));
Assert.True(new WebProxy("microsoft", false).IsBypassed(new Uri($"http://{IPAddress.Loopback}")));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void GetDefaultProxy_NotSupported()
{
#pragma warning disable 0618 // obsolete method
Assert.Throws<PlatformNotSupportedException>(() => WebProxy.GetDefaultProxy());
#pragma warning restore 0618
}
private class DummyCredentials : ICredentials
{
public NetworkCredential GetCredential(Uri uri, string authType) => null;
}
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlServerCe;
using System.DirectoryServices.Protocols;
using System.Security.Principal;
using System.Text;
using MLifter.DAL.DB;
using MLifter.DAL.DB.MsSqlCe;
using MLifter.DAL.DB.PostgreSQL;
using MLifter.DAL.Interfaces;
using MLifter.DAL.Interfaces.DB;
using MLifter.DAL.Properties;
using MLifter.DAL.Tools;
using MLifter.DAL.XML;
using Npgsql;
using SecurityFramework;
using MLifter.Generics;
using System.Diagnostics;
using MLifter.DAL.Preview;
using System.Xml;
using MLifter.DAL.LearningModulesService;
using System.DirectoryServices.AccountManagement;
namespace MLifter.DAL
{
/// <summary>
/// This is the general user class, which handles the user context for the requested connection.
/// </summary>
/// <remarks>Documented by Dev05, 2008-09-10</remarks>
public class User : IUser
{
/// <summary>
/// True is this is a WebService instance.
/// </summary>
public static bool IsWebService = false;
private IDbUserConnector connector
{
get
{
switch (Parent.CurrentUser.ConnectionString.Typ)
{
case DatabaseType.PostgreSQL:
return PgSqlUserConnector.GetInstance(Parent.GetChildParentClass(this));
case DatabaseType.MsSqlCe:
return MsSqlCeUserConnector.GetInstance(Parent.GetChildParentClass(this));
default:
throw new UnsupportedDatabaseTypeException(Parent.CurrentUser.ConnectionString.Typ);
}
}
}
private static Guid sessionId = Guid.NewGuid();
private Guid standAloneId;
/// <summary>
/// Gets the session id.
/// </summary>
/// <value>The session id.</value>
/// <remarks>Documented by Dev05, 2009-03-06</remarks>
public Guid SessionId { get { return ConnectionString.SessionId; } }
private GetLoginInformation getLogin;
private IUser user;
/// <summary>
/// Gets the base user.
/// </summary>
/// <value>The base user.</value>
/// <remarks>Documented by Dev05, 2009-03-06</remarks>
public IUser BaseUser { get { return user; } }
private bool isStandAlone = false;
/// <summary>
/// Initializes a new instance of the <see cref="User"/> class.
/// </summary>
/// <param name="getLoginInformation">A delegate used to collect login information (username/password).</param>
/// <param name="connectionString">A struct containing the connection info.</param>
/// <param name="errorMessageDelegate">A delegate used to handle login errors.</param>
/// <param name="standAlone">if set to <c>true</c> [stand alone].</param>
/// <remarks>Documented by Dev03, 2008-11-25</remarks>
public User(GetLoginInformation getLoginInformation, ConnectionStringStruct connectionString, DataAccessErrorDelegate errorMessageDelegate, bool standAlone)
{
if (getLoginInformation == null)
throw new ArgumentNullException();
if (errorMessageDelegate == null)
throw new ArgumentNullException();
isStandAlone = standAlone;
if (standAlone) standAloneId = Guid.NewGuid();
connectionString.SessionId = standAlone ? standAloneId : sessionId;
getLogin = getLoginInformation;
ErrorMessageDelegate = errorMessageDelegate;
user = new DummyUser(connectionString);
switch (connectionString.Typ)
{
case DatabaseType.MsSqlCe:
user = GetCeUser(connectionString);
break;
case DatabaseType.Web:
user = GetWebUser(connectionString);
break;
case DatabaseType.Unc:
user = new UncUser(new XmlUser(connectionString, errorMessageDelegate), new DbUser(new UserStruct(), Parent, connectionString, errorMessageDelegate, standAlone), connectionString);
break;
case DatabaseType.Xml:
user = new XmlUser(connectionString, errorMessageDelegate);
break;
case DatabaseType.PostgreSQL:
user = GetDbUser(connectionString, errorMessageDelegate, standAlone);
break;
default:
throw new UnsupportedDatabaseTypeException(connectionString.Typ);
}
}
/// <summary>
/// Gets the web user.
/// </summary>
/// <param name="connection">The connection.</param>
/// <returns></returns>
/// <remarks>Documented by Dev05, 2009-03-06</remarks>
private IUser GetWebUser(ConnectionStringStruct connection)
{
MLifterLearningModulesService webService = new MLifterLearningModulesService();
webService.Url = connection.ConnectionString;
webService.CookieContainer = new System.Net.CookieContainer();
int uid = -1;
UserStruct? user = null;
do
{
user = getLogin.Invoke(user.HasValue ? user.Value : new UserStruct(), new ConnectionStringStruct(DatabaseType.Web, connection.ConnectionString, true));
if (!user.HasValue)
break;
else if (user.Value.AuthenticationType != UserAuthenticationTyp.ListAuthentication)
uid = webService.Login(user.Value.UserName, user.Value.Password);
else
uid = webService.Login(user.Value.UserName, string.Empty);
UserStruct lastUser = user.Value;
try { Methods.CheckUserId(uid); lastUser.LastLoginError = LoginError.NoError; }
catch (InvalidUsernameException) { lastUser.LastLoginError = LoginError.InvalidUsername; }
catch (InvalidPasswordException) { lastUser.LastLoginError = LoginError.InvalidPassword; }
catch (WrongAuthenticationException) { lastUser.LastLoginError = LoginError.WrongAuthentication; }
catch (ForbiddenAuthenticationException) { lastUser.LastLoginError = LoginError.ForbiddenAuthentication; }
catch (UserSessionCreationException) { lastUser.LastLoginError = LoginError.AlreadyLoggedIn; }
user = lastUser;
}
while (user.HasValue && uid < 0);
if (!user.HasValue)
throw new NoValidUserException();
return new WebUser(uid, user.Value, connection, webService, Parent);
}
/// <summary>
/// Gets the Compact Edition user.
/// </summary>
/// <param name="connection">The connection.</param>
/// <returns></returns>
/// <remarks>Documented by Dev05, 2009-01-13</remarks>
private IUser GetCeUser(ConnectionStringStruct connection)
{
int userId;
UserStruct? userStruct = null;
List<UserStruct> users = connector.GetUserList() as List<UserStruct>;
if (connection.SyncType != SyncType.NotSynchronized)
{
if (connection.SyncType == SyncType.FullSynchronized && connection.ServerUser == null)
{
if (users.Count == 2)
{
userStruct = users[1];
userId = connector.LoginListUser(userStruct.Value.UserName, Guid.NewGuid(), true, true);
}
else
{
UserStruct? us = getLogin.Invoke(new UserStruct(Resources.CREATE_NEW_USER, UserAuthenticationTyp.ListAuthentication), connection);
if (!us.HasValue || us.Value.UserName == Resources.CREATE_NEW_USER)
userId = connector.LoginFormsUser(CurrentWindowsUserName, CurrentWindowsUserId, new Guid(), true, true);
else
userId = connector.LoginLocalDirectoryUser(us.Value.UserName, CurrentWindowsUserId, new Guid(), true, true);
}
}
else
{
userStruct = users.Find(u => u.UserName == connection.ServerUser.UserName);
userId = connector.LoginListUser(userStruct.Value.UserName, connection.ServerUser.ConnectionString.SessionId, true, true);
}
}
else if (Methods.IsOnMLifterStick(connection.ConnectionString))
{
if (users.Exists(u => u.UserName == Resources.StickUserName))
{
userStruct = users.Find(u => u.UserName == Resources.StickUserName);
userId = connector.LoginListUser(Resources.StickUserName, new Guid(), true, true);
}
else
{
userStruct = new UserStruct(Resources.StickUserName, UserAuthenticationTyp.ListAuthentication);
userId = connector.LoginFormsUser(Resources.StickUserName, string.Empty, new Guid(), true, true);
}
}
else if (users.Exists(u => u.Identifier == CurrentWindowsUserId))
{
userStruct = users.Find(u => u.Identifier == CurrentWindowsUserId);
userId = connector.LoginListUser(userStruct.Value.UserName, new Guid(), true, true);
}
else if (users.Count == 1)
userId = connector.LoginFormsUser(CurrentWindowsUserName, CurrentWindowsUserId, new Guid(), true, true);
else
{
UserStruct? us = getLogin.Invoke(new UserStruct(Resources.CREATE_NEW_USER, UserAuthenticationTyp.ListAuthentication), connection);
if (!us.HasValue || us.Value.UserName == Resources.CREATE_NEW_USER)
userId = connector.LoginFormsUser(CurrentWindowsUserName, CurrentWindowsUserId, new Guid(), true, true);
else
userId = connector.LoginLocalDirectoryUser(us.Value.UserName, CurrentWindowsUserId, new Guid(), true, true);
}
if (!userStruct.HasValue)
userStruct = new UserStruct(CurrentWindowsUserName, UserAuthenticationTyp.ListAuthentication);
DbUser newUser = new DbUser(userStruct, Parent, connection, errMsgDel, true);
newUser.SetId(userId);
return newUser;
}
/// <summary>
/// Gets the name of the current windows user.
/// </summary>
/// <value>
/// The name of the current windows user.
/// </value>
public static string CurrentWindowsUserName { get { return WindowsIdentity.GetCurrent().Name; } }
/// <summary>
/// Gets the current windows user id.
/// </summary>
public static string CurrentWindowsUserId { get { return WindowsIdentity.GetCurrent().User.Value; } }
/// <summary>
/// Gets the db user.
/// </summary>
/// <param name="connection">A struct containing the connection info.</param>
/// <param name="errorMessageDelegate">A delegate used to handle login errors.</param>
/// <param name="standAlone">if set to <c>true</c> [stand alone].</param>
/// <returns>A DB user which implements IUser</returns>
/// <remarks>Documented by Dev03, 2008-11-25</remarks>
private IUser GetDbUser(ConnectionStringStruct connection, DataAccessErrorDelegate errorMessageDelegate, bool standAlone)
{
CheckConnection(connection);
UserAuthenticationTyp authTyp = connector.GetAllowedAuthenticationModes().Value;
bool ldUserChecked = false;
IUser dbUser = null;
UserStruct? userStruct = null;
while (dbUser == null)
{
if (!IsWebService && !ldUserChecked && (authTyp & UserAuthenticationTyp.LocalDirectoryAuthentication) == UserAuthenticationTyp.LocalDirectoryAuthentication)
{
ldUserChecked = true;
try { userStruct = GetLocalDirectoryUser(); }
catch (NoValidUserException) { userStruct = null; }
}
else
userStruct = getLogin.Invoke(userStruct.HasValue ? userStruct.Value : new UserStruct(string.Empty, authTyp), ConnectionString);
if (userStruct.HasValue)
{
UserStruct lastUser = userStruct.Value;
try { dbUser = new DbUser(userStruct, Parent, connection, errorMessageDelegate, standAlone); lastUser.LastLoginError = LoginError.NoError; }
catch (InvalidUsernameException) { lastUser.LastLoginError = LoginError.InvalidUsername; }
catch (InvalidPasswordException) { lastUser.LastLoginError = LoginError.InvalidPassword; }
catch (WrongAuthenticationException) { lastUser.LastLoginError = LoginError.WrongAuthentication; }
catch (ForbiddenAuthenticationException) { lastUser.LastLoginError = LoginError.ForbiddenAuthentication; }
catch (UserSessionCreationException) { lastUser.LastLoginError = LoginError.AlreadyLoggedIn; }
userStruct = lastUser;
}
else
throw new NoValidUserException();
}
return dbUser;
}
/// <summary>
/// Tries to authenticate a user with the local directory.
/// </summary>
/// <returns>A struct containing the user information.</returns>
/// <remarks>Documented by Dev03, 2008-11-25</remarks>
private UserStruct GetLocalDirectoryUser()
{
switch (connector.GetLocalDirectoryType())
{
case LocalDirectoryType.ActiveDirectory:
string ad_username = WindowsIdentity.GetCurrent().Name;
if (ad_username.StartsWith(System.Environment.MachineName) || !CheckLocalDirectoryUser(ad_username))
throw new NoValidUserException();
return new UserStruct(ad_username, UserAuthenticationTyp.LocalDirectoryAuthentication);
case LocalDirectoryType.eDirectory:
try
{
IcNovell.NWCallsInit(0, 0);
int context = 0;
IcNovell.NWDSCreateContextHandle(ref context);
StringBuilder nds_username = new StringBuilder(256);
IcNovell.NWDSWhoAmI(context, nds_username);
IcNovell.NWDSFreeContext(context);
string usern = nds_username.ToString().Substring(nds_username.ToString().IndexOf('=') + 1);
if (nds_username.ToString() == "[Public]" || !CheckLocalDirectoryUser(usern))
throw new NoValidUserException();
return new UserStruct(nds_username.ToString(), UserAuthenticationTyp.LocalDirectoryAuthentication);
}
catch (Exception exp)
{
Trace.WriteLine(exp.ToString());
throw new NoValidUserException(exp);
}
default:
throw new NoValidUserException();
}
}
/// <summary>
/// Checks if the user is a local directory user.
/// </summary>
/// <param name="username">The username.</param>
/// <returns>[true] if the user is a local directory user.</returns>
/// <remarks>Documented by Dev03, 2008-11-25</remarks>
private bool CheckLocalDirectoryUser(string username)
{
try
{
switch (connector.GetLocalDirectoryType())
{
case LocalDirectoryType.ActiveDirectory:
string domain = username.Substring(0, username.IndexOf(@"\"));
PrincipalContext context;
if (!String.IsNullOrWhiteSpace(connector.GetLdapUser()) && !String.IsNullOrWhiteSpace(domain))
context = new PrincipalContext(ContextType.Domain, domain, connector.GetLdapUser(), connector.GetLdapPassword());
if (!String.IsNullOrWhiteSpace(domain))
context = new PrincipalContext(ContextType.Domain, domain);
else
context = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.FindByIdentity(context, username);
return user != null;
case LocalDirectoryType.eDirectory:
LdapConnection connection = new LdapConnection(new LdapDirectoryIdentifier(connector.GetLdapServer()));
connection.AuthType = AuthType.Basic;
connection.SessionOptions.SecureSocketLayer = connector.GetLdapUseSSL();
if (connector.GetLdapUser() != null && connector.GetLdapUser().Length > 0)
connection.Bind(new System.Net.NetworkCredential(connector.GetLdapUser(), connector.GetLdapPassword()));
else
connection.Bind();
string searchString = String.Format("(&(|(cn={0})(uid={0}))(|(objectClass=user)(objectClass=person)))",
username.Substring(username.LastIndexOf("\\") + 1));
SearchResponse response = connection.SendRequest(new SearchRequest(connector.GetLdapContext(),
searchString, SearchScope.Subtree, null)) as SearchResponse;
if (response.Entries.Count > 0)
return true;
break;
}
}
catch { return false; }
return true;
}
internal void GenerateNewSession()
{
sessionId = Guid.NewGuid();
ConnectionStringStruct css = user.ConnectionString;
css.SessionId = sessionId;
user.ConnectionString = css;
}
/// <summary>
/// Gets the id of a learning module.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="user">The user.</param>
/// <returns></returns>
/// <remarks>
/// Documented by CFI, 2009-03-06
/// </remarks>
public static int GetIdOfLearningModule(string path, IUser user)
{
return GetIdOfLearningModule(path, user, string.Empty);
}
/// <summary>
/// Gets the id of a learning module.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="user">The user.</param>
/// <param name="password">The password.</param>
/// <returns></returns>
/// <remarks>
/// Documented by CFI, 2009-03-06
/// </remarks>
public static int GetIdOfLearningModule(string path, IUser user, string password)
{
if (!path.EndsWith(Helper.EmbeddedDbExtension))
return -1;
int lmId = -1;
try
{
ConnectionStringStruct css = new ConnectionStringStruct(DatabaseType.MsSqlCe, path, -1);
css.Password = password;
IList<int> ids = DbDictionaries.GetConnector(new ParentClass(new DbUser(user.AuthenticationStruct, user.Parent, css, user.ErrorMessageDelegate, true), null)).GetLMIds();
if (ids.Count == 0)
return -1;
lmId = ids[0];
}
catch (ProtectedLearningModuleException) { throw; }
catch (Exception ex) { Debug.WriteLine("DbDictionaries.Dictionaries - " + ex.Message); }
return lmId;
}
/// <summary>
/// Gets the preview dictionary.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="user">The user.</param>
/// <param name="extended">if set to <c>true</c> [extended].</param>
/// <returns></returns>
/// <remarks>Documented by Dev03, 2009-03-23</remarks>
public static PreviewDictionary GetPreviewDictionary(string path, IUser user, bool extended)
{
if (extended)
return User.GetExtendedPreviewDictionary(path, user);
else
return User.GetPreviewDictionary(path, user);
}
/// <summary>
/// Gets the preview dictionary.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="user">The user.</param>
/// <returns></returns>
/// <remarks>Documented by Dev05, 2009-03-06</remarks>
public static PreviewDictionary GetPreviewDictionary(string path, IUser user)
{
PreviewDictionary dic = new PreviewDictionary(user);
using (XmlReader reader = XmlReader.Create(path))
{
try
{
if (reader.ReadToFollowing("category"))
{
int oldId, newId;
if (Int32.TryParse(reader.GetAttribute("id"), out newId) && (newId >= 0))
{
dic.Category = new Category(newId);
}
else if (Int32.TryParse(reader.ReadElementContentAsString(), out oldId) && (oldId >= 0))
{
dic.Category = new Category(oldId, false);
}
}
}
catch
{
dic.Category = new Category(0);
}
dic.Id = 1;
dic.Connection = path;
return dic;
}
}
/// <summary>
/// Gets the extended preview dictionary.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="user">The user.</param>
/// <returns></returns>
/// <remarks>Documented by Dev03, 2009-03-23</remarks>
public static PreviewDictionary GetExtendedPreviewDictionary(string path, IUser user)
{
PreviewDictionary dic = new PreviewDictionary(user);
dic.Connection = path;
return UpdatePreviewDictionary(dic);
}
/// <summary>
/// Updates the preview dictionary.
/// </summary>
/// <param name="dictionary">The dictionary.</param>
/// <returns></returns>
/// <remarks>Documented by Dev03, 2009-03-30</remarks>
public static PreviewDictionary UpdatePreviewDictionary(PreviewDictionary dictionary)
{
using (XmlReader reader = XmlReader.Create(dictionary.Connection))
{
try
{
ICard card = null;
IStatistic statistic = null;
bool imageFound = false;
while (reader.Read())
{
if (reader.IsEmptyElement || reader.NodeType == XmlNodeType.EndElement)
continue;
switch (reader.Name)
{
case "category":
int oldId, newId;
if (Int32.TryParse(reader.GetAttribute("id"), out newId) && (newId >= 0))
{
dictionary.Category = new Category(newId);
}
else if (Int32.TryParse(reader.ReadElementContentAsString(), out oldId) && (oldId >= 0))
{
dictionary.Category = new Category(oldId, false);
}
break;
case "author":
dictionary.Author = reader.ReadElementContentAsString().Trim();
break;
case "description":
dictionary.Description = reader.ReadElementContentAsString().Trim();
break;
case "sounddir":
dictionary.MediaDirectory = reader.ReadElementContentAsString().Trim();
break;
case "card":
card = dictionary.Cards.AddNew();
break;
case "answer":
if (imageFound) continue;
if (card != null)
{
card.Answer.AddWords(Helper.SplitWordList(reader.ReadElementContentAsString()));
}
break;
case "question":
if (imageFound) continue;
if (card != null)
{
card.Question.AddWords(Helper.SplitWordList(reader.ReadElementContentAsString()));
}
break;
case "answerexample":
if (imageFound) continue;
if (card != null)
{
card.AnswerExample.AddWords(Helper.SplitWordList(reader.ReadElementContentAsString()));
}
break;
case "questionexample":
if (imageFound) continue;
if (card != null)
{
card.QuestionExample.AddWords(Helper.SplitWordList(reader.ReadElementContentAsString()));
}
break;
case "questionimage":
if (imageFound) continue;
if (card != null)
{
IMedia qmedia = card.CreateMedia(EMedia.Image, reader.ReadElementContentAsString(), true, false, false);
card.AddMedia(qmedia, Side.Question);
imageFound = true;
}
break;
case "answerimage":
if (imageFound) continue;
if (card != null)
{
IMedia amedia = card.CreateMedia(EMedia.Image, reader.ReadElementContentAsString(), true, false, false);
card.AddMedia(amedia, Side.Question);
}
break;
case "stats":
statistic = new PreviewStatistic();
int sId;
if (Int32.TryParse(reader.GetAttribute("id"), out sId) && (sId >= 0))
{
(statistic as PreviewStatistic).Id = sId;
}
dictionary.Statistics.Add(statistic);
break;
case "start":
if (statistic != null)
{
statistic.StartTimestamp = XmlConvert.ToDateTime(reader.ReadElementContentAsString(), XmlDateTimeSerializationMode.RoundtripKind);
}
break;
case "end":
if (statistic != null)
{
statistic.EndTimestamp = XmlConvert.ToDateTime(reader.ReadElementContentAsString(), XmlDateTimeSerializationMode.RoundtripKind);
}
break;
case "right":
if (statistic != null)
{
statistic.Right = XmlConvert.ToInt32(reader.ReadElementContentAsString());
}
break;
case "wrong":
if (statistic != null)
{
statistic.Wrong = XmlConvert.ToInt32(reader.ReadElementContentAsString());
}
break;
default:
break;
}
//System.Threading.Thread.Sleep(5);
}
}
catch
{
dictionary.Category = new Category(0);
}
dictionary.Id = 1;
return dictionary;
}
}
#region IUser Members
/// <summary>
/// Gets the id.
/// </summary>
/// <value>The id.</value>
/// <remarks>Documented by Dev03, 2008-11-27</remarks>
public int Id { get { return user.Id; } }
/// <summary>
/// Gets the authentication struct.
/// </summary>
/// <value>The authentication struct.</value>
/// <remarks>Documented by Dev03, 2008-11-27</remarks>
public UserStruct AuthenticationStruct { get { return user.AuthenticationStruct; } }
/// <summary>
/// Gets the name of the user.
/// </summary>
/// <value>The name of the user.</value>
/// <remarks>Documented by Dev03, 2008-11-27</remarks>
public string UserName { get { return user.UserName; } }
/// <summary>
/// Gets the password. DO NOT STORE THIS IN A string-VARIABLE TO ENSURE A SECURE STORAGE!!!
/// </summary>
/// <value>The password.</value>
/// <remarks>Documented by Dev05, 2008-08-28</remarks>
/// <remarks>Documented by Dev03, 2008-11-27</remarks>
public string Password { get { return user.Password; } }
/// <summary>
/// Gets a value indicating whether this instance can open a learning module.
/// </summary>
/// <value><c>true</c> if this instance can open; otherwise, <c>false</c>.</value>
/// <remarks>Documented by Dev05, 2009-03-02</remarks>
public bool CanOpen { get { return user.CanOpen; } }
/// <summary>
/// Opens the learning module selected in the connection string.
/// </summary>
/// <returns></returns>
/// <remarks>Documented by Dev05, 2008-09-10</remarks>
/// <remarks>Documented by Dev03, 2008-11-27</remarks>
public IDictionary Open()
{
CheckConnection(ConnectionString);
if (user is XmlUser && ConnectionString.Typ != DatabaseType.Xml)
{
user.Logout();
if (ConnectionString.Typ == DatabaseType.MsSqlCe)
user = GetCeUser(ConnectionString);
else
user = GetDbUser(ConnectionString, ErrorMessageDelegate, false);
}
else if (user is DbUser && ConnectionString.Typ == DatabaseType.Xml)
{
user.Logout();
user = new XmlUser(ConnectionString, ErrorMessageDelegate);
}
IDictionary dictionary = user.Open();
return dictionary;
}
/// <summary>
/// Lists all available learning modules.
/// </summary>
/// <returns></returns>
/// <remarks>Documented by Dev05, 2008-09-10</remarks>
/// <remarks>Documented by Dev03, 2008-11-27</remarks>
public IDictionaries List()
{
if (user is XmlUser && (ConnectionString.Typ != DatabaseType.Xml && ConnectionString.Typ != DatabaseType.Unc))
user = GetDbUser(ConnectionString, ErrorMessageDelegate, false);
else if (user is DbUser && ConnectionString.Typ == DatabaseType.Xml)
user = new XmlUser(ConnectionString, ErrorMessageDelegate);
return user.List();
}
/// <summary>
/// Logins this user.
/// </summary>
public void Login() { user.Login(); }
/// <summary>
/// Gets the connection string.
/// </summary>
/// <value>The connection string.</value>
/// <remarks>Documented by Dev02, 2008-09-23</remarks>
/// <remarks>Documented by Dev03, 2008-11-27</remarks>
public ConnectionStringStruct ConnectionString
{
get
{
return user.ConnectionString;
}
set
{
dbConnectionValid = false;
value.SessionId = isStandAlone ? standAloneId : value.SessionId == new Guid() ? sessionId : value.SessionId;
user.ConnectionString = value;
}
}
/// <summary>
/// Sets the connection string.
/// </summary>
/// <param name="css">The CSS.</param>
/// <remarks>Documented by Dev05, 2010-02-03</remarks>
public void SetConnectionString(ConnectionStringStruct css)
{
user.SetConnectionString(css);
}
private static bool dbConnectionValid = false;
/// <summary>
/// Checks the connection.
/// </summary>
/// <param name="connectionString">The connection string.</param>
/// <remarks>Documented by Dev03, 2008-11-27</remarks>
public void CheckConnection(ConnectionStringStruct connectionString)
{
if (!dbConnectionValid && connectionString.Typ != DatabaseType.Xml)
{
DummyUser user = new DummyUser(connectionString);
DbConnection con = connectionString.Typ == DatabaseType.PostgreSQL ? PostgreSQLConn.CreateConnection(user) as DbConnection : MSSQLCEConn.GetConnection(user) as DbConnection;
if (con.State == System.Data.ConnectionState.Open)
dbConnectionValid = true;
else
throw new ConnectionInvalidException();
if (connectionString.Typ == DatabaseType.PostgreSQL)
con.Close();
DbDatabase.GetInstance(new ParentClass(new DummyUser(connectionString), this)).CheckIfDatabaseVersionSupported();
}
}
private Cache cache = new Cache(true);
/// <summary>
/// Gets the cache for this user.
/// </summary>
/// <value>The cache.</value>
/// <remarks>Documented by Dev05, 2008-09-24</remarks>
/// <remarks>Documented by Dev03, 2008-11-27</remarks>
public Cache Cache { get { return cache; } }
/// <summary>
/// Closes the session.
/// </summary>
/// <remarks>Documented by Dev02, 2008-11-13</remarks>
/// <remarks>Documented by Dev03, 2008-11-27</remarks>
public void Logout()
{
user.Logout();
if (!isStandAlone)
sessionId = Guid.NewGuid();
}
/// <summary>
/// Gets or sets the get login delegate.
/// </summary>
/// <value>The get login delegate.</value>
/// <remarks>Documented by Dev05, 2008-12-12</remarks>
/// <remarks>Documented by Dev05, 2008-12-12</remarks>
public GetLoginInformation GetLoginDelegate
{
get
{
return getLogin;
}
set
{
getLogin = value;
}
}
private DataAccessErrorDelegate errMsgDel;
/// <summary>
/// Gets or sets the error message delegate.
/// </summary>
/// <value>The error message delegate.</value>
/// <remarks>Documented by Dev05, 2008-11-17</remarks>
/// <remarks>Documented by Dev03, 2008-11-27</remarks>
public DataAccessErrorDelegate ErrorMessageDelegate { get { return errMsgDel; } set { errMsgDel = value; } }
/// <summary>
/// Gets the underlying database for this user.
/// </summary>
/// <value>The database.</value>
/// <remarks>Documented by Dev03, 2009-05-01</remarks>
public IDatabase Database
{
get { return user.Database; }
}
/// <summary>
/// Determines whether the specified object has the given permission.
/// </summary>
/// <param name="o">The object.</param>
/// <param name="permissionName">Name of the permission.</param>
/// <returns>
/// <c>true</c> if the specified o has permission; otherwise, <c>false</c>.
/// </returns>
/// <remarks>Documented by Dev03, 2009-01-14</remarks>
/// <remarks>Documented by Dev03, 2009-01-14</remarks>
public bool HasPermission(object o, string permissionName)
{
return user.HasPermission(o, permissionName);
}
/// <summary>
/// Gets the permissions for an object.
/// </summary>
/// <param name="o">The object.</param>
/// <returns>The list of permissions.</returns>
/// <remarks>Documented by Dev03, 2009-01-14</remarks>
/// <remarks>Documented by Dev03, 2009-01-14</remarks>
public List<PermissionInfo> GetPermissions(object o)
{
return user.GetPermissions(o);
}
#endregion
#region IParent Members
/// <summary>
/// Gets the parent.
/// </summary>
/// <value>The parent.</value>
/// <remarks>Documented by Dev03, 2008-11-27</remarks>
public ParentClass Parent
{
get { return new ParentClass(this, null); }
}
#endregion
#region IUser Members
#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.
==================================================================== */
using NPOI.POIFS.Common;
using NPOI.POIFS.Storage;
using NPOI.POIFS.Properties;
using NPOI.POIFS.NIO;
using System.Collections.Generic;
using System;
using NPOI.Util;
namespace NPOI.POIFS.FileSystem
{
/**
* This class handles the MiniStream (small block store)
* in the NIO case for {@link NPOIFSFileSystem}
*/
internal class NPOIFSMiniStore : BlockStore
{
private NPOIFSFileSystem _filesystem;
private NPOIFSStream _mini_stream;
private List<BATBlock> _sbat_blocks;
private HeaderBlock _header;
private RootProperty _root;
public NPOIFSMiniStore(NPOIFSFileSystem filesystem, RootProperty root,
List<BATBlock> sbats, HeaderBlock header)
{
this._filesystem = filesystem;
this._sbat_blocks = sbats;
this._header = header;
this._root = root;
this._mini_stream = new NPOIFSStream(filesystem, root.StartBlock);
}
/**
* Load the block at the given offset.
*/
public override ByteBuffer GetBlockAt(int offset)
{
// Which big block is this?
int byteOffset = offset * POIFSConstants.SMALL_BLOCK_SIZE;
int bigBlockNumber = byteOffset / _filesystem.GetBigBlockSize();
int bigBlockOffset = byteOffset % _filesystem.GetBigBlockSize();
// Now locate the data block for it
StreamBlockByteBufferIterator it = _mini_stream.GetBlockIterator() as StreamBlockByteBufferIterator;
for (int i = 0; i < bigBlockNumber; i++)
{
it.Next();
}
ByteBuffer dataBlock = it.Next();
if (dataBlock == null)
{
throw new IndexOutOfRangeException("Big block " + bigBlockNumber + " outside stream");
}
// Position ourselves, and take a slice
dataBlock.Position = dataBlock.Position + bigBlockOffset;
ByteBuffer miniBuffer = dataBlock.Slice();
miniBuffer.Limit = POIFSConstants.SMALL_BLOCK_SIZE;
return miniBuffer;
}
/**
* Load the block, extending the underlying stream if needed
*/
public override ByteBuffer CreateBlockIfNeeded(int offset)
{
// Try to Get it without extending the stream
try
{
return GetBlockAt(offset);
}
catch (IndexOutOfRangeException)
{
// Need to extend the stream
// TODO Replace this with proper append support
// For now, do the extending by hand...
// Ask for another block
int newBigBlock = _filesystem.GetFreeBlock();
_filesystem.CreateBlockIfNeeded(newBigBlock);
// Tack it onto the end of our chain
ChainLoopDetector loopDetector = _filesystem.GetChainLoopDetector();
int block = _mini_stream.GetStartBlock();
while (true)
{
loopDetector.Claim(block);
int next = _filesystem.GetNextBlock(block);
if (next == POIFSConstants.END_OF_CHAIN)
{
break;
}
block = next;
}
_filesystem.SetNextBlock(block, newBigBlock);
_filesystem.SetNextBlock(newBigBlock, POIFSConstants.END_OF_CHAIN);
// Now try again to Get it
return CreateBlockIfNeeded(offset);
}
}
/**
* Returns the BATBlock that handles the specified offset,
* and the relative index within it
*/
public override BATBlockAndIndex GetBATBlockAndIndex(int offset)
{
return BATBlock.GetSBATBlockAndIndex(
offset, _header, _sbat_blocks);
}
/**
* Works out what block follows the specified one.
*/
public override int GetNextBlock(int offset)
{
BATBlockAndIndex bai = GetBATBlockAndIndex(offset);
return bai.Block.GetValueAt(bai.Index);
}
/**
* Changes the record of what block follows the specified one.
*/
public override void SetNextBlock(int offset, int nextBlock)
{
BATBlockAndIndex bai = GetBATBlockAndIndex(offset);
bai.Block.SetValueAt(bai.Index, nextBlock);
}
/**
* Finds a free block, and returns its offset.
* This method will extend the file if needed, and if doing
* so, allocate new FAT blocks to Address the extra space.
*/
public override int GetFreeBlock()
{
int sectorsPerSBAT = _filesystem.GetBigBlockSizeDetails().GetBATEntriesPerBlock();
// First up, do we have any spare ones?
int offset = 0;
for (int i = 0; i < _sbat_blocks.Count; i++)
{
// Check this one
BATBlock sbat = _sbat_blocks[i];
if (sbat.HasFreeSectors)
{
// Claim one of them and return it
for (int j = 0; j < sectorsPerSBAT; j++)
{
int sbatValue = sbat.GetValueAt(j);
if (sbatValue == POIFSConstants.UNUSED_BLOCK)
{
// Bingo
return offset + j;
}
}
}
// Move onto the next SBAT
offset += sectorsPerSBAT;
}
// If we Get here, then there aren't any
// free sectors in any of the SBATs
// So, we need to extend the chain and add another
// Create a new BATBlock
BATBlock newSBAT = BATBlock.CreateEmptyBATBlock(_filesystem.GetBigBlockSizeDetails(), false);
int batForSBAT = _filesystem.GetFreeBlock();
newSBAT.OurBlockIndex = batForSBAT;
// Are we the first SBAT?
if (_header.SBATCount == 0)
{
_header.SBATStart = batForSBAT;
_header.SBATBlockCount = 1;
}
else
{
// Find the end of the SBAT stream, and add the sbat in there
ChainLoopDetector loopDetector = _filesystem.GetChainLoopDetector();
int batOffset = _header.SBATStart;
while (true)
{
loopDetector.Claim(batOffset);
int nextBat = _filesystem.GetNextBlock(batOffset);
if (nextBat == POIFSConstants.END_OF_CHAIN)
{
break;
}
batOffset = nextBat;
}
// Add it in at the end
_filesystem.SetNextBlock(batOffset, batForSBAT);
// And update the count
_header.SBATBlockCount = _header.SBATCount + 1;
}
// Finish allocating
_filesystem.SetNextBlock(batForSBAT, POIFSConstants.END_OF_CHAIN);
_sbat_blocks.Add(newSBAT);
// Return our first spot
return offset;
}
public override ChainLoopDetector GetChainLoopDetector()
{
return new ChainLoopDetector(_root.Size, this);
}
public override int GetBlockStoreBlockSize()
{
return POIFSConstants.SMALL_BLOCK_SIZE;
}
/**
* Writes the SBATs to their backing blocks
*/
public void SyncWithDataSource()
{
foreach (BATBlock sbat in _sbat_blocks)
{
ByteBuffer block = _filesystem.GetBlockAt(sbat.OurBlockIndex);
BlockAllocationTableWriter.WriteBlock(sbat, block);
}
}
}
}
| |
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using ZXing.Common;
namespace ZXing.QrCode.Internal
{
/// <summary> <p>QR Codes can encode text as bits in one of several modes, and can use multiple modes
/// in one QR Code. This class decodes the bits back into text.</p>
///
/// <p>See ISO 18004:2006, 6.4.3 - 6.4.7</p>
/// <author>Sean Owen</author>
/// </summary>
internal static class DecodedBitStreamParser
{
/// <summary>
/// See ISO 18004:2006, 6.4.4 Table 5
/// </summary>
private static readonly char[] ALPHANUMERIC_CHARS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
' ', '$', '%', '*', '+', '-', '.', '/', ':'
};
private const int GB2312_SUBSET = 1;
internal static DecoderResult decode(byte[] bytes,
Version version,
ErrorCorrectionLevel ecLevel,
IDictionary<DecodeHintType, object> hints)
{
var bits = new BitSource(bytes);
var result = new StringBuilder(50);
CharacterSetECI currentCharacterSetECI = null;
bool fc1InEffect = false;
var byteSegments = new List<byte[]>(1);
Mode mode;
do
{
// While still another segment to read...
if (bits.available() < 4)
{
// OK, assume we're done. Really, a TERMINATOR mode should have been recorded here
mode = Mode.TERMINATOR;
}
else
{
try
{
mode = Mode.forBits(bits.readBits(4)); // mode is encoded by 4 bits
}
catch (ArgumentException)
{
return null;
}
}
if (mode != Mode.TERMINATOR)
{
if (mode == Mode.FNC1_FIRST_POSITION || mode == Mode.FNC1_SECOND_POSITION)
{
// We do little with FNC1 except alter the parsed result a bit according to the spec
fc1InEffect = true;
}
else if (mode == Mode.STRUCTURED_APPEND)
{
if (bits.available() < 16)
{
return null;
}
// not really supported; all we do is ignore it
// Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue
bits.readBits(16);
}
else if (mode == Mode.ECI)
{
// Count doesn't apply to ECI
int value = parseECIValue(bits);
currentCharacterSetECI = CharacterSetECI.getCharacterSetECIByValue(value);
if (currentCharacterSetECI == null)
{
return null;
}
}
else
{
// First handle Hanzi mode which does not start with character count
if (mode == Mode.HANZI)
{
//chinese mode contains a sub set indicator right after mode indicator
int subset = bits.readBits(4);
int countHanzi = bits.readBits(mode.getCharacterCountBits(version));
if (subset == GB2312_SUBSET)
{
if (!decodeHanziSegment(bits, result, countHanzi))
return null;
}
}
else
{
// "Normal" QR code modes:
// How many characters will follow, encoded in this mode?
int count = bits.readBits(mode.getCharacterCountBits(version));
if (mode == Mode.NUMERIC)
{
if (!decodeNumericSegment(bits, result, count))
return null;
}
else if (mode == Mode.ALPHANUMERIC)
{
if (!decodeAlphanumericSegment(bits, result, count, fc1InEffect))
return null;
}
else if (mode == Mode.BYTE)
{
if (!decodeByteSegment(bits, result, count, currentCharacterSetECI, byteSegments, hints))
return null;
}
else if (mode == Mode.KANJI)
{
if (!decodeKanjiSegment(bits, result, count))
return null;
}
else
{
return null;
}
}
}
}
} while (mode != Mode.TERMINATOR);
#if WindowsCE
var resultString = result.ToString().Replace("\n", "\r\n");
#else
var resultString = result.ToString().Replace("\r\n", "\n").Replace("\n", Environment.NewLine);
#endif
return new DecoderResult(bytes,
resultString,
byteSegments.Count == 0 ? null : byteSegments,
ecLevel == null ? null : ecLevel.ToString());
}
/// <summary>
/// See specification GBT 18284-2000
/// </summary>
/// <param name="bits">The bits.</param>
/// <param name="result">The result.</param>
/// <param name="count">The count.</param>
/// <returns></returns>
private static bool decodeHanziSegment(BitSource bits,
StringBuilder result,
int count)
{
// Don't crash trying to read more bits than we have available.
if (count * 13 > bits.available())
{
return false;
}
// Each character will require 2 bytes. Read the characters as 2-byte pairs
// and decode as GB2312 afterwards
byte[] buffer = new byte[2 * count];
int offset = 0;
while (count > 0)
{
// Each 13 bits encodes a 2-byte character
int twoBytes = bits.readBits(13);
int assembledTwoBytes = ((twoBytes / 0x060) << 8) | (twoBytes % 0x060);
if (assembledTwoBytes < 0x003BF)
{
// In the 0xA1A1 to 0xAAFE range
assembledTwoBytes += 0x0A1A1;
}
else
{
// In the 0xB0A1 to 0xFAFE range
assembledTwoBytes += 0x0A6A1;
}
buffer[offset] = (byte)((assembledTwoBytes >> 8) & 0xFF);
buffer[offset + 1] = (byte)(assembledTwoBytes & 0xFF);
offset += 2;
count--;
}
try
{
result.Append(Encoding.GetEncoding(StringUtils.GB2312).GetString(buffer, 0, buffer.Length));
}
#if (WINDOWS_PHONE70 || WINDOWS_PHONE71 || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE)
catch (ArgumentException)
{
try
{
// Silverlight only supports a limited number of character sets, trying fallback to UTF-8
result.Append(Encoding.GetEncoding("UTF-8").GetString(buffer, 0, buffer.Length));
}
catch (Exception)
{
return false;
}
}
#endif
catch (Exception)
{
return false;
}
return true;
}
private static bool decodeKanjiSegment(BitSource bits,
StringBuilder result,
int count)
{
// Don't crash trying to read more bits than we have available.
if (count * 13 > bits.available())
{
return false;
}
// Each character will require 2 bytes. Read the characters as 2-byte pairs
// and decode as Shift_JIS afterwards
byte[] buffer = new byte[2 * count];
int offset = 0;
while (count > 0)
{
// Each 13 bits encodes a 2-byte character
int twoBytes = bits.readBits(13);
int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0);
if (assembledTwoBytes < 0x01F00)
{
// In the 0x8140 to 0x9FFC range
assembledTwoBytes += 0x08140;
}
else
{
// In the 0xE040 to 0xEBBF range
assembledTwoBytes += 0x0C140;
}
buffer[offset] = (byte)(assembledTwoBytes >> 8);
buffer[offset + 1] = (byte)assembledTwoBytes;
offset += 2;
count--;
}
// Shift_JIS may not be supported in some environments:
try
{
result.Append(Encoding.GetEncoding(StringUtils.SHIFT_JIS).GetString(buffer, 0, buffer.Length));
}
#if (WINDOWS_PHONE70 || WINDOWS_PHONE71 || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE)
catch (ArgumentException)
{
try
{
// Silverlight only supports a limited number of character sets, trying fallback to UTF-8
result.Append(Encoding.GetEncoding("UTF-8").GetString(buffer, 0, buffer.Length));
}
catch (Exception)
{
return false;
}
}
#endif
catch (Exception)
{
return false;
}
return true;
}
private static bool decodeByteSegment(BitSource bits,
StringBuilder result,
int count,
CharacterSetECI currentCharacterSetECI,
IList<byte[]> byteSegments,
IDictionary<DecodeHintType, object> hints)
{
// Don't crash trying to read more bits than we have available.
if (count << 3 > bits.available())
{
return false;
}
byte[] readBytes = new byte[count];
for (int i = 0; i < count; i++)
{
readBytes[i] = (byte)bits.readBits(8);
}
String encoding;
if (currentCharacterSetECI == null)
{
// The spec isn't clear on this mode; see
// section 6.4.5: t does not say which encoding to assuming
// upon decoding. I have seen ISO-8859-1 used as well as
// Shift_JIS -- without anything like an ECI designator to
// give a hint.
encoding = StringUtils.guessEncoding(readBytes, hints);
}
else
{
encoding = currentCharacterSetECI.EncodingName;
}
try
{
result.Append(Encoding.GetEncoding(encoding).GetString(readBytes, 0, readBytes.Length));
}
#if (WINDOWS_PHONE70 || WINDOWS_PHONE71 || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE)
catch (ArgumentException)
{
try
{
// Silverlight only supports a limited number of character sets, trying fallback to UTF-8
result.Append(Encoding.GetEncoding("UTF-8").GetString(readBytes, 0, readBytes.Length));
}
catch (Exception)
{
return false;
}
}
#endif
#if WindowsCE
catch (PlatformNotSupportedException)
{
try
{
// WindowsCE doesn't support all encodings. But it is device depended.
// So we try here the some different ones
if (encoding == "ISO-8859-1")
{
result.Append(Encoding.GetEncoding(1252).GetString(readBytes, 0, readBytes.Length));
}
else
{
result.Append(Encoding.GetEncoding("UTF-8").GetString(readBytes, 0, readBytes.Length));
}
}
catch (Exception)
{
return false;
}
}
#endif
catch (Exception)
{
return false;
}
byteSegments.Add(readBytes);
return true;
}
private static char toAlphaNumericChar(int value)
{
if (value >= ALPHANUMERIC_CHARS.Length)
{
throw FormatException.Instance;
}
return ALPHANUMERIC_CHARS[value];
}
private static bool decodeAlphanumericSegment(BitSource bits,
StringBuilder result,
int count,
bool fc1InEffect)
{
// Read two characters at a time
int start = result.Length;
while (count > 1)
{
if (bits.available() < 11)
{
return false;
}
int nextTwoCharsBits = bits.readBits(11);
result.Append(toAlphaNumericChar(nextTwoCharsBits / 45));
result.Append(toAlphaNumericChar(nextTwoCharsBits % 45));
count -= 2;
}
if (count == 1)
{
// special case: one character left
if (bits.available() < 6)
{
return false;
}
result.Append(toAlphaNumericChar(bits.readBits(6)));
}
// See section 6.4.8.1, 6.4.8.2
if (fc1InEffect)
{
// We need to massage the result a bit if in an FNC1 mode:
for (int i = start; i < result.Length; i++)
{
if (result[i] == '%')
{
if (i < result.Length - 1 && result[i + 1] == '%')
{
// %% is rendered as %
result.Remove(i + 1, 1);
}
else
{
// In alpha mode, % should be converted to FNC1 separator 0x1D
result.Remove(i, 1);
result.Insert(i, new[] { (char)0x1D });
}
}
}
}
return true;
}
private static bool decodeNumericSegment(BitSource bits,
StringBuilder result,
int count)
{
// Read three digits at a time
while (count >= 3)
{
// Each 10 bits encodes three digits
if (bits.available() < 10)
{
return false;
}
int threeDigitsBits = bits.readBits(10);
if (threeDigitsBits >= 1000)
{
return false;
}
result.Append(toAlphaNumericChar(threeDigitsBits / 100));
result.Append(toAlphaNumericChar((threeDigitsBits / 10) % 10));
result.Append(toAlphaNumericChar(threeDigitsBits % 10));
count -= 3;
}
if (count == 2)
{
// Two digits left over to read, encoded in 7 bits
if (bits.available() < 7)
{
return false;
}
int twoDigitsBits = bits.readBits(7);
if (twoDigitsBits >= 100)
{
return false;
}
result.Append(toAlphaNumericChar(twoDigitsBits / 10));
result.Append(toAlphaNumericChar(twoDigitsBits % 10));
}
else if (count == 1)
{
// One digit left over to read
if (bits.available() < 4)
{
return false;
}
int digitBits = bits.readBits(4);
if (digitBits >= 10)
{
return false;
}
result.Append(toAlphaNumericChar(digitBits));
}
return true;
}
private static int parseECIValue(BitSource bits)
{
int firstByte = bits.readBits(8);
if ((firstByte & 0x80) == 0)
{
// just one byte
return firstByte & 0x7F;
}
if ((firstByte & 0xC0) == 0x80)
{
// two bytes
int secondByte = bits.readBits(8);
return ((firstByte & 0x3F) << 8) | secondByte;
}
if ((firstByte & 0xE0) == 0xC0)
{
// three bytes
int secondThirdBytes = bits.readBits(16);
return ((firstByte & 0x1F) << 16) | secondThirdBytes;
}
throw new ArgumentException("Bad ECI bits starting with byte " + firstByte);
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.ADF.CATIDs;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.SystemUI;
using OpenGL;
namespace DynamicDisplayCompass
{
/// <summary>
/// Command that works in ArcMap/Map/PageLayout
/// </summary>
[Guid("38360569-7dda-4892-a3a0-ea1f3531177b")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("DynamicDisplayCompass.CompassCmd")]
public sealed class CompassCmd : BaseCommand
{
#region COM Registration Function(s)
[ComRegisterFunction()]
[ComVisible(false)]
static void RegisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryRegistration(registerType);
//
// TODO: Add any COM registration code here
//
}
[ComUnregisterFunction()]
[ComVisible(false)]
static void UnregisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryUnregistration(registerType);
//
// TODO: Add any COM unregistration code here
//
}
#region ArcGIS Component Category Registrar generated code
/// <summary>
/// Required method for ArcGIS Component Category registration -
/// Do not modify the contents of this method with the code editor.
/// </summary>
private static void ArcGISCategoryRegistration(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
ControlsCommands.Register(regKey);
}
/// <summary>
/// Required method for ArcGIS Component Category unregistration -
/// Do not modify the contents of this method with the code editor.
/// </summary>
private static void ArcGISCategoryUnregistration(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
ControlsCommands.Unregister(regKey);
}
#endregion
#endregion
#region class members
private IHookHelper m_hookHelper = null;
private IDynamicMap m_dynamicMap = null;
private bool m_bIsDynamicMode = false;
private bool m_bOnce = true;
private uint m_compassList = 0;
private tagRECT m_deviceFrame;
#endregion
#region class constructor
/// <summary>
/// constructor
/// </summary>
public CompassCmd()
{
base.m_category = ".NET Samples";
base.m_caption = "Dynamic Display Compass";
base.m_message = "Dynamic Display Compass";
base.m_toolTip = "Dynamic Display Compass";
base.m_name = "DynamicDisplay_Compass";
try
{
string bitmapResourceName = GetType().Name + ".bmp";
base.m_bitmap = new Bitmap(GetType(), bitmapResourceName);
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(ex.Message, "Invalid Bitmap");
}
}
#endregion
#region Overriden Class Methods
/// <summary>
/// Occurs when this command is created
/// </summary>
/// <param name="hook">Instance of the application</param>
public override void OnCreate(object hook)
{
if (hook == null)
return;
try
{
m_hookHelper = new HookHelperClass();
m_hookHelper.Hook = hook;
if (m_hookHelper.ActiveView == null)
m_hookHelper = null;
}
catch
{
m_hookHelper = null;
}
if (m_hookHelper == null)
base.m_enabled = false;
else
base.m_enabled = true;
// TODO: Add other initialization code
}
/// <summary>
/// Occurs when this command is clicked
/// </summary>
public override void OnClick()
{
m_dynamicMap = m_hookHelper.FocusMap as IDynamicMap;
if (!m_bIsDynamicMode)
{
//switch into dynamic mode
if (!m_dynamicMap.DynamicMapEnabled)
m_dynamicMap.DynamicMapEnabled = true;
//start listening to DynamicMap's 'After Draw' events
((IDynamicMapEvents_Event)m_dynamicMap).AfterDynamicDraw += new IDynamicMapEvents_AfterDynamicDrawEventHandler(OnAfterDynamicDraw);
}
else
{
//stop listening to DynamicMap's 'After Draw' events
((IDynamicMapEvents_Event)m_dynamicMap).AfterDynamicDraw -= new IDynamicMapEvents_AfterDynamicDrawEventHandler(OnAfterDynamicDraw);
//leave dynamic mode
if (m_dynamicMap.DynamicMapEnabled)
m_dynamicMap.DynamicMapEnabled = false;
}
m_bIsDynamicMode = !m_bIsDynamicMode;
m_hookHelper.ActiveView.Refresh ();
}
public override bool Checked
{
get { return m_bIsDynamicMode; }
}
#endregion
#region private methods
/// <summary>
/// nDeviceFrameUpdated event handler
/// </summary>
/// <param name="sender"></param>
/// <param name="sizeChanged"></param>
private void OnDeviceFrameUpdated(IDisplayTransformation sender, bool sizeChanged)
{
//update the device frame rectangle
m_deviceFrame = sender.get_DeviceFrame();
}
/// <summary>
/// DynamicMap AfterDynamicDraw event handler method
/// </summary>
/// <param name="DynamicMapDrawPhase"></param>
/// <param name="Display"></param>
/// <param name="dynamicDisplay"></param>
void OnAfterDynamicDraw(esriDynamicMapDrawPhase DynamicMapDrawPhase, IDisplay Display, IDynamicDisplay dynamicDisplay)
{
try
{
if (DynamicMapDrawPhase != esriDynamicMapDrawPhase.esriDMDPDynamicLayers)
return;
//make sure that the display is valid as well as that the layer is visible
if (null == dynamicDisplay || null == Display)
return;
if (m_bOnce)
{
//get the device frame size
m_deviceFrame = Display.DisplayTransformation.get_DeviceFrame();
//start listening to display events
((ITransformEvents_Event)Display.DisplayTransformation).DeviceFrameUpdated += new ITransformEvents_DeviceFrameUpdatedEventHandler(OnDeviceFrameUpdated);
CreateDisplayLists();
m_bOnce = false;
}
GL.glPushMatrix();
GL.glLoadIdentity();
//draw the compass list
GL.glPushMatrix();
GL.glTranslatef((float)m_deviceFrame.left + 70.0f, (float)m_deviceFrame.top + 70.0f, 0.0f);
GL.glScalef(90.0f, 90.0f, 0.0f);
GL.glRotatef((float)Display.DisplayTransformation.Rotation, 0.0f, 0.0f, 1.0f);
GL.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
GL.glCallList(m_compassList);
GL.glPopMatrix();
GL.glPopMatrix();
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message, "ERROR", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
}
}
/// <summary>
/// create the display list for the compass symbol
/// </summary>
private void CreateDisplayLists()
{
//create the display list for the animated icons
//the quad size is set to 1 unit. Therefore you will have to scale it
//each time before drawing.
//open the compass bitmap
Bitmap compassBitmap = new Bitmap(GetType(), "compass.gif");
//create the texture for the bitmap
uint textureId = CreateTexture(compassBitmap);
m_compassList = GL.glGenLists(1);
GL.glNewList(m_compassList, GL.GL_COMPILE);
GL.glPushMatrix();
//shift the item 1/2 unit to the middle so that it'll get drawn around the center
GL.glTranslatef(-0.5f, -0.5f, 0.0f);
//enable texture in order to allow for texture binding
GL.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, (int)GL.GL_MODULATE);
//bind the texture
GL.glEnable(GL.GL_TEXTURE_2D);
GL.glBindTexture(GL.GL_TEXTURE_2D, (uint)textureId);
//create the geometry (quad) and specify the texture coordinates
GL.glBegin (GL.GL_QUADS);
GL.glTexCoord2f (0.0f, 0.0f); GL.glVertex2f (0.0f, 0.0f);
GL.glTexCoord2f (1.0f, 0.0f); GL.glVertex2f (1.0f, 0.0f);
GL.glTexCoord2f (1.0f, 1.0f); GL.glVertex2f (1.0f, 1.0f);
GL.glTexCoord2f (0.0f, 1.0f); GL.glVertex2f (0.0f, 1.0f);
GL.glEnd ();
GL.glPopMatrix();
GL.glEndList();
}
/// <summary>
/// Given a bitmap (GDI+), create for it an OpenGL texture and return its ID
/// </summary>
/// <param name="bitmap"></param>
/// <returns>the OGL texture id</returns>
/// <remarks>in order to allow hardware acceleration, texture size must be power of two.</remarks>
private uint CreateTexture(Bitmap bitmap)
{
try
{
//get the bitmap's dimensions
int h = bitmap.Height;
int w = bitmap.Width;
int s = Math.Max(h, w);
//calculate the closest power of two to match the bitmap's size
//(thank god for high-school math...)
double x = Math.Log(Convert.ToDouble(s)) / Math.Log(2.0);
s = Convert.ToInt32(Math.Pow(2.0, Convert.ToDouble(Math.Ceiling(x))));
int bufferSizeInPixels = s * s;
//get the bitmap's raw data
Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
System.Drawing.Imaging.BitmapData bitmapData;
bitmapData = bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
byte[] bgrBuffer = new byte[bufferSizeInPixels * 3];
//scale the bitmap to be a power of two
unsafe
{
fixed (byte* pBgrBuffer = bgrBuffer)
{
GLU.gluScaleImage(GL.GL_BGR_EXT, bitmap.Size.Width, bitmap.Size.Height, GL.GL_UNSIGNED_BYTE, bitmapData.Scan0.ToPointer(), s, s, GL.GL_UNSIGNED_BYTE, pBgrBuffer);
}
}
//create a new buffer to store the raw data and set the transparency color (alpha = 0)
byte[] bgraBuffer = new byte[bufferSizeInPixels * 4];
int posBgr = 0;
int posBgra = 0;
for (int i = 0; i < bufferSizeInPixels; i++)
{
bgraBuffer[posBgra] = bgrBuffer[posBgr]; //B
bgraBuffer[posBgra + 1] = bgrBuffer[posBgr + 1]; //G
bgraBuffer[posBgra + 2] = bgrBuffer[posBgr + 2]; //R
//take care of the alpha
if (255 == bgrBuffer[posBgr] && 255 == bgrBuffer[posBgr + 1] && 255 == bgrBuffer[posBgr + 2])
{
bgraBuffer[posBgra + 3] = 0;
}
else
{
bgraBuffer[posBgra + 3] = 255;
}
posBgr += 3;
posBgra += 4;
}
//create the texture
uint[] texture = new uint[1];
GL.glEnable(GL.GL_TEXTURE_2D);
GL.glGenTextures(1, texture);
GL.glBindTexture(GL.GL_TEXTURE_2D, texture[0]);
//set the texture parameters
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, (int)GL.GL_LINEAR);
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, (int)GL.GL_LINEAR);
GL.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, (int)GL.GL_MODULATE);
unsafe
{
fixed (byte* pBgraBuffer = bgraBuffer)
{
GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, (int)GL.GL_RGBA, s, s, 0, GL.GL_BGRA_EXT, GL.GL_UNSIGNED_BYTE, pBgraBuffer);
}
}
//unlock the bitmap from memory
bitmap.UnlockBits(bitmapData);
//return the newly created texture id
return texture[0];
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(ex.Message);
}
return (uint)0;
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.Reflection;
using Xunit;
using Should;
namespace AutoMapper.UnitTests.Tests
{
public abstract class using_generic_configuration : AutoMapperSpecBase
{
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>()
.ForMember(d => d.Ignored, o => o.Ignore())
.ForMember(d => d.RenamedField, o => o.MapFrom(s => s.NamedProperty))
.ForMember(d => d.IntField, o => o.ResolveUsing<FakeResolver>().FromMember(s => s.StringField))
.ForMember("IntProperty", o => o.ResolveUsing<FakeResolver>().FromMember("AnotherStringField"))
.ForMember(d => d.IntProperty3,
o => o.ResolveUsing(typeof (FakeResolver)).FromMember(s => s.StringField3))
.ForMember(d => d.IntField4, o => o.ResolveUsing(new FakeResolver()).FromMember("StringField4"));
});
protected class Source
{
public int PropertyWithMatchingName { get; set; }
public NestedSource NestedSource { get; set; }
public int NamedProperty { get; set; }
public string StringField;
public string AnotherStringField;
public string StringField3;
public string StringField4;
}
protected class NestedSource
{
public int SomeField;
}
protected class Destination
{
public int PropertyWithMatchingName { get; set; }
public string NestedSourceSomeField;
public string Ignored { get; set; }
public string RenamedField;
public int IntField;
public int IntProperty { get; set; }
public int IntProperty3 { get; set; }
public int IntField4;
}
class FakeResolver : ValueResolver<string, int>
{
protected override int ResolveCore(string source)
{
return default(int);
}
}
}
public class when_members_have_matching_names : using_generic_configuration
{
const string memberName = "PropertyWithMatchingName";
static MemberInfo sourceMember;
protected override void Because_of()
{
sourceMember =
ConfigProvider.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == memberName)
.SourceMember;
}
[Fact]
public void should_not_be_null()
{
sourceMember.ShouldNotBeNull();
}
[Fact]
public void should_have_the_matching_member_of_the_source_type_as_value()
{
sourceMember.ShouldBeSameAs(typeof (Source).GetProperty(memberName));
}
}
public class when_the_destination_member_is_flattened : using_generic_configuration
{
static MemberInfo sourceMember;
protected override void Because_of()
{
sourceMember =
ConfigProvider.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "NestedSourceSomeField")
.SourceMember;
}
[Fact] public void should_not_be_null()
{
sourceMember.ShouldNotBeNull();
}
[Fact] public void should_have_the_member_of_the_nested_source_type_as_value()
{
sourceMember.ShouldBeSameAs(typeof (NestedSource).GetField("SomeField"));
}
}
public class when_the_destination_member_is_ignored : using_generic_configuration
{
static Exception exception;
static MemberInfo sourceMember;
protected override void Because_of()
{
try
{
sourceMember =
ConfigProvider.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "Ignored")
.SourceMember;
}
catch (Exception ex)
{
exception = ex;
}
}
[Fact] public void should_not_throw_an_exception()
{
exception.ShouldBeNull();
}
[Fact] public void should_be_null()
{
sourceMember.ShouldBeNull();
}
}
public class when_the_destination_member_is_projected : using_generic_configuration
{
static MemberInfo sourceMember;
protected override void Because_of()
{
sourceMember =
ConfigProvider.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "RenamedField")
.SourceMember;
}
[Fact] public void should_not_be_null()
{
sourceMember.ShouldNotBeNull();
}
[Fact] public void should_have_the_projected_member_of_the_source_type_as_value()
{
sourceMember.ShouldBeSameAs(typeof (Source).GetProperty("NamedProperty"));
}
}
public class when_the_destination_member_is_resolved_from_a_source_member : using_generic_configuration
{
static MemberInfo sourceMember;
protected override void Because_of()
{
sourceMember =
ConfigProvider.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "IntField")
.SourceMember;
}
[Fact] public void should_not_be_null()
{
sourceMember.ShouldNotBeNull();
}
[Fact] public void should_have_the_member_of_the_source_type_it_is_resolved_from_as_value()
{
sourceMember.ShouldBeSameAs(typeof (Source).GetField("StringField"));
}
}
public class when_the_destination_property_is_resolved_from_a_source_member_using_the_Magic_String_overload : using_generic_configuration
{
static MemberInfo sourceMember;
protected override void Because_of()
{
sourceMember =
ConfigProvider.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "IntProperty")
.SourceMember;
}
[Fact] public void should_not_be_null()
{
sourceMember.ShouldNotBeNull();
}
[Fact] public void should_have_the_member_of_the_source_type_it_is_resolved_from_as_value()
{
sourceMember.ShouldBeSameAs(typeof (Source).GetField("AnotherStringField"));
}
}
public class when_the_destination_property_is_resolved_from_a_source_member_using_the_non_generic_resolve_method : using_generic_configuration
{
static MemberInfo sourceMember;
protected override void Because_of()
{
sourceMember =
ConfigProvider.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "IntProperty3")
.SourceMember;
}
[Fact] public void should_not_be_null()
{
sourceMember.ShouldNotBeNull();
}
[Fact] public void should_have_the_member_of_the_source_type_it_is_resolved_from_as_value()
{
sourceMember.ShouldBeSameAs(typeof (Source).GetField("StringField3"));
}
}
public class when_the_destination_property_is_resolved_from_a_source_member_using_non_the_generic_resolve_method_and_the_Magic_String_overload : using_generic_configuration
{
static MemberInfo sourceMember;
protected override void Because_of()
{
sourceMember =
ConfigProvider.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "IntField4")
.SourceMember;
}
[Fact] public void should_not_be_null()
{
sourceMember.ShouldNotBeNull();
}
[Fact] public void should_have_the_member_of_the_source_type_it_is_resolved_from_as_value()
{
sourceMember.ShouldBeSameAs(typeof (Source).GetField("StringField4"));
}
}
public abstract class using_nongeneric_configuration : AutoMapperSpecBase
{
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap(typeof (Source), typeof (Destination))
.ForMember("RenamedProperty", o => o.MapFrom("NamedProperty"));
});
protected class Source
{
public int NamedProperty { get; set; }
}
protected class Destination
{
public string RenamedProperty { get; set; }
}
}
public class when_the_destination_property_is_projected : using_nongeneric_configuration
{
static MemberInfo sourceMember;
protected override void Because_of()
{
sourceMember =
ConfigProvider.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "RenamedProperty")
.SourceMember;
}
[Fact] public void should_not_be_null()
{
sourceMember.ShouldNotBeNull();
}
[Fact]
public void should_have_the_projected_member_of_the_source_type_as_value()
{
sourceMember.ShouldBeSameAs(typeof (Source).GetProperty("NamedProperty"));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing.Printing;
using System.Linq;
using bv.common.Configuration;
using bv.common.Core;
using bv.model.BLToolkit;
using bv.model.Model.Core;
using DevExpress.XtraReports.UI;
using eidss.model.Reports;
using eidss.model.Reports.Common;
using eidss.winclient.Reports;
using EIDSS.Reports.Factory;
namespace EIDSS.Reports.BaseControls.Report
{
public partial class BaseReport : XtraReport
{
private ReportRebinder m_ReportRebinder;
protected ClsBarCode m_BarCode = new ClsBarCode();
public BaseReport()
{
AccessRigths = new AccessRigthsRebinder(this);
InitializeComponent();
PaperKind = PaperKind.A4;
}
[Browsable(true)]
[DefaultValue(false)]
public bool CanWorkWithArchive
{
get { return CanReportWorkWithArchive(GetType()); }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public AccessRigthsRebinder AccessRigths { get; private set; }
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public ReportRebinder ReportRebinder
{
get
{
if (m_ReportRebinder == null)
{
throw new InvalidOperationException("Language is not initialized. Use SetLanguage() before getting this property");
}
return m_ReportRebinder;
}
private set { m_ReportRebinder = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public XtraReport ChildReport { get; set; }
[Browsable(false)]
public static int CommandTimeout
{
get { return Config.GetIntSetting("ReportsCommandTimeout", 600); }
}
[Browsable(false)]
protected int DeltaYear
{
get { return ModelUserContext.CurrentLanguage == Localizer.lngThai ? 543 : 0; }
}
public static bool CanReportWorkWithArchive(Type reportType)
{
Utils.CheckNotNull(reportType, "reportType");
object[] attributes = reportType.GetCustomAttributes(typeof (CanWorkWithArchiveAttribute), true);
return attributes.Length > 0;
}
public void SetLanguage(BaseModel model, DbManagerProxy manager)
{
SetLanguage(model.Language, model.PrintDate, model.OrganizationId, model.SiteId, manager);
}
protected void SetLanguage(string lang, DateTime printDate, long? organizationId, long? siteId, DbManagerProxy manager)
{
Utils.CheckNotNullOrEmpty(lang, "lang");
cellLanguage.Text = lang;
ReportRebinder = this.GetDateRebinder(lang);
ReportRebinder.RebindDateAndFontForReport();
AccessRigths.Process();
cellDate.Text = ReportRebinder.ToDateString(printDate);
cellTime.Text = ReportRebinder.ToTimeString(printDate);
if (organizationId <= 0)
{
organizationId = null;
}
m_BaseAdapter.Connection = (SqlConnection) manager.Connection;
m_BaseAdapter.Transaction = (SqlTransaction) manager.Transaction;
m_BaseAdapter.CommandTimeout = CommandTimeout;
m_BaseAdapter.Fill(m_BaseDataSet.sprepGetBaseParameters, lang, organizationId, siteId);
if (m_BaseDataSet.sprepGetBaseParameters.Count > 0)
{
m_BaseDataSet.sprepGetBaseParameters[0].strDateFormat = ReportRebinder.DestFormatNational;
}
ReportRtlHelper.SetRTL(this);
}
protected void AjustLeftHeaderHeight(int delta)
{
tableBaseInnerHeader.Height = cellBaseLeftHeader.Height + delta;
}
protected void HideBaseHeader()
{
ReportHeader.Controls.Remove(tableBaseHeader);
}
#region Fill Data with Archive methods
public static void FillDataTableWithArchive
(Action<SqlConnection, SqlTransaction> fillTableAction,
DbManagerProxy manager, DbManagerProxy archiveManager,
DataTable dataSource, ReportArchiveMode mode,
string[] keyName = null, string[] ignoreName = null,
Dictionary<string, NumAggregateHandler> numFunctions = null,
Dictionary<string, StrAggregateHanler> strFunctions = null)
{
FillDataTableWithArchive(fillTableAction, (table, dataTable) => { },
manager, archiveManager,
dataSource, mode, keyName, ignoreName, numFunctions, strFunctions);
}
public static void FillDataTableWithArchive
(Action<SqlConnection, SqlTransaction> fillTableAction, Action<DataTable, DataTable> beforeMergeWithArchive,
DbManagerProxy manager, DbManagerProxy archiveManager,
DataTable dataSource, ReportArchiveMode mode, string[] keyName, string[] ignoreName,
Dictionary<string, NumAggregateHandler> numFunctions = null,
Dictionary<string, StrAggregateHanler> strFunctions = null)
{
if (numFunctions == null)
{
numFunctions = new Dictionary<string, NumAggregateHandler>();
}
if (strFunctions == null)
{
strFunctions = new Dictionary<string, StrAggregateHanler>();
}
if (mode != ReportArchiveMode.ActualOnly)
{
if (archiveManager == null)
{
throw new ArgumentNullException("archiveManager");
}
if (archiveManager.Connection == null)
{
throw new ArgumentException("archiveManager.Connection is NULL");
}
}
switch (mode)
{
case ReportArchiveMode.ActualOnly:
fillTableAction((SqlConnection) manager.Connection, (SqlTransaction) manager.Transaction);
break;
case ReportArchiveMode.ArchiveOnly:
fillTableAction((SqlConnection) archiveManager.Connection, (SqlTransaction) archiveManager.Transaction);
break;
case ReportArchiveMode.ActualWithArchive:
fillTableAction((SqlConnection) archiveManager.Connection, (SqlTransaction) archiveManager.Transaction);
var archiveData = dataSource.Copy();
fillTableAction((SqlConnection) manager.Connection, (SqlTransaction) manager.Transaction);
beforeMergeWithArchive(dataSource, archiveData);
ArchiveDataHelper.MergeWithArchive(dataSource, archiveData, keyName, ignoreName, numFunctions, strFunctions);
break;
}
dataSource.AcceptChanges();
}
protected void ShowWarningIfDataInArchive(DbManagerProxy manager, DateTime startDate, bool useArchive)
{
if (CanWorkWithArchive && !useArchive)
{
ArchiveDataHelper.ShowWarningIfDataInArchive(manager, startDate);
}
}
#endregion
#region Helper methods
internal static void RemoveCellsExcept(XRTable table, XRTableRow row, IList<XRTableCell> toLeave = null)
{
var toDelete = new List<XRTableCell>();
var widthDictionary = new Dictionary<XRTableCell, float>();
foreach (XRTableCell cell in row.Cells)
{
if (toLeave != null && toLeave.Contains(cell))
{
widthDictionary.Add(cell, cell.WidthF);
}
else
{
toDelete.Add(cell);
}
}
if (toDelete.Count > 0)
{
((ISupportInitialize) (table)).BeginInit();
foreach (XRTableCell cell in toDelete)
{
row.Cells.Remove(cell);
}
XRTableCell lastCell = widthDictionary.Keys.Last();
foreach (KeyValuePair<XRTableCell, float> pair in widthDictionary)
{
if (pair.Key != lastCell)
{
pair.Key.WidthF = pair.Value;
}
}
((ISupportInitialize) (table)).EndInit();
}
}
internal static void RemoveCells(XRTable table, XRTableRow row, IEnumerable<XRTableCell> toDelete)
{
if (toDelete != null)
{
((ISupportInitialize) (table)).BeginInit();
foreach (XRTableCell cell in toDelete)
{
row.Cells.Remove(cell);
}
((ISupportInitialize) (table)).EndInit();
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
public abstract class VCDPadBase : MonoBehaviour
{
public enum EDirection
{
None,
Up,
Down,
Left = 4,
Right = 8
}
public string vcName;
private static Dictionary<string, VCDPadBase> _instancesByVcName;
public VCAnalogJoystickBase joystick;
public bool XAxisEnabled = true;
public bool YAxisEnabled = true;
public bool debugKeysEnabled;
public bool debugTouchKeysTogglesPress;
public KeyCode debugLeftKey = KeyCode.Keypad4;
public KeyCode debugRightKey = KeyCode.Keypad6;
public KeyCode debugUpKey = KeyCode.Keypad8;
public KeyCode debugDownKey = KeyCode.Keypad5;
protected int _pressedField;
public bool Up
{
get
{
return this.Pressed(VCDPadBase.EDirection.Up);
}
}
public bool Down
{
get
{
return this.Pressed(VCDPadBase.EDirection.Down);
}
}
public bool Left
{
get
{
return this.Pressed(VCDPadBase.EDirection.Left);
}
}
public bool Right
{
get
{
return this.Pressed(VCDPadBase.EDirection.Right);
}
}
protected bool JoystickMode
{
get
{
return this.joystick != null;
}
}
protected void AddInstance()
{
if (string.IsNullOrEmpty(this.vcName))
{
return;
}
if (VCDPadBase._instancesByVcName == null)
{
VCDPadBase._instancesByVcName = new Dictionary<string, VCDPadBase>();
}
while (VCDPadBase._instancesByVcName.ContainsKey(this.vcName))
{
this.vcName += "_copy";
LogSystem.LogWarning(new object[]
{
"Attempting to add instance with duplicate VCName!\nVCNames must be unique -- renaming this instance to " + this.vcName
});
}
VCDPadBase._instancesByVcName.Add(this.vcName, this);
}
public static VCDPadBase GetInstance(string vcName)
{
if (VCDPadBase._instancesByVcName == null || !VCDPadBase._instancesByVcName.ContainsKey(vcName))
{
return null;
}
return VCDPadBase._instancesByVcName[vcName];
}
protected abstract void SetPressedGraphics(VCDPadBase.EDirection dir, bool pressed);
public bool Pressed(VCDPadBase.EDirection dir)
{
return (this._pressedField & (int)dir) != 0;
}
protected void Start()
{
this.Init();
}
protected virtual bool Init()
{
base.useGUILayout = false;
if (VCTouchController.Instance == null)
{
LogSystem.LogWarning(new object[]
{
"Cannot find VCTouchController!\nVirtualControls requires a gameObject which has VCTouchController component attached in scene. Adding one for you..."
});
base.gameObject.AddComponent<VCTouchController>();
}
if (this.JoystickMode && !this.joystick.measureDeltaRelativeToCenter)
{
LogSystem.LogWarning(new object[]
{
"DPad in joystickMode may not function correctly when joystick's measureDeltaRelativeToCenter is not true."
});
}
this.AddInstance();
return true;
}
protected virtual void Update()
{
if (this.JoystickMode)
{
this.UpdateStateJoystickMode();
}
else
{
this.UpdateStateNonJoystickMode();
}
}
protected virtual void UpdateStateJoystickMode()
{
this.SetPressed(VCDPadBase.EDirection.Right, this.joystick.AxisX > 0f && this.XAxisEnabled);
this.SetPressed(VCDPadBase.EDirection.Left, this.joystick.AxisX < 0f && this.XAxisEnabled);
this.SetPressed(VCDPadBase.EDirection.Up, this.joystick.AxisY > 0f && this.YAxisEnabled);
this.SetPressed(VCDPadBase.EDirection.Down, this.joystick.AxisY < 0f && this.YAxisEnabled);
}
protected virtual void UpdateStateNonJoystickMode()
{
}
protected virtual void SetPressed(VCDPadBase.EDirection dir, bool pressed)
{
if (this.Pressed(dir) == pressed)
{
return;
}
this.SetBitfield(dir, pressed);
this.SetPressedGraphics(dir, pressed);
}
protected void SetBitfield(VCDPadBase.EDirection dir, bool pressed)
{
this._pressedField &= (int)(~(int)dir);
if (pressed)
{
this._pressedField |= (int)dir;
}
}
protected VCDPadBase.EDirection GetOpposite(VCDPadBase.EDirection dir)
{
switch (dir)
{
case VCDPadBase.EDirection.Up:
return VCDPadBase.EDirection.Down;
case VCDPadBase.EDirection.Down:
return VCDPadBase.EDirection.Up;
case VCDPadBase.EDirection.Left:
return VCDPadBase.EDirection.Right;
case VCDPadBase.EDirection.Right:
return VCDPadBase.EDirection.Left;
}
return VCDPadBase.EDirection.None;
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.ComIntegration
{
using System;
using System.Runtime.Diagnostics;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Description;
using System.Security.Principal;
using System.ServiceModel;
using System.Transactions;
using System.Diagnostics;
using System.ServiceModel.Diagnostics;
using System.EnterpriseServices;
using SR = System.ServiceModel.SR;
using System.Globalization;
class ComPlusThreadInitializer : ICallContextInitializer
{
ServiceInfo info;
ComPlusAuthorization comAuth;
Guid iid;
public ComPlusThreadInitializer(ContractDescription contract,
DispatchOperation operation,
ServiceInfo info)
{
this.info = info;
iid = contract.ContractType.GUID;
if (info.CheckRoles)
{
string[] serviceRoleMembers = null;
string[] contractRoleMembers = null;
string[] operationRoleMembers = null;
// Figure out the role members we want...
//
serviceRoleMembers = info.ComponentRoleMembers;
foreach (ContractInfo contractInfo in this.info.Contracts)
{
if (contractInfo.IID == iid)
{
contractRoleMembers = contractInfo.InterfaceRoleMembers;
foreach (OperationInfo opInfo in contractInfo.Operations)
{
if (opInfo.Name == operation.Name)
{
operationRoleMembers = opInfo.MethodRoleMembers;
break;
}
}
if (operationRoleMembers == null)
{
// Did not find the operation
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(
SR.GetString(SR.ComOperationNotFound,
contract.Name,
operation.Name)));
}
break;
}
}
this.comAuth = new ComPlusAuthorization(serviceRoleMembers,
contractRoleMembers,
operationRoleMembers);
}
}
public object BeforeInvoke(
InstanceContext instanceContext,
IClientChannel channel,
Message message)
{
ComPlusServerSecurity serverSecurity = null;
WindowsImpersonationContext impersonateContext = null;
bool errorTraced = false;
WindowsIdentity identity = null;
Uri from = null;
object instance = null;
int instanceID = 0;
string action = null;
TransactionProxy proxy = null;
Transaction tx = null;
Guid incomingTransactionID = Guid.Empty;
// The outer try block is to comply with FXCOP's WrapVulnerableFinallyClausesInOuterTry rule.
try
{
try
{
identity = MessageUtil.GetMessageIdentity(message);
if (message.Headers.From != null)
from = message.Headers.From.Uri;
instance = instanceContext.GetServiceInstance(message);
instanceID = instance.GetHashCode();
action = message.Headers.Action;
ComPlusMethodCallTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationInvokingMethod,
SR.TraceCodeComIntegrationInvokingMethod, this.info, from, action, identity.Name, iid, instanceID, false);
// Security
//
if (this.info.CheckRoles)
{
if (!this.comAuth.IsAuthorizedForOperation(identity))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.CallAccessDenied());
}
}
if (this.info.HostingMode != HostingMode.WebHostOutOfProcess)
{
// NOTE: This has the side effect of setting up
// the COM server security thing, so be sure
// to clear it with Dispose() eventually.
//
serverSecurity = new ComPlusServerSecurity(identity,
this.info.CheckRoles);
}
// Transactions
//
proxy = instanceContext.Extensions.Find<TransactionProxy>();
if (proxy != null)
{
// This makes the Tx header Understood.
tx = MessageUtil.GetMessageTransaction(message);
if (tx != null)
{
incomingTransactionID = tx.TransactionInformation.DistributedIdentifier;
}
try
{
if (tx != null)
{
proxy.SetTransaction(tx);
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.TransactionMismatch());
}
ComPlusMethodCallTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationInvokingMethodNewTransaction,
SR.TraceCodeComIntegrationInvokingMethodNewTransaction, this.info, from, action, identity.Name, iid, instanceID, incomingTransactionID);
}
catch (FaultException e)
{
Transaction txProxy = proxy.CurrentTransaction;
Guid currentTransactionID = Guid.Empty;
if (txProxy != null)
currentTransactionID = txProxy.TransactionInformation.DistributedIdentifier;
string identityName = String.Empty;
if (null != identity)
identityName = identity.Name;
DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error,
(ushort)System.Runtime.Diagnostics.EventLogCategory.ComPlus,
(uint)System.Runtime.Diagnostics.EventLogEventId.ComPlusInvokingMethodFailedMismatchedTransactions,
incomingTransactionID.ToString("B").ToUpperInvariant(),
currentTransactionID.ToString("B").ToUpperInvariant(),
from.ToString(),
this.info.AppID.ToString("B").ToUpperInvariant(),
this.info.Clsid.ToString("B").ToUpperInvariant(),
iid.ToString(),
action,
instanceID.ToString(CultureInfo.InvariantCulture),
System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture),
SafeNativeMethods.GetCurrentThreadId().ToString(CultureInfo.InvariantCulture),
identityName,
e.ToString());
errorTraced = true;
throw;
}
}
else
{
ComPlusMethodCallTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationInvokingMethodContextTransaction,
SR.TraceCodeComIntegrationInvokingMethodContextTransaction, this.info, from, action, identity.Name, iid, instanceID, true);
}
// Impersonation
//
if (this.info.HostingMode == HostingMode.WebHostOutOfProcess)
{
impersonateContext = identity.Impersonate();
}
CorrelationState correlationState;
correlationState = new CorrelationState(impersonateContext,
serverSecurity,
from,
action,
identity.Name,
instanceID);
impersonateContext = null;
serverSecurity = null;
return correlationState;
}
finally
{
if (impersonateContext != null)
impersonateContext.Undo();
if (serverSecurity != null)
((IDisposable)serverSecurity).Dispose();
}
}
catch (Exception e)
{
if (errorTraced == false)
{
if (DiagnosticUtility.ShouldTraceError)
{
DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error,
(ushort)System.Runtime.Diagnostics.EventLogCategory.ComPlus,
(uint)System.Runtime.Diagnostics.EventLogEventId.ComPlusInvokingMethodFailed,
from == null ? string.Empty : from.ToString(),
this.info.AppID.ToString("B").ToUpperInvariant(),
this.info.Clsid.ToString("B").ToUpperInvariant(),
iid.ToString("B").ToUpperInvariant(),
action,
instanceID.ToString(CultureInfo.InvariantCulture),
System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture),
SafeNativeMethods.GetCurrentThreadId().ToString(CultureInfo.InvariantCulture),
identity.Name,
e.ToString());
}
}
throw;
}
}
public void AfterInvoke(object correlationState)
{
CorrelationState state = (CorrelationState)correlationState;
if (state != null)
{
ComPlusMethodCallTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationInvokedMethod,
SR.TraceCodeComIntegrationInvokedMethod, this.info, state.From, state.Action, state.CallerIdentity, iid, state.InstanceID, false);
state.Cleanup();
}
}
class CorrelationState
{
WindowsImpersonationContext impersonationContext;
ComPlusServerSecurity serverSecurity;
Uri from;
string action;
string callerIdentity;
int instanceID;
public CorrelationState(WindowsImpersonationContext context,
ComPlusServerSecurity serverSecurity,
Uri from,
string action,
string callerIdentity,
int instanceID)
{
this.impersonationContext = context;
this.serverSecurity = serverSecurity;
this.from = from;
this.action = action;
this.callerIdentity = callerIdentity;
this.instanceID = instanceID;
}
public Uri From
{
get
{
return this.from;
}
}
public string Action
{
get
{
return this.action;
}
}
public string CallerIdentity
{
get
{
return this.callerIdentity;
}
}
public int InstanceID
{
get
{
return this.instanceID;
}
}
public void Cleanup()
{
if (this.impersonationContext != null)
this.impersonationContext.Undo();
if (this.serverSecurity != null)
((IDisposable)this.serverSecurity).Dispose();
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using Nini.Config;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Mono.Addins;
namespace OpenSim.Region.CoreModules.Agent.Xfer
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "XferModule")]
public class XferModule : INonSharedRegionModule, IXfer
{
private Scene m_scene;
private Dictionary<string, FileData> NewFiles = new Dictionary<string, FileData>();
private Dictionary<ulong, XferDownLoad> Transfers = new Dictionary<ulong, XferDownLoad>();
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public struct XferRequest
{
public IClientAPI remoteClient;
public ulong xferID;
public string fileName;
public DateTime timeStamp;
}
private class FileData
{
public byte[] Data;
public int Count;
}
#region INonSharedRegionModule Members
public void Initialise(IConfigSource config)
{
}
public void AddRegion(Scene scene)
{
m_scene = scene;
m_scene.EventManager.OnNewClient += NewClient;
m_scene.RegisterModuleInterface<IXfer>(this);
}
public void RemoveRegion(Scene scene)
{
m_scene.EventManager.OnNewClient -= NewClient;
m_scene.UnregisterModuleInterface<IXfer>(this);
m_scene = null;
}
public void RegionLoaded(Scene scene)
{
}
public Type ReplaceableInterface
{
get { return null; }
}
public void Close()
{
}
public string Name
{
get { return "XferModule"; }
}
#endregion
#region IXfer Members
/// <summary>
/// Let the Xfer module know about a file that the client is about to request.
/// Caller is responsible for making sure that the file is here before
/// the client starts the XferRequest.
/// </summary>
/// <param name="fileName"></param>
/// <param name="data"></param>
/// <returns></returns>
public bool AddNewFile(string fileName, byte[] data)
{
lock (NewFiles)
{
if (NewFiles.ContainsKey(fileName))
{
NewFiles[fileName].Count++;
NewFiles[fileName].Data = data;
}
else
{
FileData fd = new FileData();
fd.Count = 1;
fd.Data = data;
NewFiles.Add(fileName, fd);
}
}
return true;
}
#endregion
public void NewClient(IClientAPI client)
{
client.OnRequestXfer += RequestXfer;
client.OnConfirmXfer += AckPacket;
client.OnAbortXfer += AbortXfer;
}
/// <summary>
///
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="xferID"></param>
/// <param name="fileName"></param>
public void RequestXfer(IClientAPI remoteClient, ulong xferID, string fileName)
{
lock (NewFiles)
{
if (NewFiles.ContainsKey(fileName))
{
if (!Transfers.ContainsKey(xferID))
{
byte[] fileData = NewFiles[fileName].Data;
XferDownLoad transaction = new XferDownLoad(fileName, fileData, xferID, remoteClient);
Transfers.Add(xferID, transaction);
if (transaction.StartSend())
RemoveXferData(xferID);
// The transaction for this file is either complete or on its way
RemoveOrDecrement(fileName);
}
}
else
m_log.WarnFormat("[Xfer]: {0} not found", fileName);
}
}
public void AckPacket(IClientAPI remoteClient, ulong xferID, uint packet)
{
lock (NewFiles) // This is actually to lock Transfers
{
if (Transfers.ContainsKey(xferID))
{
XferDownLoad dl = Transfers[xferID];
if (Transfers[xferID].AckPacket(packet))
{
RemoveXferData(xferID);
RemoveOrDecrement(dl.FileName);
}
}
}
}
private void RemoveXferData(ulong xferID)
{
// NewFiles must be locked!
if (Transfers.ContainsKey(xferID))
{
XferModule.XferDownLoad xferItem = Transfers[xferID];
//string filename = xferItem.FileName;
Transfers.Remove(xferID);
xferItem.Data = new byte[0]; // Clear the data
xferItem.DataPointer = 0;
}
}
public void AbortXfer(IClientAPI remoteClient, ulong xferID)
{
lock (NewFiles)
{
if (Transfers.ContainsKey(xferID))
RemoveOrDecrement(Transfers[xferID].FileName);
RemoveXferData(xferID);
}
}
private void RemoveOrDecrement(string fileName)
{
// NewFiles must be locked
if (NewFiles.ContainsKey(fileName))
{
if (NewFiles[fileName].Count == 1)
NewFiles.Remove(fileName);
else
NewFiles[fileName].Count--;
}
}
#region Nested type: XferDownLoad
public class XferDownLoad
{
public IClientAPI Client;
private bool complete;
public byte[] Data = new byte[0];
public int DataPointer = 0;
public string FileName = String.Empty;
public uint Packet = 0;
public uint Serial = 1;
public ulong XferID = 0;
public XferDownLoad(string fileName, byte[] data, ulong xferID, IClientAPI client)
{
FileName = fileName;
Data = data;
XferID = xferID;
Client = client;
}
public XferDownLoad()
{
}
/// <summary>
/// Start a transfer
/// </summary>
/// <returns>True if the transfer is complete, false if not</returns>
public bool StartSend()
{
if (Data.Length < 1000)
{
// for now (testing) we only support files under 1000 bytes
byte[] transferData = new byte[Data.Length + 4];
Array.Copy(Utils.IntToBytes(Data.Length), 0, transferData, 0, 4);
Array.Copy(Data, 0, transferData, 4, Data.Length);
Client.SendXferPacket(XferID, 0 + 0x80000000, transferData);
complete = true;
}
else
{
byte[] transferData = new byte[1000 + 4];
Array.Copy(Utils.IntToBytes(Data.Length), 0, transferData, 0, 4);
Array.Copy(Data, 0, transferData, 4, 1000);
Client.SendXferPacket(XferID, 0, transferData);
Packet++;
DataPointer = 1000;
}
return complete;
}
/// <summary>
/// Respond to an ack packet from the client
/// </summary>
/// <param name="packet"></param>
/// <returns>True if the transfer is complete, false otherwise</returns>
public bool AckPacket(uint packet)
{
if (!complete)
{
if ((Data.Length - DataPointer) > 1000)
{
byte[] transferData = new byte[1000];
Array.Copy(Data, DataPointer, transferData, 0, 1000);
Client.SendXferPacket(XferID, Packet, transferData);
Packet++;
DataPointer += 1000;
}
else
{
byte[] transferData = new byte[Data.Length - DataPointer];
Array.Copy(Data, DataPointer, transferData, 0, Data.Length - DataPointer);
uint endPacket = Packet |= (uint) 0x80000000;
Client.SendXferPacket(XferID, endPacket, transferData);
Packet++;
DataPointer += (Data.Length - DataPointer);
complete = true;
}
}
return complete;
}
}
#endregion
}
}
| |
/*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://openapi-generator.tech
*/
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Org.OpenAPITools.Converters;
namespace Org.OpenAPITools.Models
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class PipelineRunNode : IEquatable<PipelineRunNode>
{
/// <summary>
/// Gets or Sets Class
/// </summary>
[DataMember(Name="_class", EmitDefaultValue=false)]
public string Class { get; set; }
/// <summary>
/// Gets or Sets DisplayName
/// </summary>
[DataMember(Name="displayName", EmitDefaultValue=false)]
public string DisplayName { get; set; }
/// <summary>
/// Gets or Sets DurationInMillis
/// </summary>
[DataMember(Name="durationInMillis", EmitDefaultValue=false)]
public int DurationInMillis { get; set; }
/// <summary>
/// Gets or Sets Edges
/// </summary>
[DataMember(Name="edges", EmitDefaultValue=false)]
public List<PipelineRunNodeedges> Edges { get; set; }
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public string Id { get; set; }
/// <summary>
/// Gets or Sets Result
/// </summary>
[DataMember(Name="result", EmitDefaultValue=false)]
public string Result { get; set; }
/// <summary>
/// Gets or Sets StartTime
/// </summary>
[DataMember(Name="startTime", EmitDefaultValue=false)]
public string StartTime { get; set; }
/// <summary>
/// Gets or Sets State
/// </summary>
[DataMember(Name="state", EmitDefaultValue=false)]
public string State { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class PipelineRunNode {\n");
sb.Append(" Class: ").Append(Class).Append("\n");
sb.Append(" DisplayName: ").Append(DisplayName).Append("\n");
sb.Append(" DurationInMillis: ").Append(DurationInMillis).Append("\n");
sb.Append(" Edges: ").Append(Edges).Append("\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Result: ").Append(Result).Append("\n");
sb.Append(" StartTime: ").Append(StartTime).Append("\n");
sb.Append(" State: ").Append(State).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == GetType() && Equals((PipelineRunNode)obj);
}
/// <summary>
/// Returns true if PipelineRunNode instances are equal
/// </summary>
/// <param name="other">Instance of PipelineRunNode to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PipelineRunNode other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true;
return
(
Class == other.Class ||
Class != null &&
Class.Equals(other.Class)
) &&
(
DisplayName == other.DisplayName ||
DisplayName != null &&
DisplayName.Equals(other.DisplayName)
) &&
(
DurationInMillis == other.DurationInMillis ||
DurationInMillis.Equals(other.DurationInMillis)
) &&
(
Edges == other.Edges ||
Edges != null &&
other.Edges != null &&
Edges.SequenceEqual(other.Edges)
) &&
(
Id == other.Id ||
Id != null &&
Id.Equals(other.Id)
) &&
(
Result == other.Result ||
Result != null &&
Result.Equals(other.Result)
) &&
(
StartTime == other.StartTime ||
StartTime != null &&
StartTime.Equals(other.StartTime)
) &&
(
State == other.State ||
State != null &&
State.Equals(other.State)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
var hashCode = 41;
// Suitable nullity checks etc, of course :)
if (Class != null)
hashCode = hashCode * 59 + Class.GetHashCode();
if (DisplayName != null)
hashCode = hashCode * 59 + DisplayName.GetHashCode();
hashCode = hashCode * 59 + DurationInMillis.GetHashCode();
if (Edges != null)
hashCode = hashCode * 59 + Edges.GetHashCode();
if (Id != null)
hashCode = hashCode * 59 + Id.GetHashCode();
if (Result != null)
hashCode = hashCode * 59 + Result.GetHashCode();
if (StartTime != null)
hashCode = hashCode * 59 + StartTime.GetHashCode();
if (State != null)
hashCode = hashCode * 59 + State.GetHashCode();
return hashCode;
}
}
#region Operators
#pragma warning disable 1591
public static bool operator ==(PipelineRunNode left, PipelineRunNode right)
{
return Equals(left, right);
}
public static bool operator !=(PipelineRunNode left, PipelineRunNode right)
{
return !Equals(left, right);
}
#pragma warning restore 1591
#endregion Operators
}
}
| |
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# port by: Lars Brubaker
// larsbrubaker@gmail.com
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
using MatterHackers.VectorMath;
namespace MatterHackers.Agg.Image
{
public abstract class ImageProxy : IImageByte
{
protected IImageByte linkedImage;
public IImageByte LinkedImage
{
get
{
return linkedImage;
}
set
{
linkedImage = value;
}
}
public ImageProxy(IImageByte linkedImage)
{
this.linkedImage = linkedImage;
}
public virtual void LinkToImage(IImageByte linkedImage)
{
this.linkedImage = linkedImage;
}
public virtual Vector2 OriginOffset
{
get { return linkedImage.OriginOffset; }
set { linkedImage.OriginOffset = value; }
}
public virtual int Width
{
get
{
return linkedImage.Width;
}
}
public virtual int Height
{
get
{
return linkedImage.Height;
}
}
public virtual int StrideInBytes()
{
return linkedImage.StrideInBytes();
}
public virtual int StrideInBytesAbs()
{
return linkedImage.StrideInBytesAbs();
}
public virtual RectangleInt GetBounds()
{
return linkedImage.GetBounds();
}
public Graphics2D NewGraphics2D()
{
return linkedImage.NewGraphics2D();
}
public IRecieveBlenderByte GetRecieveBlender()
{
return linkedImage.GetRecieveBlender();
}
public void SetRecieveBlender(IRecieveBlenderByte value)
{
linkedImage.SetRecieveBlender(value);
}
public virtual Color GetPixel(int x, int y)
{
return linkedImage.GetPixel(x, y);
}
public virtual void copy_pixel(int x, int y, byte[] c, int ByteOffset)
{
linkedImage.copy_pixel(x, y, c, ByteOffset);
}
public virtual void CopyFrom(IImageByte sourceRaster)
{
linkedImage.CopyFrom(sourceRaster);
}
public virtual void CopyFrom(IImageByte sourceImage, RectangleInt sourceImageRect, int destXOffset, int destYOffset)
{
linkedImage.CopyFrom(sourceImage, sourceImageRect, destXOffset, destYOffset);
}
public virtual void SetPixel(int x, int y, Color color)
{
linkedImage.SetPixel(x, y, color);
}
public virtual void BlendPixel(int x, int y, Color sourceColor, byte cover)
{
linkedImage.BlendPixel(x, y, sourceColor, cover);
}
public virtual void copy_hline(int x, int y, int len, Color sourceColor)
{
linkedImage.copy_hline(x, y, len, sourceColor);
}
public virtual void copy_vline(int x, int y, int len, Color sourceColor)
{
linkedImage.copy_vline(x, y, len, sourceColor);
}
public virtual void blend_hline(int x1, int y, int x2, Color sourceColor, byte cover)
{
linkedImage.blend_hline(x1, y, x2, sourceColor, cover);
}
public virtual void blend_vline(int x, int y1, int y2, Color sourceColor, byte cover)
{
linkedImage.blend_vline(x, y1, y2, sourceColor, cover);
}
public virtual void blend_solid_hspan(int x, int y, int len, Color c, byte[] covers, int coversIndex)
{
linkedImage.blend_solid_hspan(x, y, len, c, covers, coversIndex);
}
public virtual void copy_color_hspan(int x, int y, int len, Color[] colors, int colorIndex)
{
linkedImage.copy_color_hspan(x, y, len, colors, colorIndex);
}
public virtual void copy_color_vspan(int x, int y, int len, Color[] colors, int colorIndex)
{
linkedImage.copy_color_vspan(x, y, len, colors, colorIndex);
}
public virtual void blend_solid_vspan(int x, int y, int len, Color c, byte[] covers, int coversIndex)
{
linkedImage.blend_solid_vspan(x, y, len, c, covers, coversIndex);
}
public virtual void blend_color_hspan(int x, int y, int len, Color[] colors, int colorsIndex, byte[] covers, int coversIndex, bool firstCoverForAll)
{
linkedImage.blend_color_hspan(x, y, len, colors, colorsIndex, covers, coversIndex, firstCoverForAll);
}
public virtual void blend_color_vspan(int x, int y, int len, Color[] colors, int colorsIndex, byte[] covers, int coversIndex, bool firstCoverForAll)
{
linkedImage.blend_color_vspan(x, y, len, colors, colorsIndex, covers, coversIndex, firstCoverForAll);
}
public byte[] GetBuffer()
{
return linkedImage.GetBuffer();
}
public int GetBufferOffsetXY(int x, int y)
{
return linkedImage.GetBufferOffsetXY(x, y);
}
public int GetBufferOffsetY(int y)
{
return linkedImage.GetBufferOffsetY(y);
}
public virtual int GetBytesBetweenPixelsInclusive()
{
return linkedImage.GetBytesBetweenPixelsInclusive();
}
public virtual int BitDepth
{
get
{
return linkedImage.BitDepth;
}
}
public void MarkImageChanged()
{
linkedImage.MarkImageChanged();
}
}
public abstract class ImageProxyFloat : IImageFloat
{
protected IImageFloat linkedImage;
public ImageProxyFloat(IImageFloat linkedImage)
{
this.linkedImage = linkedImage;
}
public virtual void LinkToImage(IImageFloat linkedImage)
{
this.linkedImage = linkedImage;
}
public virtual Vector2 OriginOffset
{
get { return linkedImage.OriginOffset; }
set { linkedImage.OriginOffset = value; }
}
public virtual int Width
{
get
{
return linkedImage.Width;
}
}
public virtual int Height
{
get
{
return linkedImage.Height;
}
}
public virtual int StrideInFloats()
{
return linkedImage.StrideInFloats();
}
public virtual int StrideInFloatsAbs()
{
return linkedImage.StrideInFloatsAbs();
}
public virtual RectangleInt GetBounds()
{
return linkedImage.GetBounds();
}
public Graphics2D NewGraphics2D()
{
return linkedImage.NewGraphics2D();
}
public IRecieveBlenderFloat GetBlender()
{
return linkedImage.GetBlender();
}
public void SetRecieveBlender(IRecieveBlenderFloat value)
{
linkedImage.SetRecieveBlender(value);
}
public virtual ColorF GetPixel(int x, int y)
{
return linkedImage.GetPixel(y, x);
}
public virtual void copy_pixel(int x, int y, float[] c, int FloatOffset)
{
linkedImage.copy_pixel(x, y, c, FloatOffset);
}
public virtual void CopyFrom(IImageFloat sourceRaster)
{
linkedImage.CopyFrom(sourceRaster);
}
public virtual void CopyFrom(IImageFloat sourceImage, RectangleInt sourceImageRect, int destXOffset, int destYOffset)
{
linkedImage.CopyFrom(sourceImage, sourceImageRect, destXOffset, destYOffset);
}
public virtual void SetPixel(int x, int y, ColorF color)
{
linkedImage.SetPixel(x, y, color);
}
public virtual void BlendPixel(int x, int y, ColorF sourceColor, byte cover)
{
linkedImage.BlendPixel(x, y, sourceColor, cover);
}
public virtual void copy_hline(int x, int y, int len, ColorF sourceColor)
{
linkedImage.copy_hline(x, y, len, sourceColor);
}
public virtual void copy_vline(int x, int y, int len, ColorF sourceColor)
{
linkedImage.copy_vline(x, y, len, sourceColor);
}
public virtual void blend_hline(int x1, int y, int x2, ColorF sourceColor, byte cover)
{
linkedImage.blend_hline(x1, y, x2, sourceColor, cover);
}
public virtual void blend_vline(int x, int y1, int y2, ColorF sourceColor, byte cover)
{
linkedImage.blend_vline(x, y1, y2, sourceColor, cover);
}
public virtual void blend_solid_hspan(int x, int y, int len, ColorF c, byte[] covers, int coversIndex)
{
linkedImage.blend_solid_hspan(x, y, len, c, covers, coversIndex);
}
public virtual void copy_color_hspan(int x, int y, int len, ColorF[] colors, int colorIndex)
{
linkedImage.copy_color_hspan(x, y, len, colors, colorIndex);
}
public virtual void copy_color_vspan(int x, int y, int len, ColorF[] colors, int colorIndex)
{
linkedImage.copy_color_vspan(x, y, len, colors, colorIndex);
}
public virtual void blend_solid_vspan(int x, int y, int len, ColorF c, byte[] covers, int coversIndex)
{
linkedImage.blend_solid_vspan(x, y, len, c, covers, coversIndex);
}
public virtual void blend_color_hspan(int x, int y, int len, ColorF[] colors, int colorsIndex, byte[] covers, int coversIndex, bool firstCoverForAll)
{
linkedImage.blend_color_hspan(x, y, len, colors, colorsIndex, covers, coversIndex, firstCoverForAll);
}
public virtual void blend_color_vspan(int x, int y, int len, ColorF[] colors, int colorsIndex, byte[] covers, int coversIndex, bool firstCoverForAll)
{
linkedImage.blend_color_vspan(x, y, len, colors, colorsIndex, covers, coversIndex, firstCoverForAll);
}
public float[] GetBuffer()
{
return linkedImage.GetBuffer();
}
public int GetBufferOffsetY(int y)
{
return linkedImage.GetBufferOffsetY(y);
}
public int GetBufferOffsetXY(int x, int y)
{
return linkedImage.GetBufferOffsetXY(x, y);
}
public virtual int GetFloatsBetweenPixelsInclusive()
{
return linkedImage.GetFloatsBetweenPixelsInclusive();
}
public virtual int BitDepth
{
get
{
return linkedImage.BitDepth;
}
}
public void MarkImageChanged()
{
linkedImage.MarkImageChanged();
}
}
}
| |
//originally from Matthew Adams, who was a thorough blog on these things at http://mwadams.spaces.live.com/blog/cns!652A0FB566F633D5!133.entry
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using SIL.Progress;
using SIL.Reporting;
namespace SIL.Windows.Forms.Progress
{
/// <summary>
/// Provides a progress dialog similar to the one shown by Windows
/// </summary>
public class ProgressDialog : Form
{
public delegate void ProgressCallback(int progress);
private Label _statusLabel;
private ProgressBar _progressBar;
private Label _progressLabel;
private Button _cancelButton;
private Timer _showWindowIfTakingLongTimeTimer;
private Timer _progressTimer;
private bool _isClosing;
private Label _overviewLabel;
private DateTime _startTime;
private IContainer components;
private BackgroundWorker _backgroundWorker;
// private ProgressState _lastHeardFromProgressState;
private ProgressState _progressState;
private TableLayoutPanel tableLayout;
private bool _workerStarted;
private bool _appUsingWaitCursor;
/// <summary>
/// Standard constructor
/// </summary>
public ProgressDialog()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
_statusLabel.BackColor = Color.Transparent;
_progressLabel.BackColor = Color.Transparent;
_overviewLabel.BackColor = Color.Transparent;
_startTime = default(DateTime);
Text = UsageReporter.AppNameToUseInDialogs;
_statusLabel.Font = SystemFonts.MessageBoxFont;
_progressLabel.Font = SystemFonts.MessageBoxFont;
_overviewLabel.Font = SystemFonts.MessageBoxFont;
_statusLabel.Text = string.Empty;
_progressLabel.Text = string.Empty;
_overviewLabel.Text = string.Empty;
_cancelButton.MouseEnter += delegate
{
_appUsingWaitCursor = Application.UseWaitCursor;
_cancelButton.Cursor = Cursor = Cursors.Arrow;
Application.UseWaitCursor = false;
};
_cancelButton.MouseLeave += delegate
{
Application.UseWaitCursor = _appUsingWaitCursor;
};
//avoids the client getting null errors if he checks this when there
//has yet to be a callback from the worker
// _lastHeardFromProgressState = new NullProgressState();
}
private void HandleTableLayoutSizeChanged(object sender, EventArgs e)
{
if (!IsHandleCreated)
CreateHandle();
var desiredHeight = tableLayout.Height + Padding.Top + Padding.Bottom + (Height - ClientSize.Height);
var scn = Screen.FromControl(this);
Height = Math.Min(desiredHeight, scn.WorkingArea.Height - 20);
AutoScroll = (desiredHeight > scn.WorkingArea.Height - 20);
}
/// <summary>
/// Get / set the time in ms to delay
/// before showing the dialog
/// </summary>
private/*doesn't work yet public*/ int DelayShowInterval
{
get
{
return _showWindowIfTakingLongTimeTimer.Interval;
}
set
{
_showWindowIfTakingLongTimeTimer.Interval = value;
}
}
/// <summary>
/// Get / set the text to display in the first status panel
/// </summary>
public string StatusText
{
get
{
return _statusLabel.Text;
}
set
{
_statusLabel.Text = value;
}
}
/// <summary>
/// Description of why this dialog is even showing
/// </summary>
public string Overview
{
get
{
return _overviewLabel.Text;
}
set
{
_overviewLabel.Text = value;
}
}
/// <summary>
/// Get / set the minimum range of the progress bar
/// </summary>
public int ProgressRangeMinimum
{
get
{
return _progressBar.Minimum;
}
set
{
if (_backgroundWorker == null)
{
_progressBar.Minimum = value;
}
}
}
/// <summary>
/// Get / set the maximum range of the progress bar
/// </summary>
public int ProgressRangeMaximum
{
get
{
return _progressBar.Maximum;
}
set
{
if (_backgroundWorker != null)
{
return;
}
if (InvokeRequired)
{
Invoke(new ProgressCallback(SetMaximumCrossThread), new object[] { value });
}
else
{
_progressBar.Maximum = value;
}
}
}
private void SetMaximumCrossThread(int amount)
{
ProgressRangeMaximum = amount;
}
/// <summary>
/// Get / set the current value of the progress bar
/// </summary>
public int Progress
{
get
{
return _progressBar.Value;
}
set
{
/* these were causing weird, hard to debug (because of threads)
* failures. The debugger would reprot that value == max, so why fail?
* Debug.Assert(value <= _progressBar.Maximum);
*/
Debug.WriteLineIf(value > _progressBar.Maximum,
"***Warning progres was " + value + " but max is " + _progressBar.Maximum);
Debug.Assert(value >= _progressBar.Minimum);
if (value > _progressBar.Maximum)
{
_progressBar.Maximum = value;//not worth crashing over in Release build
}
if (value < _progressBar.Minimum)
{
return; //not worth crashing over in Release build
}
_progressBar.Value = value;
}
}
/// <summary>
/// Get/set a boolean which determines whether the form
/// will show a cancel option (true) or not (false)
/// </summary>
public bool CanCancel
{
get
{
return _cancelButton.Enabled;
}
set
{
_cancelButton.Enabled = value;
}
}
/// <summary>
/// If this is set before showing, the dialog will run the worker and respond
/// to its events
/// </summary>
public BackgroundWorker BackgroundWorker
{
get
{
return _backgroundWorker;
}
set
{
_backgroundWorker = value;
_progressBar.Minimum = 0;
_progressBar.Maximum = 100;
}
}
public ProgressState ProgressStateResult
{
get
{
return _progressState;// return _lastHeardFromProgressState;
}
}
/// <summary>
/// Gets or sets the manner in which progress should be indicated on the progress bar.
/// </summary>
public ProgressBarStyle BarStyle { get { return _progressBar.Style; } set { _progressBar.Style = value; } }
/// <summary>
/// Optional; one will be created (of some class or subclass) if you don't set it.
/// E.g. dlg.ProgressState = new BackgroundWorkerState(dlg.BackgroundWorker);
/// Also, you can use the getter to gain access to the progressstate, in order to add arguments
/// which the worker method can get at.
/// </summary>
public ProgressState ProgressState
{
get
{
if(_progressState ==null)
{
if(_backgroundWorker == null)
{
throw new ArgumentException("You must set BackgroundWorker before accessing this property.");
}
ProgressState = new BackgroundWorkerState(_backgroundWorker);
}
return _progressState;
}
set
{
if (_progressState!=null)
{
CancelRequested -= _progressState.CancelRequested;
}
_progressState = value;
CancelRequested += _progressState.CancelRequested;
_progressState.TotalNumberOfStepsChanged += OnTotalNumberOfStepsChanged;
}
}
void OnBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//BackgroundWorkerState progressState = e.Result as ProgressState;
if(e.Cancelled )
{
DialogResult = DialogResult.Cancel;
//_progressState.State = ProgressState.StateValue.Finished;
}
//NB: I don't know how to actually let the BW know there was an error
//else if (e.Error != null ||
else if (ProgressStateResult != null && (ProgressStateResult.State == ProgressState.StateValue.StoppedWithError
|| ProgressStateResult.ExceptionThatWasEncountered != null))
{
//this dialog really can't know whether this was an unexpected exception or not
//so don't do this: Reporting.ErrorReporter.ReportException(ProgressStateResult.ExceptionThatWasEncountered, this, false);
DialogResult = DialogResult.Abort;//not really matching semantics
// _progressState.State = ProgressState.StateValue.StoppedWithError;
}
else
{
DialogResult = DialogResult.OK;
// _progressState.State = ProgressState.StateValue.Finished;
}
_isClosing = true;
Close();
}
void OnBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
ProgressState state = e.UserState as ProgressState;
if (state != null)
{
// _lastHeardFromProgressState = state;
StatusText = state.StatusLabel;
}
if (state == null
|| state is BackgroundWorkerState)
{
Progress = e.ProgressPercentage;
}
else
{
ProgressRangeMaximum = state.TotalNumberOfSteps;
Progress = state.NumberOfStepsCompleted;
}
}
/// <summary>
/// Show the control, but honor the
/// <see cref="DelayShowInterval"/>.
/// </summary>
private/*doesn't work yet public*/ void DelayShow()
{
// This creates the control, but doesn't
// show it; you can't use CreateControl()
// here, because it will return because
// the control is not visible
CreateHandle();
}
//************
//the problem is that our worker reports progress, and we die (only in some circumstance not nailed-down yet)
//because of a begininvoke with no window yet. Sometimes, we don't get the callback to
//the very important OnBackgroundWorker_RunWorkerCompleted
private/*doesn't work yet public*/ void ShowDialogIfTakesLongTime()
{
DelayShow();
OnStartWorker(this, null);
while((_progressState.State == ProgressState.StateValue.NotStarted
|| _progressState.State == ProgressState.StateValue.Busy) && !this.Visible)
{
Application.DoEvents();
}
}
/// <summary>
/// Close the dialog, ignoring cancel status
/// </summary>
public void ForceClose()
{
_isClosing = true;
Close();
}
/// <summary>
/// Raised when the cancel button is clicked
/// </summary>
public event EventHandler CancelRequested;
/// <summary>
/// Raises the cancelled event
/// </summary>
/// <param name="e">Event data</param>
protected virtual void OnCancelled( EventArgs e )
{
EventHandler cancelled = CancelRequested;
if( cancelled != null )
{
cancelled( this, e );
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (_showWindowIfTakingLongTimeTimer != null)
{
_showWindowIfTakingLongTimeTimer.Stop();
}
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
/// <summary>
/// Custom handle creation code
/// </summary>
/// <param name="e">Event data</param>
// protected override void OnHandleCreated(EventArgs e)
// {
// base.OnHandleCreated (e);
// if( !_showOnce )
// {
// // First, we don't want this to happen again
// _showOnce = true;
// // Then, start the timer which will determine whether
// // we are going to show this again
// _showWindowIfTakingLongTimeTimer.Start();
// }
// }
/// <summary>
/// Custom close handler
/// </summary>
/// <param name="e">Event data</param>
// protected override void OnClosing(CancelEventArgs e)
// {
// Debug.WriteLine("Dialog:OnClosing");
// if (_showWindowIfTakingLongTimeTimer != null)
// {
// _showWindowIfTakingLongTimeTimer.Stop();
// }
//
// if( !_isClosing )
// {
// Debug.WriteLine("Warning: OnClosing called but _isClosing=false, attempting cancel click");
// e.Cancel = true;
// _cancelButton.PerformClick();
// }
// base.OnClosing( e );
// }
#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.components = new System.ComponentModel.Container();
this._statusLabel = new System.Windows.Forms.Label();
this._progressBar = new System.Windows.Forms.ProgressBar();
this._cancelButton = new System.Windows.Forms.Button();
this._progressLabel = new System.Windows.Forms.Label();
this._showWindowIfTakingLongTimeTimer = new System.Windows.Forms.Timer(this.components);
this._progressTimer = new System.Windows.Forms.Timer(this.components);
this._overviewLabel = new System.Windows.Forms.Label();
this.tableLayout = new System.Windows.Forms.TableLayoutPanel();
this.tableLayout.SuspendLayout();
this.SuspendLayout();
//
// _statusLabel
//
this._statusLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._statusLabel.AutoSize = true;
this._statusLabel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
this.tableLayout.SetColumnSpan(this._statusLabel, 2);
this._statusLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this._statusLabel.Location = new System.Drawing.Point(0, 35);
this._statusLabel.Margin = new System.Windows.Forms.Padding(0, 0, 0, 5);
this._statusLabel.Name = "_statusLabel";
this._statusLabel.Size = new System.Drawing.Size(355, 15);
this._statusLabel.TabIndex = 12;
this._statusLabel.Text = "#";
this._statusLabel.UseMnemonic = false;
//
// _progressBar
//
this._progressBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tableLayout.SetColumnSpan(this._progressBar, 2);
this._progressBar.Location = new System.Drawing.Point(0, 55);
this._progressBar.Margin = new System.Windows.Forms.Padding(0, 0, 0, 12);
this._progressBar.Name = "_progressBar";
this._progressBar.Size = new System.Drawing.Size(355, 18);
this._progressBar.Style = System.Windows.Forms.ProgressBarStyle.Continuous;
this._progressBar.TabIndex = 11;
this._progressBar.Value = 1;
//
// _cancelButton
//
this._cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this._cancelButton.AutoSize = true;
this._cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this._cancelButton.Location = new System.Drawing.Point(280, 85);
this._cancelButton.Margin = new System.Windows.Forms.Padding(8, 0, 0, 0);
this._cancelButton.Name = "_cancelButton";
this._cancelButton.Size = new System.Drawing.Size(75, 23);
this._cancelButton.TabIndex = 10;
this._cancelButton.Text = "&Cancel";
this._cancelButton.Click += new System.EventHandler(this.OnCancelButton_Click);
//
// _progressLabel
//
this._progressLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._progressLabel.AutoEllipsis = true;
this._progressLabel.AutoSize = true;
this._progressLabel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
this._progressLabel.Location = new System.Drawing.Point(0, 90);
this._progressLabel.Margin = new System.Windows.Forms.Padding(0, 5, 0, 0);
this._progressLabel.Name = "_progressLabel";
this._progressLabel.Size = new System.Drawing.Size(272, 13);
this._progressLabel.TabIndex = 9;
this._progressLabel.Text = "#";
this._progressLabel.UseMnemonic = false;
//
// _showWindowIfTakingLongTimeTimer
//
this._showWindowIfTakingLongTimeTimer.Interval = 2000;
this._showWindowIfTakingLongTimeTimer.Tick += new System.EventHandler(this.OnTakingLongTimeTimerClick);
//
// _progressTimer
//
this._progressTimer.Enabled = true;
this._progressTimer.Interval = 1000;
this._progressTimer.Tick += new System.EventHandler(this.progressTimer_Tick);
//
// _overviewLabel
//
this._overviewLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._overviewLabel.AutoSize = true;
this._overviewLabel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
this.tableLayout.SetColumnSpan(this._overviewLabel, 2);
this._overviewLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this._overviewLabel.Location = new System.Drawing.Point(0, 0);
this._overviewLabel.Margin = new System.Windows.Forms.Padding(0, 0, 0, 20);
this._overviewLabel.Name = "_overviewLabel";
this._overviewLabel.Size = new System.Drawing.Size(355, 15);
this._overviewLabel.TabIndex = 8;
this._overviewLabel.Text = "#";
this._overviewLabel.UseMnemonic = false;
//
// tableLayout
//
this.tableLayout.AutoSize = true;
this.tableLayout.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.tableLayout.BackColor = System.Drawing.Color.Transparent;
this.tableLayout.ColumnCount = 2;
this.tableLayout.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayout.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayout.Controls.Add(this._cancelButton, 1, 3);
this.tableLayout.Controls.Add(this._overviewLabel, 0, 0);
this.tableLayout.Controls.Add(this._progressLabel, 0, 3);
this.tableLayout.Controls.Add(this._progressBar, 0, 2);
this.tableLayout.Controls.Add(this._statusLabel, 0, 1);
this.tableLayout.Dock = System.Windows.Forms.DockStyle.Top;
this.tableLayout.Location = new System.Drawing.Point(12, 12);
this.tableLayout.Name = "tableLayout";
this.tableLayout.RowCount = 4;
this.tableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayout.Size = new System.Drawing.Size(355, 108);
this.tableLayout.TabIndex = 13;
this.tableLayout.SizeChanged += new System.EventHandler(this.HandleTableLayoutSizeChanged);
//
// ProgressDialog
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.AutoSize = true;
this.ClientSize = new System.Drawing.Size(379, 150);
this.ControlBox = false;
this.Controls.Add(this.tableLayout);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ProgressDialog";
this.Padding = new System.Windows.Forms.Padding(12);
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Palaso";
this.Load += new System.EventHandler(this.ProgressDialog_Load);
this.Shown += new System.EventHandler(this.ProgressDialog_Shown);
this.tableLayout.ResumeLayout(false);
this.tableLayout.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private void OnTakingLongTimeTimerClick(object sender, EventArgs e)
{
// Show the window now the timer has elapsed, and stop the timer
_showWindowIfTakingLongTimeTimer.Stop();
if (!this.Visible)
{
Show();
}
}
private void OnCancelButton_Click(object sender, EventArgs e)
{
_showWindowIfTakingLongTimeTimer.Stop();
if(_isClosing)
return;
Debug.WriteLine("Dialog:OnCancelButton_Click");
// Prevent further cancellation
_cancelButton.Enabled = false;
_progressTimer.Stop();
_progressLabel.Text = "Canceling...";
// Tell people we're canceling
OnCancelled( e );
if (_backgroundWorker != null && _backgroundWorker.WorkerSupportsCancellation)
{
_backgroundWorker.CancelAsync();
}
}
private void progressTimer_Tick(object sender, EventArgs e)
{
int range = _progressBar.Maximum - _progressBar.Minimum;
if( range <= 0 )
{
return;
}
if( _progressBar.Value <= 0 )
{
return;
}
if (_startTime != default(DateTime))
{
TimeSpan elapsed = DateTime.Now - _startTime;
double estimatedSeconds = (elapsed.TotalSeconds * range) / _progressBar.Value;
TimeSpan estimatedToGo = new TimeSpan(0, 0, 0, (int)(estimatedSeconds - elapsed.TotalSeconds), 0);
//_progressLabel.Text = String.Format(
// System.Globalization.CultureInfo.CurrentUICulture,
// "Elapsed: {0} Remaining: {1}",
// GetStringFor(elapsed),
// GetStringFor(estimatedToGo));
_progressLabel.Text = String.Format(
CultureInfo.CurrentUICulture,
"{0}",
//GetStringFor(elapsed),
GetStringFor(estimatedToGo));
}
}
private static string GetStringFor( TimeSpan span )
{
if( span.TotalDays > 1 )
{
return string.Format(CultureInfo.CurrentUICulture, "{0} day {1} hour", span.Days, span.Hours);
}
else if( span.TotalHours > 1 )
{
return string.Format(CultureInfo.CurrentUICulture, "{0} hour {1} minutes", span.Hours, span.Minutes);
}
else if( span.TotalMinutes > 1 )
{
return string.Format(CultureInfo.CurrentUICulture, "{0} minutes {1} seconds", span.Minutes, span.Seconds);
}
return string.Format( CultureInfo.CurrentUICulture, "{0} seconds", span.Seconds );
}
public void OnNumberOfStepsCompletedChanged(object sender, EventArgs e)
{
Progress = ((ProgressState) sender).NumberOfStepsCompleted;
//in case there is no event pump showing us (mono-threaded)
progressTimer_Tick(this, null);
Refresh();
}
public void OnTotalNumberOfStepsChanged(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new ProgressCallback(UpdateTotal), new object[] { ((ProgressState)sender).TotalNumberOfSteps });
}
else
{
UpdateTotal(((ProgressState) sender).TotalNumberOfSteps);
}
}
private void UpdateTotal(int steps)
{
_startTime = DateTime.Now;
ProgressRangeMaximum = steps;
Refresh();
}
public void OnStatusLabelChanged(object sender, EventArgs e)
{
StatusText = ((ProgressState)sender).StatusLabel;
Refresh();
}
private void OnStartWorker(object sender, EventArgs e)
{
_workerStarted = true;
Debug.WriteLine("Dialog:StartWorker");
if (_backgroundWorker != null)
{
//BW uses percentages (unless it's using our custom ProgressState in the UserState member)
ProgressRangeMinimum = 0;
ProgressRangeMaximum = 100;
//if the actual task can't take cancelling, the caller of this should set CanCancel to false;
_backgroundWorker.WorkerSupportsCancellation = CanCancel;
_backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(OnBackgroundWorker_ProgressChanged);
_backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnBackgroundWorker_RunWorkerCompleted);
_backgroundWorker.RunWorkerAsync(ProgressState);
}
}
//this is here, in addition to the OnShown handler, because of a weird bug were a certain,
//completely unrelated test (which doesn't use this class at all) can cause tests using this to
//fail because the OnShown event is never fired.
//I don't know why the orginal code we copied this from was using onshown instead of onload,
//but it may have something to do with its "delay show" feature (which I couldn't get to work,
//but which would be a terrific thing to have)
private void ProgressDialog_Load(object sender, EventArgs e)
{
if(!_workerStarted)
{
OnStartWorker(this, null);
}
}
private void ProgressDialog_Shown(object sender, EventArgs e)
{
if(!_workerStarted)
{
OnStartWorker(this, 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.Collections.Generic;
using System.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public class ToLookupTests
{
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void ToLookup(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
ILookup<int, int> lookup = query.ToLookup(x => x * 2);
Assert.All(lookup,
group => { seen.Add(group.Key / 2); Assert.Equal(group.Key, Assert.Single(group) * 2); });
seen.AssertComplete();
Assert.Empty(lookup[-1]);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 128 }), MemberType = typeof(UnorderedSources))]
public static void ToLookup_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
ToLookup(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void ToLookup_ElementSelector(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
ILookup<int, int> lookup = query.ToLookup(x => x, y => y * 2);
Assert.All(lookup,
group => { seen.Add(group.Key); Assert.Equal(group.Key * 2, Assert.Single(group)); });
seen.AssertComplete();
Assert.Empty(lookup[-1]);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 128 }), MemberType = typeof(UnorderedSources))]
public static void ToLookup_ElementSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
ToLookup_ElementSelector(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void ToLookup_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
ILookup<int, int> lookup = query.ToLookup(x => x * 2, new ModularCongruenceComparer(count * 2));
Assert.All(lookup,
group => { seen.Add(group.Key / 2); Assert.Equal(group.Key, Assert.Single(group) * 2); });
seen.AssertComplete();
Assert.Empty(lookup[-1]);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 128 }), MemberType = typeof(UnorderedSources))]
public static void ToLookup_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
ToLookup_CustomComparator(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void ToLookup_ElementSelector_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
ILookup<int, int> lookup = query.ToLookup(x => x, y => y * 2, new ModularCongruenceComparer(count));
Assert.All(lookup,
group => { seen.Add(group.Key); Assert.Equal(group.Key * 2, Assert.Single(group)); });
seen.AssertComplete();
if (count < 1)
{
Assert.Empty(lookup[-1]);
}
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 128 }), MemberType = typeof(UnorderedSources))]
public static void ToLookup_ElementSelector_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
ToLookup_ElementSelector_CustomComparator(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void ToLookup_DuplicateKeys(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seenOuter = new IntegerRangeSet(0, Math.Min(count, 2));
ILookup<int, int> lookup = query.ToLookup(x => x % 2);
Assert.All(lookup,
group =>
{
seenOuter.Add(group.Key);
IntegerRangeSet seenInner = new IntegerRangeSet(0, (count + ((1 + group.Key) % 2)) / 2);
Assert.All(group, y => { Assert.Equal(group.Key, y % 2); seenInner.Add(y / 2); });
seenInner.AssertComplete();
});
seenOuter.AssertComplete();
Assert.Empty(lookup[-1]);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 128 }), MemberType = typeof(UnorderedSources))]
public static void ToLookup_DuplicateKeys_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
ToLookup_DuplicateKeys(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void ToLookup_DuplicateKeys_ElementSelector(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seenOuter = new IntegerRangeSet(0, Math.Min(count, 2));
ILookup<int, int> lookup = query.ToLookup(x => x % 2, y => -y);
Assert.All(lookup,
group =>
{
seenOuter.Add(group.Key);
IntegerRangeSet seenInner = new IntegerRangeSet(0, (count + ((1 + group.Key) % 2)) / 2);
Assert.All(group, y => { Assert.Equal(group.Key, -y % 2); seenInner.Add(-y / 2); });
seenInner.AssertComplete();
});
seenOuter.AssertComplete();
Assert.Empty(lookup[-1]);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 128 }), MemberType = typeof(UnorderedSources))]
public static void ToLookup_DuplicateKeys_ElementSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
ToLookup_DuplicateKeys_ElementSelector(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void ToLookup_DuplicateKeys_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seenOuter = new IntegerRangeSet(0, Math.Min(count, 2));
ILookup<int, int> lookup = query.ToLookup(x => x, new ModularCongruenceComparer(2));
Assert.All(lookup,
group =>
{
seenOuter.Add(group.Key % 2);
IntegerRangeSet seenInner = new IntegerRangeSet(0, (count + ((1 + group.Key) % 2)) / 2);
Assert.All(group, y => { Assert.Equal(group.Key % 2, y % 2); seenInner.Add(y / 2); });
seenInner.AssertComplete();
});
seenOuter.AssertComplete();
if (count < 2)
{
Assert.Empty(lookup[-1]);
}
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 128 }), MemberType = typeof(UnorderedSources))]
public static void ToLookup_DuplicateKeys_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
ToLookup_DuplicateKeys_CustomComparator(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void ToLookup_DuplicateKeys_ElementSelector_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seenOuter = new IntegerRangeSet(0, Math.Min(count, 2));
ILookup<int, int> lookup = query.ToLookup(x => x, y => -y, new ModularCongruenceComparer(2));
Assert.All(lookup,
group =>
{
seenOuter.Add(group.Key % 2);
IntegerRangeSet seenInner = new IntegerRangeSet(0, (count + ((1 + group.Key) % 2)) / 2);
Assert.All(group, y => { Assert.Equal(group.Key % 2, -y % 2); seenInner.Add(-y / 2); });
seenInner.AssertComplete();
});
seenOuter.AssertComplete();
if (count < 2)
{
Assert.Empty(lookup[-1]);
}
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 128 }), MemberType = typeof(UnorderedSources))]
public static void ToLookup_DuplicateKeys_ElementSelector_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
ToLookup_DuplicateKeys_ElementSelector_CustomComparator(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 1 }), MemberType = typeof(UnorderedSources))]
public static void ToLookup_OperationCanceledException_PreCanceled(Labeled<ParallelQuery<int>> labeled, int count)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).ToLookup(x => x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).ToLookup(x => x, EqualityComparer<int>.Default));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).ToLookup(x => x, y => y));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).ToLookup(x => x, y => y, EqualityComparer<int>.Default));
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 1 }), MemberType = typeof(UnorderedSources))]
public static void ToLookup_AggregateException(Labeled<ParallelQuery<int>> labeled, int count)
{
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup((Func<int, int>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup((Func<int, int>)(x => { throw new DeliberateTestException(); }), y => y));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup(x => x, (Func<int, int>)(y => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup((Func<int, int>)(x => { throw new DeliberateTestException(); }), EqualityComparer<int>.Default));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup((Func<int, int>)(x => { throw new DeliberateTestException(); }), y => y, EqualityComparer<int>.Default));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup(x => x, (Func<int, int>)(y => { throw new DeliberateTestException(); }), EqualityComparer<int>.Default));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup(x => x, new FailingEqualityComparer<int>()));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup(x => x, y => y, new FailingEqualityComparer<int>()));
}
[Fact]
public static void ToLookup_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).ToLookup(x => x));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).ToLookup(x => x, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).ToLookup(x => x, y => y));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).ToLookup(x => x, y => y, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToLookup((Func<int, int>)null));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToLookup((Func<int, int>)null, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToLookup((Func<int, int>)null, y => y));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToLookup((Func<int, int>)null, y => y, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToLookup(x => x, (Func<int, int>)null));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToLookup(x => x, (Func<int, int>)null, EqualityComparer<int>.Default));
}
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Compute.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedProjectsClientTest
{
[xunit::FactAttribute]
public void GetRequestObject()
{
moq::Mock<Projects.ProjectsClient> mockGrpcClient = new moq::Mock<Projects.ProjectsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetProjectRequest request = new GetProjectRequest
{
Project = "projectaa6ff846",
};
Project expectedResponse = new Project
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
Quotas = { new Quota(), },
CommonInstanceMetadata = new Metadata(),
XpnProjectStatus = "xpn_project_status547f92f1",
DefaultServiceAccount = "default_service_accountdf12b0f2",
UsageExportLocation = new UsageExportLocation(),
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
EnabledFeatures =
{
"enabled_featuresf1f398e0",
},
DefaultNetworkTier = "default_network_tier69d9d1a9",
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ProjectsClient client = new ProjectsClientImpl(mockGrpcClient.Object, null);
Project response = client.Get(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRequestObjectAsync()
{
moq::Mock<Projects.ProjectsClient> mockGrpcClient = new moq::Mock<Projects.ProjectsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetProjectRequest request = new GetProjectRequest
{
Project = "projectaa6ff846",
};
Project expectedResponse = new Project
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
Quotas = { new Quota(), },
CommonInstanceMetadata = new Metadata(),
XpnProjectStatus = "xpn_project_status547f92f1",
DefaultServiceAccount = "default_service_accountdf12b0f2",
UsageExportLocation = new UsageExportLocation(),
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
EnabledFeatures =
{
"enabled_featuresf1f398e0",
},
DefaultNetworkTier = "default_network_tier69d9d1a9",
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Project>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ProjectsClient client = new ProjectsClientImpl(mockGrpcClient.Object, null);
Project responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Project responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Get()
{
moq::Mock<Projects.ProjectsClient> mockGrpcClient = new moq::Mock<Projects.ProjectsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetProjectRequest request = new GetProjectRequest
{
Project = "projectaa6ff846",
};
Project expectedResponse = new Project
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
Quotas = { new Quota(), },
CommonInstanceMetadata = new Metadata(),
XpnProjectStatus = "xpn_project_status547f92f1",
DefaultServiceAccount = "default_service_accountdf12b0f2",
UsageExportLocation = new UsageExportLocation(),
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
EnabledFeatures =
{
"enabled_featuresf1f398e0",
},
DefaultNetworkTier = "default_network_tier69d9d1a9",
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ProjectsClient client = new ProjectsClientImpl(mockGrpcClient.Object, null);
Project response = client.Get(request.Project);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAsync()
{
moq::Mock<Projects.ProjectsClient> mockGrpcClient = new moq::Mock<Projects.ProjectsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetProjectRequest request = new GetProjectRequest
{
Project = "projectaa6ff846",
};
Project expectedResponse = new Project
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
Quotas = { new Quota(), },
CommonInstanceMetadata = new Metadata(),
XpnProjectStatus = "xpn_project_status547f92f1",
DefaultServiceAccount = "default_service_accountdf12b0f2",
UsageExportLocation = new UsageExportLocation(),
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
EnabledFeatures =
{
"enabled_featuresf1f398e0",
},
DefaultNetworkTier = "default_network_tier69d9d1a9",
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Project>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ProjectsClient client = new ProjectsClientImpl(mockGrpcClient.Object, null);
Project responseCallSettings = await client.GetAsync(request.Project, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Project responseCancellationToken = await client.GetAsync(request.Project, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetXpnHostRequestObject()
{
moq::Mock<Projects.ProjectsClient> mockGrpcClient = new moq::Mock<Projects.ProjectsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetXpnHostProjectRequest request = new GetXpnHostProjectRequest
{
Project = "projectaa6ff846",
};
Project expectedResponse = new Project
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
Quotas = { new Quota(), },
CommonInstanceMetadata = new Metadata(),
XpnProjectStatus = "xpn_project_status547f92f1",
DefaultServiceAccount = "default_service_accountdf12b0f2",
UsageExportLocation = new UsageExportLocation(),
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
EnabledFeatures =
{
"enabled_featuresf1f398e0",
},
DefaultNetworkTier = "default_network_tier69d9d1a9",
};
mockGrpcClient.Setup(x => x.GetXpnHost(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ProjectsClient client = new ProjectsClientImpl(mockGrpcClient.Object, null);
Project response = client.GetXpnHost(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetXpnHostRequestObjectAsync()
{
moq::Mock<Projects.ProjectsClient> mockGrpcClient = new moq::Mock<Projects.ProjectsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetXpnHostProjectRequest request = new GetXpnHostProjectRequest
{
Project = "projectaa6ff846",
};
Project expectedResponse = new Project
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
Quotas = { new Quota(), },
CommonInstanceMetadata = new Metadata(),
XpnProjectStatus = "xpn_project_status547f92f1",
DefaultServiceAccount = "default_service_accountdf12b0f2",
UsageExportLocation = new UsageExportLocation(),
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
EnabledFeatures =
{
"enabled_featuresf1f398e0",
},
DefaultNetworkTier = "default_network_tier69d9d1a9",
};
mockGrpcClient.Setup(x => x.GetXpnHostAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Project>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ProjectsClient client = new ProjectsClientImpl(mockGrpcClient.Object, null);
Project responseCallSettings = await client.GetXpnHostAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Project responseCancellationToken = await client.GetXpnHostAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetXpnHost()
{
moq::Mock<Projects.ProjectsClient> mockGrpcClient = new moq::Mock<Projects.ProjectsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetXpnHostProjectRequest request = new GetXpnHostProjectRequest
{
Project = "projectaa6ff846",
};
Project expectedResponse = new Project
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
Quotas = { new Quota(), },
CommonInstanceMetadata = new Metadata(),
XpnProjectStatus = "xpn_project_status547f92f1",
DefaultServiceAccount = "default_service_accountdf12b0f2",
UsageExportLocation = new UsageExportLocation(),
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
EnabledFeatures =
{
"enabled_featuresf1f398e0",
},
DefaultNetworkTier = "default_network_tier69d9d1a9",
};
mockGrpcClient.Setup(x => x.GetXpnHost(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ProjectsClient client = new ProjectsClientImpl(mockGrpcClient.Object, null);
Project response = client.GetXpnHost(request.Project);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetXpnHostAsync()
{
moq::Mock<Projects.ProjectsClient> mockGrpcClient = new moq::Mock<Projects.ProjectsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetXpnHostProjectRequest request = new GetXpnHostProjectRequest
{
Project = "projectaa6ff846",
};
Project expectedResponse = new Project
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
Quotas = { new Quota(), },
CommonInstanceMetadata = new Metadata(),
XpnProjectStatus = "xpn_project_status547f92f1",
DefaultServiceAccount = "default_service_accountdf12b0f2",
UsageExportLocation = new UsageExportLocation(),
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
EnabledFeatures =
{
"enabled_featuresf1f398e0",
},
DefaultNetworkTier = "default_network_tier69d9d1a9",
};
mockGrpcClient.Setup(x => x.GetXpnHostAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Project>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ProjectsClient client = new ProjectsClientImpl(mockGrpcClient.Object, null);
Project responseCallSettings = await client.GetXpnHostAsync(request.Project, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Project responseCancellationToken = await client.GetXpnHostAsync(request.Project, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
namespace ToolKit.Cryptography
{
/// <summary>
/// Represents Hex, Byte, Base64, or String data to encrypt/decrypt; use the .Text property to
/// set/get a string representation use the .Hex property to set/get a string-based Hexadecimal
/// representation use the .Base64 to set/get a string-based Base64 representation.
/// </summary>
/// <remarks>
/// Adapted from code originally written by Jeff Atwood. The original code had no explicit
/// license attached to it. If licensing is a concern, you should contact the original author.
/// </remarks>
public sealed class EncryptionData : IEquatable<EncryptionData>
{
private byte[] _byteData;
/// <summary>
/// Initializes a new instance of the <see cref="EncryptionData"/> class.
/// </summary>
public EncryptionData()
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the <see cref="EncryptionData"/> class.
/// </summary>
/// <param name="data">A byte array containing the data.</param>
public EncryptionData(byte[] data)
{
Initialize();
_byteData = data;
}
/// <summary>
/// Initializes a new instance of the <see cref="EncryptionData"/> class.
/// </summary>
/// <param name="data">A string containing the data.</param>
public EncryptionData(string data)
{
Initialize();
Text = data;
}
/// <summary>
/// Initializes a new instance of the <see cref="EncryptionData"/> class.
/// </summary>
/// <param name="data">A string containing the data.</param>
/// <param name="encoding">The encoding to use to convert the string to a byte array.</param>
public EncryptionData(string data, Encoding encoding)
{
Initialize();
EncodingToUse = encoding;
Text = data;
}
/// <summary>
/// Gets or sets the Base64 string representation of this data.
/// </summary>
/// <value>The Base64 string representation of this data.</value>
public string Base64
{
get => Base64Encoding.ToString(Bytes);
set => Bytes = Base64Encoding.ToBytes(value);
}
/// <summary>
/// Gets or sets the byte representation of the data.
/// </summary>
/// <value>
/// The byte representation of the data; This will be padded to MinBytes and trimmed to
/// MaxBytes as necessary.
/// </value>
[SuppressMessage(
"Performance",
"CA1819:Properties should not return arrays",
Justification = "Not Going To Change This.")]
public byte[] Bytes
{
get
{
if ((MaximumBytes > 0) && (_byteData.Length > MaximumBytes))
{
var b = new byte[MaximumBytes];
Array.Copy(_byteData, b, b.Length);
_byteData = b;
}
if ((MinimumBytes > 0) && (_byteData.Length < MinimumBytes))
{
var b = new byte[MinimumBytes];
Array.Copy(_byteData, b, _byteData.Length);
_byteData = b;
}
return _byteData;
}
set => _byteData = value;
}
/// <summary>
/// Gets or sets the text encoding for this instance.
/// </summary>
public Encoding EncodingToUse { get; set; }
/// <summary>
/// Gets or sets the Hex string representation of this data.
/// </summary>
/// <value>The Hex string representation of this data.</value>
public string Hex
{
get => HexEncoding.ToString(Bytes);
set => Bytes = HexEncoding.ToBytes(value);
}
/// <summary>
/// Gets a value indicating whether this instance is empty.
/// </summary>
/// <value><c>true</c> if no data is present; otherwise, <c>false</c>.</value>
public bool IsEmpty => Bytes == null || Bytes.Length == 0;
/// <summary>
/// Gets or sets the maximum number of bits allowed for this data.
/// </summary>
/// <value>The he maximum number of bits allowed for this data; if 0, no limit.</value>
public int MaximumBits
{
get => MaximumBytes * 8;
set => MaximumBytes = value / 8;
}
/// <summary>
/// Gets or sets the maximum number of bytes allowed for this data.
/// </summary>
/// <value>The maximum number of bytes allowed for this data; if 0, no limit.</value>
public int MaximumBytes { get; set; }
/// <summary>
/// Gets or sets the minimum number of bits allowed for this data.
/// </summary>
/// <value>The he minimum number of bits allowed for this data; if 0, no limit.</value>
public int MinimumBits
{
get => MinimumBytes * 8;
set => MinimumBytes = value / 8;
}
/// <summary>
/// Gets or sets the minimum number of bytes allowed for this data.
/// </summary>
/// <value>The he minimum number of bytes allowed for this data; if 0, no limit.</value>
public int MinimumBytes { get; set; }
/// <summary>
/// Gets or sets the text representation of bytes using the text encoding assigned to this instance.
/// </summary>
/// <value>The text representation of bytes.</value>
public string Text
{
get
{
if (Bytes == null)
{
return string.Empty;
}
// Need to handle nulls here; oddly, C# will happily convert nulls into the string
// whereas VB stops converting at the first null.
var i = Array.IndexOf(Bytes, Convert.ToByte(0));
return i >= 0 ? EncodingToUse.GetString(Bytes, 0, i) : EncodingToUse.GetString(Bytes);
}
set => Bytes = EncodingToUse.GetBytes(value);
}
/// <summary>
/// Determines if two instances of EncryptionData instances are not equal.
/// </summary>
/// <param name="left">The left <see cref="EncryptionData"/> instance.</param>
/// <param name="right">The right <see cref="EncryptionData"/> instance.</param>
/// <returns><c>true</c> if the two instances are not equal.</returns>
public static bool operator !=(EncryptionData left, EncryptionData right) => !Equals(left, right);
/// <summary>
/// Determines if two instances of EncryptionData instances are equal.
/// </summary>
/// <param name="left">The left <see cref="EncryptionData"/> instance.</param>
/// <param name="right">The right <see cref="EncryptionData"/> instance.</param>
/// <returns><c>true</c> if the two instances are equal.</returns>
public static bool operator ==(EncryptionData left, EncryptionData right) => Equals(left, right);
/// <inheritdoc/>
public bool Equals(EncryptionData other) =>
!(other is null) && (ReferenceEquals(this, other) || _byteData.SequenceEqual(other.Bytes));
/// <inheritdoc/>
public override bool Equals(object obj) => obj is EncryptionData encryptionData && Equals(encryptionData);
/// <inheritdoc/>
[SuppressMessage("ReSharper", "NonReadonlyMemberInGetHashCode", Justification = "It's ok to have a non-read only member in this case.")]
#pragma warning disable S2328 // "GetHashCode" should not reference mutable fields
public override int GetHashCode() =>
#pragma warning restore S2328 // "GetHashCode" should not reference mutable fields
_byteData == null
? 0
: (37 * (_byteData[0] + _byteData.Length)) +
_byteData[_byteData.Length - 1] + _byteData.Length;
/// <summary>
/// returns Base64 string representation of this data.
/// </summary>
/// <returns>a Base64 string representation of this data.</returns>
public string ToBase64() => Base64;
/// <summary>
/// returns Hex string representation of this data.
/// </summary>
/// <returns>a hex string representation of this data.</returns>
public string ToHex() => Hex;
/// <summary>
/// Returns text representation of bytes using the default text encoding.
/// </summary>
/// <returns>A <see cref="string"/> that represents this instance.</returns>
public override string ToString() => Text;
private void Initialize()
{
MinimumBytes = 0;
MaximumBytes = 0;
EncodingToUse = Encoding.UTF8;
}
}
}
| |
/* ****************************************************************************
*
* 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 !CLR2
using System.Globalization;
using System.Linq.Expressions;
#else
using Microsoft.Scripting.Ast;
#endif
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace System.Management.Automation.Interpreter
{
internal sealed class LocalVariable
{
private const int IsBoxedFlag = 1;
private const int InClosureFlag = 2;
public readonly int Index;
private int _flags;
public bool IsBoxed
{
get
{
return (_flags & IsBoxedFlag) != 0;
}
set
{
if (value)
{
_flags |= IsBoxedFlag;
}
else
{
_flags &= ~IsBoxedFlag;
}
}
}
public bool InClosure
{
get { return (_flags & InClosureFlag) != 0; }
}
public bool InClosureOrBoxed
{
get { return InClosure || IsBoxed; }
}
internal LocalVariable(int index, bool closure, bool boxed)
{
Index = index;
_flags = (closure ? InClosureFlag : 0) | (boxed ? IsBoxedFlag : 0);
}
internal Expression LoadFromArray(Expression frameData, Expression closure)
{
Expression result = Expression.ArrayAccess(InClosure ? closure : frameData, Expression.Constant(Index));
return IsBoxed ? Expression.Convert(result, typeof(StrongBox<object>)) : result;
}
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "{0}: {1} {2}", Index, IsBoxed ? "boxed" : null, InClosure ? "in closure" : null);
}
}
internal readonly struct LocalDefinition
{
private readonly int _index;
private readonly ParameterExpression _parameter;
internal LocalDefinition(int localIndex, ParameterExpression parameter)
{
_index = localIndex;
_parameter = parameter;
}
public int Index
{
get
{
return _index;
}
}
public ParameterExpression Parameter
{
get
{
return _parameter;
}
}
public override bool Equals(object obj)
{
if (obj is LocalDefinition)
{
LocalDefinition other = (LocalDefinition)obj;
return other.Index == Index && other.Parameter == Parameter;
}
return false;
}
public override int GetHashCode()
{
if (_parameter == null)
{
return 0;
}
return _parameter.GetHashCode() ^ _index.GetHashCode();
}
public static bool operator ==(LocalDefinition self, LocalDefinition other)
{
return self.Index == other.Index && self.Parameter == other.Parameter;
}
public static bool operator !=(LocalDefinition self, LocalDefinition other)
{
return self.Index != other.Index || self.Parameter != other.Parameter;
}
}
internal sealed class LocalVariables
{
private readonly HybridReferenceDictionary<ParameterExpression, VariableScope> _variables = new HybridReferenceDictionary<ParameterExpression, VariableScope>();
private Dictionary<ParameterExpression, LocalVariable> _closureVariables;
private int _localCount, _maxLocalCount;
internal LocalVariables()
{
}
public LocalDefinition DefineLocal(ParameterExpression variable, int start)
{
// ContractUtils.RequiresNotNull(variable, "variable");
// ContractUtils.Requires(start >= 0, "start", "start must be positive");
LocalVariable result = new LocalVariable(_localCount++, false, false);
_maxLocalCount = System.Math.Max(_localCount, _maxLocalCount);
VariableScope existing, newScope;
if (_variables.TryGetValue(variable, out existing))
{
newScope = new VariableScope(result, start, existing);
if (existing.ChildScopes == null)
{
existing.ChildScopes = new List<VariableScope>();
}
existing.ChildScopes.Add(newScope);
}
else
{
newScope = new VariableScope(result, start, null);
}
_variables[variable] = newScope;
return new LocalDefinition(result.Index, variable);
}
public void UndefineLocal(LocalDefinition definition, int end)
{
var scope = _variables[definition.Parameter];
scope.Stop = end;
if (scope.Parent != null)
{
_variables[definition.Parameter] = scope.Parent;
}
else
{
_variables.Remove(definition.Parameter);
}
_localCount--;
}
internal void Box(ParameterExpression variable, InstructionList instructions)
{
var scope = _variables[variable];
LocalVariable local = scope.Variable;
Debug.Assert(!local.IsBoxed && !local.InClosure);
_variables[variable].Variable.IsBoxed = true;
int curChild = 0;
for (int i = scope.Start; i < scope.Stop && i < instructions.Count; i++)
{
if (scope.ChildScopes != null && scope.ChildScopes[curChild].Start == i)
{
// skip boxing in the child scope
var child = scope.ChildScopes[curChild];
i = child.Stop;
curChild++;
continue;
}
instructions.SwitchToBoxed(local.Index, i);
}
}
public int LocalCount
{
get { return _maxLocalCount; }
}
public int GetOrDefineLocal(ParameterExpression var)
{
int index = GetLocalIndex(var);
if (index == -1)
{
return DefineLocal(var, 0).Index;
}
return index;
}
public int GetLocalIndex(ParameterExpression var)
{
VariableScope loc;
return _variables.TryGetValue(var, out loc) ? loc.Variable.Index : -1;
}
public bool TryGetLocalOrClosure(ParameterExpression var, out LocalVariable local)
{
VariableScope scope;
if (_variables.TryGetValue(var, out scope))
{
local = scope.Variable;
return true;
}
if (_closureVariables != null && _closureVariables.TryGetValue(var, out local))
{
return true;
}
local = null;
return false;
}
/// <summary>
/// Gets a copy of the local variables which are defined in the current scope.
/// </summary>
/// <returns></returns>
internal Dictionary<ParameterExpression, LocalVariable> CopyLocals()
{
var res = new Dictionary<ParameterExpression, LocalVariable>(_variables.Count);
foreach (var keyValue in _variables)
{
res[keyValue.Key] = keyValue.Value.Variable;
}
return res;
}
/// <summary>
/// Checks to see if the given variable is defined within the current local scope.
/// </summary>
internal bool ContainsVariable(ParameterExpression variable)
{
return _variables.ContainsKey(variable);
}
/// <summary>
/// Gets the variables which are defined in an outer scope and available within the current scope.
/// </summary>
internal Dictionary<ParameterExpression, LocalVariable> ClosureVariables
{
get
{
return _closureVariables;
}
}
internal LocalVariable AddClosureVariable(ParameterExpression variable)
{
if (_closureVariables == null)
{
_closureVariables = new Dictionary<ParameterExpression, LocalVariable>();
}
LocalVariable result = new LocalVariable(_closureVariables.Count, true, false);
_closureVariables.Add(variable, result);
return result;
}
/// <summary>
/// Tracks where a variable is defined and what range of instructions it's used in.
/// </summary>
private sealed class VariableScope
{
public readonly int Start;
public int Stop = Int32.MaxValue;
public readonly LocalVariable Variable;
public readonly VariableScope Parent;
public List<VariableScope> ChildScopes;
public VariableScope(LocalVariable variable, int start, VariableScope parent)
{
Variable = variable;
Start = start;
Parent = parent;
}
}
}
}
| |
using System;
using System.Xml.Serialization;
using System.Xml.Schema;
namespace RtmNet
{
/// <summary>
/// Contains a list of <see cref="Contact"/> items for a given user.
/// </summary>
[System.Serializable]
public class Tasks
{
/// <summary>
/// An array of <see cref="Contact"/> items for the user.
/// </summary>
[XmlElement("list", Form=XmlSchemaForm.Unqualified)]
public List[] ListCollection = new List[0];
}
/// <remarks/>
[System.Serializable]
public class TaskSeries
{
private string id = System.Guid.NewGuid().ToString();
private string name;
private string rawCreated;
private string rawModified;
private DateTime created = DateTime.MinValue;
private DateTime modified = DateTime.MinValue;
/// <remarks/>
[XmlAttribute("id", Form=XmlSchemaForm.Unqualified)]
public string TaskID { get { return id; } set { id = value; } }
/// <remarks/>
[XmlAttribute("created", Form=XmlSchemaForm.Unqualified)]
public string RawCreated
{
get { return rawCreated; }
set {
if(value.Length > 0) {
rawCreated = value;
created = Utils.DateStringToDateTime(rawCreated);
}
}
}
/// <summary>
/// Converts the raw created field to a <see cref="DateTime"/>.
/// </summary>
[XmlIgnore]
public DateTime Created
{
get { return created; }
set { created = value; }
}
/// <remarks/>
[XmlAttribute("modified", Form=XmlSchemaForm.Unqualified)]
public string RawModified
{
get { return rawModified; }
set {
if(value.Length > 0) {
rawModified = value;
modified = Utils.DateStringToDateTime(rawModified);
}
}
}
/// <summary>
/// Converts the raw modified field to a <see cref="DateTime"/>.
/// </summary>
[XmlIgnore]
public DateTime Modified
{
get { return modified; }
set { modified = value; }
}
/// <remarks/>
[XmlAttribute("name", Form=XmlSchemaForm.Unqualified)]
public string Name { get { return name; } set { name = value; } }
/// <remarks/>
[XmlAttribute("source", Form=XmlSchemaForm.Unqualified)]
public string source;
[XmlElement("task", Form=XmlSchemaForm.Unqualified)]
public Task Task;
/// <remarks/>
[XmlElement("notes", Form=XmlSchemaForm.Unqualified)]
public Notes Notes;
}
/// <remarks/>
[System.Serializable]
public class Task
{
private string id;
private string rawDue;
private string rawAdded;
private string rawCompleted;
private string rawDeleted;
private DateTime due = DateTime.MinValue;
private DateTime added = DateTime.MinValue;
private DateTime completed = DateTime.MinValue;
private DateTime deleted = DateTime.MinValue;
/// <remarks/>
[XmlAttribute("id", Form=XmlSchemaForm.Unqualified)]
public string TaskID { get { return id; } set { id = value; } }
/// <remarks/>
[XmlAttribute("due", Form=XmlSchemaForm.Unqualified)]
public string RawDue
{
get { return rawDue; }
set {
if(value.Length > 0) {
rawDue = value;
due = Utils.DateStringToDateTime(rawDue);
}
}
}
/// <summary>
/// Converts the raw created field to a <see cref="DateTime"/>.
/// </summary>
[XmlIgnore]
public DateTime Due
{
get { return due; }
set { due = value; }
}
/// <summary>
/// Is this contact marked as a friend contact?
/// </summary>
[XmlAttribute("has_due_time", Form=XmlSchemaForm.Unqualified)]
public int HasDueTime;
/// <remarks/>
[XmlAttribute("added", Form=XmlSchemaForm.Unqualified)]
public string RawAdded
{
get { return rawAdded; }
set {
if(value.Length > 0) {
rawAdded = value;
added = Utils.DateStringToDateTime(rawAdded);
}
}
}
/// <value>
/// Holds the date time for when the task was added
/// </value>
[XmlIgnore]
public DateTime Added
{
get { return added; }
set { added = value; }
}
/// <remarks/>
[XmlAttribute("completed", Form=XmlSchemaForm.Unqualified)]
public string RawCompleted
{
get { return rawCompleted; }
set {
if(value.Length > 0) {
rawCompleted = value;
completed = Utils.DateStringToDateTime(rawCompleted);
}
}
}
/// <summary>
/// Converts the raw created field to a <see cref="DateTime"/>.
/// </summary>
[XmlIgnore]
public DateTime Completed
{
get { return completed; }
set { completed = value; }
}
/// <remarks/>
[XmlAttribute("deleted", Form=XmlSchemaForm.Unqualified)]
public string RawDeleted
{
get { return rawDeleted; }
set {
if(value.Length > 0) {
rawDeleted = value;
deleted = Utils.DateStringToDateTime(rawDeleted);
}
}
}
/// <summary>
/// Converts the raw created field to a <see cref="DateTime"/>.
/// </summary>
[XmlIgnore]
public DateTime Deleted
{
get { return deleted; }
set { deleted = value; }
}
/// <remarks/>
[XmlAttribute("priority", Form=XmlSchemaForm.Unqualified)]
public string Priority;
/// <remarks/>
[XmlAttribute("postponed", Form=XmlSchemaForm.Unqualified)]
public string Postponed;
/// <remarks/>
[XmlAttribute("estimate", Form=XmlSchemaForm.Unqualified)]
public string Estimate;
}
}
| |
// Copyright 2020, Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Cloud.Spanner.Data;
using Google.Cloud.Spanner.V1;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace Google.Cloud.EntityFrameworkCore.Spanner.Storage.Internal
{
/// <summary>
/// This is internal functionality and not intended for public use.
/// </summary>
public class SpannerTypeMappingSource : RelationalTypeMappingSource
{
internal const int StringMax = 2621440;
internal const int BytesMax = 10485760;
// --- Non-array types ---
private static readonly BoolTypeMapping s_bool
= new SpannerBoolTypeMapping(SpannerDbType.Bool.ToString());
private static readonly SpannerDateTypeMapping s_date = new SpannerDateTypeMapping();
private static readonly SpannerTimestampTypeMapping s_datetime = new SpannerTimestampTypeMapping();
private static readonly StringTypeMapping s_defaultString
= new SpannerStringTypeMapping(SpannerDbType.String.ToString(), unicode: true, sqlDbType: SpannerDbType.String);
private static readonly CharTypeMapping s_char
= new CharTypeMapping("STRING(1)", DbType.String);
private static readonly SpannerComplexTypeMapping s_float =
new SpannerComplexTypeMapping(SpannerDbType.Float64, typeof(float));
private static readonly DoubleTypeMapping s_double = new SpannerDoubleTypeMapping();
private static readonly SpannerComplexTypeMapping s_int =
new SpannerComplexTypeMapping(SpannerDbType.Int64, typeof(int));
private static readonly LongTypeMapping s_long
= new LongTypeMapping(SpannerDbType.Int64.ToString(), DbType.Int64);
private static readonly SpannerComplexTypeMapping s_uint
= new SpannerComplexTypeMapping(SpannerDbType.Int64, typeof(uint));
private static readonly SpannerComplexTypeMapping s_short
= new SpannerComplexTypeMapping(SpannerDbType.Int64, typeof(short));
private static readonly SpannerNumericTypeMapping s_numeric = new SpannerNumericTypeMapping();
private static readonly SpannerJsonTypeMapping s_json = new SpannerJsonTypeMapping();
private static readonly SpannerGuidTypeMapping s_guid
= new SpannerGuidTypeMapping("STRING(36)", DbType.String);
private static readonly SpannerComplexTypeMapping s_byte
= new SpannerComplexTypeMapping(SpannerDbType.Int64, typeof(byte));
private static readonly SpannerComplexTypeMapping s_sbyte
= new SpannerComplexTypeMapping(SpannerDbType.Int64, typeof(sbyte));
private static readonly SpannerComplexTypeMapping s_ulong
= new SpannerComplexTypeMapping(SpannerDbType.Int64, typeof(ulong));
private static readonly SpannerComplexTypeMapping s_ushort
= new SpannerComplexTypeMapping(SpannerDbType.Int64, typeof(ushort));
private static readonly ByteArrayTypeMapping s_bytes
= new ByteArrayTypeMapping(SpannerDbType.Bytes.ToString(), DbType.Binary);
// --- Array Types ---
private static readonly SpannerComplexTypeMapping s_byteArray
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.Bytes), typeof(byte[][]));
private static readonly SpannerComplexTypeMapping s_byteList
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.Bytes), typeof(List<byte[]>));
private static readonly SpannerComplexTypeMapping s_stringArray
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.String), typeof(string[]), true);
private static readonly SpannerComplexTypeMapping s_stringList
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.String), typeof(List<string>), true);
private static readonly SpannerComplexTypeMapping s_nullableBoolArray
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.Bool), typeof(bool?[]));
private static readonly SpannerComplexTypeMapping s_boolArray
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.Bool), typeof(bool[]));
private static readonly SpannerComplexTypeMapping s_nullableBoolList
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.Bool), typeof(List<bool?>));
private static readonly SpannerComplexTypeMapping s_boolList
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.Bool), typeof(List<bool>));
private static readonly SpannerComplexTypeMapping s_nullableDoubleArray
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.Float64), typeof(double?[]));
private static readonly SpannerComplexTypeMapping s_doubleArray
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.Float64), typeof(double[]));
private static readonly SpannerComplexTypeMapping s_nullableDoubleList
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.Float64), typeof(List<double?>));
private static readonly SpannerComplexTypeMapping s_doubleList
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.Float64), typeof(List<double>));
private static readonly SpannerComplexTypeMapping s_nullableLongArray
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.Int64), typeof(long?[]));
private static readonly SpannerComplexTypeMapping s_longArray
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.Int64), typeof(long[]));
private static readonly SpannerComplexTypeMapping s_nullableLongList
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.Int64), typeof(List<long?>));
private static readonly SpannerComplexTypeMapping s_longList
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.Int64), typeof(List<long>));
private static readonly SpannerNullableDateArrayTypeMapping s_nullableDateArray = new SpannerNullableDateArrayTypeMapping();
private static readonly SpannerDateArrayTypeMapping s_dateArray = new SpannerDateArrayTypeMapping();
private static readonly SpannerNullableDateListTypeMapping s_nullableDateList = new SpannerNullableDateListTypeMapping();
private static readonly SpannerDateListTypeMapping s_dateList = new SpannerDateListTypeMapping();
private static readonly SpannerComplexTypeMapping s_nullableTimestampArray
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.Timestamp), typeof(DateTime?[]));
private static readonly SpannerComplexTypeMapping s_timestampArray
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.Timestamp), typeof(DateTime[]));
private static readonly SpannerComplexTypeMapping s_nullableTimestampList
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.Timestamp), typeof(List<DateTime?>));
private static readonly SpannerComplexTypeMapping s_timestampList
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.Timestamp), typeof(List<DateTime>));
private static readonly SpannerComplexTypeMapping s_nullableNumericArray
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.Numeric), typeof(SpannerNumeric?[]));
private static readonly SpannerComplexTypeMapping s_numericArray
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.Numeric), typeof(SpannerNumeric[]));
private static readonly SpannerComplexTypeMapping s_nullableNumericList
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.Numeric), typeof(List<SpannerNumeric?>));
private static readonly SpannerComplexTypeMapping s_numericList
= new SpannerComplexTypeMapping(SpannerDbType.ArrayOf(SpannerDbType.Numeric), typeof(List<SpannerNumeric>));
private static readonly SpannerJsonArrayTypeMapping s_jsonArray = new SpannerJsonArrayTypeMapping();
private static readonly SpannerJsonListTypeMapping s_jsonList = new SpannerJsonListTypeMapping();
private readonly Dictionary<System.Type, RelationalTypeMapping> _clrTypeMappings;
private readonly Dictionary<string, RelationalTypeMapping> _storeTypeMappings;
private readonly Dictionary<string, RelationalTypeMapping> _arrayTypeMappings;
public SpannerTypeMappingSource(
TypeMappingSourceDependencies dependencies,
RelationalTypeMappingSourceDependencies relationalDependencies)
: base(dependencies, relationalDependencies)
{
_clrTypeMappings
= new Dictionary<System.Type, RelationalTypeMapping>
{
{typeof(short), s_short},
{typeof(int), s_int},
{typeof(long), s_long},
{typeof(decimal), s_numeric},
{typeof(SpannerNumeric), s_numeric},
{typeof(JsonDocument), s_json},
{typeof(uint), s_uint},
{typeof(bool), s_bool},
{typeof(SpannerDate), s_date},
{typeof(DateTime), s_datetime},
{typeof(float), s_float},
{typeof(double), s_double},
{typeof(string), s_defaultString},
{typeof(char), s_char},
{typeof(Guid), s_guid},
{typeof(Regex), s_defaultString },
{typeof(byte), s_byte},
{typeof(sbyte), s_sbyte},
{typeof(ulong), s_ulong},
{typeof(ushort), s_ushort},
{typeof(byte[]), s_bytes},
{typeof(decimal[]), s_numericArray},
{typeof(decimal?[]), s_nullableNumericArray},
{typeof(SpannerNumeric[]), s_numericArray},
{typeof(SpannerNumeric?[]), s_nullableNumericArray},
{typeof(List<decimal>), s_numericList},
{typeof(List<decimal?>), s_nullableNumericList},
{typeof(List<SpannerNumeric>), s_numericList},
{typeof(List<SpannerNumeric?>), s_nullableNumericList},
{typeof(JsonDocument[]), s_jsonArray},
{typeof(List<JsonDocument>), s_jsonList},
{typeof(string[]), s_stringArray},
{typeof(List<string>), s_stringList},
{typeof(bool[]), s_boolArray},
{typeof(bool?[]), s_nullableBoolArray},
{typeof(List<bool>), s_boolList},
{typeof(List<bool?>), s_nullableBoolList},
{typeof(double[]), s_doubleArray},
{typeof(double?[]), s_nullableDoubleArray},
{typeof(List<double>), s_doubleList},
{typeof(List<double?>), s_nullableDoubleList},
{typeof(long[]), s_longArray},
{typeof(long?[]), s_nullableLongArray},
{typeof(List<long>), s_longList},
{typeof(List<long?>), s_nullableLongList},
{typeof(SpannerDate[]), s_dateArray},
{typeof(SpannerDate?[]), s_nullableDateArray},
{typeof(List<SpannerDate>), s_dateList},
{typeof(List<SpannerDate?>), s_nullableDateList},
{typeof(List<DateTime>), s_timestampList},
{typeof(List<DateTime?>), s_nullableTimestampList},
{typeof(DateTime[]), s_timestampArray},
{typeof(DateTime?[]), s_nullableTimestampArray},
{typeof(byte[][]), s_byteArray},
{typeof(List<byte[]>), s_byteList},
};
_storeTypeMappings = new Dictionary<string, RelationalTypeMapping>
{
{SpannerDbType.Bool.ToString(), s_bool},
{SpannerDbType.Bytes.ToString(), s_bytes},
{SpannerDbType.Date.ToString(), s_date},
{SpannerDbType.Float64.ToString(), s_double},
{SpannerDbType.Int64.ToString(), s_long},
{SpannerDbType.Timestamp.ToString(), s_datetime},
{SpannerDbType.String.ToString(), s_defaultString},
{SpannerDbType.Numeric.ToString(), s_numeric},
{SpannerDbType.Json.ToString(), s_json},
{"ARRAY<BOOL>", s_nullableBoolList},
{"ARRAY<BYTES", s_byteList},
{"ARRAY<DATE>", s_nullableDateList},
{"ARRAY<FLOAT64>", s_nullableDoubleList},
{"ARRAY<INT64>", s_nullableLongList},
{"ARRAY<STRING", s_stringList},
{"ARRAY<TIMESTAMP>", s_nullableTimestampList},
{"ARRAY<NUMERIC>", s_nullableNumericList},
{"ARRAY<JSON>", s_jsonList}
};
_arrayTypeMappings = new Dictionary<string, RelationalTypeMapping>
{
{"ARRAY<BOOL>", s_nullableBoolArray},
{"ARRAY<BYTES", s_byteArray},
{"ARRAY<DATE>", s_nullableDateArray},
{"ARRAY<FLOAT64>", s_nullableDoubleArray},
{"ARRAY<INT64>", s_nullableLongArray},
{"ARRAY<STRING", s_stringArray},
{"ARRAY<TIMESTAMP>", s_nullableTimestampArray},
{"ARRAY<NUMERIC>", s_nullableNumericArray},
{"ARRAY<JSON>", s_jsonArray}
};
}
protected override RelationalTypeMapping FindMapping(in RelationalTypeMappingInfo mappingInfo)
=> FindRawMapping(mappingInfo)?.Clone(mappingInfo)
?? base.FindMapping(mappingInfo);
private RelationalTypeMapping FindRawMapping(RelationalTypeMappingInfo mappingInfo)
{
var clrType = mappingInfo.ClrType;
var storeTypeName = mappingInfo.StoreTypeName;
var storeTypeNameBase = mappingInfo.StoreTypeNameBase;
if (storeTypeName != null)
{
if (_storeTypeMappings.TryGetValue(storeTypeName, out var mapping)
|| _storeTypeMappings.TryGetValue(storeTypeNameBase, out mapping))
{
if (clrType == null
|| mapping.ClrType == clrType
|| mapping.Converter?.ProviderClrType == clrType)
{
return mapping;
}
if (_arrayTypeMappings.TryGetValue(storeTypeName, out var arrayMapping)
|| _arrayTypeMappings.TryGetValue(storeTypeNameBase, out arrayMapping))
{
if (arrayMapping.ClrType == clrType
|| arrayMapping.Converter?.ProviderClrType == clrType)
{
return arrayMapping;
}
}
}
if (TryFindConverterMapping(storeTypeName, clrType, out mapping))
{
return mapping;
}
}
if (clrType != null)
{
if (_clrTypeMappings.TryGetValue(clrType, out var mapping))
{
return mapping;
}
}
return null;
}
private bool TryFindConverterMapping(string storeType, System.Type clrType, out RelationalTypeMapping mapping)
{
foreach (var m in _clrTypeMappings.Values)
{
if (m.Converter?.ProviderClrType == clrType && m.StoreType == storeType)
{
mapping = m;
return true;
}
}
mapping = null;
return false;
}
}
}
| |
using XPT.Games.Generic.Constants;
using XPT.Games.Generic.Maps;
using XPT.Games.Twinion.Entities;
namespace XPT.Games.Twinion.Maps {
class TwMap11 : TwMap {
public override int MapIndex => 11;
public override int MapID => 0x0501;
protected override int RandomEncounterChance => 5;
protected override int RandomEncounterExtraCount => 1;
private const int LAKE = 1;
protected override void FnEvent01(TwPlayerServer player, MapEventType type, bool doMsgs) {
DisableHealing(player, type, doMsgs);
if ((GetFlag(player, type, doMsgs, FlagTypeTile, LAKE) == 0)) {
DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs) / 4);
ShowText(player, type, doMsgs, "The waters drain your life energy.");
SetFlag(player, type, doMsgs, FlagTypeTile, LAKE, 1);
}
}
protected override void FnEvent02(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasItem(player, type, doMsgs, LIFEJACKET)) {
ShowText(player, type, doMsgs, "The Life Jacket keeps you from drowning.");
}
else {
ShowText(player, type, doMsgs, "The platform buckles under your weight.");
ShowText(player, type, doMsgs, "Your foot is snared by the sinking platform and you are dragged to the bottom of the lake.");
DamXit(player, type, doMsgs);
}
}
protected override void FnEvent03(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "What appeared to be a platform is actually the back of a giant underwater creature.");
if (HasItem(player, type, doMsgs, LIFEJACKET)) {
ShowText(player, type, doMsgs, "He is awakened by your weight on his back and plunges deep into the lake, taking you to the bottom with him.");
ShowText(player, type, doMsgs, "You have drowned!");
DamXit(player, type, doMsgs);
}
else {
ShowText(player, type, doMsgs, "However, he remains asleep and offers you a stable stepping stone.");
}
}
protected override void FnEvent04(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Beyond the door are stairs leading down to the Cellar.");
TeleportParty(player, type, doMsgs, 6, 1, 8, Direction.South);
}
protected override void FnEvent05(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You step into a stream of lava.");
DamXit(player, type, doMsgs);
}
protected override void FnEvent06(TwPlayerServer player, MapEventType type, bool doMsgs) {
TeleportParty(player, type, doMsgs, 6, 1, 89, Direction.South);
}
protected override void FnEvent07(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, FOUNTAIN);
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.HERBAL) == 1) {
HealFtn(player, type, doMsgs);
ShowText(player, type, doMsgs, "The medicinal waters of Herbal Fountain heal you and renew your spell casting powers.");
}
else {
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.HERBAL, 1);
HealFtn(player, type, doMsgs);
if (GetGuild(player, type, doMsgs) == RANGER) {
GiveSpell(player, type, doMsgs, LIGHTNING_SPELL, 1);
ShowText(player, type, doMsgs, "The medicinal waters of Herbal Fountain heal you, renew your spell casting powers and endow you with the Lightning spell.");
}
else {
GiveSpell(player, type, doMsgs, CURE_SPELL, 1);
ShowText(player, type, doMsgs, "The medicinal waters of Herbal Fountain heal you, renew your spell casting powers and endow you with the Cure spell.");
}
}
}
protected override void FnEvent08(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PARCHMENT_MAP) == 1) {
if (HasItem(player, type, doMsgs, PARCHMENTMAP)) {
ShowText(player, type, doMsgs, "The heat from the lava is almost unbearable.");
}
else {
GiveItem(player, type, doMsgs, PARCHMENTMAP);
ShowText(player, type, doMsgs, "You detect signs of a struggle on the ground near a torn parchment.");
ShowText(player, type, doMsgs, "It is one of the four maps the Queen asked you to find.");
}
}
else {
GiveItem(player, type, doMsgs, PARCHMENTMAP);
ModifyExperience(player, type, doMsgs, 200000);
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PARCHMENT_MAP, 1);
ShowText(player, type, doMsgs, "You approach two men fighting over a piece of parchment.");
ShowText(player, type, doMsgs, "Before you can intervene, they topple into the lava. The parchment flutters gracefully to the ground.");
ShowText(player, type, doMsgs, "A glance at the Parchment Map proves it is one of the four maps Queen Aeowyn asked you to find.");
}
}
protected override void FnEvent09(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "The teleport will lead you to the Carriage House.");
TeleportParty(player, type, doMsgs, 6, 1, 68, Direction.North);
}
protected override void FnEvent0A(TwPlayerServer player, MapEventType type, bool doMsgs) {
DisableAutomaps(player, type, doMsgs);
ShowText(player, type, doMsgs, "You fall into a pit.");
DamXit(player, type, doMsgs);
}
protected override void FnEvent0B(TwPlayerServer player, MapEventType type, bool doMsgs) {
ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
protected override void FnEvent0C(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.JACKET) == 1) {
RemoveItem(player, type, doMsgs, LIFEJACKET);
if (HasItem(player, type, doMsgs, FELLOWSHIPKEY)) {
ShowText(player, type, doMsgs, "The room is empty.");
}
else {
GiveItem(player, type, doMsgs, FELLOWSHIPKEY);
ShowText(player, type, doMsgs, "While stooping down to pick up a key, your Life Jacket falls into the water and floats away.");
ShowText(player, type, doMsgs, "The grasp of the key is engraved with two arms clasped in fellowship.");
}
}
else {
if (HasItem(player, type, doMsgs, LIFEJACKET)) {
GiveItem(player, type, doMsgs, FELLOWSHIPKEY);
GiveItem(player, type, doMsgs, STORMSBOW);
GiveItem(player, type, doMsgs, FREEDOMRING);
ModifyExperience(player, type, doMsgs, 50000);
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.JACKET, 1);
ShowText(player, type, doMsgs, "While stooping down to pick up some items, your Life Jacket falls into the water and floats away.");
ShowText(player, type, doMsgs, "The grasp of the key is engraved with two arms clasped in fellowship.");
RemoveItem(player, type, doMsgs, LIFEJACKET);
}
else {
ShowText(player, type, doMsgs, "You stoop down to pick up a key but accidentally knock it into the water.");
ShowText(player, type, doMsgs, "Unfortunately, you lack what you need to retrieve it.");
}
}
}
protected override void FnEvent0D(TwPlayerServer player, MapEventType type, bool doMsgs) {
DisableAutomaps(player, type, doMsgs);
}
protected override void FnEvent0E(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Posted on the door you see: 'DANGER! Unstable ground.'");
}
protected override void FnEvent0F(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You overhear passers-by discussing the fact that not all pits lead to death; some have been transformed into passages.");
}
protected override void FnEvent10(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "A jump into the pit lands you in the Library.");
TeleportParty(player, type, doMsgs, 6, 1, 90, Direction.North);
}
protected override void FnEvent11(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, GNOMEWIZARD);
ShowText(player, type, doMsgs, "A half-crazed Gnome Wizard looks in the direction of the Cartography Shop.");
ShowText(player, type, doMsgs, "'Riddles, riddles,' he says mysteriously and wanders off.");
}
protected override void FnEvent12(TwPlayerServer player, MapEventType type, bool doMsgs) {
ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
protected override void FnEvent13(TwPlayerServer player, MapEventType type, bool doMsgs) {
TeleportParty(player, type, doMsgs, 5, 1, 64, Direction.South);
}
protected override void FnEvent14(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
protected override void FnEvent15(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Through this teleport you will find the Stables.");
TeleportParty(player, type, doMsgs, 6, 1, 164, Direction.South);
}
protected override void FnEvent16(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You fall into the Carriage House.");
TeleportParty(player, type, doMsgs, 6, 1, 118, Direction.East);
}
protected override void FnEvent17(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasItem(player, type, doMsgs, DIAMONDLOCKPICK)) {
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.VAULT) == 1) {
ShowText(player, type, doMsgs, "You see an empty safe.");
}
else {
ModifyGold(player, type, doMsgs, 100000);
GiveItem(player, type, doMsgs, NEROSLYRE);
GiveItem(player, type, doMsgs, CRESCENTMOON);
GiveItem(player, type, doMsgs, STAFFOFJUSTICE);
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.VAULT, 1);
ShowText(player, type, doMsgs, "The safe opens easily with the Diamond Lockpick.");
ShowText(player, type, doMsgs, "Inside are 100,000 gold pieces, which somehow find their way into your pocket, and a few items which were tucked away for safekeeping.");
}
}
else {
ShowText(player, type, doMsgs, "Deep within the Vault you find a safe; unfortunately, it is secured shut with a diamond shaped lock.");
}
}
protected override void FnEvent18(TwPlayerServer player, MapEventType type, bool doMsgs) {
DisableAutomaps(player, type, doMsgs);
if ((GetFlag(player, type, doMsgs, FlagTypeTile, LAKE) == 0)) {
SetFacing(player, type, doMsgs, Direction.West);
SetFlag(player, type, doMsgs, FlagTypeTile, LAKE, 1);
}
}
protected override void FnEvent19(TwPlayerServer player, MapEventType type, bool doMsgs) {
DisableAutomaps(player, type, doMsgs);
if ((GetFlag(player, type, doMsgs, FlagTypeTile, LAKE) == 0)) {
SetFacing(player, type, doMsgs, Direction.South);
SetFlag(player, type, doMsgs, FlagTypeTile, LAKE, 1);
}
}
protected override void FnEvent1A(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You discover a short cut to the Stables.");
TeleportParty(player, type, doMsgs, 6, 1, 134, Direction.South);
}
protected override void FnEvent1D(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You can barely read the water-stained sign. It says, 'To Clueless.'");
TeleportParty(player, type, doMsgs, 4, 1, 69, Direction.South);
}
protected override void FnEvent1E(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "This way leads to Tipekans' Bridge.");
TeleportParty(player, type, doMsgs, 7, 1, 161, Direction.East);
}
protected override void FnEvent1F(TwPlayerServer player, MapEventType type, bool doMsgs) {
DisableAutomaps(player, type, doMsgs);
ShowPortrait(player, type, doMsgs, HALFLINGTHIEF);
ShowText(player, type, doMsgs, "Smug grins at the sight of your Ruby Lockpick.");
ShowText(player, type, doMsgs, "He crooks a thumb towards the door to the west.");
}
protected override void FnEvent20(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "The ground gives way beneath you.");
DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs));
}
protected override void FnEvent21(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (UsedItem(player, type, ref doMsgs, RUBYLOCKPICK, RUBYLOCKPICK)) {
ShowText(player, type, doMsgs, "As you try to open the door, you spring a trap set by Smug.");
DamXit(player, type, doMsgs);
}
else {
ShowText(player, type, doMsgs, "This is the back door to Smug's Jewelry Shop.");
WallBlock(player, type, doMsgs);
}
}
protected override void FnEvent22(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "A message is scrawled on the wall -");
ShowText(player, type, doMsgs, "'Inventory items have been known to change hazardous steps into safe steps.'");
}
protected override void FnEvent25(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasItem(player, type, doMsgs, ROPE)) {
ShowText(player, type, doMsgs, "The ground gives way and you slide down a tunnel.");
ShowText(player, type, doMsgs, "You quickly throw your rope over a rock and lower yourself into the Library.");
TeleportParty(player, type, doMsgs, 6, 1, 73, Direction.East);
}
else {
ShowText(player, type, doMsgs, "The ground gives way and you slide down a forked tunnel.");
ShowText(player, type, doMsgs, "This time, you tumble down the left tube.");
TeleportParty(player, type, doMsgs, 6, 1, 70, Direction.West);
}
}
protected override void FnEvent26(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetGuild(player, type, doMsgs) == THIEF) {
ShowText(player, type, doMsgs, "A sign on the door - 'THIEVES ONLY.'");
DoorHere(player, type, doMsgs);
WallClear(player, type, doMsgs);
}
else {
WallBlock(player, type, doMsgs);
}
}
protected override void FnEvent27(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (UsedItem(player, type, ref doMsgs, RUBYLOCKPICK, RUBYLOCKPICK)) {
WallClear(player, type, doMsgs);
DoorHere(player, type, doMsgs);
ShowText(player, type, doMsgs, "You successfully unlock the door.");
}
else {
WallBlock(player, type, doMsgs);
ShowText(player, type, doMsgs, "The entrance to Smug's Jewelry Shop is locked.");
}
}
protected override void FnEvent28(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "The Rich Waters of Sterling Fountain heal and restore you.");
FntnPic(player, type, doMsgs);
HealFtn(player, type, doMsgs);
}
protected override void FnEvent2C(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "A ghostly voice cackles in glee, 'Cursed you are, cursed to go where I wish! Muhahahaha!'");
if (HasItem(player, type, doMsgs, SKELETONKEY)) {
TeleportParty(player, type, doMsgs, 5, 3, 15, Direction.South);
}
else if (HasItem(player, type, doMsgs, SCROLLOFTHESUN)) {
TeleportParty(player, type, doMsgs, 5, 1, 61, Direction.West);
}
else if (HasItem(player, type, doMsgs, BLESSPOTION)) {
TeleportParty(player, type, doMsgs, 5, 1, 182, Direction.South);
}
else if (HasItem(player, type, doMsgs, HALOSCROLL)) {
TeleportParty(player, type, doMsgs, 4, 3, 64, Direction.South);
}
else {
TeleportParty(player, type, doMsgs, 4, 1, 241, Direction.East);
}
}
protected override void FnEvent2D(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "It looks like you're not the only one to discover the thieves' hiding place.");
if (HasItem(player, type, doMsgs, STAFFOFGIANTS)) {
SetTreasure(player, type, doMsgs, CURSEDSCROLL, SCROLLOFPROTECTION, 0, 0, 0, 1000);
}
else {
SetTreasure(player, type, doMsgs, STAFFOFGIANTS, MANAELIXIR, SCROLLOFTHESUN, 0, 0, 3000);
}
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 6);
AddEncounter(player, type, doMsgs, 02, 7);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 4);
AddEncounter(player, type, doMsgs, 02, 5);
AddEncounter(player, type, doMsgs, 03, 13);
}
else {
AddEncounter(player, type, doMsgs, 01, 27);
AddEncounter(player, type, doMsgs, 02, 28);
AddEncounter(player, type, doMsgs, 03, 28);
AddEncounter(player, type, doMsgs, 05, 35);
AddEncounter(player, type, doMsgs, 06, 36);
}
}
protected override void FnEvent2E(TwPlayerServer player, MapEventType type, bool doMsgs) {
DisableAutomaps(player, type, doMsgs);
if (GetGuild(player, type, doMsgs) == THIEF) {
if (HasItem(player, type, doMsgs, SKELETONKEY)) {
ShowText(player, type, doMsgs, "The room is empty.");
}
else if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ARMORY_ITEM) == 1) {
GiveItem(player, type, doMsgs, SKELETONKEY);
ShowText(player, type, doMsgs, "You find a key which may open seemingly impassable doors in your race to finish Queen Aeowyn's Map Quest.");
ShowText(player, type, doMsgs, "The key is made of bone and features a skull and crossed arm bones.");
}
else {
GiveItem(player, type, doMsgs, SKELETONKEY);
ShowText(player, type, doMsgs, "Your Guildmaster left you a special key that will give you access to magical armor.");
ShowText(player, type, doMsgs, "The key is made of bone. The grasp is shaped like a skull and the shaft like two crossed, bony arms.");
}
}
else {
ShowText(player, type, doMsgs, "The room is bare.");
}
}
protected override void FnEvent2F(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Beyond the door lies a twisted maze. To find your way through would be aMAZEing.");
TeleportParty(player, type, doMsgs, 4, 2, 240, Direction.North);
}
protected override void FnEvent30(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "`Pluthros`");
ShowText(player, type, doMsgs, "Ashakkar is where all who oppose Chaos shall find this Fate.");
}
protected override void FnEvent31(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
SetTileBlock(player, type, doMsgs, 191);
ShowText(player, type, doMsgs, "Carved in the base you see the name `Lord Zzuf`");
ShowText(player, type, doMsgs, "This work of art, however is unfinished; perhaps later you can come back and see it completed.");
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ROPE_FLAG) == 1) {
ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
ClearTileBlock(player, type, doMsgs, 191);
SetWallItem(player, type, doMsgs, GATEWAY, 191, Direction.East);
ShowText(player, type, doMsgs, "Your quest bag shifts and hits the statue of Lord Zzuf, causing the great explorer's icon to move slightly.");
ShowText(player, type, doMsgs, "You push the statue's base and find enough room for a person to squeeze through.");
}
}
protected override void FnEvent32(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "`Juvalad`");
ShowText(player, type, doMsgs, "Enakkar is where all who oppose Harmony shall find this Fate.");
}
protected override void FnEvent33(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "`Malos`");
ShowText(player, type, doMsgs, "En-Li-Kil's master, and guardian to the Elementals.");
}
protected override void FnEvent34(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "`Crysillus Draco and Sayvut d'Oi Vey`");
ShowText(player, type, doMsgs, "These were the great engineers who built the shrines to the Fates those many moons ago.");
}
protected override void FnEvent35(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "'Enter at your own risk!'");
}
protected override void FnEvent36(TwPlayerServer player, MapEventType type, bool doMsgs) {
{
if (HasItem(player, type, doMsgs, EMERALDLOCKPICK)) {
SetTreasure(player, type, doMsgs, CURATIVEELIXIR, 0, 0, 0, 0, 1000);
}
else {
SetTreasure(player, type, doMsgs, EMERALDLOCKPICK, CURATIVEELIXIR, ELIXIROFHEALTH, 0, 0, 3000);
ShowText(player, type, doMsgs, "You see something green on the ground - and something nasty charging at you.");
}
}
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 22);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 20);
AddEncounter(player, type, doMsgs, 02, 20);
AddEncounter(player, type, doMsgs, 05, 23);
}
else {
AddEncounter(player, type, doMsgs, 01, 20);
AddEncounter(player, type, doMsgs, 02, 20);
AddEncounter(player, type, doMsgs, 03, 22);
AddEncounter(player, type, doMsgs, 05, 23);
AddEncounter(player, type, doMsgs, 06, 34);
}
}
protected override void FnEvent37(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetGuild(player, type, doMsgs) == CLERIC) {
ShowText(player, type, doMsgs, "A sign on the door - 'CLERICS ONLY.'");
DoorHere(player, type, doMsgs);
WallClear(player, type, doMsgs);
}
else {
WallBlock(player, type, doMsgs);
}
}
protected override void FnEvent38(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetGuild(player, type, doMsgs) == CLERIC) {
if (HasItem(player, type, doMsgs, SKELETONKEY)) {
ShowText(player, type, doMsgs, "The room is empty.");
}
else if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ARMORY_ITEM) == 1) {
GiveItem(player, type, doMsgs, SKELETONKEY);
ShowText(player, type, doMsgs, "You find a key which may open seemingly impassable doors in your race to finish Queen Aeowyn's Map Quest.");
ShowText(player, type, doMsgs, "The key is made of bone and features a skull and crossed arm bones.");
}
else {
GiveItem(player, type, doMsgs, SKELETONKEY);
ShowText(player, type, doMsgs, "Your Guildmaster left you a special key that will give you access to magical armor.");
ShowText(player, type, doMsgs, "The key is made of bone. The grasp is shaped like a skull and the shaft like two crossed, bony arms.");
}
}
else {
ShowText(player, type, doMsgs, "The room is bare.");
}
}
protected override void FnEvent39(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "`Astelligus`");
ShowText(player, type, doMsgs, "The blackest pitch cannot compare to this Fate's home.");
}
protected override void FnEvent3A(TwPlayerServer player, MapEventType type, bool doMsgs) {
if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ARMORY_ITEM) == 0)) {
ShowPortrait(player, type, doMsgs, ORCKNIGHT);
ShowText(player, type, doMsgs, "An Orc Knight is frantically searching the ground.");
ShowText(player, type, doMsgs, "'All I need to get into the secret armory rooms is that blasted Skeleton Key I dropped somewhere back here!");
ShowText(player, type, doMsgs, "Of course, one needs more than that, as you well know!'");
ShowText(player, type, doMsgs, "The Knight dashes off before you can say anything.");
}
}
protected override void FnEvent3B(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Be sure of your footing when you scale the heights of Cliffhanger.");
TeleportParty(player, type, doMsgs, 4, 1, 34, Direction.East);
}
protected override void FnEvent3C(TwPlayerServer player, MapEventType type, bool doMsgs) {
DisableAutomaps(player, type, doMsgs);
ShowText(player, type, doMsgs, "Magical forces swirl about you, where you might end up you have no clue.");
if (HasItem(player, type, doMsgs, SLATEMAP)) {
TeleportParty(player, type, doMsgs, 6, 1, 0, Direction.South);
}
else if (HasItem(player, type, doMsgs, FRONTDOORKEY)) {
TeleportParty(player, type, doMsgs, 4, 2, 228, Direction.South);
}
else if (HasItem(player, type, doMsgs, CRYSTALSCROLL)) {
TeleportParty(player, type, doMsgs, 4, 1, 58, Direction.South);
}
else if (HasItem(player, type, doMsgs, IRONCROWN)) {
TeleportParty(player, type, doMsgs, 5, 1, 203, Direction.South);
}
else {
TeleportParty(player, type, doMsgs, 5, 1, 0, Direction.East);
}
}
protected override void FnEvent3D(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
SetWallItem(player, type, doMsgs, GATEWAY, GetTile(player, type, doMsgs), Direction.East);
ShowText(player, type, doMsgs, "You have discovered the secret portal to the Ballroom.");
}
else {
TeleportParty(player, type, doMsgs, 5, 1, 207, Direction.West);
ShowText(player, type, doMsgs, "The space is too narrow for more than one person to squeeze through.");
}
}
protected override void FnEvent3E(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "`Corpeus`");
ShowText(player, type, doMsgs, "This Fate welcomes all to sample his wisdom; or die from his wrath.");
}
protected override void FnEvent3F(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 1);
AddEncounter(player, type, doMsgs, 02, 3);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 1);
AddEncounter(player, type, doMsgs, 02, 3);
AddEncounter(player, type, doMsgs, 05, 25);
}
else {
AddEncounter(player, type, doMsgs, 01, 3);
AddEncounter(player, type, doMsgs, 02, 3);
AddEncounter(player, type, doMsgs, 03, 1);
AddEncounter(player, type, doMsgs, 05, 26);
AddEncounter(player, type, doMsgs, 06, 26);
}
}
protected override void FnEvent40(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 6);
AddEncounter(player, type, doMsgs, 02, 5);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 28);
AddEncounter(player, type, doMsgs, 02, 29);
AddEncounter(player, type, doMsgs, 06, 9);
}
else {
AddEncounter(player, type, doMsgs, 01, 10);
AddEncounter(player, type, doMsgs, 02, 10);
AddEncounter(player, type, doMsgs, 03, 11);
AddEncounter(player, type, doMsgs, 05, 28);
AddEncounter(player, type, doMsgs, 06, 29);
}
}
protected override void FnEvent41(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 17);
AddEncounter(player, type, doMsgs, 02, 38);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 17);
AddEncounter(player, type, doMsgs, 02, 17);
AddEncounter(player, type, doMsgs, 03, 18);
AddEncounter(player, type, doMsgs, 04, 39);
}
else {
AddEncounter(player, type, doMsgs, 01, 17);
AddEncounter(player, type, doMsgs, 02, 17);
AddEncounter(player, type, doMsgs, 03, 19);
AddEncounter(player, type, doMsgs, 04, 19);
AddEncounter(player, type, doMsgs, 06, 39);
}
}
protected override void FnEvent42(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 39);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 17);
AddEncounter(player, type, doMsgs, 02, 18);
AddEncounter(player, type, doMsgs, 05, 35);
}
else {
AddEncounter(player, type, doMsgs, 01, 37);
AddEncounter(player, type, doMsgs, 02, 37);
AddEncounter(player, type, doMsgs, 03, 39);
AddEncounter(player, type, doMsgs, 04, 39);
AddEncounter(player, type, doMsgs, 06, 38);
}
}
protected override void FnEvent43(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 14);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 13);
AddEncounter(player, type, doMsgs, 02, 15);
AddEncounter(player, type, doMsgs, 06, 17);
}
else {
AddEncounter(player, type, doMsgs, 01, 33);
AddEncounter(player, type, doMsgs, 02, 33);
AddEncounter(player, type, doMsgs, 04, 35);
AddEncounter(player, type, doMsgs, 05, 36);
AddEncounter(player, type, doMsgs, 06, 40);
}
}
protected override void FnEvent44(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 10);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 9);
AddEncounter(player, type, doMsgs, 02, 10);
AddEncounter(player, type, doMsgs, 04, 31);
}
else {
AddEncounter(player, type, doMsgs, 01, 10);
AddEncounter(player, type, doMsgs, 02, 10);
AddEncounter(player, type, doMsgs, 04, 11);
AddEncounter(player, type, doMsgs, 05, 30);
AddEncounter(player, type, doMsgs, 06, 32);
}
}
protected override void FnEvent45(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 5);
AddEncounter(player, type, doMsgs, 05, 6);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 6);
AddEncounter(player, type, doMsgs, 02, 6);
AddEncounter(player, type, doMsgs, 05, 19);
}
else {
AddEncounter(player, type, doMsgs, 01, 6);
AddEncounter(player, type, doMsgs, 02, 6);
AddEncounter(player, type, doMsgs, 03, 8);
AddEncounter(player, type, doMsgs, 05, 19);
AddEncounter(player, type, doMsgs, 06, 19);
}
}
protected override void FnEvent46(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetWallItem(player, type, doMsgs, GATEWAY, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
TeleportParty(player, type, doMsgs, 4, 1, 185, Direction.South);
}
private void DamXit(TwPlayerServer player, MapEventType type, bool doMsgs) {
DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs));
}
private void HealFtn(TwPlayerServer player, MapEventType type, bool doMsgs) {
ModifyHealth(player, type, doMsgs, GetHealthMax(player, type, doMsgs));
ModifyMana(player, type, doMsgs, 10000);
}
private void WallClear(TwPlayerServer player, MapEventType type, bool doMsgs) {
ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
private void WallBlock(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
private void DoorHere(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetWallItem(player, type, doMsgs, DOOR, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
private void FntnPic(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, FOUNTAIN);
}
protected override void FnEvent47(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasItem(player, type, doMsgs, EMERALDLOCKPICK)) {
ShowPortrait(player, type, doMsgs, GNOMETHIEF);
ShowText(player, type, doMsgs, "'Lockpicks for sale!! Lockpicks for sale!!");
ShowText(player, type, doMsgs, "Can I sell you a lockpick, brave champion? I see you have one, beautiful too. Care to sell it?");
ShowText(player, type, doMsgs, "You must know that the brothers seek red, only red! No? Drat! Then be off with you and let me sell my wares!'");
}
else {
ShowPortrait(player, type, doMsgs, GNOMETHIEF);
ShowText(player, type, doMsgs, "'Brave Warrior! Are you in search of the Emerald Lockpick, too? I must find it and get to Tipekans!'");
}
}
}
}
| |
// 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.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Net.Test.Common;
using System.Reflection;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
public sealed class SocketsHttpHandler_HttpProtocolTests : HttpProtocolTests
{
protected override bool UseSocketsHttpHandler => true;
}
public sealed class SocketsHttpHandler_HttpProtocolTests_Dribble : HttpProtocolTests_Dribble
{
protected override bool UseSocketsHttpHandler => true;
}
public sealed class SocketsHttpHandler_HttpClientTest : HttpClientTest
{
protected override bool UseSocketsHttpHandler => true;
}
public sealed class SocketsHttpHandler_DiagnosticsTest : DiagnosticsTest
{
protected override bool UseSocketsHttpHandler => true;
}
public sealed class SocketsHttpHandler_HttpClientEKUTest : HttpClientEKUTest
{
protected override bool UseSocketsHttpHandler => true;
}
public sealed class SocketsHttpHandler_HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test : HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test
{
protected override bool UseSocketsHttpHandler => true;
}
public sealed class SocketsHttpHandler_HttpClientHandler_ClientCertificates_Test : HttpClientHandler_ClientCertificates_Test
{
public SocketsHttpHandler_HttpClientHandler_ClientCertificates_Test(ITestOutputHelper output) : base(output) { }
protected override bool UseSocketsHttpHandler => true;
}
public sealed class SocketsHttpHandler_HttpClientHandler_DefaultProxyCredentials_Test : HttpClientHandler_DefaultProxyCredentials_Test
{
protected override bool UseSocketsHttpHandler => true;
}
public sealed class SocketsHttpHandler_HttpClientHandler_MaxConnectionsPerServer_Test : HttpClientHandler_MaxConnectionsPerServer_Test
{
protected override bool UseSocketsHttpHandler => true;
}
public sealed class SocketsHttpHandler_HttpClientHandler_ServerCertificates_Test : HttpClientHandler_ServerCertificates_Test
{
protected override bool UseSocketsHttpHandler => true;
}
public sealed class SocketsHttpHandler_HttpClientHandler_ResponseDrain_Test : HttpClientHandler_ResponseDrain_Test
{
protected override bool UseSocketsHttpHandler => true;
}
public sealed class SocketsHttpHandler_PostScenarioTest : PostScenarioTest
{
public SocketsHttpHandler_PostScenarioTest(ITestOutputHelper output) : base(output) { }
protected override bool UseSocketsHttpHandler => true;
}
public sealed class SocketsHttpHandler_ResponseStreamTest : ResponseStreamTest
{
public SocketsHttpHandler_ResponseStreamTest(ITestOutputHelper output) : base(output) { }
protected override bool UseSocketsHttpHandler => true;
}
public sealed class SocketsHttpHandler_HttpClientHandler_SslProtocols_Test : HttpClientHandler_SslProtocols_Test
{
protected override bool UseSocketsHttpHandler => true;
}
public sealed class SocketsHttpHandler_SchSendAuxRecordHttpTest : SchSendAuxRecordHttpTest
{
public SocketsHttpHandler_SchSendAuxRecordHttpTest(ITestOutputHelper output) : base(output) { }
protected override bool UseSocketsHttpHandler => true;
}
public sealed class SocketsHttpHandler_HttpClientMiniStress : HttpClientMiniStress
{
protected override bool UseSocketsHttpHandler => true;
}
public sealed class SocketsHttpHandler_HttpClientHandlerTest : HttpClientHandlerTest
{
public SocketsHttpHandler_HttpClientHandlerTest(ITestOutputHelper output) : base(output) { }
protected override bool UseSocketsHttpHandler => true;
}
public sealed class SocketsHttpHandler_DefaultCredentialsTest : DefaultCredentialsTest
{
public SocketsHttpHandler_DefaultCredentialsTest(ITestOutputHelper output) : base(output) { }
protected override bool UseSocketsHttpHandler => true;
}
public sealed class SocketsHttpHandler_IdnaProtocolTests : IdnaProtocolTests
{
protected override bool UseSocketsHttpHandler => true;
protected override bool SupportsIdna => true;
}
public sealed class SocketsHttpHandler_HttpRetryProtocolTests : HttpRetryProtocolTests
{
protected override bool UseSocketsHttpHandler => true;
}
public sealed class SocketsHttpHandler_HttpCookieProtocolTests : HttpCookieProtocolTests
{
protected override bool UseSocketsHttpHandler => true;
}
public sealed class SocketsHttpHandler_HttpClientHandler_Cancellation_Test : HttpClientHandler_Cancellation_Test
{
protected override bool UseSocketsHttpHandler => true;
[Fact]
public void ConnectTimeout_Default()
{
using (var handler = new SocketsHttpHandler())
{
Assert.Equal(Timeout.InfiniteTimeSpan, handler.ConnectTimeout);
}
}
[Theory]
[InlineData(0)]
[InlineData(-2)]
[InlineData(int.MaxValue + 1L)]
public void ConnectTimeout_InvalidValues(long ms)
{
using (var handler = new SocketsHttpHandler())
{
Assert.Throws<ArgumentOutOfRangeException>(() => handler.ConnectTimeout = TimeSpan.FromMilliseconds(ms));
}
}
[Theory]
[InlineData(-1)]
[InlineData(1)]
[InlineData(int.MaxValue - 1)]
[InlineData(int.MaxValue)]
public void ConnectTimeout_ValidValues_Roundtrip(long ms)
{
using (var handler = new SocketsHttpHandler())
{
handler.ConnectTimeout = TimeSpan.FromMilliseconds(ms);
Assert.Equal(TimeSpan.FromMilliseconds(ms), handler.ConnectTimeout);
}
}
[Fact]
public void ConnectTimeout_SetAfterUse_Throws()
{
using (var handler = new SocketsHttpHandler())
using (var client = new HttpClient(handler))
{
handler.ConnectTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
client.GetAsync("http://" + Guid.NewGuid().ToString("N")); // ignoring failure
Assert.Equal(TimeSpan.FromMilliseconds(int.MaxValue), handler.ConnectTimeout);
Assert.Throws<InvalidOperationException>(() => handler.ConnectTimeout = TimeSpan.FromMilliseconds(1));
}
}
[OuterLoop]
[Fact]
public async Task ConnectTimeout_TimesOutSSLAuth_Throws()
{
var releaseServer = new TaskCompletionSource<bool>();
await LoopbackServer.CreateClientAndServerAsync(async uri =>
{
using (var handler = new SocketsHttpHandler())
using (var invoker = new HttpMessageInvoker(handler))
{
handler.ConnectTimeout = TimeSpan.FromSeconds(1);
var sw = Stopwatch.StartNew();
await Assert.ThrowsAsync<OperationCanceledException>(() =>
invoker.SendAsync(new HttpRequestMessage(HttpMethod.Get,
new UriBuilder(uri) { Scheme = "https" }.ToString()), default));
sw.Stop();
Assert.InRange(sw.ElapsedMilliseconds, 500, 30_000);
releaseServer.SetResult(true);
}
}, server => releaseServer.Task); // doesn't establish SSL connection
}
[Fact]
public void Expect100ContinueTimeout_Default()
{
using (var handler = new SocketsHttpHandler())
{
Assert.Equal(TimeSpan.FromSeconds(1), handler.Expect100ContinueTimeout);
}
}
[Theory]
[InlineData(-2)]
[InlineData(int.MaxValue + 1L)]
public void Expect100ContinueTimeout_InvalidValues(long ms)
{
using (var handler = new SocketsHttpHandler())
{
Assert.Throws<ArgumentOutOfRangeException>(() => handler.Expect100ContinueTimeout = TimeSpan.FromMilliseconds(ms));
}
}
[Theory]
[InlineData(-1)]
[InlineData(1)]
[InlineData(int.MaxValue - 1)]
[InlineData(int.MaxValue)]
public void Expect100ContinueTimeout_ValidValues_Roundtrip(long ms)
{
using (var handler = new SocketsHttpHandler())
{
handler.Expect100ContinueTimeout = TimeSpan.FromMilliseconds(ms);
Assert.Equal(TimeSpan.FromMilliseconds(ms), handler.Expect100ContinueTimeout);
}
}
[Fact]
public void Expect100ContinueTimeout_SetAfterUse_Throws()
{
using (var handler = new SocketsHttpHandler())
using (var client = new HttpClient(handler))
{
handler.Expect100ContinueTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
client.GetAsync("http://" + Guid.NewGuid().ToString("N")); // ignoring failure
Assert.Equal(TimeSpan.FromMilliseconds(int.MaxValue), handler.Expect100ContinueTimeout);
Assert.Throws<InvalidOperationException>(() => handler.Expect100ContinueTimeout = TimeSpan.FromMilliseconds(1));
}
}
[OuterLoop("Incurs significant delay")]
[Fact]
public async Task Expect100Continue_WaitsExpectedPeriodOfTimeBeforeSendingContent()
{
await LoopbackServer.CreateClientAndServerAsync(async uri =>
{
using (var handler = new SocketsHttpHandler())
using (var invoker = new HttpMessageInvoker(handler))
{
TimeSpan delay = TimeSpan.FromSeconds(3);
handler.Expect100ContinueTimeout = delay;
var tcs = new TaskCompletionSource<bool>();
var content = new SetTcsContent(new MemoryStream(new byte[1]), tcs);
var request = new HttpRequestMessage(HttpMethod.Post, uri) { Content = content };
request.Headers.ExpectContinue = true;
var sw = Stopwatch.StartNew();
(await invoker.SendAsync(request, default)).Dispose();
sw.Stop();
Assert.InRange(sw.Elapsed, delay - TimeSpan.FromSeconds(.5), delay * 10); // arbitrary wiggle room
}
}, async server =>
{
await server.AcceptConnectionAsync(async connection =>
{
await connection.ReadRequestHeaderAsync();
await connection.Reader.ReadAsync(new char[1]);
await connection.SendResponseAsync();
});
});
}
private sealed class SetTcsContent : StreamContent
{
private readonly TaskCompletionSource<bool> _tcs;
public SetTcsContent(Stream stream, TaskCompletionSource<bool> tcs) : base(stream) => _tcs = tcs;
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
_tcs.SetResult(true);
return base.SerializeToStreamAsync(stream, context);
}
}
}
public sealed class SocketsHttpHandler_HttpClientHandler_MaxResponseHeadersLength_Test : HttpClientHandler_MaxResponseHeadersLength_Test
{
protected override bool UseSocketsHttpHandler => true;
}
public sealed class SocketsHttpHandler_HttpClientHandler_Authentication_Test : HttpClientHandler_Authentication_Test
{
protected override bool UseSocketsHttpHandler => true;
[Theory]
[MemberData(nameof(Authentication_SocketsHttpHandler_TestData))]
public async void SocketsHttpHandler_Authentication_Succeeds(string authenticateHeader, bool result)
{
await HttpClientHandler_Authentication_Succeeds(authenticateHeader, result);
}
public static IEnumerable<object[]> Authentication_SocketsHttpHandler_TestData()
{
// These test cases pass on SocketsHttpHandler, fail everywhere else.
// TODO: #27113: Fix failing authentication test cases on different httpclienthandlers.
yield return new object[] { "Basic realm=\"testrealm1\" basic realm=\"testrealm1\"", true };
yield return new object[] { "Basic something digest something", true };
yield return new object[] { "Digest ", false };
yield return new object[] { "Digest realm=withoutquotes, nonce=withoutquotes", false };
yield return new object[] { "Digest realm=\"testrealm\", nonce=\"testnonce\", algorithm=\"myown\"", false };
}
}
public sealed class SocketsHttpHandler_ConnectionUpgrade_Test : HttpClientTestBase
{
protected override bool UseSocketsHttpHandler => true;
[Fact]
public async Task UpgradeConnection_ReturnsReadableAndWritableStream()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (HttpClient client = CreateHttpClient())
{
// We need to use ResponseHeadersRead here, otherwise we will hang trying to buffer the response body.
Task<HttpResponseMessage> getResponseTask = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
await server.AcceptConnectionAsync(async connection =>
{
Task<List<string>> serverTask = connection.ReadRequestHeaderAndSendCustomResponseAsync($"HTTP/1.1 101 Switching Protocols\r\nDate: {DateTimeOffset.UtcNow:R}\r\n\r\n");
await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask);
using (Stream clientStream = await (await getResponseTask).Content.ReadAsStreamAsync())
{
// Boolean properties returning correct values
Assert.True(clientStream.CanWrite);
Assert.True(clientStream.CanRead);
Assert.False(clientStream.CanSeek);
// Not supported operations
Assert.Throws<NotSupportedException>(() => clientStream.Length);
Assert.Throws<NotSupportedException>(() => clientStream.Position);
Assert.Throws<NotSupportedException>(() => clientStream.Position = 0);
Assert.Throws<NotSupportedException>(() => clientStream.Seek(0, SeekOrigin.Begin));
Assert.Throws<NotSupportedException>(() => clientStream.SetLength(0));
// Invalid arguments
var nonWritableStream = new MemoryStream(new byte[1], false);
var disposedStream = new MemoryStream();
disposedStream.Dispose();
Assert.Throws<ArgumentNullException>(() => clientStream.CopyTo(null));
Assert.Throws<ArgumentOutOfRangeException>(() => clientStream.CopyTo(Stream.Null, 0));
Assert.Throws<ArgumentNullException>(() => { clientStream.CopyToAsync(null, 100, default); });
Assert.Throws<ArgumentOutOfRangeException>(() => { clientStream.CopyToAsync(Stream.Null, 0, default); });
Assert.Throws<ArgumentOutOfRangeException>(() => { clientStream.CopyToAsync(Stream.Null, -1, default); });
Assert.Throws<NotSupportedException>(() => { clientStream.CopyToAsync(nonWritableStream, 100, default); });
Assert.Throws<ObjectDisposedException>(() => { clientStream.CopyToAsync(disposedStream, 100, default); });
Assert.Throws<ArgumentNullException>(() => clientStream.Read(null, 0, 100));
Assert.Throws<ArgumentOutOfRangeException>(() => clientStream.Read(new byte[1], -1, 1));
Assert.ThrowsAny<ArgumentException>(() => clientStream.Read(new byte[1], 2, 1));
Assert.Throws<ArgumentOutOfRangeException>(() => clientStream.Read(new byte[1], 0, -1));
Assert.ThrowsAny<ArgumentException>(() => clientStream.Read(new byte[1], 0, 2));
Assert.Throws<ArgumentNullException>(() => clientStream.BeginRead(null, 0, 100, null, null));
Assert.Throws<ArgumentOutOfRangeException>(() => clientStream.BeginRead(new byte[1], -1, 1, null, null));
Assert.ThrowsAny<ArgumentException>(() => clientStream.BeginRead(new byte[1], 2, 1, null, null));
Assert.Throws<ArgumentOutOfRangeException>(() => clientStream.BeginRead(new byte[1], 0, -1, null, null));
Assert.ThrowsAny<ArgumentException>(() => clientStream.BeginRead(new byte[1], 0, 2, null, null));
Assert.Throws<ArgumentNullException>(() => clientStream.EndRead(null));
Assert.Throws<ArgumentNullException>(() => { clientStream.ReadAsync(null, 0, 100, default); });
Assert.Throws<ArgumentOutOfRangeException>(() => { clientStream.ReadAsync(new byte[1], -1, 1, default); });
Assert.ThrowsAny<ArgumentException>(() => { clientStream.ReadAsync(new byte[1], 2, 1, default); });
Assert.Throws<ArgumentOutOfRangeException>(() => { clientStream.ReadAsync(new byte[1], 0, -1, default); });
Assert.ThrowsAny<ArgumentException>(() => { clientStream.ReadAsync(new byte[1], 0, 2, default); });
// Validate writing APIs on clientStream
clientStream.WriteByte((byte)'!');
clientStream.Write(new byte[] { (byte)'\r', (byte)'\n' }, 0, 2);
Assert.Equal("!", await connection.Reader.ReadLineAsync());
clientStream.Write(new Span<byte>(new byte[] { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', (byte)'\r', (byte)'\n' }));
Assert.Equal("hello", await connection.Reader.ReadLineAsync());
await clientStream.WriteAsync(new byte[] { (byte)'w', (byte)'o', (byte)'r', (byte)'l', (byte)'d', (byte)'\r', (byte)'\n' }, 0, 7);
Assert.Equal("world", await connection.Reader.ReadLineAsync());
await clientStream.WriteAsync(new Memory<byte>(new byte[] { (byte)'a', (byte)'n', (byte)'d', (byte)'\r', (byte)'\n' }, 0, 5));
Assert.Equal("and", await connection.Reader.ReadLineAsync());
await Task.Factory.FromAsync(clientStream.BeginWrite, clientStream.EndWrite, new byte[] { (byte)'b', (byte)'e', (byte)'y', (byte)'o', (byte)'n', (byte)'d', (byte)'\r', (byte)'\n' }, 0, 8, null);
Assert.Equal("beyond", await connection.Reader.ReadLineAsync());
clientStream.Flush();
await clientStream.FlushAsync();
// Validate reading APIs on clientStream
await connection.Stream.WriteAsync(Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwxyz"));
var buffer = new byte[1];
Assert.Equal('a', clientStream.ReadByte());
Assert.Equal(1, clientStream.Read(buffer, 0, 1));
Assert.Equal((byte)'b', buffer[0]);
Assert.Equal(1, clientStream.Read(new Span<byte>(buffer, 0, 1)));
Assert.Equal((byte)'c', buffer[0]);
Assert.Equal(1, await clientStream.ReadAsync(buffer, 0, 1));
Assert.Equal((byte)'d', buffer[0]);
Assert.Equal(1, await clientStream.ReadAsync(new Memory<byte>(buffer, 0, 1)));
Assert.Equal((byte)'e', buffer[0]);
Assert.Equal(1, await Task.Factory.FromAsync(clientStream.BeginRead, clientStream.EndRead, buffer, 0, 1, null));
Assert.Equal((byte)'f', buffer[0]);
var ms = new MemoryStream();
Task copyTask = clientStream.CopyToAsync(ms);
string bigString = string.Concat(Enumerable.Repeat("abcdefghijklmnopqrstuvwxyz", 1000));
Task lotsOfDataSent = connection.Socket.SendAsync(Encoding.ASCII.GetBytes(bigString), SocketFlags.None);
connection.Socket.Shutdown(SocketShutdown.Send);
await copyTask;
await lotsOfDataSent;
Assert.Equal("ghijklmnopqrstuvwxyz" + bigString, Encoding.ASCII.GetString(ms.ToArray()));
}
});
}
});
}
}
public sealed class SocketsHttpHandler_Connect_Test : HttpClientTestBase
{
protected override bool UseSocketsHttpHandler => true;
[Fact]
public async Task ConnectMethod_Success()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (HttpClient client = CreateHttpClient())
{
HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("CONNECT"), url);
request.Headers.Host = "foo.com:345";
// We need to use ResponseHeadersRead here, otherwise we will hang trying to buffer the response body.
Task<HttpResponseMessage> responseTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
await server.AcceptConnectionAsync(async connection =>
{
// Verify that Host header exist and has same value and URI authority.
List<string> lines = await connection.ReadRequestHeaderAsync().ConfigureAwait(false);
string authority = lines[0].Split()[1];
foreach (string line in lines)
{
if (line.StartsWith("Host:",StringComparison.InvariantCultureIgnoreCase))
{
Assert.Equal(line, "Host: foo.com:345");
break;
}
}
Task serverTask = connection.SendResponseAsync(HttpStatusCode.OK);
await TestHelper.WhenAllCompletedOrAnyFailed(responseTask, serverTask).ConfigureAwait(false);
using (Stream clientStream = await (await responseTask).Content.ReadAsStreamAsync())
{
Assert.True(clientStream.CanWrite);
Assert.True(clientStream.CanRead);
Assert.False(clientStream.CanSeek);
TextReader clientReader = new StreamReader(clientStream);
TextWriter clientWriter = new StreamWriter(clientStream) { AutoFlush = true };
TextReader serverReader = connection.Reader;
TextWriter serverWriter = connection.Writer;
const string helloServer = "hello server";
const string helloClient = "hello client";
const string goodbyeServer = "goodbye server";
const string goodbyeClient = "goodbye client";
clientWriter.WriteLine(helloServer);
Assert.Equal(helloServer, serverReader.ReadLine());
serverWriter.WriteLine(helloClient);
Assert.Equal(helloClient, clientReader.ReadLine());
clientWriter.WriteLine(goodbyeServer);
Assert.Equal(goodbyeServer, serverReader.ReadLine());
serverWriter.WriteLine(goodbyeClient);
Assert.Equal(goodbyeClient, clientReader.ReadLine());
}
});
}
});
}
[Fact]
public async Task ConnectMethod_Fails()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (HttpClient client = CreateHttpClient())
{
HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("CONNECT"), url);
request.Headers.Host = "foo.com:345";
// We need to use ResponseHeadersRead here, otherwise we will hang trying to buffer the response body.
Task<HttpResponseMessage> responseTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
await server.AcceptConnectionAsync(async connection =>
{
Task<List<string>> serverTask = connection.ReadRequestHeaderAndSendResponseAsync(HttpStatusCode.Forbidden, content: "error");
await TestHelper.WhenAllCompletedOrAnyFailed(responseTask, serverTask);
HttpResponseMessage response = await responseTask;
Assert.True(response.StatusCode == HttpStatusCode.Forbidden);
});
}
});
}
}
public sealed class SocketsHttpHandler_HttpClientHandler_ConnectionPooling_Test : HttpClientTestBase
{
protected override bool UseSocketsHttpHandler => true;
// TODO: ISSUE #27272
// Currently the subsequent tests sometimes fail/hang with WinHttpHandler / CurlHandler.
// In theory they should pass with any handler that does appropriate connection pooling.
// We should understand why they sometimes fail there and ideally move them to be
// used by all handlers this test project tests.
[Fact]
public async Task MultipleIterativeRequests_SameConnectionReused()
{
using (HttpClient client = CreateHttpClient())
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
var ep = (IPEndPoint)listener.LocalEndPoint;
var uri = new Uri($"http://{ep.Address}:{ep.Port}/");
string responseBody =
"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
"Content-Length: 0\r\n" +
"\r\n";
Task<string> firstRequest = client.GetStringAsync(uri);
using (Socket server = await listener.AcceptAsync())
using (var serverStream = new NetworkStream(server, ownsSocket: false))
using (var serverReader = new StreamReader(serverStream))
{
while (!string.IsNullOrWhiteSpace(await serverReader.ReadLineAsync()));
await server.SendAsync(new ArraySegment<byte>(Encoding.ASCII.GetBytes(responseBody)), SocketFlags.None);
await firstRequest;
Task<Socket> secondAccept = listener.AcceptAsync(); // shouldn't complete
Task<string> additionalRequest = client.GetStringAsync(uri);
while (!string.IsNullOrWhiteSpace(await serverReader.ReadLineAsync()));
await server.SendAsync(new ArraySegment<byte>(Encoding.ASCII.GetBytes(responseBody)), SocketFlags.None);
await additionalRequest;
Assert.False(secondAccept.IsCompleted, $"Second accept should never complete");
}
}
}
[OuterLoop("Incurs a delay")]
[Fact]
public async Task ServerDisconnectsAfterInitialRequest_SubsequentRequestUsesDifferentConnection()
{
using (HttpClient client = CreateHttpClient())
{
await LoopbackServer.CreateServerAsync(async (server, uri) =>
{
// Make multiple requests iteratively.
for (int i = 0; i < 2; i++)
{
Task<string> request = client.GetStringAsync(uri);
await server.AcceptConnectionSendResponseAndCloseAsync();
await request;
if (i == 0)
{
await Task.Delay(2000); // give client time to see the closing before next connect
}
}
});
}
}
[Fact]
public async Task ServerSendsGarbageAfterInitialRequest_SubsequentRequestUsesDifferentConnection()
{
using (HttpClient client = CreateHttpClient())
{
await LoopbackServer.CreateServerAsync(async (server, uri) =>
{
// Make multiple requests iteratively.
for (int i = 0; i < 2; i++)
{
Task<string> request = client.GetStringAsync(uri);
string response = LoopbackServer.GetHttpResponse() + "here is a bunch of garbage";
await server.AcceptConnectionSendCustomResponseAndCloseAsync(response);
await request;
}
});
}
}
[Fact]
public async Task ServerSendsConnectionClose_SubsequentRequestUsesDifferentConnection()
{
using (HttpClient client = CreateHttpClient())
{
await LoopbackServer.CreateServerAsync(async (server, uri) =>
{
string responseBody =
"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
"Content-Length: 0\r\n" +
"Connection: close\r\n" +
"\r\n";
// Make first request.
Task<string> request1 = client.GetStringAsync(uri);
await server.AcceptConnectionAsync(async connection1 =>
{
await connection1.ReadRequestHeaderAndSendCustomResponseAsync(responseBody);
await request1;
// Make second request and expect it to be served from a different connection.
Task<string> request2 = client.GetStringAsync(uri);
await server.AcceptConnectionAsync(async connection2 =>
{
await connection2.ReadRequestHeaderAndSendCustomResponseAsync(responseBody);
await request2;
});
});
});
}
}
[Theory]
[InlineData("PooledConnectionLifetime")]
[InlineData("PooledConnectionIdleTimeout")]
public async Task SmallConnectionTimeout_SubsequentRequestUsesDifferentConnection(string timeoutPropertyName)
{
using (var handler = new SocketsHttpHandler())
{
switch (timeoutPropertyName)
{
case "PooledConnectionLifetime": handler.PooledConnectionLifetime = TimeSpan.FromMilliseconds(1); break;
case "PooledConnectionIdleTimeout": handler.PooledConnectionLifetime = TimeSpan.FromMilliseconds(1); break;
default: throw new ArgumentOutOfRangeException(nameof(timeoutPropertyName));
}
using (HttpClient client = new HttpClient(handler))
{
await LoopbackServer.CreateServerAsync(async (server, uri) =>
{
// Make first request.
Task<string> request1 = client.GetStringAsync(uri);
await server.AcceptConnectionAsync(async connection =>
{
await connection.ReadRequestHeaderAndSendResponseAsync();
await request1;
// Wait a small amount of time before making the second request, to give the first request time to timeout.
await Task.Delay(100);
// Make second request and expect it to be served from a different connection.
Task<string> request2 = client.GetStringAsync(uri);
await server.AcceptConnectionAsync(async connection2 =>
{
await connection2.ReadRequestHeaderAndSendResponseAsync();
await request2;
});
});
});
}
}
}
}
public sealed class SocketsHttpHandler_PublicAPIBehavior_Test
{
private static async Task IssueRequestAsync(HttpMessageHandler handler)
{
using (var c = new HttpMessageInvoker(handler, disposeHandler: false))
await Assert.ThrowsAnyAsync<Exception>(() =>
c.SendAsync(new HttpRequestMessage(HttpMethod.Get, new Uri("/shouldquicklyfail", UriKind.Relative)), default));
}
[Fact]
public void AllowAutoRedirect_GetSet_Roundtrips()
{
using (var handler = new SocketsHttpHandler())
{
Assert.True(handler.AllowAutoRedirect);
handler.AllowAutoRedirect = true;
Assert.True(handler.AllowAutoRedirect);
handler.AllowAutoRedirect = false;
Assert.False(handler.AllowAutoRedirect);
}
}
[Fact]
public void AutomaticDecompression_GetSet_Roundtrips()
{
using (var handler = new SocketsHttpHandler())
{
Assert.Equal(DecompressionMethods.None, handler.AutomaticDecompression);
handler.AutomaticDecompression = DecompressionMethods.GZip;
Assert.Equal(DecompressionMethods.GZip, handler.AutomaticDecompression);
handler.AutomaticDecompression = DecompressionMethods.Deflate;
Assert.Equal(DecompressionMethods.Deflate, handler.AutomaticDecompression);
handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
Assert.Equal(DecompressionMethods.GZip | DecompressionMethods.Deflate, handler.AutomaticDecompression);
}
}
[Fact]
public void CookieContainer_GetSet_Roundtrips()
{
using (var handler = new SocketsHttpHandler())
{
CookieContainer container = handler.CookieContainer;
Assert.Same(container, handler.CookieContainer);
var newContainer = new CookieContainer();
handler.CookieContainer = newContainer;
Assert.Same(newContainer, handler.CookieContainer);
}
}
[Fact]
public void Credentials_GetSet_Roundtrips()
{
using (var handler = new SocketsHttpHandler())
{
Assert.Null(handler.Credentials);
var newCredentials = new NetworkCredential("username", "password");
handler.Credentials = newCredentials;
Assert.Same(newCredentials, handler.Credentials);
}
}
[Fact]
public void DefaultProxyCredentials_GetSet_Roundtrips()
{
using (var handler = new SocketsHttpHandler())
{
Assert.Null(handler.DefaultProxyCredentials);
var newCredentials = new NetworkCredential("username", "password");
handler.DefaultProxyCredentials = newCredentials;
Assert.Same(newCredentials, handler.DefaultProxyCredentials);
}
}
[Fact]
public void MaxAutomaticRedirections_GetSet_Roundtrips()
{
using (var handler = new SocketsHttpHandler())
{
Assert.Equal(50, handler.MaxAutomaticRedirections);
handler.MaxAutomaticRedirections = int.MaxValue;
Assert.Equal(int.MaxValue, handler.MaxAutomaticRedirections);
handler.MaxAutomaticRedirections = 1;
Assert.Equal(1, handler.MaxAutomaticRedirections);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.MaxAutomaticRedirections = 0);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.MaxAutomaticRedirections = -1);
}
}
[Fact]
public void MaxConnectionsPerServer_GetSet_Roundtrips()
{
using (var handler = new SocketsHttpHandler())
{
Assert.Equal(int.MaxValue, handler.MaxConnectionsPerServer);
handler.MaxConnectionsPerServer = int.MaxValue;
Assert.Equal(int.MaxValue, handler.MaxConnectionsPerServer);
handler.MaxConnectionsPerServer = 1;
Assert.Equal(1, handler.MaxConnectionsPerServer);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.MaxConnectionsPerServer = 0);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.MaxConnectionsPerServer = -1);
}
}
[Fact]
public void MaxResponseHeadersLength_GetSet_Roundtrips()
{
using (var handler = new SocketsHttpHandler())
{
Assert.Equal(64, handler.MaxResponseHeadersLength);
handler.MaxResponseHeadersLength = int.MaxValue;
Assert.Equal(int.MaxValue, handler.MaxResponseHeadersLength);
handler.MaxResponseHeadersLength = 1;
Assert.Equal(1, handler.MaxResponseHeadersLength);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.MaxResponseHeadersLength = 0);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.MaxResponseHeadersLength = -1);
}
}
[Fact]
public void PreAuthenticate_GetSet_Roundtrips()
{
using (var handler = new SocketsHttpHandler())
{
Assert.False(handler.PreAuthenticate);
handler.PreAuthenticate = false;
Assert.False(handler.PreAuthenticate);
handler.PreAuthenticate = true;
Assert.True(handler.PreAuthenticate);
}
}
[Fact]
public void PooledConnectionIdleTimeout_GetSet_Roundtrips()
{
using (var handler = new SocketsHttpHandler())
{
Assert.Equal(TimeSpan.FromMinutes(2), handler.PooledConnectionIdleTimeout);
handler.PooledConnectionIdleTimeout = Timeout.InfiniteTimeSpan;
Assert.Equal(Timeout.InfiniteTimeSpan, handler.PooledConnectionIdleTimeout);
handler.PooledConnectionIdleTimeout = TimeSpan.FromSeconds(0);
Assert.Equal(TimeSpan.FromSeconds(0), handler.PooledConnectionIdleTimeout);
handler.PooledConnectionIdleTimeout = TimeSpan.FromSeconds(1);
Assert.Equal(TimeSpan.FromSeconds(1), handler.PooledConnectionIdleTimeout);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.PooledConnectionIdleTimeout = TimeSpan.FromSeconds(-2));
}
}
[Fact]
public void PooledConnectionLifetime_GetSet_Roundtrips()
{
using (var handler = new SocketsHttpHandler())
{
Assert.Equal(Timeout.InfiniteTimeSpan, handler.PooledConnectionLifetime);
handler.PooledConnectionLifetime = Timeout.InfiniteTimeSpan;
Assert.Equal(Timeout.InfiniteTimeSpan, handler.PooledConnectionLifetime);
handler.PooledConnectionLifetime = TimeSpan.FromSeconds(0);
Assert.Equal(TimeSpan.FromSeconds(0), handler.PooledConnectionLifetime);
handler.PooledConnectionLifetime = TimeSpan.FromSeconds(1);
Assert.Equal(TimeSpan.FromSeconds(1), handler.PooledConnectionLifetime);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.PooledConnectionLifetime = TimeSpan.FromSeconds(-2));
}
}
[Fact]
public void Properties_Roundtrips()
{
using (var handler = new SocketsHttpHandler())
{
IDictionary<string, object> props = handler.Properties;
Assert.NotNull(props);
Assert.Empty(props);
props.Add("hello", "world");
Assert.Equal(1, props.Count);
Assert.Equal("world", props["hello"]);
}
}
[Fact]
public void Proxy_GetSet_Roundtrips()
{
using (var handler = new SocketsHttpHandler())
{
Assert.Null(handler.Proxy);
var proxy = new WebProxy();
handler.Proxy = proxy;
Assert.Same(proxy, handler.Proxy);
}
}
[Fact]
public void SslOptions_GetSet_Roundtrips()
{
using (var handler = new SocketsHttpHandler())
{
SslClientAuthenticationOptions options = handler.SslOptions;
Assert.NotNull(options);
Assert.True(options.AllowRenegotiation);
Assert.Null(options.ApplicationProtocols);
Assert.Equal(X509RevocationMode.NoCheck, options.CertificateRevocationCheckMode);
Assert.Null(options.ClientCertificates);
Assert.Equal(SslProtocols.None, options.EnabledSslProtocols);
Assert.Equal(EncryptionPolicy.RequireEncryption, options.EncryptionPolicy);
Assert.Null(options.LocalCertificateSelectionCallback);
Assert.Null(options.RemoteCertificateValidationCallback);
Assert.Null(options.TargetHost);
Assert.Same(options, handler.SslOptions);
var newOptions = new SslClientAuthenticationOptions();
handler.SslOptions = newOptions;
Assert.Same(newOptions, handler.SslOptions);
}
}
[Fact]
public void UseCookies_GetSet_Roundtrips()
{
using (var handler = new SocketsHttpHandler())
{
Assert.True(handler.UseCookies);
handler.UseCookies = true;
Assert.True(handler.UseCookies);
handler.UseCookies = false;
Assert.False(handler.UseCookies);
}
}
[Fact]
public void UseProxy_GetSet_Roundtrips()
{
using (var handler = new SocketsHttpHandler())
{
Assert.True(handler.UseProxy);
handler.UseProxy = false;
Assert.False(handler.UseProxy);
handler.UseProxy = true;
Assert.True(handler.UseProxy);
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task AfterDisposeSendAsync_GettersUsable_SettersThrow(bool dispose)
{
using (var handler = new SocketsHttpHandler())
{
Type expectedExceptionType;
if (dispose)
{
handler.Dispose();
expectedExceptionType = typeof(ObjectDisposedException);
}
else
{
await IssueRequestAsync(handler);
expectedExceptionType = typeof(InvalidOperationException);
}
Assert.True(handler.AllowAutoRedirect);
Assert.Equal(DecompressionMethods.None, handler.AutomaticDecompression);
Assert.NotNull(handler.CookieContainer);
Assert.Null(handler.Credentials);
Assert.Null(handler.DefaultProxyCredentials);
Assert.Equal(50, handler.MaxAutomaticRedirections);
Assert.Equal(int.MaxValue, handler.MaxConnectionsPerServer);
Assert.Equal(64, handler.MaxResponseHeadersLength);
Assert.False(handler.PreAuthenticate);
Assert.Equal(TimeSpan.FromMinutes(2), handler.PooledConnectionIdleTimeout);
Assert.Equal(Timeout.InfiniteTimeSpan, handler.PooledConnectionLifetime);
Assert.NotNull(handler.Properties);
Assert.Null(handler.Proxy);
Assert.NotNull(handler.SslOptions);
Assert.True(handler.UseCookies);
Assert.True(handler.UseProxy);
Assert.Throws(expectedExceptionType, () => handler.AllowAutoRedirect = false);
Assert.Throws(expectedExceptionType, () => handler.AutomaticDecompression = DecompressionMethods.GZip);
Assert.Throws(expectedExceptionType, () => handler.CookieContainer = new CookieContainer());
Assert.Throws(expectedExceptionType, () => handler.Credentials = new NetworkCredential("anotheruser", "anotherpassword"));
Assert.Throws(expectedExceptionType, () => handler.DefaultProxyCredentials = new NetworkCredential("anotheruser", "anotherpassword"));
Assert.Throws(expectedExceptionType, () => handler.MaxAutomaticRedirections = 2);
Assert.Throws(expectedExceptionType, () => handler.MaxConnectionsPerServer = 2);
Assert.Throws(expectedExceptionType, () => handler.MaxResponseHeadersLength = 2);
Assert.Throws(expectedExceptionType, () => handler.PreAuthenticate = false);
Assert.Throws(expectedExceptionType, () => handler.PooledConnectionIdleTimeout = TimeSpan.FromSeconds(2));
Assert.Throws(expectedExceptionType, () => handler.PooledConnectionLifetime = TimeSpan.FromSeconds(2));
Assert.Throws(expectedExceptionType, () => handler.Proxy = new WebProxy());
Assert.Throws(expectedExceptionType, () => handler.SslOptions = new SslClientAuthenticationOptions());
Assert.Throws(expectedExceptionType, () => handler.UseCookies = false);
Assert.Throws(expectedExceptionType, () => handler.UseProxy = false);
}
}
}
public sealed class SocketsHttpHandler_ExternalConfiguration_Test : HttpClientTestBase
{
private const string EnvironmentVariableSettingName = "DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER";
private const string AppContextSettingName = "System.Net.Http.UseSocketsHttpHandler";
private static bool UseSocketsHttpHandlerEnvironmentVariableIsNotSet =>
string.IsNullOrEmpty(Environment.GetEnvironmentVariable(EnvironmentVariableSettingName));
[ConditionalTheory(nameof(UseSocketsHttpHandlerEnvironmentVariableIsNotSet))]
[InlineData("true", true)]
[InlineData("TRUE", true)]
[InlineData("tRuE", true)]
[InlineData("1", true)]
[InlineData("0", false)]
[InlineData("false", false)]
[InlineData("helloworld", false)]
[InlineData("", false)]
public void HttpClientHandler_SettingEnvironmentVariableChangesDefault(string envVarValue, bool expectedUseSocketsHandler)
{
RemoteInvoke((innerEnvVarValue, innerExpectedUseSocketsHandler) =>
{
Environment.SetEnvironmentVariable(EnvironmentVariableSettingName, innerEnvVarValue);
using (var handler = new HttpClientHandler())
{
Assert.Equal(bool.Parse(innerExpectedUseSocketsHandler), IsSocketsHttpHandler(handler));
}
return SuccessExitCode;
}, envVarValue, expectedUseSocketsHandler.ToString()).Dispose();
}
[Fact]
public void HttpClientHandler_SettingAppContextChangesDefault()
{
RemoteInvoke(() =>
{
AppContext.SetSwitch(AppContextSettingName, isEnabled: true);
using (var handler = new HttpClientHandler())
{
Assert.True(IsSocketsHttpHandler(handler));
}
AppContext.SetSwitch(AppContextSettingName, isEnabled: false);
using (var handler = new HttpClientHandler())
{
Assert.False(IsSocketsHttpHandler(handler));
}
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void HttpClientHandler_AppContextOverridesEnvironmentVariable()
{
RemoteInvoke(() =>
{
Environment.SetEnvironmentVariable(EnvironmentVariableSettingName, "true");
using (var handler = new HttpClientHandler())
{
Assert.True(IsSocketsHttpHandler(handler));
}
AppContext.SetSwitch(AppContextSettingName, isEnabled: false);
using (var handler = new HttpClientHandler())
{
Assert.False(IsSocketsHttpHandler(handler));
}
AppContext.SetSwitch(AppContextSettingName, isEnabled: true);
Environment.SetEnvironmentVariable(EnvironmentVariableSettingName, null);
using (var handler = new HttpClientHandler())
{
Assert.True(IsSocketsHttpHandler(handler));
}
return SuccessExitCode;
}).Dispose();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Text;
using DokanNet.Native;
using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME;
namespace DokanNet
{
internal sealed class DokanOperationProxy
{
#region Delegates
public delegate int CleanupDelegate(
[MarshalAs(UnmanagedType.LPWStr)] string rawFileName,
[MarshalAs(UnmanagedType.LPStruct), In, Out] DokanFileInfo rawFileInfo);
public delegate int CloseFileDelegate(
[MarshalAs(UnmanagedType.LPWStr)] string rawFileName,
[MarshalAs(UnmanagedType.LPStruct), In, Out] DokanFileInfo rawFileInfo);
public delegate int CreateDirectoryDelegate(
[MarshalAs(UnmanagedType.LPWStr)] string rawFileName,
[MarshalAs(UnmanagedType.LPStruct), In/*, Out*/] DokanFileInfo rawFileInfo);
public delegate int CreateFileDelegate(
[MarshalAs(UnmanagedType.LPWStr)] string rawFileName, uint rawAccessMode, uint rawShare,
uint rawCreationDisposition, uint rawFlagsAndAttributes,
[MarshalAs(UnmanagedType.LPStruct), In, Out] DokanFileInfo dokanFileInfo);
public delegate int DeleteDirectoryDelegate(
[MarshalAs(UnmanagedType.LPWStr)] string rawFileName,
[MarshalAs(UnmanagedType.LPStruct), In/*, Out*/] DokanFileInfo rawFileInfo);
public delegate int DeleteFileDelegate(
[MarshalAs(UnmanagedType.LPWStr)] string rawFileName,
[MarshalAs(UnmanagedType.LPStruct), In/*, Out*/] DokanFileInfo rawFileInfo);
public delegate int FindFilesDelegate(
[MarshalAs(UnmanagedType.LPWStr)] string rawFileName, IntPtr rawFillFindData, // function pointer
[MarshalAs(UnmanagedType.LPStruct), In/*, Out*/] DokanFileInfo rawFileInfo);
/* public delegate int FindFilesWithPatternDelegate(
[MarshalAs(UnmanagedType.LPWStr)] string rawFileName,
[MarshalAs(UnmanagedType.LPWStr)] string rawSearchPattern,
IntPtr rawFillFindData, // function pointer
[MarshalAs(UnmanagedType.LPStruct), In, Out] DokanFileInfo rawFileInfo);*/
public delegate int FlushFileBuffersDelegate(
[MarshalAs(UnmanagedType.LPWStr)] string rawFileName,
[MarshalAs(UnmanagedType.LPStruct), In/*, Out*/] DokanFileInfo rawFileInfo);
public delegate int GetDiskFreeSpaceDelegate(ref long rawFreeBytesAvailable, ref long rawTotalNumberOfBytes,
ref long rawTotalNumberOfFreeBytes,
[MarshalAs(UnmanagedType.LPStruct), In] DokanFileInfo rawFileInfo);
public delegate int GetFileInformationDelegate(
[MarshalAs(UnmanagedType.LPWStr)] string fileName, ref BY_HANDLE_FILE_INFORMATION handleFileInfo,
[MarshalAs(UnmanagedType.LPStruct), In/*, Out*/] DokanFileInfo fileInfo);
public delegate int GetFileSecurityDelegate(
[MarshalAs(UnmanagedType.LPWStr)] string rawFileName,[In] ref SECURITY_INFORMATION rawRequestedInformation,
IntPtr rawSecurityDescriptor, uint rawSecurityDescriptorLength,
ref uint rawSecurityDescriptorLengthNeeded,
[MarshalAs(UnmanagedType.LPStruct), In/*, Out*/] DokanFileInfo rawFileInfo);
public delegate int GetVolumeInformationDelegate(
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder rawVolumeNameBuffer, uint rawVolumeNameSize,
ref uint rawVolumeSerialNumber,
ref uint rawMaximumComponentLength, ref FileSystemFeatures rawFileSystemFlags,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder rawFileSystemNameBuffer,
uint rawFileSystemNameSize, [MarshalAs(UnmanagedType.LPStruct), In] DokanFileInfo rawFileInfo);
public delegate int LockFileDelegate(
[MarshalAs(UnmanagedType.LPWStr)] string rawFileName, long rawByteOffset, long rawLength,
[MarshalAs(UnmanagedType.LPStruct), In/*, Out*/] DokanFileInfo rawFileInfo);
public delegate int MoveFileDelegate(
[MarshalAs(UnmanagedType.LPWStr)] string rawFileName,
[MarshalAs(UnmanagedType.LPWStr)] string rawNewFileName,
[MarshalAs(UnmanagedType.Bool)] bool rawReplaceIfExisting,
[MarshalAs(UnmanagedType.LPStruct), In, Out] DokanFileInfo rawFileInfo);
public delegate int OpenDirectoryDelegate(
[MarshalAs(UnmanagedType.LPWStr)] string fileName,
[MarshalAs(UnmanagedType.LPStruct), In, Out] DokanFileInfo fileInfo);
public delegate int ReadFileDelegate(
[MarshalAs(UnmanagedType.LPWStr)] string rawFileName,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2), Out] byte[] rawBuffer, uint rawBufferLength,
ref int rawReadLength, long rawOffset,
[MarshalAs(UnmanagedType.LPStruct), In/*, Out*/] DokanFileInfo rawFileInfo);
public delegate int SetAllocationSizeDelegate(
[MarshalAs(UnmanagedType.LPWStr)] string rawFileName, long rawLength,
[MarshalAs(UnmanagedType.LPStruct), In/*, Out*/] DokanFileInfo rawFileInfo);
public delegate int SetEndOfFileDelegate(
[MarshalAs(UnmanagedType.LPWStr)] string rawFileName, long rawByteOffset,
[MarshalAs(UnmanagedType.LPStruct), In/*, Out*/] DokanFileInfo rawFileInfo);
public delegate int SetFileAttributesDelegate(
[MarshalAs(UnmanagedType.LPWStr)] string rawFileName, uint rawAttributes,
[MarshalAs(UnmanagedType.LPStruct), In/*, Out*/] DokanFileInfo rawFileInfo);
public delegate int SetFileSecurityDelegate(
[MarshalAs(UnmanagedType.LPWStr)] string rawFileName,[In] ref SECURITY_INFORMATION rawSecurityInformation,
IntPtr rawSecurityDescriptor, uint rawSecurityDescriptorLength,
[MarshalAs(UnmanagedType.LPStruct), In/*, Out*/] DokanFileInfo rawFileInfo);
public delegate int SetFileTimeDelegate(
[MarshalAs(UnmanagedType.LPWStr)] string rawFileName,
ref FILETIME rawCreationTime,
ref FILETIME rawLastAccessTime,
ref FILETIME rawLastWriteTime, [MarshalAs(UnmanagedType.LPStruct), In/*, Out*/] DokanFileInfo rawFileInfo);
public delegate int UnlockFileDelegate(
[MarshalAs(UnmanagedType.LPWStr)] string rawFileName, long rawByteOffset, long rawLength,
[MarshalAs(UnmanagedType.LPStruct), In/*, Out*/] DokanFileInfo rawFileInfo);
public delegate int UnmountDelegate([MarshalAs(UnmanagedType.LPStruct), In] DokanFileInfo rawFileInfo);
public delegate int WriteFileDelegate(
[MarshalAs(UnmanagedType.LPWStr)] string rawFileName,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] rawBuffer, uint rawNumberOfBytesToWrite,
ref int rawNumberOfBytesWritten, long rawOffset,
[MarshalAs(UnmanagedType.LPStruct), In/*, Out*/] DokanFileInfo rawFileInfo);
#endregion
private const int ERROR_FILE_NOT_FOUND = -2;
private const int ERROR_INVALID_FUNCTION = -1;
private const int ERROR_SUCCESS = 0;
private const int ERROR_INSUFFICIENT_BUFFER = -122;
private const int ERROR_INVALID_HANDLE = -6;
private readonly IDokanOperations _operations;
private readonly uint _serialNumber;
public DokanOperationProxy(IDokanOperations operations)
{
_operations = operations;
_serialNumber = (uint) _operations.GetHashCode();
}
public int CreateFileProxy(string rawFileName, uint rawAccessMode,
uint rawShare, uint rawCreationDisposition, uint rawFlagsAndAttributes,
DokanFileInfo rawFileInfo)
{
try
{
return (int) _operations.CreateFile(rawFileName, (FileAccess) rawAccessMode, (FileShare) rawShare,
(FileMode) rawCreationDisposition,
(FileOptions) (rawFlagsAndAttributes & 0xffffc000), //& 0xffffc000
(FileAttributes) (rawFlagsAndAttributes & 0x3fff), rawFileInfo);
//& 0x3ffflower 14 bits i think are file atributes and rest are file options WRITE_TROUGH etc.
}
catch
{
#if DEBUG
throw;
#else
return ERROR_FILE_NOT_FOUND;
#endif
}
}
////
public int OpenDirectoryProxy(string rawFileName,
DokanFileInfo rawFileInfo)
{
try
{
return (int) _operations.OpenDirectory(rawFileName, rawFileInfo);
}
catch
{
#if DEBUG
throw;
#else
return ERROR_INVALID_FUNCTION;
#endif
}
}
////
public int CreateDirectoryProxy(string rawFileName,
DokanFileInfo rawFileInfo)
{
try
{
return (int) _operations.CreateDirectory(rawFileName, rawFileInfo);
}
catch
{
#if DEBUG
throw;
#else
return ERROR_INVALID_FUNCTION;
#endif
}
}
////
public int CleanupProxy(string rawFileName,
DokanFileInfo rawFileInfo)
{
try
{
return (int) _operations.Cleanup(rawFileName, rawFileInfo);
}
catch
{
#if DEBUG
throw;
#else
return ERROR_INVALID_FUNCTION;
#endif
}
}
////
public int CloseFileProxy(string rawFileName,
DokanFileInfo rawFileInfo)
{
try
{
return (int) _operations.CloseFile(rawFileName, rawFileInfo);
}
catch
{
#if DEBUG
throw;
#else
return ERROR_INVALID_FUNCTION;
#endif
}
}
////
public int ReadFileProxy(string rawFileName, byte[] rawBuffer,
uint rawBufferLength, ref int rawReadLength, long rawOffset,
DokanFileInfo rawFileInfo)
{
try
{
return (int) _operations.ReadFile(rawFileName, rawBuffer, out rawReadLength, rawOffset,
rawFileInfo);
}
catch
{
#if DEBUG
throw;
#else
return ERROR_INVALID_FUNCTION;
#endif
}
}
////
public int WriteFileProxy(string rawFileName, byte[] rawBuffer,
uint rawNumberOfBytesToWrite, ref int rawNumberOfBytesWritten, long rawOffset,
DokanFileInfo rawFileInfo)
{
try
{
return (int) _operations.WriteFile(rawFileName, rawBuffer,
out rawNumberOfBytesWritten, rawOffset,
rawFileInfo);
}
catch
{
#if DEBUG
throw;
#else
return ERROR_INVALID_FUNCTION;
#endif
}
}
////
public int FlushFileBuffersProxy(string rawFileName,
DokanFileInfo rawFileInfo)
{
try
{
return (int) _operations.FlushFileBuffers(rawFileName, rawFileInfo);
}
catch
{
#if DEBUG
throw;
#else
return ERROR_INVALID_FUNCTION;
#endif
}
}
////
public int GetFileInformationProxy(string rawFileName,
ref BY_HANDLE_FILE_INFORMATION rawHandleFileInformation,
DokanFileInfo rawFileInfo)
{
FileInformation fi ;
try
{
int ret = (int) _operations.GetFileInformation(rawFileName, out fi, rawFileInfo);
if (ret == ERROR_SUCCESS)
{
Debug.Assert(fi.FileName!=null);
rawHandleFileInformation.dwFileAttributes = (uint) fi.Attributes /* + FILE_ATTRIBUTE_VIRTUAL*/;
long ctime = fi.CreationTime.ToFileTime();
long atime = fi.LastAccessTime.ToFileTime();
long mtime = fi.LastWriteTime.ToFileTime();
rawHandleFileInformation.ftCreationTime.dwHighDateTime = (int) (ctime >> 32);
rawHandleFileInformation.ftCreationTime.dwLowDateTime =
(int) (ctime & 0xffffffff);
rawHandleFileInformation.ftLastAccessTime.dwHighDateTime =
(int) (atime >> 32);
rawHandleFileInformation.ftLastAccessTime.dwLowDateTime =
(int) (atime & 0xffffffff);
rawHandleFileInformation.ftLastWriteTime.dwHighDateTime =
(int) (mtime >> 32);
rawHandleFileInformation.ftLastWriteTime.dwLowDateTime =
(int) (mtime & 0xffffffff);
rawHandleFileInformation.dwVolumeSerialNumber = _serialNumber;
rawHandleFileInformation.nFileSizeLow = (uint) (fi.Length & 0xffffffff);
rawHandleFileInformation.nFileSizeHigh = (uint) (fi.Length >> 32);
rawHandleFileInformation.dwNumberOfLinks = 1;
rawHandleFileInformation.nFileIndexHigh = 0;
rawHandleFileInformation.nFileIndexLow = (uint) fi.FileName.GetHashCode();
}
return ret;
}
catch
{
#if DEBUG
throw;
#else
return ERROR_INVALID_FUNCTION;
#endif
}
}
////
public int FindFilesProxy(string rawFileName, IntPtr rawFillFindData,
// function pointer
DokanFileInfo rawFileInfo)
{
try
{
IList<FileInformation> files ;
int ret = (int) _operations.FindFiles(rawFileName, out files, rawFileInfo);
Debug.Assert(files!=null);
if (ret == ERROR_SUCCESS&&files.Count!=0)
{
var fill =
(FILL_FIND_DATA)Marshal.GetDelegateForFunctionPointer(rawFillFindData, typeof(FILL_FIND_DATA));
// Used a single entry call to speed up the "enumeration" of the list
for (int index = 0; index < files.Count; index++)
{
Addto(fill, rawFileInfo, files[index]);
}
}
return ret;
}
catch
{
#if DEBUG
throw;
#else
return ERROR_INVALID_HANDLE;
#endif
}
}
private static void Addto(FILL_FIND_DATA fill, DokanFileInfo rawFileInfo, FileInformation fi)
{
Debug.Assert(!String.IsNullOrEmpty(fi.FileName));
long ctime = fi.CreationTime.ToFileTime();
long atime = fi.LastAccessTime.ToFileTime();
long mtime = fi.LastWriteTime.ToFileTime();
var data = new WIN32_FIND_DATA
{
dwFileAttributes = fi.Attributes,
ftCreationTime =
{
dwHighDateTime = (int) (ctime >> 32),
dwLowDateTime = (int) (ctime & 0xffffffff)
},
ftLastAccessTime =
{
dwHighDateTime = (int) (atime >> 32),
dwLowDateTime = (int) (atime & 0xffffffff)
},
ftLastWriteTime =
{
dwHighDateTime = (int) (mtime >> 32),
dwLowDateTime = (int) (mtime & 0xffffffff)
},
nFileSizeLow = (uint) (fi.Length & 0xffffffff),
nFileSizeHigh = (uint) (fi.Length >> 32),
cFileName = fi.FileName
};
//ZeroMemory(&data, sizeof(WIN32_FIND_DATAW));
fill(ref data, rawFileInfo);
}
////
public int SetEndOfFileProxy(string rawFileName, long rawByteOffset,
DokanFileInfo rawFileInfo)
{
try
{
return (int) _operations.SetEndOfFile(rawFileName, rawByteOffset, rawFileInfo);
}
catch
{
#if DEBUG
throw;
#else
return ERROR_INVALID_FUNCTION;
#endif
}
}
public int SetAllocationSizeProxy(string rawFileName, long rawLength,
DokanFileInfo rawFileInfo)
{
try
{
return (int) _operations.SetAllocationSize(rawFileName, rawLength, rawFileInfo);
}
catch
{
#if DEBUG
throw;
#else
return ERROR_INVALID_FUNCTION;
#endif
}
}
////
public int SetFileAttributesProxy(string rawFileName, uint rawAttributes,
DokanFileInfo rawFileInfo)
{
try
{
return (int) _operations.SetFileAttributes(rawFileName, (FileAttributes) rawAttributes, rawFileInfo);
}
catch
{
#if DEBUG
throw;
#else
return ERROR_INVALID_FUNCTION;
#endif
}
}
////
public int SetFileTimeProxy(string rawFileName,
ref FILETIME rawCreationTime,
ref FILETIME rawLastAccessTime,
ref FILETIME rawLastWriteTime,
DokanFileInfo rawFileInfo)
{
var ctime = ( rawCreationTime.dwLowDateTime != 0 || rawCreationTime.dwHighDateTime != 0) && (rawCreationTime.dwLowDateTime != -1 || rawCreationTime.dwHighDateTime != -1)
? DateTime.FromFileTime(((long) rawCreationTime.dwHighDateTime << 32) |
(uint) rawCreationTime.dwLowDateTime)
: (DateTime?) null;
var atime =(rawLastAccessTime.dwLowDateTime != 0 || rawLastAccessTime.dwHighDateTime != 0) && (rawLastAccessTime.dwLowDateTime != -1 || rawLastAccessTime.dwHighDateTime != -1)
? DateTime.FromFileTime(((long) rawLastAccessTime.dwHighDateTime << 32) |
(uint) rawLastAccessTime.dwLowDateTime)
: (DateTime?) null;
var mtime = (rawLastWriteTime.dwLowDateTime != 0 || rawLastWriteTime.dwHighDateTime != 0) && (rawLastWriteTime.dwLowDateTime != -1 || rawLastWriteTime.dwHighDateTime != -1)
? DateTime.FromFileTime(((long) rawLastWriteTime.dwHighDateTime << 32) |
(uint) rawLastWriteTime.dwLowDateTime)
: (DateTime?) null;
try
{
return (int) _operations.SetFileTime(rawFileName, ctime, atime,
mtime, rawFileInfo);
}
catch
{
#if DEBUG
throw;
#else
return ERROR_INVALID_FUNCTION;
#endif
}
}
////
public int DeleteFileProxy(string rawFileName, DokanFileInfo rawFileInfo)
{
try
{
return (int) _operations.DeleteFile(rawFileName, rawFileInfo);
}
catch
{
#if DEBUG
throw;
#else
return ERROR_INVALID_FUNCTION;
#endif
}
}
////
public int DeleteDirectoryProxy(string rawFileName,
DokanFileInfo rawFileInfo)
{
try
{
return (int) _operations.DeleteDirectory(rawFileName, rawFileInfo);
}
catch
{
#if DEBUG
throw;
#else
return ERROR_INVALID_FUNCTION;
#endif
}
}
////
public int MoveFileProxy(string rawFileName,
string rawNewFileName, bool rawReplaceIfExisting,
DokanFileInfo rawFileInfo)
{
try
{
return (int) _operations.MoveFile(rawFileName, rawNewFileName, rawReplaceIfExisting,
rawFileInfo);
}
catch
{
#if DEBUG
throw;
#else
return ERROR_INVALID_FUNCTION;
#endif
}
}
////
public int LockFileProxy(string rawFileName, long rawByteOffset,
long rawLength, DokanFileInfo rawFileInfo)
{
try
{
return
(int) _operations.LockFile(rawFileName, rawByteOffset, rawLength, rawFileInfo);
}
catch
{
#if DEBUG
throw;
#else
return ERROR_INVALID_FUNCTION;
#endif
}
}
////
public int UnlockFileProxy(string rawFileName, long rawByteOffset,
long rawLength, DokanFileInfo rawFileInfo)
{
try
{
return
(int)
_operations.UnlockFile(rawFileName, rawByteOffset, rawLength, rawFileInfo);
}
catch
{
#if DEBUG
throw;
#else
return ERROR_INVALID_FUNCTION;
#endif
}
}
////
public int GetDiskFreeSpaceProxy(ref long rawFreeBytesAvailable, ref long rawTotalNumberOfBytes,
ref long rawTotalNumberOfFreeBytes, DokanFileInfo rawFileInfo)
{
try
{
return (int) _operations.GetDiskFreeSpace(out rawFreeBytesAvailable, out rawTotalNumberOfBytes,
out rawTotalNumberOfFreeBytes,
rawFileInfo);
}
catch
{
#if DEBUG
throw;
#else
return ERROR_INVALID_FUNCTION;
#endif
}
}
public int GetVolumeInformationProxy(StringBuilder rawVolumeNameBuffer,
uint rawVolumeNameSize,
ref uint rawVolumeSerialNumber,
ref uint rawMaximumComponentLength, ref FileSystemFeatures rawFileSystemFlags,
StringBuilder rawFileSystemNameBuffer,
uint rawFileSystemNameSize,
DokanFileInfo fileInfo)
{
rawMaximumComponentLength = 256;
rawVolumeSerialNumber = _serialNumber;
string label;
string name;
try
{
int ret = (int) _operations.GetVolumeInformation(out label,
out rawFileSystemFlags, out name,
fileInfo);
if (ret == ERROR_SUCCESS)
{
Debug.Assert(!String.IsNullOrEmpty(name));
Debug.Assert(!String.IsNullOrEmpty(label));
rawVolumeNameBuffer.Append(label);
rawFileSystemNameBuffer.Append(name);
}
return ret;
}
catch
{
#if DEBUG
throw;
#else
return ERROR_INVALID_FUNCTION;
#endif
}
}
public int UnmountProxy(DokanFileInfo rawFileInfo)
{
try
{
return (int) _operations.Unmount(rawFileInfo);
}
catch
{
#if DEBUG
throw;
#else
return ERROR_INVALID_FUNCTION;
#endif
}
}
public int GetFileSecurityProxy(string rawFileName, ref SECURITY_INFORMATION rawRequestedInformation,
IntPtr rawSecurityDescriptor, uint rawSecurityDescriptorLength,
ref uint rawSecurityDescriptorLengthNeeded,
DokanFileInfo rawFileInfo)
{
FileSystemSecurity sec;
var sect = AccessControlSections.None;
if (rawRequestedInformation.HasFlag(SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION))
{
sect |= AccessControlSections.Owner;
}
if (rawRequestedInformation.HasFlag(SECURITY_INFORMATION.GROUP_SECURITY_INFORMATION))
{
sect |= AccessControlSections.Group;
}
if (rawRequestedInformation.HasFlag(SECURITY_INFORMATION.DACL_SECURITY_INFORMATION) ||
rawRequestedInformation.HasFlag(SECURITY_INFORMATION.PROTECTED_DACL_SECURITY_INFORMATION) ||
rawRequestedInformation.HasFlag(SECURITY_INFORMATION.UNPROTECTED_DACL_SECURITY_INFORMATION))
{
sect |= AccessControlSections.Access;
}
if (rawRequestedInformation.HasFlag(SECURITY_INFORMATION.SACL_SECURITY_INFORMATION) ||
rawRequestedInformation.HasFlag(SECURITY_INFORMATION.PROTECTED_SACL_SECURITY_INFORMATION) ||
rawRequestedInformation.HasFlag(SECURITY_INFORMATION.UNPROTECTED_SACL_SECURITY_INFORMATION))
{
sect |= AccessControlSections.Audit;
}
try
{
int ret = (int) _operations.GetFileSecurity(rawFileName, out sec, sect, rawFileInfo);
if (ret == ERROR_SUCCESS /*&& sec != null*/)
{
Debug.Assert(sec!=null);
var buffer = sec.GetSecurityDescriptorBinaryForm();
rawSecurityDescriptorLengthNeeded = (uint)buffer.Length;
if (buffer.Length > rawSecurityDescriptorLength)
{
return ERROR_INSUFFICIENT_BUFFER;
}
Marshal.Copy(buffer, 0, rawSecurityDescriptor, buffer.Length);
}
return ret;
}
catch
{
#if DEBUG
throw;
#else
return ERROR_INVALID_FUNCTION;
#endif
}
}
public int SetFileSecurityProxy(
string rawFileName, ref SECURITY_INFORMATION rawSecurityInformation,
IntPtr rawSecurityDescriptor, uint rawSecurityDescriptorLength,
DokanFileInfo rawFileInfo)
{
var sect = AccessControlSections.None;
if (rawSecurityInformation.HasFlag(SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION))
{
sect |= AccessControlSections.Owner;
}
if (rawSecurityInformation.HasFlag(SECURITY_INFORMATION.GROUP_SECURITY_INFORMATION))
{
sect |= AccessControlSections.Group;
}
if (rawSecurityInformation.HasFlag(SECURITY_INFORMATION.DACL_SECURITY_INFORMATION) ||
rawSecurityInformation.HasFlag(SECURITY_INFORMATION.PROTECTED_DACL_SECURITY_INFORMATION) ||
rawSecurityInformation.HasFlag(SECURITY_INFORMATION.UNPROTECTED_DACL_SECURITY_INFORMATION))
{
sect |= AccessControlSections.Access;
}
if (rawSecurityInformation.HasFlag(SECURITY_INFORMATION.SACL_SECURITY_INFORMATION) ||
rawSecurityInformation.HasFlag(SECURITY_INFORMATION.PROTECTED_SACL_SECURITY_INFORMATION) ||
rawSecurityInformation.HasFlag(SECURITY_INFORMATION.UNPROTECTED_SACL_SECURITY_INFORMATION))
{
sect |= AccessControlSections.Audit;
}
var buffer = new byte[rawSecurityDescriptorLength];
try
{
Marshal.Copy(rawSecurityDescriptor, buffer, 0, (int) rawSecurityDescriptorLength);
var sec = rawFileInfo.IsDirectory ? (FileSystemSecurity) new DirectorySecurity() : new FileSecurity();
sec.SetSecurityDescriptorBinaryForm(buffer);
return (int) _operations.SetFileSecurity(rawFileName, sec, sect, rawFileInfo);
}
catch
{
#if DEBUG
throw;
#else
return ERROR_INVALID_FUNCTION;
#endif
}
}
#region Nested type: FILL_FIND_DATA
private delegate int FILL_FIND_DATA(
ref WIN32_FIND_DATA rawFindData, [MarshalAs(UnmanagedType.LPStruct), In] DokanFileInfo rawFileInfo);
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\Arm\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.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void Encrypt_Vector128_Byte()
{
var test = new AesBinaryOpTest__Encrypt_Vector128_Byte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.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 (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.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 (AdvSimd.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 (AdvSimd.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 (AdvSimd.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 AesBinaryOpTest__Encrypt_Vector128_Byte
{
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(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 16 && alignment != 8) || (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<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, 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<Byte> _fld1;
public Vector128<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
return testStruct;
}
public void RunStructFldScenario(AesBinaryOpTest__Encrypt_Vector128_Byte testClass)
{
var result = Aes.Encrypt(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(AesBinaryOpTest__Encrypt_Vector128_Byte testClass)
{
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = Aes.Encrypt(
AdvSimd.LoadVector128((Byte*)(pFld1)),
AdvSimd.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[16] {0xEF, 0xCD, 0xAB, 0x89, 0x67, 0x45, 0x23, 0x01, 0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA, 0x99, 0x88};
private static Byte[] _data2 = new Byte[16] {0xFF, 0xDD, 0xBB, 0x99, 0x77, 0x55, 0x33, 0x11, 0xEE, 0xCC, 0xAA, 0x88, 0x66, 0x44, 0x22, 0x00};
private static Byte[] _expectedRet = new Byte[16] {0xCA, 0xCA, 0xF5, 0xC4, 0xCA, 0x93, 0xEA, 0xCA, 0x82, 0x28, 0xCA, 0xCA, 0xC1, 0xCA, 0xCA, 0x1B};
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private DataTable _dataTable;
static AesBinaryOpTest__Encrypt_Vector128_Byte()
{
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public AesBinaryOpTest__Encrypt_Vector128_Byte()
{
Succeeded = true;
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
_dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Aes.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Aes.Encrypt(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Aes.Encrypt(
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Aes).GetMethod(nameof(Aes.Encrypt), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Aes).GetMethod(nameof(Aes.Encrypt), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Aes.Encrypt(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Byte>* pClsVar1 = &_clsVar1)
fixed (Vector128<Byte>* pClsVar2 = &_clsVar2)
{
var result = Aes.Encrypt(
AdvSimd.LoadVector128((Byte*)(pClsVar1)),
AdvSimd.LoadVector128((Byte*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Aes.Encrypt(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr));
var right = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Aes.Encrypt(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new AesBinaryOpTest__Encrypt_Vector128_Byte();
var result = Aes.Encrypt(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new AesBinaryOpTest__Encrypt_Vector128_Byte();
fixed (Vector128<Byte>* pFld1 = &test._fld1)
fixed (Vector128<Byte>* pFld2 = &test._fld2)
{
var result = Aes.Encrypt(
AdvSimd.LoadVector128((Byte*)(pFld1)),
AdvSimd.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Aes.Encrypt(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = Aes.Encrypt(
AdvSimd.LoadVector128((Byte*)(pFld1)),
AdvSimd.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Aes.Encrypt(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Aes.Encrypt(
AdvSimd.LoadVector128((Byte*)(&test._fld1)),
AdvSimd.LoadVector128((Byte*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_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(void* result, [CallerMemberName] string method = "")
{
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(outArray, method);
}
private void ValidateResult(Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < result.Length; i++)
{
if (result[i] != _expectedRet[i] )
{
succeeded = false;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Aes)}.{nameof(Aes.Encrypt)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" expectedRet: ({string.Join(", ", _expectedRet)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
namespace System.Xml.Xsl.Qil
{
/// <summary>
/// Factory methods for constructing QilExpression nodes.
/// </summary>
/// <remarks>
/// See <see href="http://dynamo/qil/qil.xml">the QIL functional specification</see> for documentation.
/// </remarks>
internal sealed class QilFactory
{
private QilTypeChecker _typeCheck;
public QilFactory()
{
_typeCheck = new QilTypeChecker();
}
public QilTypeChecker TypeChecker
{
get { return _typeCheck; }
}
//-----------------------------------------------
// Convenience methods
//-----------------------------------------------
public QilExpression QilExpression(QilNode root, QilFactory factory)
{
QilExpression n = new QilExpression(QilNodeType.QilExpression, root, factory);
n.XmlType = _typeCheck.CheckQilExpression(n);
TraceNode(n);
return n;
}
public QilList ActualParameterList(IList<QilNode> values)
{
QilList seq = ActualParameterList();
seq.Add(values);
return seq;
}
public QilList FormalParameterList(IList<QilNode> values)
{
QilList seq = FormalParameterList();
seq.Add(values);
return seq;
}
public QilList BranchList(IList<QilNode> values)
{
QilList seq = BranchList();
seq.Add(values);
return seq;
}
public QilList Sequence(IList<QilNode> values)
{
QilList seq = Sequence();
seq.Add(values);
return seq;
}
public QilParameter Parameter(XmlQueryType xmlType)
{
return Parameter(null, null, xmlType);
}
public QilStrConcat StrConcat(QilNode values)
{
return StrConcat(LiteralString(""), values);
}
public QilName LiteralQName(string local)
{
return LiteralQName(local, string.Empty, string.Empty);
}
public QilTargetType TypeAssert(QilNode expr, XmlQueryType xmlType)
{
return TypeAssert(expr, (QilNode)LiteralType(xmlType));
}
public QilTargetType IsType(QilNode expr, XmlQueryType xmlType)
{
return IsType(expr, (QilNode)LiteralType(xmlType));
}
public QilTargetType XsltConvert(QilNode expr, XmlQueryType xmlType)
{
return XsltConvert(expr, (QilNode)LiteralType(xmlType));
}
public QilFunction Function(QilNode arguments, QilNode sideEffects, XmlQueryType xmlType)
{
return Function(arguments, Unknown(xmlType), sideEffects, xmlType);
}
#region AUTOGENERATED
#region meta
public QilList FunctionList()
{
QilList n = new QilList(QilNodeType.FunctionList);
n.XmlType = _typeCheck.CheckFunctionList(n);
TraceNode(n);
return n;
}
public QilList GlobalVariableList()
{
QilList n = new QilList(QilNodeType.GlobalVariableList);
n.XmlType = _typeCheck.CheckGlobalVariableList(n);
TraceNode(n);
return n;
}
public QilList GlobalParameterList()
{
QilList n = new QilList(QilNodeType.GlobalParameterList);
n.XmlType = _typeCheck.CheckGlobalParameterList(n);
TraceNode(n);
return n;
}
public QilList ActualParameterList()
{
QilList n = new QilList(QilNodeType.ActualParameterList);
n.XmlType = _typeCheck.CheckActualParameterList(n);
TraceNode(n);
return n;
}
public QilList FormalParameterList()
{
QilList n = new QilList(QilNodeType.FormalParameterList);
n.XmlType = _typeCheck.CheckFormalParameterList(n);
TraceNode(n);
return n;
}
public QilList SortKeyList()
{
QilList n = new QilList(QilNodeType.SortKeyList);
n.XmlType = _typeCheck.CheckSortKeyList(n);
TraceNode(n);
return n;
}
public QilList BranchList()
{
QilList n = new QilList(QilNodeType.BranchList);
n.XmlType = _typeCheck.CheckBranchList(n);
TraceNode(n);
return n;
}
public QilUnary OptimizeBarrier(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.OptimizeBarrier, child);
n.XmlType = _typeCheck.CheckOptimizeBarrier(n);
TraceNode(n);
return n;
}
public QilNode Unknown(XmlQueryType xmlType)
{
QilNode n = new QilNode(QilNodeType.Unknown, xmlType);
n.XmlType = _typeCheck.CheckUnknown(n);
TraceNode(n);
return n;
}
#endregion // meta
#region specials
//-----------------------------------------------
// specials
//-----------------------------------------------
public QilDataSource DataSource(QilNode name, QilNode baseUri)
{
QilDataSource n = new QilDataSource(QilNodeType.DataSource, name, baseUri);
n.XmlType = _typeCheck.CheckDataSource(n);
TraceNode(n);
return n;
}
public QilUnary Nop(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Nop, child);
n.XmlType = _typeCheck.CheckNop(n);
TraceNode(n);
return n;
}
public QilUnary Error(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Error, child);
n.XmlType = _typeCheck.CheckError(n);
TraceNode(n);
return n;
}
public QilUnary Warning(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Warning, child);
n.XmlType = _typeCheck.CheckWarning(n);
TraceNode(n);
return n;
}
#endregion // specials
#region variables
//-----------------------------------------------
// variables
//-----------------------------------------------
public QilIterator For(QilNode binding)
{
QilIterator n = new QilIterator(QilNodeType.For, binding);
n.XmlType = _typeCheck.CheckFor(n);
TraceNode(n);
return n;
}
public QilIterator Let(QilNode binding)
{
QilIterator n = new QilIterator(QilNodeType.Let, binding);
n.XmlType = _typeCheck.CheckLet(n);
TraceNode(n);
return n;
}
public QilParameter Parameter(QilNode defaultValue, QilNode name, XmlQueryType xmlType)
{
QilParameter n = new QilParameter(QilNodeType.Parameter, defaultValue, name, xmlType);
n.XmlType = _typeCheck.CheckParameter(n);
TraceNode(n);
return n;
}
public QilUnary PositionOf(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.PositionOf, child);
n.XmlType = _typeCheck.CheckPositionOf(n);
TraceNode(n);
return n;
}
#endregion // variables
#region literals
//-----------------------------------------------
// literals
//-----------------------------------------------
public QilNode True()
{
QilNode n = new QilNode(QilNodeType.True);
n.XmlType = _typeCheck.CheckTrue(n);
TraceNode(n);
return n;
}
public QilNode False()
{
QilNode n = new QilNode(QilNodeType.False);
n.XmlType = _typeCheck.CheckFalse(n);
TraceNode(n);
return n;
}
public QilLiteral LiteralString(string value)
{
QilLiteral n = new QilLiteral(QilNodeType.LiteralString, value);
n.XmlType = _typeCheck.CheckLiteralString(n);
TraceNode(n);
return n;
}
public QilLiteral LiteralInt32(int value)
{
QilLiteral n = new QilLiteral(QilNodeType.LiteralInt32, value);
n.XmlType = _typeCheck.CheckLiteralInt32(n);
TraceNode(n);
return n;
}
public QilLiteral LiteralInt64(long value)
{
QilLiteral n = new QilLiteral(QilNodeType.LiteralInt64, value);
n.XmlType = _typeCheck.CheckLiteralInt64(n);
TraceNode(n);
return n;
}
public QilLiteral LiteralDouble(double value)
{
QilLiteral n = new QilLiteral(QilNodeType.LiteralDouble, value);
n.XmlType = _typeCheck.CheckLiteralDouble(n);
TraceNode(n);
return n;
}
public QilLiteral LiteralDecimal(decimal value)
{
QilLiteral n = new QilLiteral(QilNodeType.LiteralDecimal, value);
n.XmlType = _typeCheck.CheckLiteralDecimal(n);
TraceNode(n);
return n;
}
public QilName LiteralQName(string localName, string namespaceUri, string prefix)
{
QilName n = new QilName(QilNodeType.LiteralQName, localName, namespaceUri, prefix);
n.XmlType = _typeCheck.CheckLiteralQName(n);
TraceNode(n);
return n;
}
public QilLiteral LiteralType(XmlQueryType value)
{
QilLiteral n = new QilLiteral(QilNodeType.LiteralType, value);
n.XmlType = _typeCheck.CheckLiteralType(n);
TraceNode(n);
return n;
}
public QilLiteral LiteralObject(object value)
{
QilLiteral n = new QilLiteral(QilNodeType.LiteralObject, value);
n.XmlType = _typeCheck.CheckLiteralObject(n);
TraceNode(n);
return n;
}
#endregion // literals
#region boolean operators
//-----------------------------------------------
// boolean operators
//-----------------------------------------------
public QilBinary And(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.And, left, right);
n.XmlType = _typeCheck.CheckAnd(n);
TraceNode(n);
return n;
}
public QilBinary Or(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Or, left, right);
n.XmlType = _typeCheck.CheckOr(n);
TraceNode(n);
return n;
}
public QilUnary Not(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Not, child);
n.XmlType = _typeCheck.CheckNot(n);
TraceNode(n);
return n;
}
#endregion // boolean operators
#region choice
//-----------------------------------------------
// choice
//-----------------------------------------------
public QilTernary Conditional(QilNode left, QilNode center, QilNode right)
{
QilTernary n = new QilTernary(QilNodeType.Conditional, left, center, right);
n.XmlType = _typeCheck.CheckConditional(n);
TraceNode(n);
return n;
}
public QilChoice Choice(QilNode expression, QilNode branches)
{
QilChoice n = new QilChoice(QilNodeType.Choice, expression, branches);
n.XmlType = _typeCheck.CheckChoice(n);
TraceNode(n);
return n;
}
#endregion // choice
#region collection operators
//-----------------------------------------------
// collection operators
//-----------------------------------------------
public QilUnary Length(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Length, child);
n.XmlType = _typeCheck.CheckLength(n);
TraceNode(n);
return n;
}
public QilList Sequence()
{
QilList n = new QilList(QilNodeType.Sequence);
n.XmlType = _typeCheck.CheckSequence(n);
TraceNode(n);
return n;
}
public QilBinary Union(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Union, left, right);
n.XmlType = _typeCheck.CheckUnion(n);
TraceNode(n);
return n;
}
public QilBinary Intersection(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Intersection, left, right);
n.XmlType = _typeCheck.CheckIntersection(n);
TraceNode(n);
return n;
}
public QilBinary Difference(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Difference, left, right);
n.XmlType = _typeCheck.CheckDifference(n);
TraceNode(n);
return n;
}
public QilUnary Sum(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Sum, child);
n.XmlType = _typeCheck.CheckSum(n);
TraceNode(n);
return n;
}
#endregion // collection operators
#region arithmetic operators
//-----------------------------------------------
// arithmetic operators
//-----------------------------------------------
public QilUnary Negate(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Negate, child);
n.XmlType = _typeCheck.CheckNegate(n);
TraceNode(n);
return n;
}
public QilBinary Add(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Add, left, right);
n.XmlType = _typeCheck.CheckAdd(n);
TraceNode(n);
return n;
}
public QilBinary Subtract(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Subtract, left, right);
n.XmlType = _typeCheck.CheckSubtract(n);
TraceNode(n);
return n;
}
public QilBinary Multiply(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Multiply, left, right);
n.XmlType = _typeCheck.CheckMultiply(n);
TraceNode(n);
return n;
}
public QilBinary Divide(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Divide, left, right);
n.XmlType = _typeCheck.CheckDivide(n);
TraceNode(n);
return n;
}
public QilBinary Modulo(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Modulo, left, right);
n.XmlType = _typeCheck.CheckModulo(n);
TraceNode(n);
return n;
}
#endregion // arithmetic operators
#region string operators
//-----------------------------------------------
// string operators
//-----------------------------------------------
public QilUnary StrLength(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.StrLength, child);
n.XmlType = _typeCheck.CheckStrLength(n);
TraceNode(n);
return n;
}
public QilStrConcat StrConcat(QilNode delimiter, QilNode values)
{
QilStrConcat n = new QilStrConcat(QilNodeType.StrConcat, delimiter, values);
n.XmlType = _typeCheck.CheckStrConcat(n);
TraceNode(n);
return n;
}
public QilBinary StrParseQName(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.StrParseQName, left, right);
n.XmlType = _typeCheck.CheckStrParseQName(n);
TraceNode(n);
return n;
}
#endregion // string operators
#region value comparison operators
//-----------------------------------------------
// value comparison operators
//-----------------------------------------------
public QilBinary Ne(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Ne, left, right);
n.XmlType = _typeCheck.CheckNe(n);
TraceNode(n);
return n;
}
public QilBinary Eq(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Eq, left, right);
n.XmlType = _typeCheck.CheckEq(n);
TraceNode(n);
return n;
}
public QilBinary Gt(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Gt, left, right);
n.XmlType = _typeCheck.CheckGt(n);
TraceNode(n);
return n;
}
public QilBinary Ge(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Ge, left, right);
n.XmlType = _typeCheck.CheckGe(n);
TraceNode(n);
return n;
}
public QilBinary Lt(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Lt, left, right);
n.XmlType = _typeCheck.CheckLt(n);
TraceNode(n);
return n;
}
public QilBinary Le(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Le, left, right);
n.XmlType = _typeCheck.CheckLe(n);
TraceNode(n);
return n;
}
#endregion // value comparison operators
#region node comparison operators
//-----------------------------------------------
// node comparison operators
//-----------------------------------------------
public QilBinary Is(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Is, left, right);
n.XmlType = _typeCheck.CheckIs(n);
TraceNode(n);
return n;
}
public QilBinary Before(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Before, left, right);
n.XmlType = _typeCheck.CheckBefore(n);
TraceNode(n);
return n;
}
#endregion // node comparison operators
#region loops
//-----------------------------------------------
// loops
//-----------------------------------------------
public QilLoop Loop(QilNode variable, QilNode body)
{
QilLoop n = new QilLoop(QilNodeType.Loop, variable, body);
n.XmlType = _typeCheck.CheckLoop(n);
TraceNode(n);
return n;
}
public QilLoop Filter(QilNode variable, QilNode body)
{
QilLoop n = new QilLoop(QilNodeType.Filter, variable, body);
n.XmlType = _typeCheck.CheckFilter(n);
TraceNode(n);
return n;
}
#endregion // loops
#region sorting
//-----------------------------------------------
// sorting
//-----------------------------------------------
public QilLoop Sort(QilNode variable, QilNode body)
{
QilLoop n = new QilLoop(QilNodeType.Sort, variable, body);
n.XmlType = _typeCheck.CheckSort(n);
TraceNode(n);
return n;
}
public QilSortKey SortKey(QilNode key, QilNode collation)
{
QilSortKey n = new QilSortKey(QilNodeType.SortKey, key, collation);
n.XmlType = _typeCheck.CheckSortKey(n);
TraceNode(n);
return n;
}
public QilUnary DocOrderDistinct(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.DocOrderDistinct, child);
n.XmlType = _typeCheck.CheckDocOrderDistinct(n);
TraceNode(n);
return n;
}
#endregion // sorting
#region function definition and invocation
//-----------------------------------------------
// function definition and invocation
//-----------------------------------------------
public QilFunction Function(QilNode arguments, QilNode definition, QilNode sideEffects, XmlQueryType xmlType)
{
QilFunction n = new QilFunction(QilNodeType.Function, arguments, definition, sideEffects, xmlType);
n.XmlType = _typeCheck.CheckFunction(n);
TraceNode(n);
return n;
}
public QilInvoke Invoke(QilNode function, QilNode arguments)
{
QilInvoke n = new QilInvoke(QilNodeType.Invoke, function, arguments);
n.XmlType = _typeCheck.CheckInvoke(n);
TraceNode(n);
return n;
}
#endregion // function definition and invocation
#region XML navigation
//-----------------------------------------------
// XML navigation
//-----------------------------------------------
public QilUnary Content(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Content, child);
n.XmlType = _typeCheck.CheckContent(n);
TraceNode(n);
return n;
}
public QilBinary Attribute(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Attribute, left, right);
n.XmlType = _typeCheck.CheckAttribute(n);
TraceNode(n);
return n;
}
public QilUnary Parent(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Parent, child);
n.XmlType = _typeCheck.CheckParent(n);
TraceNode(n);
return n;
}
public QilUnary Root(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Root, child);
n.XmlType = _typeCheck.CheckRoot(n);
TraceNode(n);
return n;
}
public QilNode XmlContext()
{
QilNode n = new QilNode(QilNodeType.XmlContext);
n.XmlType = _typeCheck.CheckXmlContext(n);
TraceNode(n);
return n;
}
public QilUnary Descendant(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Descendant, child);
n.XmlType = _typeCheck.CheckDescendant(n);
TraceNode(n);
return n;
}
public QilUnary DescendantOrSelf(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.DescendantOrSelf, child);
n.XmlType = _typeCheck.CheckDescendantOrSelf(n);
TraceNode(n);
return n;
}
public QilUnary Ancestor(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Ancestor, child);
n.XmlType = _typeCheck.CheckAncestor(n);
TraceNode(n);
return n;
}
public QilUnary AncestorOrSelf(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.AncestorOrSelf, child);
n.XmlType = _typeCheck.CheckAncestorOrSelf(n);
TraceNode(n);
return n;
}
public QilUnary Preceding(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Preceding, child);
n.XmlType = _typeCheck.CheckPreceding(n);
TraceNode(n);
return n;
}
public QilUnary FollowingSibling(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.FollowingSibling, child);
n.XmlType = _typeCheck.CheckFollowingSibling(n);
TraceNode(n);
return n;
}
public QilUnary PrecedingSibling(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.PrecedingSibling, child);
n.XmlType = _typeCheck.CheckPrecedingSibling(n);
TraceNode(n);
return n;
}
public QilBinary NodeRange(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.NodeRange, left, right);
n.XmlType = _typeCheck.CheckNodeRange(n);
TraceNode(n);
return n;
}
public QilBinary Deref(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Deref, left, right);
n.XmlType = _typeCheck.CheckDeref(n);
TraceNode(n);
return n;
}
#endregion // XML navigation
#region XML construction
//-----------------------------------------------
// XML construction
//-----------------------------------------------
public QilBinary ElementCtor(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.ElementCtor, left, right);
n.XmlType = _typeCheck.CheckElementCtor(n);
TraceNode(n);
return n;
}
public QilBinary AttributeCtor(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.AttributeCtor, left, right);
n.XmlType = _typeCheck.CheckAttributeCtor(n);
TraceNode(n);
return n;
}
public QilUnary CommentCtor(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.CommentCtor, child);
n.XmlType = _typeCheck.CheckCommentCtor(n);
TraceNode(n);
return n;
}
public QilBinary PICtor(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.PICtor, left, right);
n.XmlType = _typeCheck.CheckPICtor(n);
TraceNode(n);
return n;
}
public QilUnary TextCtor(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.TextCtor, child);
n.XmlType = _typeCheck.CheckTextCtor(n);
TraceNode(n);
return n;
}
public QilUnary RawTextCtor(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.RawTextCtor, child);
n.XmlType = _typeCheck.CheckRawTextCtor(n);
TraceNode(n);
return n;
}
public QilUnary DocumentCtor(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.DocumentCtor, child);
n.XmlType = _typeCheck.CheckDocumentCtor(n);
TraceNode(n);
return n;
}
public QilBinary NamespaceDecl(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.NamespaceDecl, left, right);
n.XmlType = _typeCheck.CheckNamespaceDecl(n);
TraceNode(n);
return n;
}
public QilBinary RtfCtor(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.RtfCtor, left, right);
n.XmlType = _typeCheck.CheckRtfCtor(n);
TraceNode(n);
return n;
}
#endregion // XML construction
#region Node properties
//-----------------------------------------------
// Node properties
//-----------------------------------------------
public QilUnary NameOf(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.NameOf, child);
n.XmlType = _typeCheck.CheckNameOf(n);
TraceNode(n);
return n;
}
public QilUnary LocalNameOf(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.LocalNameOf, child);
n.XmlType = _typeCheck.CheckLocalNameOf(n);
TraceNode(n);
return n;
}
public QilUnary NamespaceUriOf(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.NamespaceUriOf, child);
n.XmlType = _typeCheck.CheckNamespaceUriOf(n);
TraceNode(n);
return n;
}
public QilUnary PrefixOf(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.PrefixOf, child);
n.XmlType = _typeCheck.CheckPrefixOf(n);
TraceNode(n);
return n;
}
#endregion // Node properties
#region Type operators
//-----------------------------------------------
// Type operators
//-----------------------------------------------
public QilTargetType TypeAssert(QilNode source, QilNode targetType)
{
QilTargetType n = new QilTargetType(QilNodeType.TypeAssert, source, targetType);
n.XmlType = _typeCheck.CheckTypeAssert(n);
TraceNode(n);
return n;
}
public QilTargetType IsType(QilNode source, QilNode targetType)
{
QilTargetType n = new QilTargetType(QilNodeType.IsType, source, targetType);
n.XmlType = _typeCheck.CheckIsType(n);
TraceNode(n);
return n;
}
public QilUnary IsEmpty(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.IsEmpty, child);
n.XmlType = _typeCheck.CheckIsEmpty(n);
TraceNode(n);
return n;
}
#endregion // Type operators
#region XPath operators
//-----------------------------------------------
// XPath operators
//-----------------------------------------------
public QilUnary XPathNodeValue(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.XPathNodeValue, child);
n.XmlType = _typeCheck.CheckXPathNodeValue(n);
TraceNode(n);
return n;
}
public QilUnary XPathFollowing(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.XPathFollowing, child);
n.XmlType = _typeCheck.CheckXPathFollowing(n);
TraceNode(n);
return n;
}
public QilUnary XPathPreceding(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.XPathPreceding, child);
n.XmlType = _typeCheck.CheckXPathPreceding(n);
TraceNode(n);
return n;
}
public QilUnary XPathNamespace(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.XPathNamespace, child);
n.XmlType = _typeCheck.CheckXPathNamespace(n);
TraceNode(n);
return n;
}
#endregion // XPath operators
#region XSLT
//-----------------------------------------------
// XSLT
//-----------------------------------------------
public QilUnary XsltGenerateId(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.XsltGenerateId, child);
n.XmlType = _typeCheck.CheckXsltGenerateId(n);
TraceNode(n);
return n;
}
public QilInvokeLateBound XsltInvokeLateBound(QilNode name, QilNode arguments)
{
QilInvokeLateBound n = new QilInvokeLateBound(QilNodeType.XsltInvokeLateBound, name, arguments);
n.XmlType = _typeCheck.CheckXsltInvokeLateBound(n);
TraceNode(n);
return n;
}
public QilInvokeEarlyBound XsltInvokeEarlyBound(QilNode name, QilNode clrMethod, QilNode arguments, XmlQueryType xmlType)
{
QilInvokeEarlyBound n = new QilInvokeEarlyBound(QilNodeType.XsltInvokeEarlyBound, name, clrMethod, arguments, xmlType);
n.XmlType = _typeCheck.CheckXsltInvokeEarlyBound(n);
TraceNode(n);
return n;
}
public QilBinary XsltCopy(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.XsltCopy, left, right);
n.XmlType = _typeCheck.CheckXsltCopy(n);
TraceNode(n);
return n;
}
public QilUnary XsltCopyOf(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.XsltCopyOf, child);
n.XmlType = _typeCheck.CheckXsltCopyOf(n);
TraceNode(n);
return n;
}
public QilTargetType XsltConvert(QilNode source, QilNode targetType)
{
QilTargetType n = new QilTargetType(QilNodeType.XsltConvert, source, targetType);
n.XmlType = _typeCheck.CheckXsltConvert(n);
TraceNode(n);
return n;
}
#endregion // XSLT
#endregion
#region Diagnostic Support
[System.Diagnostics.Conditional("QIL_TRACE_NODE_CREATION")]
public void TraceNode(QilNode n)
{
#if QIL_TRACE_NODE_CREATION
this.diag.AddNode(n);
#endif
}
#endregion
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using Microsoft.Win32;
using System.Threading;
using System.IO;
namespace Earlab
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private RegistryKey mModuleKey;
private RegistryKey mApplicationKey;
private RegistryString mModuleDirectory;
private RegistryString mInputDirectory;
private RegistryString mOutputDirectory;
private RegistryString mDiagramFile;
private RegistryString mParameterFile;
private RegistryInt mFrameCount;
private RegistryFormWindowState mWindowState;
private RegistryPoint mWindowLocation;
private RegistrySize mWindowSize;
private RegistryBool mEnableSuperuserMode;
private Thread mExecutionThread;
private bool mStopModel, mRunning, mStoppedCleanly;
private LogCallback mLogCallback;
private static Form1 mMainForm;
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuFileExit;
private System.Windows.Forms.MenuItem menuModelChooseDiagramFile;
private System.Windows.Forms.MenuItem menuModelChooseParameterFile;
private System.Windows.Forms.MenuItem menuItem6;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.MenuItem menuModelRun;
private System.Windows.Forms.MenuItem menuEnvironmentSetModuleDirectory;
private System.Windows.Forms.OpenFileDialog openFileDialog;
private System.Windows.Forms.TextBox txtStatusDisplay;
private System.Windows.Forms.NumericUpDown udFrameCount;
private System.Windows.Forms.StatusBar statusBar;
private System.Windows.Forms.StatusBarPanel sbTextPanel;
private System.Windows.Forms.Button btnRun;
private System.Windows.Forms.Button btnStop;
private System.Windows.Forms.RichTextBox logDisplay;
private System.Windows.Forms.Timer timer;
private System.Windows.Forms.Button btnAbort;
private System.Windows.Forms.FolderBrowserDialog folderBrowser;
private System.Windows.Forms.ProgressBar progressBar;
private System.Windows.Forms.MenuItem menuHelp;
private System.Windows.Forms.MenuItem menuHelpAbout;
private System.Windows.Forms.MenuItem menuModelSetOutputDirectory;
private System.Windows.Forms.MenuItem menuModelSetInputDirectory;
private System.Windows.Forms.MenuItem menuFileOpenParameters;
private System.Windows.Forms.MenuItem menuFileOpenDiagram;
private System.Windows.Forms.MenuItem menuEnvironment;
private System.Windows.Forms.MenuItem menuFileSeparator;
private System.ComponentModel.IContainer components;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
mModuleKey = Registry.LocalMachine.CreateSubKey(@"Software\EarLab");
mApplicationKey = Registry.CurrentUser.CreateSubKey(@"Software\EarLab\EarLab GUI");
mLogCallback = new LogCallback(LogCallback);
mModuleDirectory = new RegistryString(mModuleKey, "ModulesPath", @"C:\Program Files\EarLab\Modules");
mInputDirectory = new RegistryString(mApplicationKey, "InputDirectory", System.Environment.ExpandEnvironmentVariables("%USERPROFILE%") + @"\My Documents\EarLab\Signals");
mOutputDirectory = new RegistryString(mApplicationKey, "OutputDirectory", System.Environment.ExpandEnvironmentVariables("%USERPROFILE%") + @"\My Documents\EarLab\Output");
mDiagramFile = new RegistryString(mApplicationKey, "RunParameterFile", null);
mParameterFile = new RegistryString(mApplicationKey, "ModuleParameterFile", null);
mFrameCount = new RegistryInt(mApplicationKey, "FrameCount", 0);
mEnableSuperuserMode = new RegistryBool(mApplicationKey, "SuperuserMode", false);
udFrameCount.Value = mFrameCount.Value;
mWindowState = new RegistryFormWindowState(mApplicationKey, "WindowState", FormWindowState.Normal);
mWindowLocation = new RegistryPoint(mApplicationKey, "WindowLocation", this.Location);
mWindowSize = new RegistrySize(mApplicationKey, "WindowSize", this.MinimumSize);
this.Location = mWindowLocation.Value;
this.Size = mWindowSize.Value;
this.WindowState = mWindowState.Value;
if (mEnableSuperuserMode.Value)
{
menuEnvironment.Enabled = true;
menuEnvironment.Visible = true;
menuFileOpenDiagram.Enabled = true;
menuFileOpenDiagram.Visible = true;
menuFileOpenParameters.Enabled = true;
menuFileOpenParameters.Visible = true;
menuFileSeparator.Enabled = true;
menuFileSeparator.Visible = true;
}
udFrameCount.Focus();
UpdateStatusDisplay();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region 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.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1));
this.mainMenu1 = new System.Windows.Forms.MainMenu();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuFileOpenDiagram = new System.Windows.Forms.MenuItem();
this.menuFileOpenParameters = new System.Windows.Forms.MenuItem();
this.menuFileSeparator = new System.Windows.Forms.MenuItem();
this.menuFileExit = new System.Windows.Forms.MenuItem();
this.menuItem6 = new System.Windows.Forms.MenuItem();
this.menuModelChooseDiagramFile = new System.Windows.Forms.MenuItem();
this.menuModelChooseParameterFile = new System.Windows.Forms.MenuItem();
this.menuModelSetInputDirectory = new System.Windows.Forms.MenuItem();
this.menuModelSetOutputDirectory = new System.Windows.Forms.MenuItem();
this.menuModelRun = new System.Windows.Forms.MenuItem();
this.menuEnvironment = new System.Windows.Forms.MenuItem();
this.menuEnvironmentSetModuleDirectory = new System.Windows.Forms.MenuItem();
this.menuHelp = new System.Windows.Forms.MenuItem();
this.menuHelpAbout = new System.Windows.Forms.MenuItem();
this.label3 = new System.Windows.Forms.Label();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.txtStatusDisplay = new System.Windows.Forms.TextBox();
this.udFrameCount = new System.Windows.Forms.NumericUpDown();
this.statusBar = new System.Windows.Forms.StatusBar();
this.sbTextPanel = new System.Windows.Forms.StatusBarPanel();
this.btnRun = new System.Windows.Forms.Button();
this.btnStop = new System.Windows.Forms.Button();
this.logDisplay = new System.Windows.Forms.RichTextBox();
this.timer = new System.Windows.Forms.Timer(this.components);
this.btnAbort = new System.Windows.Forms.Button();
this.folderBrowser = new System.Windows.Forms.FolderBrowserDialog();
this.progressBar = new System.Windows.Forms.ProgressBar();
((System.ComponentModel.ISupportInitialize)(this.udFrameCount)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.sbTextPanel)).BeginInit();
this.SuspendLayout();
//
// mainMenu1
//
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem1,
this.menuItem6,
this.menuEnvironment,
this.menuHelp});
//
// menuItem1
//
this.menuItem1.Index = 0;
this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuFileOpenDiagram,
this.menuFileOpenParameters,
this.menuFileSeparator,
this.menuFileExit});
this.menuItem1.Text = "&File";
//
// menuFileOpenDiagram
//
this.menuFileOpenDiagram.Enabled = false;
this.menuFileOpenDiagram.Index = 0;
this.menuFileOpenDiagram.Text = "Open Diagram File...";
this.menuFileOpenDiagram.Visible = false;
this.menuFileOpenDiagram.Click += new System.EventHandler(this.menuFileOpenDiagram_Click);
//
// menuFileOpenParameters
//
this.menuFileOpenParameters.Enabled = false;
this.menuFileOpenParameters.Index = 1;
this.menuFileOpenParameters.Text = "Open Parameter File...";
this.menuFileOpenParameters.Visible = false;
this.menuFileOpenParameters.Click += new System.EventHandler(this.menuFileOpenParameters_Click);
//
// menuFileSeparator
//
this.menuFileSeparator.Enabled = false;
this.menuFileSeparator.Index = 2;
this.menuFileSeparator.Text = "-";
this.menuFileSeparator.Visible = false;
//
// menuFileExit
//
this.menuFileExit.Index = 3;
this.menuFileExit.Shortcut = System.Windows.Forms.Shortcut.AltF4;
this.menuFileExit.Text = "E&xit";
this.menuFileExit.Click += new System.EventHandler(this.menuFileExit_Click);
//
// menuItem6
//
this.menuItem6.Index = 1;
this.menuItem6.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuModelChooseDiagramFile,
this.menuModelChooseParameterFile,
this.menuModelSetInputDirectory,
this.menuModelSetOutputDirectory,
this.menuModelRun});
this.menuItem6.Text = "&Model";
//
// menuModelChooseDiagramFile
//
this.menuModelChooseDiagramFile.Index = 0;
this.menuModelChooseDiagramFile.Shortcut = System.Windows.Forms.Shortcut.CtrlD;
this.menuModelChooseDiagramFile.Text = "Choose Diagram File...";
this.menuModelChooseDiagramFile.Click += new System.EventHandler(this.menuModelChooseDiagramFile_Click);
//
// menuModelChooseParameterFile
//
this.menuModelChooseParameterFile.Index = 1;
this.menuModelChooseParameterFile.Shortcut = System.Windows.Forms.Shortcut.CtrlP;
this.menuModelChooseParameterFile.Text = "Choose Parameter File...";
this.menuModelChooseParameterFile.Click += new System.EventHandler(this.menuModelChooseParameterFile_Click);
//
// menuModelSetInputDirectory
//
this.menuModelSetInputDirectory.Index = 2;
this.menuModelSetInputDirectory.Shortcut = System.Windows.Forms.Shortcut.CtrlI;
this.menuModelSetInputDirectory.Text = "Set Input Directory...";
this.menuModelSetInputDirectory.Click += new System.EventHandler(this.menuModelSetInputDirectory_Click);
//
// menuModelSetOutputDirectory
//
this.menuModelSetOutputDirectory.Index = 3;
this.menuModelSetOutputDirectory.Shortcut = System.Windows.Forms.Shortcut.CtrlO;
this.menuModelSetOutputDirectory.Text = "Set Output Directory...";
this.menuModelSetOutputDirectory.Click += new System.EventHandler(this.menuModelSetOutputDirectory_Click);
//
// menuModelRun
//
this.menuModelRun.Index = 4;
this.menuModelRun.Shortcut = System.Windows.Forms.Shortcut.F5;
this.menuModelRun.Text = "Run Model...";
this.menuModelRun.Click += new System.EventHandler(this.menuModelRun_Click);
//
// menuEnvironment
//
this.menuEnvironment.Enabled = false;
this.menuEnvironment.Index = 2;
this.menuEnvironment.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuEnvironmentSetModuleDirectory});
this.menuEnvironment.Text = "Environment";
this.menuEnvironment.Visible = false;
//
// menuEnvironmentSetModuleDirectory
//
this.menuEnvironmentSetModuleDirectory.Index = 0;
this.menuEnvironmentSetModuleDirectory.Text = "Set Module Directory...";
this.menuEnvironmentSetModuleDirectory.Click += new System.EventHandler(this.menuEnvironmentSetModuleDirectory_Click);
//
// menuHelp
//
this.menuHelp.Index = 3;
this.menuHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuHelpAbout});
this.menuHelp.Text = "Help";
//
// menuHelpAbout
//
this.menuHelpAbout.Index = 0;
this.menuHelpAbout.Text = "About Desktop Earlab...";
this.menuHelpAbout.Click += new System.EventHandler(this.menuHelpAbout_Click);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(8, 88);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(68, 16);
this.label3.TabIndex = 7;
this.label3.Text = "Frame count";
//
// txtStatusDisplay
//
this.txtStatusDisplay.AcceptsReturn = true;
this.txtStatusDisplay.AcceptsTab = true;
this.txtStatusDisplay.BackColor = System.Drawing.SystemColors.Control;
this.txtStatusDisplay.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtStatusDisplay.Location = new System.Drawing.Point(8, 8);
this.txtStatusDisplay.Multiline = true;
this.txtStatusDisplay.Name = "txtStatusDisplay";
this.txtStatusDisplay.ReadOnly = true;
this.txtStatusDisplay.Size = new System.Drawing.Size(536, 72);
this.txtStatusDisplay.TabIndex = 14;
this.txtStatusDisplay.TabStop = false;
this.txtStatusDisplay.Text = "Status Display";
//
// udFrameCount
//
this.udFrameCount.Location = new System.Drawing.Point(8, 104);
this.udFrameCount.Maximum = new System.Decimal(new int[] {
1000000,
0,
0,
0});
this.udFrameCount.Name = "udFrameCount";
this.udFrameCount.Size = new System.Drawing.Size(72, 20);
this.udFrameCount.TabIndex = 1;
this.udFrameCount.ValueChanged += new System.EventHandler(this.udFrameCount_ValueChanged);
//
// statusBar
//
this.statusBar.Location = new System.Drawing.Point(0, 347);
this.statusBar.Name = "statusBar";
this.statusBar.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
this.sbTextPanel});
this.statusBar.ShowPanels = true;
this.statusBar.Size = new System.Drawing.Size(552, 22);
this.statusBar.TabIndex = 16;
//
// sbTextPanel
//
this.sbTextPanel.Alignment = System.Windows.Forms.HorizontalAlignment.Center;
this.sbTextPanel.Text = "Not Ready";
this.sbTextPanel.Width = 200;
//
// btnRun
//
this.btnRun.Enabled = false;
this.btnRun.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnRun.Location = new System.Drawing.Point(104, 104);
this.btnRun.Name = "btnRun";
this.btnRun.TabIndex = 2;
this.btnRun.Text = "Run";
this.btnRun.Click += new System.EventHandler(this.btnRun_Click);
//
// btnStop
//
this.btnStop.Enabled = false;
this.btnStop.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnStop.Location = new System.Drawing.Point(192, 104);
this.btnStop.Name = "btnStop";
this.btnStop.TabIndex = 3;
this.btnStop.Text = "Stop";
this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
//
// logDisplay
//
this.logDisplay.AcceptsTab = true;
this.logDisplay.Location = new System.Drawing.Point(8, 128);
this.logDisplay.Name = "logDisplay";
this.logDisplay.ReadOnly = true;
this.logDisplay.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.Vertical;
this.logDisplay.Size = new System.Drawing.Size(536, 216);
this.logDisplay.TabIndex = 19;
this.logDisplay.TabStop = false;
this.logDisplay.Text = "";
this.logDisplay.TextChanged += new System.EventHandler(this.logDisplay_TextChanged);
//
// timer
//
this.timer.Tick += new System.EventHandler(this.timer_Tick);
//
// btnAbort
//
this.btnAbort.Enabled = false;
this.btnAbort.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnAbort.Location = new System.Drawing.Point(280, 104);
this.btnAbort.Name = "btnAbort";
this.btnAbort.TabIndex = 20;
this.btnAbort.Text = "Abort";
this.btnAbort.Click += new System.EventHandler(this.btnAbort_Click);
//
// progressBar
//
this.progressBar.Location = new System.Drawing.Point(200, 352);
this.progressBar.Name = "progressBar";
this.progressBar.Size = new System.Drawing.Size(328, 16);
this.progressBar.TabIndex = 21;
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(552, 369);
this.Controls.Add(this.progressBar);
this.Controls.Add(this.btnAbort);
this.Controls.Add(this.logDisplay);
this.Controls.Add(this.btnStop);
this.Controls.Add(this.btnRun);
this.Controls.Add(this.udFrameCount);
this.Controls.Add(this.txtStatusDisplay);
this.Controls.Add(this.label3);
this.Controls.Add(this.statusBar);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Menu = this.mainMenu1;
this.MinimumSize = new System.Drawing.Size(448, 381);
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.Text = "Desktop Earlab";
this.Resize += new System.EventHandler(this.Form1_Resize);
this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);
this.Load += new System.EventHandler(this.Form1_Load);
this.LocationChanged += new System.EventHandler(this.Form1_LocationChanged);
((System.ComponentModel.ISupportInitialize)(this.udFrameCount)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.sbTextPanel)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
mMainForm = new Form1();
Application.Run(mMainForm);
}
static void LogCallback(String Message)
{
mMainForm.Log(Message);
}
private void menuEnvironmentSetModuleDirectory_Click(object sender, System.EventArgs e)
{
folderBrowser.Reset();
//folderBrowser.RootFolder = Environment.SpecialFolder.Desktop;
if (mModuleDirectory != null)
folderBrowser.SelectedPath = mModuleDirectory.Value;
folderBrowser.ShowNewFolderButton = false;
folderBrowser.Description = "Choose the directory that contains the Earlab modules";
if (folderBrowser.ShowDialog() == DialogResult.OK)
{
mModuleDirectory.Value = folderBrowser.SelectedPath;
UpdateStatusDisplay();
}
}
private void menuModelSetOutputDirectory_Click(object sender, System.EventArgs e)
{
folderBrowser.Reset();
if (mModuleDirectory != null)
folderBrowser.SelectedPath = mOutputDirectory.Value;
folderBrowser.ShowNewFolderButton = true;
folderBrowser.Description = "Choose the directory that will hold your output files";
if (folderBrowser.ShowDialog() == DialogResult.OK)
{
mOutputDirectory.Value = folderBrowser.SelectedPath;
UpdateStatusDisplay();
}
}
private void menuModelSetInputDirectory_Click(object sender, System.EventArgs e)
{
folderBrowser.Reset();
if (mModuleDirectory != null)
folderBrowser.SelectedPath = mInputDirectory.Value;
folderBrowser.ShowNewFolderButton = false;
folderBrowser.Description = "Choose the directory that holds your input files";
if (folderBrowser.ShowDialog() == DialogResult.OK)
{
mInputDirectory.Value = folderBrowser.SelectedPath;
UpdateStatusDisplay();
}
}
private void menuFileExit_Click(object sender, System.EventArgs e)
{
StopModelAndWait();
Application.Exit();
}
private void menuModelChooseDiagramFile_Click(object sender, System.EventArgs e)
{
openFileDialog.FileName = mDiagramFile.Value;
openFileDialog.Title = "Choose Diagram file";
openFileDialog.CheckFileExists = true;
openFileDialog.CheckPathExists = true;
openFileDialog.Filter = "Diagram files (*.diagram)|*.diagram|All files (*.*)|*.*";
openFileDialog.FilterIndex = 0;
openFileDialog.Multiselect = false;
openFileDialog.RestoreDirectory = true;
openFileDialog.ValidateNames = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
mDiagramFile.Value = openFileDialog.FileName;
UpdateStatusDisplay();
}
}
private void menuModelChooseParameterFile_Click(object sender, System.EventArgs e)
{
openFileDialog.FileName = mParameterFile.Value;
openFileDialog.Title = "Choose Parameter file";
openFileDialog.CheckFileExists = true;
openFileDialog.CheckPathExists = true;
openFileDialog.Filter = "Parameter files (*.parameters)|*.parameters|All files (*.*)|*.*";
openFileDialog.FilterIndex = 0;
openFileDialog.Multiselect = false;
openFileDialog.RestoreDirectory = true;
openFileDialog.ValidateNames = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
mParameterFile.Value = openFileDialog.FileName;
UpdateStatusDisplay();
}
}
private void UpdateStatusDisplay()
{
string [] MyLines = new string[5];
bool SimOK = true;
int LineCount = 0;
if (mDiagramFile.Value != null)
MyLines[LineCount++] = "Diagram file is \"" + mDiagramFile.Value + "\"";
else
{
MyLines[LineCount++] = "Diagram file is not set";
SimOK = false;
}
if (mParameterFile.Value != null)
MyLines[LineCount++] = "Parameter file is \"" + mParameterFile.Value + "\"";
else
{
MyLines[LineCount++] = "Parameter file is not set";
SimOK = false;
}
if (mInputDirectory.Value != null)
MyLines[LineCount++] = "Input Directory is \"" + mInputDirectory.Value + "\"";
else
{
MyLines[LineCount++] = "Input Directory is not set";
SimOK = false;
}
if (mOutputDirectory.Value != null)
MyLines[LineCount++] = "Output Directory is \"" + mOutputDirectory.Value + "\"";
else
{
MyLines[LineCount++] = "Output Directory is not set";
SimOK = false;
}
if (mFrameCount.Value != 0)
MyLines[LineCount++] = "Simulation will run for " + mFrameCount.Value + " frames";
else
{
MyLines[LineCount++] = "Frame count not set";
SimOK = false;
}
txtStatusDisplay.Lines = MyLines;
if (SimOK)
{
sbTextPanel.Text = "Ready";
btnRun.Enabled = true;
txtStatusDisplay.ForeColor = SystemColors.ControlText;
}
else
{
btnRun.Enabled = false;
sbTextPanel.Text = "Not Ready";
txtStatusDisplay.ForeColor = Color.Red;
}
txtStatusDisplay.SelectionLength = 0;
udFrameCount.Focus();
}
private void udFrameCount_ValueChanged(object sender, System.EventArgs e)
{
mFrameCount.Value = (int)udFrameCount.Value;
UpdateStatusDisplay();
}
private void btnRun_Click(object sender, System.EventArgs e)
{
DoRun();
}
private void DoRun()
{
mExecutionThread = new Thread(new ThreadStart(RunModel));
mExecutionThread.IsBackground = true;
mExecutionThread.Name = "Model Execution Thread";
mStopModel = false;
progressBar.Value = 0;
progressBar.Visible = true;
progressBar.Minimum = 0;
progressBar.Maximum = mFrameCount.Value + 1;
//mExecutionThread.Priority = ThreadPriority.BelowNormal;
mExecutionThread.Start();
timer.Enabled = true;
}
private void btnStop_Click(object sender, System.EventArgs e)
{
btnAbort.Enabled = true;
StopModel();
}
private void RunModel()
{
int i;
DesktopEarlabDLL theDLL = new DesktopEarlabDLL();
mStoppedCleanly = false;
btnRun.Enabled = false;
btnStop.Enabled = true;
udFrameCount.Enabled = false;
progressBar.Visible = true;
menuModelRun.Enabled = false;
ClearLog();
mRunning = false;
sbTextPanel.Text = "Running";
Log("Starting simulation");
Log("Current path is: " + Directory.GetCurrentDirectory());
theDLL.SetLogCallback(mLogCallback);
Log("Module directory: \"" + mModuleDirectory.Value + "\"");
if (theDLL.SetModuleDirectory(mModuleDirectory.Value) == 0)
{
Log("Error setting module directory");
return;
}
Log("Model configuration: \"" + mDiagramFile.Value + "\"");
if (theDLL.LoadModelConfigFile(mDiagramFile.Value, 1000.0f) == 0)
{
Log("Error loading model config file");
return;
}
Log("Module parameters: \"" + mParameterFile.Value + "\"");
if (theDLL.LoadModuleParameters(mParameterFile.Value) == 0)
{
Log("Error loading module parameter file");
return;
}
Log("Output directory: \"" + mOutputDirectory.Value + "\"");
theDLL.SetOutputDirectory(mOutputDirectory.Value);
Log("Input directory: \"" + mInputDirectory.Value + "\"");
theDLL.SetInputDirectory(mInputDirectory.Value);
Log("Starting modules");
if (theDLL.StartModules() == 0)
{
Log("Error starting modules");
return;
}
for (i = 0; i < mFrameCount.Value; i++)
{
mRunning = true;
if (mStopModel)
break;
progressBar.Value = i;
sbTextPanel.Text = "Processing frame " + (i + 1) + " of " + mFrameCount.Value;
if (i == 0)
Log("Starting frame " + (i + 1) + " of " + mFrameCount.Value);
try
{
if (theDLL.AdvanceModules() == 0)
{
Log("Error processing frame " + i + " of " + mFrameCount.Value);
return;
}
}
catch (Exception e)
{
Log("Caught exception: " + e.ToString());
}
Application.DoEvents();
Thread.Sleep(100);
theDLL.SetLogCallback(null);
}
theDLL.SetLogCallback(mLogCallback);
sbTextPanel.Text = "Stopping";
Log("Stopping modules");
if (theDLL.StopModules() == 0)
{
Log("Error stopping modules");
return;
}
Log("Unloading modules");
if (theDLL.UnloadModel() == 0)
{
Log("Error unloading model");
return;
}
btnRun.Enabled = true;
btnStop.Enabled = false;
btnAbort.Enabled = false;
udFrameCount.Enabled = true;
progressBar.Visible = false;
UpdateStatusDisplay();
udFrameCount.Focus();
mStoppedCleanly = true;
mRunning = false;
menuModelRun.Enabled = true;
}
void ClearLog()
{
logDisplay.Text = "";
}
void Log(string Message)
{
logDisplay.AppendText(DateTime.Now.ToString() + " " + Message + "\r\n");
}
private void logDisplay_TextChanged(object sender, System.EventArgs e)
{
logDisplay.Focus();
logDisplay.SelectionStart = logDisplay.TextLength;
//logDisplay.SelectionLength = 0;
logDisplay.ScrollToCaret();
}
private void Form1_Resize(object sender, System.EventArgs e)
{
if (this.WindowState == FormWindowState.Normal)
{
mWindowSize.Value = this.Size;
txtStatusDisplay.Width = this.ClientSize.Width - 16;
logDisplay.Width = this.ClientSize.Width - 16;
logDisplay.Height = (this.ClientSize.Height - 24) - logDisplay.Top;
progressBar.Top = statusBar.Top + ((statusBar.Height - progressBar.Height) / 2);
progressBar.Width = this.Width - progressBar.Left - 30;
}
mWindowState.Value = this.WindowState;
}
private void Form1_LocationChanged(object sender, System.EventArgs e)
{
if (this.WindowState == FormWindowState.Normal)
mWindowLocation.Value = this.Location;
mWindowState.Value = this.WindowState;
}
private void StopModel()
{
sbTextPanel.Text = "Stopping (User request)";
Log("User requested stop");
if ((mExecutionThread != null) && mExecutionThread.IsAlive && mRunning)
mStopModel = true;
} // private void StopModel()
private void StopModelAndWait()
{
int WaitTimeout = 3000; // Wait 30 seconds for model to stop
StopModel();
while ((mExecutionThread != null) && mExecutionThread.IsAlive && mRunning && (WaitTimeout > 0))
{
Thread.Sleep(10);
Application.DoEvents();
WaitTimeout--;
}
if (WaitTimeout <= 0)
AbortModel();
} // private void StopModel()
private void AbortModel()
{
if (mExecutionThread.IsAlive)
{
Log("User requested abort");
mExecutionThread.Abort();
mStoppedCleanly = false;
sbTextPanel.Text = "Aborted";
} // if (mExecutionThread.IsAlive)
btnAbort.Enabled = false;
}
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
StopModelAndWait();
}
private void timer_Tick(object sender, System.EventArgs e)
{
if (!mExecutionThread.IsAlive)
{
if (!mStoppedCleanly)
Log("Model failed");
else
Log("Model stopped");
timer.Enabled = false;
btnRun.Enabled = true;
btnStop.Enabled = false;
btnAbort.Enabled = false;
UpdateStatusDisplay();
progressBar.Visible = false;
progressBar.Value = 0;
menuModelRun.Enabled = true;
}
}
private void btnAbort_Click(object sender, System.EventArgs e)
{
AbortModel();
}
private void Form1_Load(object sender, System.EventArgs e)
{
progressBar.Visible = false;
}
private void menuHelpAbout_Click(object sender, System.EventArgs e)
{
Form About = new EarlabGUI.About();
About.Show();
}
private void menuFileOpenParameters_Click(object sender, System.EventArgs e)
{
System.Diagnostics.Process.Start("notepad", mParameterFile.Value);
}
private void menuFileOpenDiagram_Click(object sender, System.EventArgs e)
{
System.Diagnostics.Process.Start("notepad", mDiagramFile.Value);
}
private void menuModelRun_Click(object sender, System.EventArgs e)
{
DoRun();
}
}
}
| |
//
// HardwareManager.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2008-2009 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Addins;
using Hyena;
using Banshee.ServiceStack;
namespace Banshee.Hardware
{
public sealed class HardwareManager : IService, IHardwareManager, IDisposable
{
private IHardwareManager manager;
private Dictionary<string, ICustomDeviceProvider> custom_device_providers = new Dictionary<string, ICustomDeviceProvider> ();
public event DeviceAddedHandler DeviceAdded;
public event DeviceRemovedHandler DeviceRemoved;
public HardwareManager ()
{
foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes ("/Banshee/Platform/HardwareManager")) {
try {
if (manager != null) {
throw new Exception (String.Format (
"A HardwareManager has already been loaded ({0}). Only one can be loaded.",
manager.GetType ().FullName));
}
manager = (IHardwareManager)node.CreateInstance (typeof (IHardwareManager));
} catch (Exception e) {
Log.Warning ("Hardware manager extension failed to load", e.Message);
}
}
if (manager == null) {
throw new Exception ("No HardwareManager extensions could be loaded. Hardware support will be disabled.");
}
manager.DeviceAdded += OnDeviceAdded;
manager.DeviceRemoved += OnDeviceRemoved;
ServiceManager.Get<DBusCommandService> ().ArgumentPushed += OnCommandLineArgument;
AddinManager.AddExtensionNodeHandler ("/Banshee/Platform/HardwareDeviceProvider", OnExtensionChanged);
}
public void Dispose ()
{
lock (this) {
if (manager != null) {
manager.DeviceAdded -= OnDeviceAdded;
manager.DeviceRemoved -= OnDeviceRemoved;
manager.Dispose ();
manager = null;
}
ServiceManager.Get<DBusCommandService> ().ArgumentPushed -= OnCommandLineArgument;
if (custom_device_providers != null) {
foreach (ICustomDeviceProvider provider in custom_device_providers.Values) {
provider.Dispose ();
}
custom_device_providers.Clear ();
custom_device_providers = null;
}
AddinManager.RemoveExtensionNodeHandler ("/Banshee/Platform/HardwareDeviceProvider", OnExtensionChanged);
}
}
private void OnExtensionChanged (object o, ExtensionNodeEventArgs args)
{
lock (this) {
TypeExtensionNode node = (TypeExtensionNode)args.ExtensionNode;
if (args.Change == ExtensionChange.Add && !custom_device_providers.ContainsKey (node.Id)) {
custom_device_providers.Add (node.Id, (ICustomDeviceProvider)node.CreateInstance ());
} else if (args.Change == ExtensionChange.Remove && custom_device_providers.ContainsKey (node.Id)) {
ICustomDeviceProvider provider = custom_device_providers[node.Id];
provider.Dispose ();
custom_device_providers.Remove (node.Id);
}
}
}
#region Device Command Line Argument Handling
private event DeviceCommandHandler device_command;
public event DeviceCommandHandler DeviceCommand {
add {
try {
device_command += value;
} finally {
if (value != null && StartupDeviceCommand != null) {
value (this, StartupDeviceCommand);
}
}
}
remove { device_command -= value; }
}
private Banshee.Hardware.DeviceCommand startup_device_command;
private bool startup_device_command_checked = false;
public Banshee.Hardware.DeviceCommand StartupDeviceCommand {
get {
lock (this) {
if (startup_device_command_checked) {
return startup_device_command;
}
startup_device_command_checked = true;
foreach (KeyValuePair<string, string> argument in Banshee.Base.ApplicationContext.CommandLine.Arguments) {
startup_device_command = Banshee.Hardware.DeviceCommand.ParseCommandLine (argument.Key, argument.Value);
if (startup_device_command != null) {
break;
}
}
return startup_device_command;
}
}
}
private void OnCommandLineArgument (string argument, object value, bool isFile)
{
Banshee.Hardware.DeviceCommand command = Banshee.Hardware.DeviceCommand.ParseCommandLine (argument, value.ToString ());
if (command == null) {
return;
}
DeviceCommandHandler handler = device_command;
if (handler != null) {
handler (this, command);
}
}
#endregion
private void OnDeviceAdded (object o, DeviceAddedArgs args)
{
lock (this) {
DeviceAddedHandler handler = DeviceAdded;
if (handler != null) {
DeviceAddedArgs raise_args = args;
IDevice cast_device = CastToCustomDevice<IDevice> (args.Device);
if (cast_device != args.Device) {
raise_args = new DeviceAddedArgs (cast_device);
}
handler (this, raise_args);
}
}
}
private void OnDeviceRemoved (object o, DeviceRemovedArgs args)
{
lock (this) {
DeviceRemovedHandler handler = DeviceRemoved;
if (handler != null) {
handler (this, args);
}
}
}
private T CastToCustomDevice<T> (T device) where T : class, IDevice
{
foreach (ICustomDeviceProvider provider in custom_device_providers.Values) {
T new_device = provider.GetCustomDevice (device);
if (new_device != device) {
return new_device;
}
}
return device;
}
private IEnumerable<T> CastToCustomDevice<T> (IEnumerable<T> devices) where T : class, IDevice
{
foreach (T device in devices) {
yield return CastToCustomDevice<T> (device);
}
}
public IEnumerable<IDevice> GetAllDevices ()
{
return CastToCustomDevice<IDevice> (manager.GetAllDevices ());
}
public IEnumerable<IBlockDevice> GetAllBlockDevices ()
{
return CastToCustomDevice<IBlockDevice> (manager.GetAllBlockDevices ());
}
public IEnumerable<ICdromDevice> GetAllCdromDevices ()
{
return CastToCustomDevice<ICdromDevice> (manager.GetAllCdromDevices ());
}
public IEnumerable<IDiskDevice> GetAllDiskDevices ()
{
return CastToCustomDevice<IDiskDevice> (manager.GetAllDiskDevices ());
}
public void Test ()
{
Console.WriteLine ("All Block Devices:");
PrintBlockDeviceList (GetAllBlockDevices ());
Console.WriteLine ("All CD-ROM Devices:");
PrintBlockDeviceList (GetAllCdromDevices ());
Console.WriteLine ("All Disk Devices:");
PrintBlockDeviceList (GetAllDiskDevices ());
}
private void PrintBlockDeviceList (System.Collections.IEnumerable devices)
{
foreach (IBlockDevice device in devices) {
Console.WriteLine ("{0}, {1}", device.GetType ().FullName, device);
foreach (IVolume volume in device.Volumes) {
Console.WriteLine (" {0}, {1}", volume.GetType ().FullName, volume);
}
}
}
string IService.ServiceName {
get { return "HardwareManager"; }
}
}
}
| |
/*
* Farseer Physics Engine:
* Copyright (c) 2012 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System.Diagnostics;
using Astrid.Core;
using Astrid.FarseerPhysics.Common;
namespace Astrid.FarseerPhysics.Collision.Shapes
{
/// <summary>
/// A chain shape is a free form sequence of line segments.
/// The chain has two-sided collision, so you can use inside and outside collision.
/// Therefore, you may use any winding order.
/// Connectivity information is used to create smooth collisions.
/// WARNING: The chain will not collide properly if there are self-intersections.
/// </summary>
public class ChainShape : Shape
{
/// <summary>
/// The vertices. These are not owned/freed by the chain Shape.
/// </summary>
public Vertices Vertices;
private Vector2 _prevVertex, _nextVertex;
private bool _hasPrevVertex, _hasNextVertex;
private static EdgeShape _edgeShape = new EdgeShape();
/// <summary>
/// Constructor for ChainShape. By default have 0 in density.
/// </summary>
public ChainShape()
: base(0)
{
ShapeType = ShapeType.Chain;
_radius = Settings.PolygonRadius;
}
/// <summary>
/// Create a new chainshape from the vertices.
/// </summary>
/// <param name="vertices">The vertices to use. Must contain 2 or more vertices.</param>
/// <param name="createLoop">Set to true to create a closed loop. It connects the first vertice to the last, and automatically adjusts connectivity to create smooth collisions along the chain.</param>
public ChainShape(Vertices vertices, bool createLoop = false)
: base(0)
{
ShapeType = ShapeType.Chain;
_radius = Settings.PolygonRadius;
Debug.Assert(vertices != null && vertices.Count >= 3);
Debug.Assert(vertices[0] != vertices[vertices.Count - 1]); // FPE. See http://www.box2d.org/forum/viewtopic.php?f=4&t=7973&p=35363
for (int i = 1; i < vertices.Count; ++i)
{
Vector2 v1 = vertices[i - 1];
Vector2 v2 = vertices[i];
// If the code crashes here, it means your vertices are too close together.
Debug.Assert(Vector2.DistanceSquared(v1, v2) > Settings.LinearSlop * Settings.LinearSlop);
}
Vertices = new Vertices(vertices);
if (createLoop)
{
Vertices.Add(vertices[0]);
PrevVertex = Vertices[Vertices.Count - 2]; //FPE: We use the properties instead of the private fields here.
NextVertex = Vertices[1]; //FPE: We use the properties instead of the private fields here.
}
}
public override int ChildCount
{
// edge count = vertex count - 1
get { return Vertices.Count - 1; }
}
/// <summary>
/// Establish connectivity to a vertex that precedes the first vertex.
/// Don't call this for loops.
/// </summary>
public Vector2 PrevVertex
{
get { return _prevVertex; }
set
{
Debug.Assert(value != null);
_prevVertex = value;
_hasPrevVertex = true;
}
}
/// <summary>
/// Establish connectivity to a vertex that follows the last vertex.
/// Don't call this for loops.
/// </summary>
public Vector2 NextVertex
{
get { return _nextVertex; }
set
{
Debug.Assert(value != null);
_nextVertex = value;
_hasNextVertex = true;
}
}
/// <summary>
/// This method has been optimized to reduce garbage.
/// </summary>
/// <param name="edge">The cached edge to set properties on.</param>
/// <param name="index">The index.</param>
internal void GetChildEdge(EdgeShape edge, int index)
{
Debug.Assert(0 <= index && index < Vertices.Count - 1);
Debug.Assert(edge != null);
edge.ShapeType = ShapeType.Edge;
edge._radius = _radius;
edge.Vertex1 = Vertices[index + 0];
edge.Vertex2 = Vertices[index + 1];
if (index > 0)
{
edge.Vertex0 = Vertices[index - 1];
edge.HasVertex0 = true;
}
else
{
edge.Vertex0 = _prevVertex;
edge.HasVertex0 = _hasPrevVertex;
}
if (index < Vertices.Count - 2)
{
edge.Vertex3 = Vertices[index + 2];
edge.HasVertex3 = true;
}
else
{
edge.Vertex3 = _nextVertex;
edge.HasVertex3 = _hasNextVertex;
}
}
/// <summary>
/// Get a child edge.
/// </summary>
/// <param name="index">The index.</param>
public EdgeShape GetChildEdge(int index)
{
EdgeShape edgeShape = new EdgeShape();
GetChildEdge(edgeShape, index);
return edgeShape;
}
public override bool TestPoint(ref Transform transform, ref Vector2 point)
{
return false;
}
public override bool RayCast(out RayCastOutput output, ref RayCastInput input, ref Transform transform, int childIndex)
{
Debug.Assert(childIndex < Vertices.Count);
int i1 = childIndex;
int i2 = childIndex + 1;
if (i2 == Vertices.Count)
{
i2 = 0;
}
_edgeShape.Vertex1 = Vertices[i1];
_edgeShape.Vertex2 = Vertices[i2];
return _edgeShape.RayCast(out output, ref input, ref transform, 0);
}
public override void ComputeAABB(out AABB aabb, ref Transform transform, int childIndex)
{
Debug.Assert(childIndex < Vertices.Count);
int i1 = childIndex;
int i2 = childIndex + 1;
if (i2 == Vertices.Count)
{
i2 = 0;
}
Vector2 v1 = MathUtils.Mul(ref transform, Vertices[i1]);
Vector2 v2 = MathUtils.Mul(ref transform, Vertices[i2]);
aabb.LowerBound = Vector2.Min(v1, v2);
aabb.UpperBound = Vector2.Max(v1, v2);
}
protected override void ComputeProperties()
{
//Does nothing. Chain shapes don't have properties.
}
public override float ComputeSubmergedArea(ref Vector2 normal, float offset, ref Transform xf, out Vector2 sc)
{
sc = Vector2.Zero;
return 0;
}
/// <summary>
/// Compare the chain to another chain
/// </summary>
/// <param name="shape">The other chain</param>
/// <returns>True if the two chain shapes are the same</returns>
public bool CompareTo(ChainShape shape)
{
if (Vertices.Count != shape.Vertices.Count)
return false;
for (int i = 0; i < Vertices.Count; i++)
{
if (Vertices[i] != shape.Vertices[i])
return false;
}
return PrevVertex == shape.PrevVertex && NextVertex == shape.NextVertex;
}
public override Shape Clone()
{
ChainShape clone = new ChainShape();
clone.ShapeType = ShapeType;
clone._density = _density;
clone._radius = _radius;
clone.PrevVertex = _prevVertex;
clone.NextVertex = _nextVertex;
clone._hasNextVertex = _hasNextVertex;
clone._hasPrevVertex = _hasPrevVertex;
clone.Vertices = new Vertices(Vertices);
clone.MassData = MassData;
return clone;
}
}
}
| |
using Neo.Cryptography;
using Neo.Cryptography.ECC;
using Neo.IO;
using Neo.Ledger;
using Neo.Network.P2P.Payloads;
using Neo.Persistence;
using Neo.SmartContract;
using Neo.SmartContract.Native;
using Neo.VM;
using Neo.Wallets;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
namespace Neo.Consensus
{
internal class ConsensusContext : IDisposable, ISerializable
{
/// <summary>
/// Key for saving consensus state.
/// </summary>
private const byte ConsensusStatePrefix = 0xf4;
public Block Block;
public byte ViewNumber;
public ECPoint[] Validators;
public int MyIndex;
public UInt256[] TransactionHashes;
public Dictionary<UInt256, Transaction> Transactions;
public ConsensusPayload[] PreparationPayloads;
public ConsensusPayload[] CommitPayloads;
public ConsensusPayload[] ChangeViewPayloads;
public ConsensusPayload[] LastChangeViewPayloads;
// LastSeenMessage array stores the height of the last seen message, for each validator.
// if this node never heard from validator i, LastSeenMessage[i] will be -1.
public int[] LastSeenMessage;
/// <summary>
/// Store all verified unsorted transactions' senders' fee currently in the consensus context.
/// </summary>
public SendersFeeMonitor SendersFeeMonitor = new SendersFeeMonitor();
public SnapshotView Snapshot { get; private set; }
private KeyPair keyPair;
private int _witnessSize;
private readonly Wallet wallet;
private readonly IStore store;
public int F => (Validators.Length - 1) / 3;
public int M => Validators.Length - F;
public bool IsPrimary => MyIndex == Block.ConsensusData.PrimaryIndex;
public bool IsBackup => MyIndex >= 0 && MyIndex != Block.ConsensusData.PrimaryIndex;
public bool WatchOnly => MyIndex < 0;
public Header PrevHeader => Snapshot.GetHeader(Block.PrevHash);
public int CountCommitted => CommitPayloads.Count(p => p != null);
public int CountFailed => LastSeenMessage.Count(p => p < (((int)Block.Index) - 1));
#region Consensus States
public bool RequestSentOrReceived => PreparationPayloads[Block.ConsensusData.PrimaryIndex] != null;
public bool ResponseSent => !WatchOnly && PreparationPayloads[MyIndex] != null;
public bool CommitSent => !WatchOnly && CommitPayloads[MyIndex] != null;
public bool BlockSent => Block.Transactions != null;
public bool ViewChanging => !WatchOnly && ChangeViewPayloads[MyIndex]?.GetDeserializedMessage<ChangeView>().NewViewNumber > ViewNumber;
public bool NotAcceptingPayloadsDueToViewChanging => ViewChanging && !MoreThanFNodesCommittedOrLost;
// A possible attack can happen if the last node to commit is malicious and either sends change view after his
// commit to stall nodes in a higher view, or if he refuses to send recovery messages. In addition, if a node
// asking change views loses network or crashes and comes back when nodes are committed in more than one higher
// numbered view, it is possible for the node accepting recovery to commit in any of the higher views, thus
// potentially splitting nodes among views and stalling the network.
public bool MoreThanFNodesCommittedOrLost => (CountCommitted + CountFailed) > F;
#endregion
public int Size => throw new NotImplementedException();
public ConsensusContext(Wallet wallet, IStore store)
{
this.wallet = wallet;
this.store = store;
}
public Block CreateBlock()
{
EnsureHeader();
Contract contract = Contract.CreateMultiSigContract(M, Validators);
ContractParametersContext sc = new ContractParametersContext(Block);
for (int i = 0, j = 0; i < Validators.Length && j < M; i++)
{
if (CommitPayloads[i]?.ConsensusMessage.ViewNumber != ViewNumber) continue;
sc.AddSignature(contract, Validators[i], CommitPayloads[i].GetDeserializedMessage<Commit>().Signature);
j++;
}
Block.Witness = sc.GetWitnesses()[0];
Block.Transactions = TransactionHashes.Select(p => Transactions[p]).ToArray();
return Block;
}
public void Deserialize(BinaryReader reader)
{
Reset(0);
if (reader.ReadUInt32() != Block.Version) throw new FormatException();
if (reader.ReadUInt32() != Block.Index) throw new InvalidOperationException();
Block.Timestamp = reader.ReadUInt64();
Block.NextConsensus = reader.ReadSerializable<UInt160>();
if (Block.NextConsensus.Equals(UInt160.Zero))
Block.NextConsensus = null;
Block.ConsensusData = reader.ReadSerializable<ConsensusData>();
ViewNumber = reader.ReadByte();
TransactionHashes = reader.ReadSerializableArray<UInt256>();
Transaction[] transactions = reader.ReadSerializableArray<Transaction>(Block.MaxTransactionsPerBlock);
PreparationPayloads = reader.ReadNullableArray<ConsensusPayload>(Blockchain.MaxValidators);
CommitPayloads = reader.ReadNullableArray<ConsensusPayload>(Blockchain.MaxValidators);
ChangeViewPayloads = reader.ReadNullableArray<ConsensusPayload>(Blockchain.MaxValidators);
LastChangeViewPayloads = reader.ReadNullableArray<ConsensusPayload>(Blockchain.MaxValidators);
if (TransactionHashes.Length == 0 && !RequestSentOrReceived)
TransactionHashes = null;
Transactions = transactions.Length == 0 && !RequestSentOrReceived ? null : transactions.ToDictionary(p => p.Hash);
SendersFeeMonitor = new SendersFeeMonitor();
if (Transactions != null)
{
foreach (Transaction tx in Transactions.Values)
SendersFeeMonitor.AddSenderFee(tx);
}
}
public void Dispose()
{
Snapshot?.Dispose();
}
public Block EnsureHeader()
{
if (TransactionHashes == null) return null;
if (Block.MerkleRoot is null)
Block.MerkleRoot = Block.CalculateMerkleRoot(Block.ConsensusData.Hash, TransactionHashes);
return Block;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public uint GetPrimaryIndex(byte viewNumber)
{
int p = ((int)Block.Index - viewNumber) % Validators.Length;
return p >= 0 ? (uint)p : (uint)(p + Validators.Length);
}
public bool Load()
{
byte[] data = store.TryGet(ConsensusStatePrefix, null);
if (data is null || data.Length == 0) return false;
using (MemoryStream ms = new MemoryStream(data, false))
using (BinaryReader reader = new BinaryReader(ms))
{
try
{
Deserialize(reader);
}
catch
{
return false;
}
return true;
}
}
public ConsensusPayload MakeChangeView(ChangeViewReason reason)
{
return ChangeViewPayloads[MyIndex] = MakeSignedPayload(new ChangeView
{
Reason = reason,
Timestamp = TimeProvider.Current.UtcNow.ToTimestampMS()
});
}
public ConsensusPayload MakeCommit()
{
return CommitPayloads[MyIndex] ?? (CommitPayloads[MyIndex] = MakeSignedPayload(new Commit
{
Signature = EnsureHeader().Sign(keyPair)
}));
}
private ConsensusPayload MakeSignedPayload(ConsensusMessage message)
{
message.ViewNumber = ViewNumber;
ConsensusPayload payload = new ConsensusPayload
{
Version = Block.Version,
PrevHash = Block.PrevHash,
BlockIndex = Block.Index,
ValidatorIndex = (ushort)MyIndex,
ConsensusMessage = message
};
SignPayload(payload);
return payload;
}
private void SignPayload(ConsensusPayload payload)
{
ContractParametersContext sc;
try
{
sc = new ContractParametersContext(payload);
wallet.Sign(sc);
}
catch (InvalidOperationException)
{
return;
}
payload.Witness = sc.GetWitnesses()[0];
}
/// <summary>
/// Return the expected block size
/// </summary>
internal int GetExpectedBlockSize()
{
return GetExpectedBlockSizeWithoutTransactions(Transactions.Count) + // Base size
Transactions.Values.Sum(u => u.Size); // Sum Txs
}
/// <summary>
/// Return the expected block size without txs
/// </summary>
/// <param name="expectedTransactions">Expected transactions</param>
internal int GetExpectedBlockSizeWithoutTransactions(int expectedTransactions)
{
var blockSize =
// BlockBase
sizeof(uint) + //Version
UInt256.Length + //PrevHash
UInt256.Length + //MerkleRoot
sizeof(ulong) + //Timestamp
sizeof(uint) + //Index
UInt160.Length + //NextConsensus
1 + //
_witnessSize; //Witness
blockSize +=
// Block
Block.ConsensusData.Size + //ConsensusData
IO.Helper.GetVarSize(expectedTransactions + 1); //Transactions count
return blockSize;
}
/// <summary>
/// Prevent that block exceed the max size
/// </summary>
/// <param name="txs">Ordered transactions</param>
internal void EnsureMaxBlockSize(IEnumerable<Transaction> txs)
{
uint maxBlockSize = NativeContract.Policy.GetMaxBlockSize(Snapshot);
uint maxTransactionsPerBlock = NativeContract.Policy.GetMaxTransactionsPerBlock(Snapshot);
// Limit Speaker proposal to the limit `MaxTransactionsPerBlock` or all available transactions of the mempool
txs = txs.Take((int)maxTransactionsPerBlock);
List<UInt256> hashes = new List<UInt256>();
Transactions = new Dictionary<UInt256, Transaction>();
SendersFeeMonitor = new SendersFeeMonitor();
// Expected block size
var blockSize = GetExpectedBlockSizeWithoutTransactions(txs.Count());
// Iterate transaction until reach the size
foreach (Transaction tx in txs)
{
// Check if maximum block size has been already exceeded with the current selected set
blockSize += tx.Size;
if (blockSize > maxBlockSize) break;
hashes.Add(tx.Hash);
Transactions.Add(tx.Hash, tx);
SendersFeeMonitor.AddSenderFee(tx);
}
TransactionHashes = hashes.ToArray();
}
public ConsensusPayload MakePrepareRequest()
{
var random = new Random();
byte[] buffer = new byte[sizeof(ulong)];
random.NextBytes(buffer);
Block.ConsensusData.Nonce = BitConverter.ToUInt64(buffer, 0);
EnsureMaxBlockSize(Blockchain.Singleton.MemPool.GetSortedVerifiedTransactions());
Block.Timestamp = Math.Max(TimeProvider.Current.UtcNow.ToTimestampMS(), PrevHeader.Timestamp + 1);
return PreparationPayloads[MyIndex] = MakeSignedPayload(new PrepareRequest
{
Timestamp = Block.Timestamp,
Nonce = Block.ConsensusData.Nonce,
TransactionHashes = TransactionHashes
});
}
public ConsensusPayload MakeRecoveryRequest()
{
return MakeSignedPayload(new RecoveryRequest
{
Timestamp = TimeProvider.Current.UtcNow.ToTimestampMS()
});
}
public ConsensusPayload MakeRecoveryMessage()
{
PrepareRequest prepareRequestMessage = null;
if (TransactionHashes != null)
{
prepareRequestMessage = new PrepareRequest
{
ViewNumber = ViewNumber,
Timestamp = Block.Timestamp,
Nonce = Block.ConsensusData.Nonce,
TransactionHashes = TransactionHashes
};
}
return MakeSignedPayload(new RecoveryMessage()
{
ChangeViewMessages = LastChangeViewPayloads.Where(p => p != null).Select(p => RecoveryMessage.ChangeViewPayloadCompact.FromPayload(p)).Take(M).ToDictionary(p => (int)p.ValidatorIndex),
PrepareRequestMessage = prepareRequestMessage,
// We only need a PreparationHash set if we don't have the PrepareRequest information.
PreparationHash = TransactionHashes == null ? PreparationPayloads.Where(p => p != null).GroupBy(p => p.GetDeserializedMessage<PrepareResponse>().PreparationHash, (k, g) => new { Hash = k, Count = g.Count() }).OrderByDescending(p => p.Count).Select(p => p.Hash).FirstOrDefault() : null,
PreparationMessages = PreparationPayloads.Where(p => p != null).Select(p => RecoveryMessage.PreparationPayloadCompact.FromPayload(p)).ToDictionary(p => (int)p.ValidatorIndex),
CommitMessages = CommitSent
? CommitPayloads.Where(p => p != null).Select(p => RecoveryMessage.CommitPayloadCompact.FromPayload(p)).ToDictionary(p => (int)p.ValidatorIndex)
: new Dictionary<int, RecoveryMessage.CommitPayloadCompact>()
});
}
public ConsensusPayload MakePrepareResponse()
{
return PreparationPayloads[MyIndex] = MakeSignedPayload(new PrepareResponse
{
PreparationHash = PreparationPayloads[Block.ConsensusData.PrimaryIndex].Hash
});
}
public void Reset(byte viewNumber)
{
if (viewNumber == 0)
{
Snapshot?.Dispose();
Snapshot = Blockchain.Singleton.GetSnapshot();
Block = new Block
{
PrevHash = Snapshot.CurrentBlockHash,
Index = Snapshot.Height + 1,
NextConsensus = Blockchain.GetConsensusAddress(NativeContract.NEO.GetValidators(Snapshot).ToArray())
};
var pv = Validators;
Validators = NativeContract.NEO.GetNextBlockValidators(Snapshot);
if (_witnessSize == 0 || (pv != null && pv.Length != Validators.Length))
{
// Compute the expected size of the witness
using (ScriptBuilder sb = new ScriptBuilder())
{
for (int x = 0; x < M; x++)
{
sb.EmitPush(new byte[64]);
}
_witnessSize = new Witness
{
InvocationScript = sb.ToArray(),
VerificationScript = Contract.CreateMultiSigRedeemScript(M, Validators)
}.Size;
}
}
MyIndex = -1;
ChangeViewPayloads = new ConsensusPayload[Validators.Length];
LastChangeViewPayloads = new ConsensusPayload[Validators.Length];
CommitPayloads = new ConsensusPayload[Validators.Length];
if (LastSeenMessage == null)
{
LastSeenMessage = new int[Validators.Length];
for (int i = 0; i < Validators.Length; i++)
LastSeenMessage[i] = -1;
}
keyPair = null;
for (int i = 0; i < Validators.Length; i++)
{
WalletAccount account = wallet?.GetAccount(Validators[i]);
if (account?.HasKey != true) continue;
MyIndex = i;
keyPair = account.GetKey();
break;
}
}
else
{
for (int i = 0; i < LastChangeViewPayloads.Length; i++)
if (ChangeViewPayloads[i]?.GetDeserializedMessage<ChangeView>().NewViewNumber >= viewNumber)
LastChangeViewPayloads[i] = ChangeViewPayloads[i];
else
LastChangeViewPayloads[i] = null;
}
ViewNumber = viewNumber;
Block.ConsensusData = new ConsensusData
{
PrimaryIndex = GetPrimaryIndex(viewNumber)
};
Block.MerkleRoot = null;
Block.Timestamp = 0;
Block.Transactions = null;
TransactionHashes = null;
PreparationPayloads = new ConsensusPayload[Validators.Length];
if (MyIndex >= 0) LastSeenMessage[MyIndex] = (int)Block.Index;
}
public void Save()
{
store.PutSync(ConsensusStatePrefix, null, this.ToArray());
}
public void Serialize(BinaryWriter writer)
{
writer.Write(Block.Version);
writer.Write(Block.Index);
writer.Write(Block.Timestamp);
writer.Write(Block.NextConsensus ?? UInt160.Zero);
writer.Write(Block.ConsensusData);
writer.Write(ViewNumber);
writer.Write(TransactionHashes ?? new UInt256[0]);
writer.Write(Transactions?.Values.ToArray() ?? new Transaction[0]);
writer.WriteNullableArray(PreparationPayloads);
writer.WriteNullableArray(CommitPayloads);
writer.WriteNullableArray(ChangeViewPayloads);
writer.WriteNullableArray(LastChangeViewPayloads);
}
}
}
| |
/*
* 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 OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.World.Land;
using OpenSim.Region.DataSnapshot.Interfaces;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Xml;
namespace OpenSim.Region.DataSnapshot.Providers
{
public class LandSnapshot : IDataSnapshotProvider
{
//private Dictionary<int, Land> m_landIndexed = new Dictionary<int, Land>();
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private DataSnapshotManager m_parent = null;
private Scene m_scene = null;
private bool m_stale = true;
#region Dead code
/*
* David, I don't think we need this at all. When we do the snapshot, we can
* simply look into the parcels that are marked for ShowDirectory -- see
* conditional in RequestSnapshotData
*
//Revise this, look for more direct way of checking for change in land
#region Client hooks
public void OnNewClient(IClientAPI client)
{
//Land hooks
client.OnParcelDivideRequest += ParcelSplitHook;
client.OnParcelJoinRequest += ParcelSplitHook;
client.OnParcelPropertiesUpdateRequest += ParcelPropsHook;
}
public void ParcelSplitHook(int west, int south, int east, int north, IClientAPI remote_client)
{
PrepareData();
}
public void ParcelPropsHook(ParcelPropertiesUpdatePacket packet, IClientAPI remote_client)
{
PrepareData();
}
#endregion Client hooks
public void PrepareData()
{
m_log.Info("[EXTERNALDATA]: Generating land data.");
m_landIndexed.Clear();
//Index sim land
foreach (KeyValuePair<int, Land> curLand in m_scene.LandManager.landList)
{
//if ((curLand.Value.LandData.landFlags & (uint)ParcelFlags.ShowDirectory) == (uint)ParcelFlags.ShowDirectory)
//{
m_landIndexed.Add(curLand.Key, curLand.Value.Copy());
//}
}
}
public Dictionary<int,Land> IndexedLand {
get { return m_landIndexed; }
}
*/
#endregion Dead code
#region IDataSnapshotProvider members
public event ProviderStale OnStale;
public Scene GetParentScene
{
get { return m_scene; }
}
public String Name
{
get { return "LandSnapshot"; }
}
public bool Stale
{
get
{
return m_stale;
}
set
{
m_stale = value;
if (m_stale)
OnStale(this);
}
}
public void Initialize(Scene scene, DataSnapshotManager parent)
{
m_scene = scene;
m_parent = parent;
//Brought back from the dead for staleness checks.
m_scene.EventManager.OnNewClient += OnNewClient;
}
public XmlNode RequestSnapshotData(XmlDocument nodeFactory)
{
ILandChannel landChannel = m_scene.LandChannel;
List<ILandObject> parcels = landChannel.AllParcels();
IDwellModule dwellModule = m_scene.RequestModuleInterface<IDwellModule>();
XmlNode parent = nodeFactory.CreateNode(XmlNodeType.Element, "parceldata", "");
if (parcels != null)
{
//foreach (KeyValuePair<int, Land> curParcel in m_landIndexed)
foreach (ILandObject parcel_interface in parcels)
{
// Play it safe
if (!(parcel_interface is LandObject))
continue;
LandObject land = (LandObject)parcel_interface;
LandData parcel = land.LandData;
if (m_parent.ExposureLevel.Equals("all") ||
(m_parent.ExposureLevel.Equals("minimum") &&
(parcel.Flags & (uint)ParcelFlags.ShowDirectory) == (uint)ParcelFlags.ShowDirectory))
{
//TODO: make better method of marshalling data from LandData to XmlNode
XmlNode xmlparcel = nodeFactory.CreateNode(XmlNodeType.Element, "parcel", "");
// Attributes of the parcel node
XmlAttribute scripts_attr = nodeFactory.CreateAttribute("scripts");
scripts_attr.Value = GetScriptsPermissions(parcel);
XmlAttribute build_attr = nodeFactory.CreateAttribute("build");
build_attr.Value = GetBuildPermissions(parcel);
XmlAttribute public_attr = nodeFactory.CreateAttribute("public");
public_attr.Value = GetPublicPermissions(parcel);
// Check the category of the Parcel
XmlAttribute category_attr = nodeFactory.CreateAttribute("category");
category_attr.Value = ((int)parcel.Category).ToString();
// Check if the parcel is for sale
XmlAttribute forsale_attr = nodeFactory.CreateAttribute("forsale");
forsale_attr.Value = CheckForSale(parcel);
XmlAttribute sales_attr = nodeFactory.CreateAttribute("salesprice");
sales_attr.Value = parcel.SalePrice.ToString();
XmlAttribute directory_attr = nodeFactory.CreateAttribute("showinsearch");
directory_attr.Value = GetShowInSearch(parcel);
//XmlAttribute entities_attr = nodeFactory.CreateAttribute("entities");
//entities_attr.Value = land.primsOverMe.Count.ToString();
xmlparcel.Attributes.Append(directory_attr);
xmlparcel.Attributes.Append(scripts_attr);
xmlparcel.Attributes.Append(build_attr);
xmlparcel.Attributes.Append(public_attr);
xmlparcel.Attributes.Append(category_attr);
xmlparcel.Attributes.Append(forsale_attr);
xmlparcel.Attributes.Append(sales_attr);
//xmlparcel.Attributes.Append(entities_attr);
//name, description, area, and UUID
XmlNode name = nodeFactory.CreateNode(XmlNodeType.Element, "name", "");
name.InnerText = parcel.Name;
xmlparcel.AppendChild(name);
XmlNode desc = nodeFactory.CreateNode(XmlNodeType.Element, "description", "");
desc.InnerText = parcel.Description;
xmlparcel.AppendChild(desc);
XmlNode uuid = nodeFactory.CreateNode(XmlNodeType.Element, "uuid", "");
uuid.InnerText = parcel.GlobalID.ToString();
xmlparcel.AppendChild(uuid);
XmlNode area = nodeFactory.CreateNode(XmlNodeType.Element, "area", "");
area.InnerText = parcel.Area.ToString();
xmlparcel.AppendChild(area);
//default location
XmlNode tpLocation = nodeFactory.CreateNode(XmlNodeType.Element, "location", "");
Vector3 loc = parcel.UserLocation;
if (loc.Equals(Vector3.Zero)) // This test is moot at this point: the location is wrong by default
loc = new Vector3((parcel.AABBMax.X + parcel.AABBMin.X) / 2, (parcel.AABBMax.Y + parcel.AABBMin.Y) / 2, (parcel.AABBMax.Z + parcel.AABBMin.Z) / 2);
tpLocation.InnerText = loc.X.ToString() + "/" + loc.Y.ToString() + "/" + loc.Z.ToString();
xmlparcel.AppendChild(tpLocation);
XmlNode infouuid = nodeFactory.CreateNode(XmlNodeType.Element, "infouuid", "");
uint x = (uint)loc.X, y = (uint)loc.Y;
findPointInParcel(land, ref x, ref y); // find a suitable spot
infouuid.InnerText = Util.BuildFakeParcelID(
m_scene.RegionInfo.RegionHandle, x, y).ToString();
xmlparcel.AppendChild(infouuid);
XmlNode dwell = nodeFactory.CreateNode(XmlNodeType.Element, "dwell", "");
if (dwellModule != null)
dwell.InnerText = dwellModule.GetDwell(parcel.GlobalID).ToString();
else
dwell.InnerText = "0";
xmlparcel.AppendChild(dwell);
//TODO: figure how to figure out teleport system landData.landingType
//land texture snapshot uuid
if (parcel.SnapshotID != UUID.Zero)
{
XmlNode textureuuid = nodeFactory.CreateNode(XmlNodeType.Element, "image", "");
textureuuid.InnerText = parcel.SnapshotID.ToString();
xmlparcel.AppendChild(textureuuid);
}
string groupName = String.Empty;
//attached user and group
if (parcel.GroupID != UUID.Zero)
{
XmlNode groupblock = nodeFactory.CreateNode(XmlNodeType.Element, "group", "");
XmlNode groupuuid = nodeFactory.CreateNode(XmlNodeType.Element, "groupuuid", "");
groupuuid.InnerText = parcel.GroupID.ToString();
groupblock.AppendChild(groupuuid);
IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
if (gm != null)
{
GroupRecord g = gm.GetGroupRecord(parcel.GroupID);
if (g != null)
groupName = g.GroupName;
}
XmlNode groupname = nodeFactory.CreateNode(XmlNodeType.Element, "groupname", "");
groupname.InnerText = groupName;
groupblock.AppendChild(groupname);
xmlparcel.AppendChild(groupblock);
}
XmlNode userblock = nodeFactory.CreateNode(XmlNodeType.Element, "owner", "");
UUID userOwnerUUID = parcel.OwnerID;
XmlNode useruuid = nodeFactory.CreateNode(XmlNodeType.Element, "uuid", "");
useruuid.InnerText = userOwnerUUID.ToString();
userblock.AppendChild(useruuid);
if (!parcel.IsGroupOwned)
{
try
{
XmlNode username = nodeFactory.CreateNode(XmlNodeType.Element, "name", "");
UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, userOwnerUUID);
username.InnerText = account.FirstName + " " + account.LastName;
userblock.AppendChild(username);
}
catch (Exception)
{
//m_log.Info("[DATASNAPSHOT]: Cannot find owner name; ignoring this parcel");
}
}
else
{
XmlNode username = nodeFactory.CreateNode(XmlNodeType.Element, "name", "");
username.InnerText = groupName;
userblock.AppendChild(username);
}
xmlparcel.AppendChild(userblock);
parent.AppendChild(xmlparcel);
}
}
//snap.AppendChild(parent);
}
this.Stale = false;
return parent;
}
#endregion IDataSnapshotProvider members
#region Helper functions
private string CheckForSale(LandData parcel)
{
if ((parcel.Flags & (uint)ParcelFlags.ForSale) == (uint)ParcelFlags.ForSale)
return "true";
else
return "false";
}
private string GetBuildPermissions(LandData parcel)
{
if ((parcel.Flags & (uint)ParcelFlags.CreateObjects) == (uint)ParcelFlags.CreateObjects)
return "true";
else
return "false";
}
private string GetPublicPermissions(LandData parcel)
{
if ((parcel.Flags & (uint)ParcelFlags.UseAccessList) == (uint)ParcelFlags.UseAccessList)
return "false";
else
return "true";
}
private string GetScriptsPermissions(LandData parcel)
{
if ((parcel.Flags & (uint)ParcelFlags.AllowOtherScripts) == (uint)ParcelFlags.AllowOtherScripts)
return "true";
else
return "false";
}
private string GetShowInSearch(LandData parcel)
{
if ((parcel.Flags & (uint)ParcelFlags.ShowDirectory) == (uint)ParcelFlags.ShowDirectory)
return "true";
else
return "false";
}
#endregion Helper functions
#region Change detection hooks
public void OnNewClient(IClientAPI client)
{
//Land hooks
client.OnParcelDivideRequest += delegate(int west, int south, int east, int north,
IClientAPI remote_client) { this.Stale = true; };
client.OnParcelJoinRequest += delegate(int west, int south, int east, int north,
IClientAPI remote_client) { this.Stale = true; };
client.OnParcelPropertiesUpdateRequest += delegate(LandUpdateArgs args, int local_id,
IClientAPI remote_client) { this.Stale = true; };
client.OnParcelBuy += delegate(UUID agentId, UUID groupId, bool final, bool groupOwned,
bool removeContribution, int parcelLocalID, int parcelArea, int parcelPrice, bool authenticated)
{ this.Stale = true; };
}
public void ParcelPropsHook(LandUpdateArgs args, int local_id, IClientAPI remote_client)
{
this.Stale = true;
}
public void ParcelSplitHook(int west, int south, int east, int north, IClientAPI remote_client)
{
this.Stale = true;
}
#endregion Change detection hooks
// this is needed for non-convex parcels (example: rectangular parcel, and in the exact center
// another, smaller rectangular parcel). Both will have the same initial coordinates.
private void findPointInParcel(ILandObject land, ref uint refX, ref uint refY)
{
m_log.DebugFormat("[DATASNAPSHOT] trying {0}, {1}", refX, refY);
// the point we started with already is in the parcel
if (land.ContainsPoint((int)refX, (int)refY)) return;
// ... otherwise, we have to search for a point within the parcel
uint startX = (uint)land.LandData.AABBMin.X;
uint startY = (uint)land.LandData.AABBMin.Y;
uint endX = (uint)land.LandData.AABBMax.X;
uint endY = (uint)land.LandData.AABBMax.Y;
// default: center of the parcel
refX = (startX + endX) / 2;
refY = (startY + endY) / 2;
// If the center point is within the parcel, take that one
if (land.ContainsPoint((int)refX, (int)refY)) return;
// otherwise, go the long way.
for (uint y = startY; y <= endY; ++y)
{
for (uint x = startX; x <= endX; ++x)
{
if (land.ContainsPoint((int)x, (int)y))
{
// found a point
refX = x;
refY = y;
return;
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.Build.Evaluation;
using Microsoft.SourceBrowser.Common;
namespace Microsoft.SourceBrowser.BuildLogParser
{
public class LogAnalyzer
{
public Dictionary<string, string> intermediateAssemblyPathToOutputAssemblyPathMap =
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
public MultiDictionary<string, string> assemblyNameToProjectFilePathsMap =
new MultiDictionary<string, string>(StringComparer.OrdinalIgnoreCase, StringComparer.OrdinalIgnoreCase);
private Dictionary<string, string> projectFilePathToAssemblyNameMap =
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private HashSet<CompilerInvocation> finalInvocations =
new HashSet<CompilerInvocation>(CompilerInvocation.Comparer);
public static HashSet<string> cacheOfKnownExistingBinaries =
new HashSet<string>(StringComparer.OrdinalIgnoreCase);
public readonly Dictionary<string, List<string>> ambiguousFinalDestinations =
new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
public static MultiDictionary<string, CompilerInvocation> ambiguousInvocations =
new MultiDictionary<string, CompilerInvocation>(StringComparer.OrdinalIgnoreCase, null);
public static MultiDictionary<string, CompilerInvocation> nonExistingReferencesToCompilerInvocationMap =
new MultiDictionary<string, CompilerInvocation>();
public LogAnalyzer()
{
cacheOfKnownExistingBinaries.Clear();
nonExistingReferencesToCompilerInvocationMap.Clear();
}
public static void DisposeStatics()
{
cacheOfKnownExistingBinaries.Clear();
cacheOfKnownExistingBinaries = null;
ambiguousInvocations.Clear();
ambiguousInvocations = null;
nonExistingReferencesToCompilerInvocationMap.Clear();
nonExistingReferencesToCompilerInvocationMap = null;
}
public static IEnumerable<CompilerInvocation> GetInvocations(string logFilePath)
{
return GetInvocations(logFiles: new[] { logFilePath });
}
public static IEnumerable<CompilerInvocation> GetInvocations(Options options = null, IEnumerable<string> logFiles = null)
{
var analyzer = new LogAnalyzer();
var invocationBuckets = new Dictionary<string, IEnumerable<CompilerInvocation>>(StringComparer.OrdinalIgnoreCase);
using (Disposable.Timing("Analyzing log files"))
{
#if true
Parallel.ForEach(logFiles, logFile =>
{
var set = analyzer.AnalyzeLogFile(logFile);
lock (invocationBuckets)
{
invocationBuckets.Add(Path.GetFileNameWithoutExtension(logFile), set);
}
});
#else
foreach (var logFile in logFiles)
{
var set = analyzer.AnalyzeLogFile(logFile);
lock (invocationBuckets)
{
invocationBuckets.Add(Path.GetFileNameWithoutExtension(logFile), set);
}
}
#endif
}
var buckets = invocationBuckets.OrderBy(kvp => kvp.Key).ToArray();
foreach (var bucket in buckets)
{
foreach (var invocation in bucket.Value)
{
analyzer.SelectFinalInvocation(invocation);
}
}
FixOutputPaths(analyzer);
if (options != null && options.SanityCheck)
{
using (Disposable.Timing("Sanity check"))
{
SanityCheck(analyzer, options);
}
}
return analyzer.Invocations;
}
public class Options
{
public bool CheckForOrphans = true;
public bool CheckForMissingOutputBinary = true;
public bool CheckForNonExistingReferences = false;
public bool SanityCheck = true;
}
private static void FixOutputPaths(LogAnalyzer analyzer)
{
foreach (var invocation in analyzer.Invocations)
{
// TypeScript
if (invocation.OutputAssemblyPath == null)
{
continue;
}
if (invocation.OutputAssemblyPath.StartsWith(".") || invocation.OutputAssemblyPath.StartsWith("\\"))
{
invocation.OutputAssemblyPath = Path.GetFullPath(
Path.Combine(
Path.GetDirectoryName(invocation.ProjectFilePath),
invocation.OutputAssemblyPath));
}
invocation.OutputAssemblyPath = Path.GetFullPath(invocation.OutputAssemblyPath);
invocation.ProjectFilePath = Path.GetFullPath(invocation.ProjectFilePath);
}
}
private static void SanityCheck(LogAnalyzer analyzer, Options options = null)
{
var dupes = analyzer.Invocations
.Where(i => i.AssemblyName != null)
.GroupBy(i => i.AssemblyName, StringComparer.OrdinalIgnoreCase)
.Where(g => g.Count() > 1).ToArray();
if (dupes.Any())
{
foreach (var dupe in dupes)
{
Log.Exception("=== Dupes: " + dupe.Key);
foreach (var value in dupe)
{
Log.Exception(value.ToString());
}
}
}
var ambiguousProjects = analyzer.assemblyNameToProjectFilePathsMap.Where(kvp => kvp.Value.Count > 1).ToArray();
if (ambiguousProjects.Any())
{
foreach (var ambiguousProject in ambiguousProjects)
{
Log.Exception("Multiple projects for the same assembly name: " + ambiguousProject.Key);
foreach (var value in ambiguousProject.Value)
{
Log.Exception(value);
}
}
}
var ambiguousIntermediatePaths = analyzer.intermediateAssemblyPathToOutputAssemblyPathMap
.GroupBy(kvp => Path.GetFileNameWithoutExtension(kvp.Key), StringComparer.OrdinalIgnoreCase)
.Where(g => g.Count() > 1)
.OrderByDescending(g => g.Count());
if (ambiguousIntermediatePaths.Any())
{
}
if (analyzer.ambiguousFinalDestinations.Any())
{
}
foreach (var assemblyName in ambiguousInvocations.Keys.ToArray())
{
var values = ambiguousInvocations[assemblyName].ToArray();
bool shouldRemove = true;
for (int i = 1; i < values.Length; i++)
{
if (!values[i].OutputAssemblyPath.Equals(values[0].OutputAssemblyPath))
{
// if entries in a bucket are different, we keep the bucket to report it at the end
shouldRemove = false;
break;
}
}
// remove buckets where all entries are exactly the same
if (shouldRemove)
{
ambiguousInvocations.Remove(assemblyName);
}
}
if (ambiguousInvocations.Any())
{
foreach (var ambiguousInvocation in ambiguousInvocations)
{
Log.Exception("Ambiguous invocations for the same assembly name: " + ambiguousInvocation.Key);
foreach (var value in ambiguousInvocation.Value)
{
Log.Exception(value.ToString());
}
}
}
if (options.CheckForNonExistingReferences)
{
DumpNonExistingReferences();
}
}
private static void DumpNonExistingReferences()
{
foreach (var kvp in nonExistingReferencesToCompilerInvocationMap)
{
Log.Exception(string.Format("Non existing reference {0} in {1} invocations", kvp.Key, kvp.Value.Count));
}
}
public static void SanityCheckAfterMetadataAsSource(IEnumerable<CompilerInvocation> invocations, Options options = null)
{
var allInvocationAssemblyNames = new HashSet<string>(
invocations.Select(i => i.AssemblyName),
StringComparer.OrdinalIgnoreCase);
var allReferenceAssemblyNames = new HashSet<string>(
invocations
.SelectMany(i => i.ReferencedBinaries)
.Select(b => Path.GetFileNameWithoutExtension(b)), StringComparer.OrdinalIgnoreCase);
allReferenceAssemblyNames.ExceptWith(allInvocationAssemblyNames);
//var invocationsWithUnindexedReferences = analyzer.Invocations
// .Where(i => i.ReferencedBinaries.Any(b => !allInvocationAssemblyNames.Contains(Path.GetFileNameWithoutExtension(b))))
// .Select(i => Tuple.Create(i, i.ReferencedBinaries.Where(b => !allInvocationAssemblyNames.Contains(Path.GetFileNameWithoutExtension(b))).ToArray()))
// .ToArray();
//if (invocationsWithUnindexedReferences.Length > 0)
//{
// throw new InvalidOperationException("Invocation with unindexed references: " + invocationsWithUnindexedReferences.First().Item1.ProjectFilePath);
//}
if (options == null || options.CheckForMissingOutputBinary)
{
var invocationsWhereBinaryDoesntExist = invocations.Where(
i => !File.Exists(i.OutputAssemblyPath)).ToArray();
if (invocationsWhereBinaryDoesntExist.Length > 0)
{
throw new InvalidOperationException("Invocation where output binary doesn't exist: " + invocationsWhereBinaryDoesntExist.First().OutputAssemblyPath);
}
}
}
public IEnumerable<CompilerInvocation> AnalyzeLogFile(string logFile)
{
Log.Write(logFile);
return ProcessLogFileLines(logFile);
}
private IEnumerable<CompilerInvocation> ProcessLogFileLines(string logFile)
{
var invocations = new HashSet<CompilerInvocation>();
var lines = File.ReadLines(logFile);
foreach (var currentLine in lines)
{
string line = currentLine;
line = line.Trim();
if (ProcessCopyingFileFrom(line))
{
continue;
}
if (ProcessDoneBuildingProject(line))
{
continue;
}
if (ProcessInvocation(line, i => invocations.Add(i)))
{
continue;
}
}
return invocations;
}
private bool ProcessCopyingFileFrom(string line)
{
if (line.Contains("Copying file from \"") || line.Contains("Moving file from \""))
{
int from = line.IndexOf("\"") + 1;
int to = line.IndexOf("\" to \"");
string intermediateAssemblyPath = line.Substring(from, to - from);
if (intermediateAssemblyPath.Contains(".."))
{
intermediateAssemblyPath = Path.GetFullPath(intermediateAssemblyPath);
}
string outputAssemblyPath = line.Substring(to + 6, line.Length - to - 8);
if (!outputAssemblyPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) &&
!outputAssemblyPath.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) &&
!outputAssemblyPath.EndsWith(".netmodule", StringComparison.OrdinalIgnoreCase))
{
// not even an assembly, we don't care about it
return true;
}
var assemblyName = Path.GetFileNameWithoutExtension(outputAssemblyPath);
if ((outputAssemblyPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ||
outputAssemblyPath.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) ||
outputAssemblyPath.EndsWith(".module", StringComparison.OrdinalIgnoreCase) ||
outputAssemblyPath.EndsWith(".netmodule", StringComparison.OrdinalIgnoreCase)) &&
!outputAssemblyPath.EndsWith(".resources.dll", StringComparison.OrdinalIgnoreCase) &&
!outputAssemblyPath.EndsWith(".XmlSerializers.dll", StringComparison.OrdinalIgnoreCase))
{
int tempPlacingIndex = intermediateAssemblyPath.IndexOf(@"\\TempPlacing");
if (tempPlacingIndex > -1)
{
intermediateAssemblyPath = intermediateAssemblyPath.Remove(tempPlacingIndex, 13);
}
intermediateAssemblyPath = intermediateAssemblyPath.Replace(@"\\", @"\");
lock (this.intermediateAssemblyPathToOutputAssemblyPathMap)
{
if (!this.intermediateAssemblyPathToOutputAssemblyPathMap.TryGetValue(intermediateAssemblyPath, out string existing))
{
this.intermediateAssemblyPathToOutputAssemblyPathMap[intermediateAssemblyPath] = outputAssemblyPath;
}
else if (!string.Equals(existing, outputAssemblyPath))
{
if (!ambiguousFinalDestinations.TryGetValue(assemblyName, out List<string> bucket))
{
bucket = new List<string>();
ambiguousFinalDestinations.Add(assemblyName, bucket);
bucket.Add(existing);
}
bucket.Add(outputAssemblyPath);
if (outputAssemblyPath.Length < existing.Length)
{
this.intermediateAssemblyPathToOutputAssemblyPathMap[intermediateAssemblyPath] = outputAssemblyPath;
}
}
}
}
return true;
}
return false;
}
private bool ProcessDoneBuildingProject(string line)
{
var doneBuildingProject = line.IndexOf("Done Building Project");
if (doneBuildingProject > -1)
{
string projectFilePath = ExtractProjectFilePath(line, doneBuildingProject);
if (!File.Exists(projectFilePath))
{
Log.Message("Project doesn't exist: " + projectFilePath);
return true;
}
string outputAssemblyName = GetAssemblyNameFromProject(projectFilePath);
if (string.IsNullOrWhiteSpace(outputAssemblyName))
{
return true;
}
lock (this.projectFilePathToAssemblyNameMap)
{
if (!this.projectFilePathToAssemblyNameMap.ContainsKey(projectFilePath))
{
lock (this.assemblyNameToProjectFilePathsMap)
{
this.assemblyNameToProjectFilePathsMap.Add(outputAssemblyName, projectFilePath);
}
this.projectFilePathToAssemblyNameMap[projectFilePath] = outputAssemblyName;
}
}
return true;
}
return false;
}
private string GetAssemblyNameFromProject(string projectFilePath)
{
string assemblyName = null;
lock (projectFilePathToAssemblyNameCache)
{
if (projectFilePathToAssemblyNameCache.TryGetValue(projectFilePath, out assemblyName))
{
return assemblyName;
}
}
assemblyName = AssemblyNameExtractor.GetAssemblyNameFromProject(projectFilePath);
if (assemblyName == null)
{
Log.Exception("Couldn't extract AssemblyName from project: " + projectFilePath);
}
else
{
lock (projectFilePathToAssemblyNameCache)
{
projectFilePathToAssemblyNameCache[projectFilePath] = assemblyName;
}
}
return assemblyName;
}
private bool ProcessInvocation(string line, Action<CompilerInvocation> collector)
{
bool csc = false;
bool vbc = false;
bool tsc = false;
csc = line.IndexOf("csc", StringComparison.OrdinalIgnoreCase) != -1;
if (csc &&
(line.IndexOf(@"\csc.exe ", StringComparison.OrdinalIgnoreCase) != -1 ||
line.IndexOf(@"\csc2.exe ", StringComparison.OrdinalIgnoreCase) != -1 ||
line.IndexOf(@"\rcsc.exe ", StringComparison.OrdinalIgnoreCase) != -1 ||
line.IndexOf(@"\rcsc2.exe ", StringComparison.OrdinalIgnoreCase) != -1))
{
AddInvocation(line, collector);
return true;
}
vbc = line.IndexOf("vbc", StringComparison.OrdinalIgnoreCase) != -1;
if (vbc &&
(line.IndexOf(@"\vbc.exe ", StringComparison.OrdinalIgnoreCase) != -1 ||
line.IndexOf(@"\vbc2.exe ", StringComparison.OrdinalIgnoreCase) != -1 ||
line.IndexOf(@"\rvbc.exe ", StringComparison.OrdinalIgnoreCase) != -1 ||
line.IndexOf(@"\rvbc2.exe ", StringComparison.OrdinalIgnoreCase) != -1))
{
AddInvocation(line, collector);
return true;
}
tsc = line.IndexOf("\tsc.exe ", StringComparison.OrdinalIgnoreCase) != -1;
if (tsc)
{
AddTypeScriptInvocation(line, collector);
return true;
}
return false;
}
private void AddTypeScriptInvocation(string line, Action<CompilerInvocation> collector)
{
var invocation = CompilerInvocation.CreateTypeScript(line);
collector(invocation);
}
private static void AddInvocation(string line, Action<CompilerInvocation> collector)
{
var invocation = new CompilerInvocation(line);
collector(invocation);
lock (cacheOfKnownExistingBinaries)
{
foreach (var reference in invocation.ReferencedBinaries)
{
cacheOfKnownExistingBinaries.Add(reference);
}
}
}
private void AssignProjectFilePath(CompilerInvocation invocation)
{
HashSet<string> projectFilePaths = null;
lock (this.assemblyNameToProjectFilePathsMap)
{
if (this.assemblyNameToProjectFilePathsMap.TryGetValue(invocation.AssemblyName, out projectFilePaths))
{
invocation.ProjectFilePath = projectFilePaths.First();
}
}
}
private void AssignOutputAssemblyPath(CompilerInvocation invocation)
{
string outputAssemblyFilePath = null;
lock (this.intermediateAssemblyPathToOutputAssemblyPathMap)
{
if (this.intermediateAssemblyPathToOutputAssemblyPathMap.TryGetValue(invocation.IntermediateAssemblyPath, out outputAssemblyFilePath))
{
outputAssemblyFilePath = Path.GetFullPath(outputAssemblyFilePath);
invocation.OutputAssemblyPath = outputAssemblyFilePath;
var realAssemblyName = Path.GetFileNameWithoutExtension(outputAssemblyFilePath);
if (invocation.AssemblyName != realAssemblyName)
{
invocation.AssemblyName = realAssemblyName;
}
}
else
{
invocation.UnknownIntermediatePath = true;
}
}
}
private static Dictionary<string, string> projectFilePathToAssemblyNameCache = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
internal void SelectFinalInvocation(CompilerInvocation invocation)
{
if (invocation.Language == "TypeScript")
{
lock (finalInvocations)
{
finalInvocations.Add(invocation);
}
return;
}
AssignProjectFilePath(invocation);
AssignOutputAssemblyPath(invocation);
if (invocation.UnknownIntermediatePath)
{
Log.Exception("Unknown intermediate path: " + invocation.IntermediateAssemblyPath);
}
lock (finalInvocations)
{
if (finalInvocations.Contains(invocation))
{
if (!ambiguousInvocations.ContainsKey(invocation.AssemblyName))
{
var existing = finalInvocations.First(i => StringComparer.OrdinalIgnoreCase.Equals(i.AssemblyName, invocation.AssemblyName));
ambiguousInvocations.Add(existing.AssemblyName, existing);
}
ambiguousInvocations.Add(invocation.AssemblyName, invocation);
}
finalInvocations.Add(invocation);
}
}
private string ExtractProjectFilePath(string line, int start)
{
start += 23;
int end = line.IndexOf('"', start + 1);
string projectFilePath = line.Substring(start, end - start);
return projectFilePath;
}
public static void WriteInvocationsToFile(IEnumerable<CompilerInvocation> invocations, string fileName)
{
var projects = invocations
.Where(i => i.ProjectFilePath != null && i.ProjectFilePath.Length >= 3)
.Select(i => i.ProjectFilePath.Substring(3))
.OrderBy(p => p, StringComparer.OrdinalIgnoreCase)
.ToArray();
var sortedInvocations = invocations
.OrderBy(i => i.AssemblyName, StringComparer.OrdinalIgnoreCase);
var assemblies = sortedInvocations
.Select(i => i.AssemblyName);
var assemblyPaths = GetAssemblyPaths(sortedInvocations);
assemblyPaths = assemblyPaths
.OrderBy(s => Path.GetFileName(s));
var lines = sortedInvocations
.SelectMany(i => new[] { i.ProjectFilePath ?? "-", i.OutputAssemblyPath, i.CommandLine });
var path = Path.GetDirectoryName(fileName);
var assembliesTxt = Path.Combine(path, "Assemblies.txt");
var projectsTxt = Path.Combine(path, "Projects.txt");
var assemblyPathsTxt = Path.Combine(path, "AssemblyPaths.txt");
File.WriteAllLines(fileName, lines);
File.WriteAllLines(projectsTxt, projects);
File.WriteAllLines(assembliesTxt, assemblies);
File.WriteAllLines(assemblyPathsTxt, assemblyPaths);
}
private static IEnumerable<string> GetAssemblyPaths(IEnumerable<CompilerInvocation> invocations)
{
var assemblyNameToFilePathMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var invocation in invocations)
{
AddAssemblyToMap(assemblyNameToFilePathMap, invocation.OutputAssemblyPath);
foreach (var reference in invocation.ReferencedBinaries)
{
AddAssemblyToMap(assemblyNameToFilePathMap, reference);
}
}
return assemblyNameToFilePathMap.Values;
}
private static void AddAssemblyToMap(Dictionary<string, string> assemblyNameToFilePathMap, string reference)
{
var assemblyName = Path.GetFileNameWithoutExtension(reference);
if (!assemblyNameToFilePathMap.TryGetValue(assemblyName, out string existing) ||
existing.Length > reference.Length ||
(existing.Length == reference.Length && string.Compare(existing, reference) < 0))
{
assemblyNameToFilePathMap[assemblyName] = reference;
}
}
public IEnumerable<CompilerInvocation> Invocations
{
get
{
return this.finalInvocations;
}
}
public static void AddMetadataAsSourceAssemblies(List<CompilerInvocation> invocations)
{
var indexedAssemblies = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var invocation in invocations)
{
indexedAssemblies.Add(invocation.AssemblyName);
}
var notIndexedAssemblies = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var binary in invocations.SelectMany(i => i.ReferencedBinaries))
{
var assemblyName = Path.GetFileNameWithoutExtension(binary);
if (!indexedAssemblies.Contains(assemblyName) && ShouldIncludeNotIndexedAssembly(binary))
{
if (!notIndexedAssemblies.TryGetValue(assemblyName, out string existing) ||
binary.Length < existing.Length ||
(binary.Length == existing.Length && binary.CompareTo(existing) > 0))
{
// make sure we always prefer the .dll that has shortest file path on disk
// Not only to disambiguate in a stable fashion, but also it's a good heuristic
// Shorter paths seem to be more widely used and are less obscure.
notIndexedAssemblies[assemblyName] = binary;
}
}
}
foreach (var notIndexedAssembly in notIndexedAssemblies)
{
var invocation = new CompilerInvocation()
{
AssemblyName = notIndexedAssembly.Key,
CommandLine = "-",
OutputAssemblyPath = notIndexedAssembly.Value,
ProjectFilePath = "-"
};
invocations.Add(invocation);
}
}
private static bool ShouldIncludeNotIndexedAssembly(string binary) => File.Exists(binary);
public static void AddNonExistingReference(
CompilerInvocation compilerInvocation,
string nonExistingReferenceFilePath)
{
lock (nonExistingReferencesToCompilerInvocationMap)
{
nonExistingReferencesToCompilerInvocationMap.Add(
nonExistingReferenceFilePath,
compilerInvocation);
}
}
}
}
| |
namespace VistaControlsApp
{
partial class NewMain
{
/// <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.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NewMain));
System.Windows.Forms.TreeNode treeNode1 = new System.Windows.Forms.TreeNode("Node1");
System.Windows.Forms.TreeNode treeNode2 = new System.Windows.Forms.TreeNode("Node2");
System.Windows.Forms.TreeNode treeNode3 = new System.Windows.Forms.TreeNode("Node0");
System.Windows.Forms.TreeNode treeNode4 = new System.Windows.Forms.TreeNode("Node16");
System.Windows.Forms.TreeNode treeNode5 = new System.Windows.Forms.TreeNode("Node17");
System.Windows.Forms.TreeNode treeNode6 = new System.Windows.Forms.TreeNode("Node14", new System.Windows.Forms.TreeNode[] {
treeNode4,
treeNode5});
System.Windows.Forms.TreeNode treeNode7 = new System.Windows.Forms.TreeNode("Node15");
System.Windows.Forms.TreeNode treeNode8 = new System.Windows.Forms.TreeNode("Node12", new System.Windows.Forms.TreeNode[] {
treeNode3,
treeNode6,
treeNode7});
System.Windows.Forms.TreeNode treeNode9 = new System.Windows.Forms.TreeNode("Node2", new System.Windows.Forms.TreeNode[] {
treeNode8});
System.Windows.Forms.TreeNode treeNode10 = new System.Windows.Forms.TreeNode("Node37");
System.Windows.Forms.TreeNode treeNode11 = new System.Windows.Forms.TreeNode("Node36", new System.Windows.Forms.TreeNode[] {
treeNode10});
System.Windows.Forms.TreeNode treeNode12 = new System.Windows.Forms.TreeNode("Node35", new System.Windows.Forms.TreeNode[] {
treeNode11});
System.Windows.Forms.TreeNode treeNode13 = new System.Windows.Forms.TreeNode("Node33", new System.Windows.Forms.TreeNode[] {
treeNode12});
System.Windows.Forms.TreeNode treeNode14 = new System.Windows.Forms.TreeNode("Node32", new System.Windows.Forms.TreeNode[] {
treeNode13});
System.Windows.Forms.TreeNode treeNode15 = new System.Windows.Forms.TreeNode("Node11", new System.Windows.Forms.TreeNode[] {
treeNode14});
System.Windows.Forms.TreeNode treeNode16 = new System.Windows.Forms.TreeNode("Node8", new System.Windows.Forms.TreeNode[] {
treeNode15});
System.Windows.Forms.TreeNode treeNode17 = new System.Windows.Forms.TreeNode("Node34");
System.Windows.Forms.TreeNode treeNode18 = new System.Windows.Forms.TreeNode("Node9", new System.Windows.Forms.TreeNode[] {
treeNode17});
System.Windows.Forms.TreeNode treeNode19 = new System.Windows.Forms.TreeNode("Node10");
System.Windows.Forms.TreeNode treeNode20 = new System.Windows.Forms.TreeNode("Node3", new System.Windows.Forms.TreeNode[] {
treeNode16,
treeNode18,
treeNode19});
System.Windows.Forms.TreeNode treeNode21 = new System.Windows.Forms.TreeNode("Node4");
System.Windows.Forms.TreeNode treeNode22 = new System.Windows.Forms.TreeNode("Node29");
System.Windows.Forms.TreeNode treeNode23 = new System.Windows.Forms.TreeNode("Node41");
System.Windows.Forms.TreeNode treeNode24 = new System.Windows.Forms.TreeNode("Node40", new System.Windows.Forms.TreeNode[] {
treeNode23});
System.Windows.Forms.TreeNode treeNode25 = new System.Windows.Forms.TreeNode("Node39", new System.Windows.Forms.TreeNode[] {
treeNode24});
System.Windows.Forms.TreeNode treeNode26 = new System.Windows.Forms.TreeNode("Node38", new System.Windows.Forms.TreeNode[] {
treeNode25});
System.Windows.Forms.TreeNode treeNode27 = new System.Windows.Forms.TreeNode("Node30", new System.Windows.Forms.TreeNode[] {
treeNode26});
System.Windows.Forms.TreeNode treeNode28 = new System.Windows.Forms.TreeNode("Node31");
System.Windows.Forms.TreeNode treeNode29 = new System.Windows.Forms.TreeNode("Node27", new System.Windows.Forms.TreeNode[] {
treeNode22,
treeNode27,
treeNode28});
System.Windows.Forms.TreeNode treeNode30 = new System.Windows.Forms.TreeNode("Node26", new System.Windows.Forms.TreeNode[] {
treeNode29});
System.Windows.Forms.TreeNode treeNode31 = new System.Windows.Forms.TreeNode("Node5", new System.Windows.Forms.TreeNode[] {
treeNode30});
System.Windows.Forms.TreeNode treeNode32 = new System.Windows.Forms.TreeNode("Node25");
System.Windows.Forms.TreeNode treeNode33 = new System.Windows.Forms.TreeNode("Node23", new System.Windows.Forms.TreeNode[] {
treeNode32});
System.Windows.Forms.TreeNode treeNode34 = new System.Windows.Forms.TreeNode("Node24");
System.Windows.Forms.TreeNode treeNode35 = new System.Windows.Forms.TreeNode("Node21", new System.Windows.Forms.TreeNode[] {
treeNode33,
treeNode34});
System.Windows.Forms.TreeNode treeNode36 = new System.Windows.Forms.TreeNode("Node22");
System.Windows.Forms.TreeNode treeNode37 = new System.Windows.Forms.TreeNode("Node28");
System.Windows.Forms.TreeNode treeNode38 = new System.Windows.Forms.TreeNode("Node18", new System.Windows.Forms.TreeNode[] {
treeNode35,
treeNode36,
treeNode37});
System.Windows.Forms.TreeNode treeNode39 = new System.Windows.Forms.TreeNode("Node19");
System.Windows.Forms.TreeNode treeNode40 = new System.Windows.Forms.TreeNode("Node20");
System.Windows.Forms.TreeNode treeNode41 = new System.Windows.Forms.TreeNode("Node6", new System.Windows.Forms.TreeNode[] {
treeNode38,
treeNode39,
treeNode40});
System.Windows.Forms.TreeNode treeNode42 = new System.Windows.Forms.TreeNode("Node7");
System.Windows.Forms.ListViewItem listViewItem1 = new System.Windows.Forms.ListViewItem("Item 1", 0);
System.Windows.Forms.ListViewItem listViewItem2 = new System.Windows.Forms.ListViewItem("Item 2", 4);
System.Windows.Forms.ListViewItem listViewItem3 = new System.Windows.Forms.ListViewItem("Item 3", 10);
System.Windows.Forms.ListViewItem listViewItem4 = new System.Windows.Forms.ListViewItem("Item 4", 2);
System.Windows.Forms.ListViewItem listViewItem5 = new System.Windows.Forms.ListViewItem("Item 5", 3);
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.themedLabel2 = new VistaControls.ThemeText.ThemedLabel();
this.themedLabel1 = new VistaControls.ThemeText.ThemedLabel();
this.searchTextBox1 = new VistaControls.SearchTextBox();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.button1 = new VistaControls.Button();
this.splitButton1 = new VistaControls.SplitButton();
this.contextMenu1 = new System.Windows.Forms.ContextMenu();
this.menuItem3 = new System.Windows.Forms.MenuItem();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.commandLink1 = new VistaControls.CommandLink();
this.commandLink2 = new VistaControls.CommandLink();
this.commandLink3 = new VistaControls.CommandLink();
this.commandLink4 = new VistaControls.CommandLink();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.flowLayoutPanel2 = new System.Windows.Forms.FlowLayoutPanel();
this.progressBar1 = new VistaControls.ProgressBar();
this.progressBar2 = new VistaControls.ProgressBar();
this.progressBar3 = new VistaControls.ProgressBar();
this.progressBar4 = new VistaControls.ProgressBar();
this.tabPage3 = new System.Windows.Forms.TabPage();
this.flowLayoutPanel4 = new System.Windows.Forms.FlowLayoutPanel();
this.button2 = new System.Windows.Forms.Button();
this.button11 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.button8 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.button5 = new System.Windows.Forms.Button();
this.button6 = new System.Windows.Forms.Button();
this.button7 = new System.Windows.Forms.Button();
this.button10 = new System.Windows.Forms.Button();
this.button9 = new System.Windows.Forms.Button();
this.tabPage4 = new System.Windows.Forms.TabPage();
this.flowLayoutPanel3 = new System.Windows.Forms.FlowLayoutPanel();
this.textBox1 = new VistaControls.TextBox();
this.textBox2 = new VistaControls.TextBox();
this.comboBox1 = new VistaControls.ComboBox();
this.searchTextBox2 = new VistaControls.SearchTextBox();
this.treeView1 = new VistaControls.TreeView();
this.listView1 = new VistaControls.ListView();
this.imageList2 = new System.Windows.Forms.ImageList(this.components);
this.tabPage5 = new System.Windows.Forms.TabPage();
this.thumbnailViewer1 = new VistaControls.Dwm.ThumbnailViewer();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
this.flowLayoutPanel1.SuspendLayout();
this.tabPage2.SuspendLayout();
this.flowLayoutPanel2.SuspendLayout();
this.tabPage3.SuspendLayout();
this.flowLayoutPanel4.SuspendLayout();
this.tabPage4.SuspendLayout();
this.flowLayoutPanel3.SuspendLayout();
this.tabPage5.SuspendLayout();
this.SuspendLayout();
//
// imageList1
//
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
this.imageList1.Images.SetKeyName(0, "audiosrv.dll_I00cb_0409.png");
this.imageList1.Images.SetKeyName(1, "ActiveContentWizard.ico");
this.imageList1.Images.SetKeyName(2, "feedback.ico");
this.imageList1.Images.SetKeyName(3, "imageres.15.ico");
this.imageList1.Images.SetKeyName(4, "imageres.13.ico");
this.imageList1.Images.SetKeyName(5, "accessibilitycpl.dll_I0146_0409.png");
this.imageList1.Images.SetKeyName(6, "bthprops.cpl_I0097_0409.png");
this.imageList1.Images.SetKeyName(7, "accessibilitycpl.dll_I0144_0409.png");
this.imageList1.Images.SetKeyName(8, "digitalx.exe_I0065_0409.png");
this.imageList1.Images.SetKeyName(9, "hdwwiz.exe_I05dd_0409.png");
this.imageList1.Images.SetKeyName(10, "setup_wm.exe_I0046_0409.png");
//
// themedLabel2
//
this.themedLabel2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.themedLabel2.Cursor = System.Windows.Forms.Cursors.Default;
this.themedLabel2.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.themedLabel2.Location = new System.Drawing.Point(268, 396);
this.themedLabel2.Name = "themedLabel2";
this.themedLabel2.Padding = new System.Windows.Forms.Padding(0, 0, 6, 6);
this.themedLabel2.Size = new System.Drawing.Size(331, 23);
this.themedLabel2.TabIndex = 26;
this.themedLabel2.Text = "Welcome!";
this.themedLabel2.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.themedLabel2.TextAlignVertical = System.Windows.Forms.VisualStyles.VerticalAlignment.Bottom;
//
// themedLabel1
//
this.themedLabel1.BackColor = System.Drawing.SystemColors.Control;
this.themedLabel1.Font = new System.Drawing.Font("Segoe UI", 20.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.themedLabel1.ForeColor = System.Drawing.SystemColors.ControlText;
this.themedLabel1.Location = new System.Drawing.Point(0, 0);
this.themedLabel1.Name = "themedLabel1";
this.themedLabel1.Padding = new System.Windows.Forms.Padding(8, 0, 0, 0);
this.themedLabel1.ShadowType = VistaControls.ThemeText.Options.ShadowOption.ShadowType.Single;
this.themedLabel1.Size = new System.Drawing.Size(365, 58);
this.themedLabel1.TabIndex = 25;
this.themedLabel1.Text = "Vista Controls for .NET 2.0";
this.themedLabel1.TextAlignVertical = System.Windows.Forms.VisualStyles.VerticalAlignment.Center;
//
// searchTextBox1
//
this.searchTextBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.searchTextBox1.BackColor = System.Drawing.SystemColors.InactiveBorder;
this.searchTextBox1.Cursor = System.Windows.Forms.Cursors.IBeam;
this.searchTextBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F);
this.searchTextBox1.ForeColor = System.Drawing.SystemColors.GrayText;
this.searchTextBox1.InactiveFont = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.searchTextBox1.InactiveText = "Search tabs...";
this.searchTextBox1.Location = new System.Drawing.Point(389, 62);
this.searchTextBox1.Name = "searchTextBox1";
this.searchTextBox1.SearchTimer = 600;
this.searchTextBox1.Size = new System.Drawing.Size(196, 20);
this.searchTextBox1.StartSearchOnEnter = true;
this.searchTextBox1.TabIndex = 1;
this.searchTextBox1.SearchStarted += new System.EventHandler(this.Search);
this.searchTextBox1.SearchCancelled += new System.EventHandler(this.Search_cancelled);
//
// tabControl1
//
this.tabControl1.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.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Controls.Add(this.tabPage3);
this.tabControl1.Controls.Add(this.tabPage4);
this.tabControl1.Controls.Add(this.tabPage5);
this.tabControl1.Location = new System.Drawing.Point(12, 66);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(575, 313);
this.tabControl1.TabIndex = 0;
//
// tabPage1
//
this.tabPage1.BackColor = System.Drawing.Color.Transparent;
this.tabPage1.Controls.Add(this.flowLayoutPanel1);
this.tabPage1.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tabPage1.ForeColor = System.Drawing.SystemColors.ControlText;
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.Size = new System.Drawing.Size(567, 287);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Buttons";
this.tabPage1.UseVisualStyleBackColor = true;
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.Controls.Add(this.button1);
this.flowLayoutPanel1.Controls.Add(this.splitButton1);
this.flowLayoutPanel1.Controls.Add(this.commandLink1);
this.flowLayoutPanel1.Controls.Add(this.commandLink2);
this.flowLayoutPanel1.Controls.Add(this.commandLink3);
this.flowLayoutPanel1.Controls.Add(this.commandLink4);
this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.flowLayoutPanel1.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.flowLayoutPanel1.Location = new System.Drawing.Point(3, 3);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Size = new System.Drawing.Size(561, 281);
this.flowLayoutPanel1.TabIndex = 0;
//
// button1
//
this.button1.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.button1.Location = new System.Drawing.Point(3, 3);
this.button1.Name = "button1";
this.button1.ShowShield = true;
this.button1.Size = new System.Drawing.Size(122, 23);
this.button1.TabIndex = 0;
this.button1.Text = "Shield Button";
this.button1.UseVisualStyleBackColor = true;
//
// splitButton1
//
this.splitButton1.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.splitButton1.Location = new System.Drawing.Point(3, 32);
this.splitButton1.Name = "splitButton1";
this.splitButton1.Size = new System.Drawing.Size(122, 23);
this.splitButton1.SplitMenu = this.contextMenu1;
this.splitButton1.TabIndex = 1;
this.splitButton1.Text = "Split";
this.splitButton1.UseVisualStyleBackColor = true;
//
// contextMenu1
//
this.contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem3,
this.menuItem1,
this.menuItem2});
//
// menuItem3
//
this.menuItem3.Index = 0;
this.menuItem3.Text = "Automatic";
//
// menuItem1
//
this.menuItem1.Index = 1;
this.menuItem1.Text = "Context";
//
// menuItem2
//
this.menuItem2.Index = 2;
this.menuItem2.Text = "Menu";
//
// commandLink1
//
this.commandLink1.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.commandLink1.Location = new System.Drawing.Point(3, 61);
this.commandLink1.Name = "commandLink1";
this.commandLink1.Note = "Note.";
this.commandLink1.Size = new System.Drawing.Size(207, 60);
this.commandLink1.TabIndex = 2;
this.commandLink1.Text = "Command Link";
this.commandLink1.UseVisualStyleBackColor = true;
this.commandLink1.Click += new System.EventHandler(this.commandLink1_Click);
//
// commandLink2
//
this.commandLink2.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.commandLink2.Location = new System.Drawing.Point(3, 127);
this.commandLink2.Name = "commandLink2";
this.commandLink2.Note = "Note 2.";
this.commandLink2.ShowShield = true;
this.commandLink2.Size = new System.Drawing.Size(207, 60);
this.commandLink2.TabIndex = 3;
this.commandLink2.Text = "Shield";
this.commandLink2.UseVisualStyleBackColor = true;
//
// commandLink3
//
this.commandLink3.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.commandLink3.Location = new System.Drawing.Point(3, 193);
this.commandLink3.Name = "commandLink3";
this.commandLink3.Size = new System.Drawing.Size(234, 62);
this.commandLink3.TabIndex = 4;
this.commandLink3.Text = "Show Test Vertical Panel";
this.commandLink3.UseVisualStyleBackColor = true;
this.commandLink3.Click += new System.EventHandler(this.commandLink3_Click);
//
// commandLink4
//
this.commandLink4.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.commandLink4.Location = new System.Drawing.Point(243, 3);
this.commandLink4.Name = "commandLink4";
this.commandLink4.Size = new System.Drawing.Size(261, 61);
this.commandLink4.TabIndex = 5;
this.commandLink4.Text = "Show Test Horizontal Panel";
this.commandLink4.UseVisualStyleBackColor = true;
this.commandLink4.Click += new System.EventHandler(this.commandLink4_Click);
//
// tabPage2
//
this.tabPage2.Controls.Add(this.flowLayoutPanel2);
this.tabPage2.Location = new System.Drawing.Point(4, 22);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
this.tabPage2.Size = new System.Drawing.Size(567, 287);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "Progress bars";
this.tabPage2.UseVisualStyleBackColor = true;
//
// flowLayoutPanel2
//
this.flowLayoutPanel2.Controls.Add(this.progressBar1);
this.flowLayoutPanel2.Controls.Add(this.progressBar2);
this.flowLayoutPanel2.Controls.Add(this.progressBar3);
this.flowLayoutPanel2.Controls.Add(this.progressBar4);
this.flowLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill;
this.flowLayoutPanel2.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.flowLayoutPanel2.Location = new System.Drawing.Point(3, 3);
this.flowLayoutPanel2.Name = "flowLayoutPanel2";
this.flowLayoutPanel2.Size = new System.Drawing.Size(561, 281);
this.flowLayoutPanel2.TabIndex = 0;
//
// progressBar1
//
this.progressBar1.Location = new System.Drawing.Point(3, 3);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(355, 23);
this.progressBar1.TabIndex = 0;
this.progressBar1.Value = 35;
//
// progressBar2
//
this.progressBar2.Location = new System.Drawing.Point(3, 32);
this.progressBar2.Name = "progressBar2";
this.progressBar2.ProgressState = VistaControls.ProgressBar.States.Paused;
this.progressBar2.Size = new System.Drawing.Size(355, 23);
this.progressBar2.TabIndex = 1;
this.progressBar2.Value = 50;
//
// progressBar3
//
this.progressBar3.Location = new System.Drawing.Point(3, 61);
this.progressBar3.Name = "progressBar3";
this.progressBar3.ProgressState = VistaControls.ProgressBar.States.Error;
this.progressBar3.Size = new System.Drawing.Size(355, 23);
this.progressBar3.TabIndex = 2;
this.progressBar3.Value = 75;
//
// progressBar4
//
this.progressBar4.Location = new System.Drawing.Point(3, 90);
this.progressBar4.Name = "progressBar4";
this.progressBar4.Size = new System.Drawing.Size(355, 23);
this.progressBar4.Style = System.Windows.Forms.ProgressBarStyle.Marquee;
this.progressBar4.TabIndex = 3;
//
// tabPage3
//
this.tabPage3.Controls.Add(this.flowLayoutPanel4);
this.tabPage3.Location = new System.Drawing.Point(4, 22);
this.tabPage3.Name = "tabPage3";
this.tabPage3.Size = new System.Drawing.Size(567, 287);
this.tabPage3.TabIndex = 2;
this.tabPage3.Text = "Task Dialogs";
this.tabPage3.UseVisualStyleBackColor = true;
//
// flowLayoutPanel4
//
this.flowLayoutPanel4.Controls.Add(this.button2);
this.flowLayoutPanel4.Controls.Add(this.button11);
this.flowLayoutPanel4.Controls.Add(this.button3);
this.flowLayoutPanel4.Controls.Add(this.button8);
this.flowLayoutPanel4.Controls.Add(this.button4);
this.flowLayoutPanel4.Controls.Add(this.button5);
this.flowLayoutPanel4.Controls.Add(this.button6);
this.flowLayoutPanel4.Controls.Add(this.button7);
this.flowLayoutPanel4.Controls.Add(this.button10);
this.flowLayoutPanel4.Controls.Add(this.button9);
this.flowLayoutPanel4.Dock = System.Windows.Forms.DockStyle.Fill;
this.flowLayoutPanel4.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.flowLayoutPanel4.Location = new System.Drawing.Point(0, 0);
this.flowLayoutPanel4.Name = "flowLayoutPanel4";
this.flowLayoutPanel4.Size = new System.Drawing.Size(567, 287);
this.flowLayoutPanel4.TabIndex = 0;
//
// button2
//
this.button2.Location = new System.Drawing.Point(3, 3);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(112, 23);
this.button2.TabIndex = 0;
this.button2.Text = "Information";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.td_info);
//
// button11
//
this.button11.Location = new System.Drawing.Point(3, 32);
this.button11.Name = "button11";
this.button11.Size = new System.Drawing.Size(112, 23);
this.button11.TabIndex = 1;
this.button11.Text = "Warning";
this.button11.UseVisualStyleBackColor = true;
this.button11.Click += new System.EventHandler(this.ts_warning);
//
// button3
//
this.button3.Location = new System.Drawing.Point(3, 61);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(112, 23);
this.button3.TabIndex = 2;
this.button3.Text = "Error";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.td_error);
//
// button8
//
this.button8.Location = new System.Drawing.Point(3, 90);
this.button8.Name = "button8";
this.button8.Size = new System.Drawing.Size(112, 23);
this.button8.TabIndex = 3;
this.button8.Text = "Shield";
this.button8.UseVisualStyleBackColor = true;
this.button8.Click += new System.EventHandler(this.td_shield);
//
// button4
//
this.button4.Location = new System.Drawing.Point(3, 119);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(112, 23);
this.button4.TabIndex = 4;
this.button4.Text = "Security Error";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.td_shielderror);
//
// button5
//
this.button5.Location = new System.Drawing.Point(3, 148);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(112, 23);
this.button5.TabIndex = 5;
this.button5.Text = "Security Success";
this.button5.UseVisualStyleBackColor = true;
this.button5.Click += new System.EventHandler(this.td_shieldsuccess);
//
// button6
//
this.button6.Location = new System.Drawing.Point(3, 177);
this.button6.Name = "button6";
this.button6.Size = new System.Drawing.Size(112, 23);
this.button6.TabIndex = 6;
this.button6.Text = "Blue shield";
this.button6.UseVisualStyleBackColor = true;
this.button6.Click += new System.EventHandler(this.td_blueshield);
//
// button7
//
this.button7.Location = new System.Drawing.Point(3, 206);
this.button7.Name = "button7";
this.button7.Size = new System.Drawing.Size(112, 23);
this.button7.TabIndex = 7;
this.button7.Text = "Gray shield";
this.button7.UseVisualStyleBackColor = true;
this.button7.Click += new System.EventHandler(this.td_grayshield);
//
// button10
//
this.button10.Location = new System.Drawing.Point(121, 3);
this.button10.Name = "button10";
this.button10.Size = new System.Drawing.Size(112, 52);
this.button10.TabIndex = 8;
this.button10.Text = "Complex dialog";
this.button10.UseVisualStyleBackColor = true;
this.button10.Click += new System.EventHandler(this.td_complex);
//
// button9
//
this.button9.Location = new System.Drawing.Point(121, 61);
this.button9.Name = "button9";
this.button9.Size = new System.Drawing.Size(112, 52);
this.button9.TabIndex = 9;
this.button9.Text = "Progress bar dialog";
this.button9.UseVisualStyleBackColor = true;
this.button9.Click += new System.EventHandler(this.td_progress);
//
// tabPage4
//
this.tabPage4.Controls.Add(this.flowLayoutPanel3);
this.tabPage4.Location = new System.Drawing.Point(4, 22);
this.tabPage4.Name = "tabPage4";
this.tabPage4.Padding = new System.Windows.Forms.Padding(3);
this.tabPage4.Size = new System.Drawing.Size(567, 287);
this.tabPage4.TabIndex = 3;
this.tabPage4.Text = "Data controls";
this.tabPage4.UseVisualStyleBackColor = true;
//
// flowLayoutPanel3
//
this.flowLayoutPanel3.AutoScroll = true;
this.flowLayoutPanel3.Controls.Add(this.textBox1);
this.flowLayoutPanel3.Controls.Add(this.textBox2);
this.flowLayoutPanel3.Controls.Add(this.comboBox1);
this.flowLayoutPanel3.Controls.Add(this.searchTextBox2);
this.flowLayoutPanel3.Controls.Add(this.treeView1);
this.flowLayoutPanel3.Controls.Add(this.listView1);
this.flowLayoutPanel3.Dock = System.Windows.Forms.DockStyle.Fill;
this.flowLayoutPanel3.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.flowLayoutPanel3.Location = new System.Drawing.Point(3, 3);
this.flowLayoutPanel3.Name = "flowLayoutPanel3";
this.flowLayoutPanel3.Size = new System.Drawing.Size(561, 281);
this.flowLayoutPanel3.TabIndex = 0;
//
// textBox1
//
this.textBox1.CueBannerText = "Cue banner";
this.textBox1.Location = new System.Drawing.Point(3, 3);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(196, 22);
this.textBox1.TabIndex = 0;
//
// textBox2
//
this.textBox2.CueBannerText = "Cue banner (w/focus)";
this.textBox2.Location = new System.Drawing.Point(3, 29);
this.textBox2.Name = "textBox2";
this.textBox2.ShowCueFocused = true;
this.textBox2.Size = new System.Drawing.Size(196, 22);
this.textBox2.TabIndex = 1;
//
// comboBox1
//
this.comboBox1.CueBannerText = "Cue banner";
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Items.AddRange(new object[] {
"1",
"2",
"3",
"4",
"5"});
this.comboBox1.Location = new System.Drawing.Point(3, 55);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(196, 21);
this.comboBox1.TabIndex = 2;
//
// searchTextBox2
//
this.searchTextBox2.ActiveFont = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.searchTextBox2.BackColor = System.Drawing.SystemColors.InactiveBorder;
this.searchTextBox2.Cursor = System.Windows.Forms.Cursors.IBeam;
this.searchTextBox2.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.searchTextBox2.ForeColor = System.Drawing.SystemColors.GrayText;
this.searchTextBox2.Location = new System.Drawing.Point(3, 82);
this.searchTextBox2.Name = "searchTextBox2";
this.searchTextBox2.Size = new System.Drawing.Size(196, 20);
this.searchTextBox2.TabIndex = 3;
//
// treeView1
//
this.treeView1.HotTracking = true;
this.treeView1.ImageIndex = 0;
this.treeView1.ImageList = this.imageList1;
this.treeView1.Location = new System.Drawing.Point(205, 3);
this.treeView1.Name = "treeView1";
treeNode1.ImageIndex = 10;
treeNode1.Name = "Node1";
treeNode1.Text = "Node1";
treeNode2.ImageIndex = 1;
treeNode2.Name = "Node2";
treeNode2.Text = "Node2";
treeNode3.Name = "Node0";
treeNode3.Text = "Node0";
treeNode4.Name = "Node16";
treeNode4.Text = "Node16";
treeNode5.Name = "Node17";
treeNode5.Text = "Node17";
treeNode6.Name = "Node14";
treeNode6.Text = "Node14";
treeNode7.Name = "Node15";
treeNode7.Text = "Node15";
treeNode8.Name = "Node12";
treeNode8.Text = "Node12";
treeNode9.ImageIndex = 3;
treeNode9.Name = "Node2";
treeNode9.Text = "Node2";
treeNode10.Name = "Node37";
treeNode10.Text = "Node37";
treeNode11.ImageIndex = 8;
treeNode11.Name = "Node36";
treeNode11.Text = "Node36";
treeNode12.ImageIndex = 10;
treeNode12.Name = "Node35";
treeNode12.Text = "Node35";
treeNode13.ImageIndex = 4;
treeNode13.Name = "Node33";
treeNode13.Text = "Node33";
treeNode14.ImageIndex = 6;
treeNode14.Name = "Node32";
treeNode14.Text = "Node32";
treeNode15.ImageIndex = 4;
treeNode15.Name = "Node11";
treeNode15.Text = "Node11";
treeNode16.Name = "Node8";
treeNode16.Text = "Node8";
treeNode17.Name = "Node34";
treeNode17.Text = "Node34";
treeNode18.ImageIndex = 9;
treeNode18.Name = "Node9";
treeNode18.Text = "Node9";
treeNode19.Name = "Node10";
treeNode19.Text = "Node10";
treeNode20.ImageIndex = 5;
treeNode20.Name = "Node3";
treeNode20.Text = "Node3";
treeNode21.ImageIndex = 2;
treeNode21.Name = "Node4";
treeNode21.Text = "Node4";
treeNode22.ImageIndex = 1;
treeNode22.Name = "Node29";
treeNode22.Text = "Node29";
treeNode23.Name = "Node41";
treeNode23.Text = "Node41";
treeNode24.ImageIndex = 5;
treeNode24.Name = "Node40";
treeNode24.Text = "Node40";
treeNode25.ImageIndex = 6;
treeNode25.Name = "Node39";
treeNode25.Text = "Node39";
treeNode26.ImageIndex = 10;
treeNode26.Name = "Node38";
treeNode26.Text = "Node38";
treeNode27.ImageIndex = 9;
treeNode27.Name = "Node30";
treeNode27.Text = "Node30";
treeNode28.Name = "Node31";
treeNode28.Text = "Node31";
treeNode29.ImageIndex = 7;
treeNode29.Name = "Node27";
treeNode29.Text = "Node27";
treeNode30.Name = "Node26";
treeNode30.Text = "Node26";
treeNode31.ImageIndex = 3;
treeNode31.Name = "Node5";
treeNode31.Text = "Node5";
treeNode32.ImageIndex = 5;
treeNode32.Name = "Node25";
treeNode32.Text = "Node25";
treeNode33.ImageIndex = 4;
treeNode33.Name = "Node23";
treeNode33.Text = "Node23";
treeNode34.Name = "Node24";
treeNode34.Text = "Node24";
treeNode35.ImageIndex = 1;
treeNode35.Name = "Node21";
treeNode35.Text = "Node21";
treeNode36.ImageIndex = 2;
treeNode36.Name = "Node22";
treeNode36.Text = "Node22";
treeNode37.ImageIndex = 7;
treeNode37.Name = "Node28";
treeNode37.Text = "Node28";
treeNode38.Name = "Node18";
treeNode38.Text = "Node18";
treeNode39.Name = "Node19";
treeNode39.Text = "Node19";
treeNode40.ImageIndex = 10;
treeNode40.Name = "Node20";
treeNode40.Text = "Node20";
treeNode41.ImageIndex = 3;
treeNode41.Name = "Node6";
treeNode41.Text = "Node6";
treeNode42.Name = "Node7";
treeNode42.Text = "Node7";
this.treeView1.Nodes.AddRange(new System.Windows.Forms.TreeNode[] {
treeNode1,
treeNode2,
treeNode9,
treeNode20,
treeNode21,
treeNode31,
treeNode41,
treeNode42});
this.treeView1.SelectedImageIndex = 0;
this.treeView1.ShowLines = false;
this.treeView1.Size = new System.Drawing.Size(122, 240);
this.treeView1.TabIndex = 4;
//
// listView1
//
this.listView1.Items.AddRange(new System.Windows.Forms.ListViewItem[] {
listViewItem1,
listViewItem2,
listViewItem3,
listViewItem4,
listViewItem5});
this.listView1.LargeImageList = this.imageList2;
this.listView1.Location = new System.Drawing.Point(333, 3);
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(255, 199);
this.listView1.SmallImageList = this.imageList1;
this.listView1.TabIndex = 5;
this.listView1.UseCompatibleStateImageBehavior = false;
//
// imageList2
//
this.imageList2.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList2.ImageStream")));
this.imageList2.TransparentColor = System.Drawing.Color.Transparent;
this.imageList2.Images.SetKeyName(0, "audiosrv.dll_I00cb_0409.png");
this.imageList2.Images.SetKeyName(1, "ActiveContentWizard.ico");
this.imageList2.Images.SetKeyName(2, "feedback.ico");
this.imageList2.Images.SetKeyName(3, "imageres.15.ico");
this.imageList2.Images.SetKeyName(4, "imageres.13.ico");
this.imageList2.Images.SetKeyName(5, "accessibilitycpl.dll_I0146_0409.png");
this.imageList2.Images.SetKeyName(6, "bthprops.cpl_I0097_0409.png");
this.imageList2.Images.SetKeyName(7, "accessibilitycpl.dll_I0144_0409.png");
this.imageList2.Images.SetKeyName(8, "digitalx.exe_I0065_0409.png");
this.imageList2.Images.SetKeyName(9, "hdwwiz.exe_I05dd_0409.png");
this.imageList2.Images.SetKeyName(10, "setup_wm.exe_I0046_0409.png");
//
// tabPage5
//
this.tabPage5.Controls.Add(this.thumbnailViewer1);
this.tabPage5.Location = new System.Drawing.Point(4, 22);
this.tabPage5.Name = "tabPage5";
this.tabPage5.Padding = new System.Windows.Forms.Padding(3);
this.tabPage5.Size = new System.Drawing.Size(567, 287);
this.tabPage5.TabIndex = 4;
this.tabPage5.Text = "DWM";
this.tabPage5.UseVisualStyleBackColor = true;
//
// thumbnailViewer1
//
this.thumbnailViewer1.Location = new System.Drawing.Point(6, 6);
this.thumbnailViewer1.Name = "thumbnailViewer1";
this.thumbnailViewer1.ScaleSmallerThumbnails = false;
this.thumbnailViewer1.Size = new System.Drawing.Size(168, 168);
this.thumbnailViewer1.TabIndex = 0;
this.thumbnailViewer1.Text = "thumbnailViewer1";
this.thumbnailViewer1.ThumbnailAlignment = System.Drawing.ContentAlignment.MiddleCenter;
//
// NewMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(599, 419);
this.Controls.Add(this.searchTextBox1);
this.Controls.Add(this.tabControl1);
this.Controls.Add(this.themedLabel2);
this.Controls.Add(this.themedLabel1);
this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.HideTitle = true;
this.Margin = new System.Windows.Forms.Padding(2);
this.MaximizeBox = false;
this.MinimumSize = new System.Drawing.Size(590, 455);
this.Name = "NewMain";
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.Text = "Vista Controls";
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.flowLayoutPanel1.ResumeLayout(false);
this.tabPage2.ResumeLayout(false);
this.flowLayoutPanel2.ResumeLayout(false);
this.tabPage3.ResumeLayout(false);
this.flowLayoutPanel4.ResumeLayout(false);
this.tabPage4.ResumeLayout(false);
this.flowLayoutPanel3.ResumeLayout(false);
this.flowLayoutPanel3.PerformLayout();
this.tabPage5.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ImageList imageList1;
private VistaControls.ThemeText.ThemedLabel themedLabel1;
private VistaControls.ThemeText.ThemedLabel themedLabel2;
private VistaControls.SearchTextBox searchTextBox1;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.TabPage tabPage3;
private System.Windows.Forms.ContextMenu contextMenu1;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuItem2;
private System.Windows.Forms.MenuItem menuItem3;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel2;
private VistaControls.ProgressBar progressBar1;
private VistaControls.ProgressBar progressBar2;
private VistaControls.ProgressBar progressBar3;
private VistaControls.ProgressBar progressBar4;
private System.Windows.Forms.TabPage tabPage4;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel3;
private VistaControls.TextBox textBox1;
private VistaControls.ComboBox comboBox1;
private VistaControls.SearchTextBox searchTextBox2;
private VistaControls.TreeView treeView1;
private VistaControls.ListView listView1;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel4;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button11;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button8;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.Button button5;
private System.Windows.Forms.Button button6;
private System.Windows.Forms.Button button7;
private System.Windows.Forms.Button button10;
private System.Windows.Forms.Button button9;
private System.Windows.Forms.TabPage tabPage5;
private VistaControls.TextBox textBox2;
private System.Windows.Forms.ImageList imageList2;
private VistaControls.Dwm.ThumbnailViewer thumbnailViewer1;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private VistaControls.Button button1;
private VistaControls.SplitButton splitButton1;
private VistaControls.CommandLink commandLink1;
private VistaControls.CommandLink commandLink2;
private VistaControls.CommandLink commandLink3;
private VistaControls.CommandLink commandLink4;
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.IO;
using SharpDX.Direct3D11;
using SharpDX.IO;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// A Texture 2D front end to <see cref="SharpDX.Direct3D11.Texture2D"/>.
/// </summary>
public class Texture2D : Texture2DBase
{
internal Texture2D(GraphicsDevice device, Texture2DDescription description2D, params DataBox[] dataBoxes) : base(device, description2D, dataBoxes)
{
Initialize(Resource);
}
internal Texture2D(GraphicsDevice device, Direct3D11.Texture2D texture) : base(device, texture)
{
Initialize(Resource);
}
internal override TextureView GetRenderTargetView(ViewType viewType, int arrayOrDepthSlice, int mipMapSlice)
{
throw new System.NotSupportedException();
}
/// <summary>
/// Makes a copy of this texture.
/// </summary>
/// <remarks>
/// This method doesn't copy the content of the texture.
/// </remarks>
/// <returns>
/// A copy of this texture.
/// </returns>
public override Texture Clone()
{
return new Texture2D(GraphicsDevice, this.Description);
}
/// <summary>
/// Creates a new texture from a <see cref="Texture2DDescription"/>.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="description">The description.</param>
/// <returns>
/// A new instance of <see cref="Texture2D"/> class.
/// </returns>
/// <msdn-id>ff476521</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short>
public static Texture2D New(GraphicsDevice device, Texture2DDescription description)
{
return new Texture2D(device, description);
}
/// <summary>
/// Creates a new texture from a <see cref="Direct3D11.Texture2D"/>.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="texture">The native texture <see cref="Direct3D11.Texture2D"/>.</param>
/// <returns>
/// A new instance of <see cref="Texture2D"/> class.
/// </returns>
/// <msdn-id>ff476521</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short>
public static Texture2D New(GraphicsDevice device, Direct3D11.Texture2D texture)
{
return new Texture2D(device, texture);
}
/// <summary>
/// Creates a new <see cref="Texture2D" /> with a single mipmap.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="format">Describes the format to use.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="arraySize">Size of the texture 2D array, default to 1.</param>
/// <param name="usage">The usage.</param>
/// <returns>A new instance of <see cref="Texture2D" /> class.</returns>
/// <msdn-id>ff476521</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short>
public static Texture2D New(GraphicsDevice device, int width, int height, PixelFormat format, TextureFlags flags = TextureFlags.ShaderResource, int arraySize = 1, ResourceUsage usage = ResourceUsage.Default)
{
return New(device, width, height, false, format, flags, arraySize, usage);
}
/// <summary>
/// Creates a new <see cref="Texture2D" />.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="format">Describes the format to use.</param>
/// <param name="mipCount">Number of mipmaps, set to true to have all mipmaps, set to an int >=1 for a particular mipmap count.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="arraySize">Size of the texture 2D array, default to 1.</param>
/// <param name="usage">The usage.</param>
/// <returns>A new instance of <see cref="Texture2D" /> class.</returns>
/// <msdn-id>ff476521</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short>
public static Texture2D New(GraphicsDevice device, int width, int height, MipMapCount mipCount, PixelFormat format, TextureFlags flags = TextureFlags.ShaderResource, int arraySize = 1, ResourceUsage usage = ResourceUsage.Default)
{
return new Texture2D(device, NewDescription(width, height, format, flags, mipCount, arraySize, usage));
}
/// <summary>
/// Creates a new <see cref="Texture2D" /> with a single level of mipmap.
/// </summary>
/// <typeparam name="T">Type of the pixel data to upload to the texture.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="format">Describes the format to use.</param>
/// <param name="usage">The usage.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="textureData">The texture data for a single mipmap and a single array slice. See remarks</param>
/// <returns>A new instance of <see cref="Texture2D" /> class.</returns>
/// <msdn-id>ff476521</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short>
/// <remarks>
/// Each value in textureData is a pixel in the destination texture.
/// </remarks>
public unsafe static Texture2D New<T>(GraphicsDevice device, int width, int height, PixelFormat format, T[] textureData, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) where T : struct
{
Texture2D tex = null;
Utilities.Pin(textureData, ptr =>
{
tex = New(device, width, height, 1, format, new[] { GetDataBox(format, width, height, 1, textureData, ptr) }, flags, 1, usage);
});
return tex;
}
/// <summary>
/// Creates a new <see cref="Texture2D" />.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="format">Describes the format to use.</param>
/// <param name="mipCount">Number of mipmaps, set to true to have all mipmaps, set to an int >=1 for a particular mipmap count.</param>
/// <param name="textureData">Texture data through an array of <see cref="DataBox"/> </param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="arraySize">Size of the texture 2D array, default to 1.</param>
/// <param name="usage">The usage.</param>
/// <returns>A new instance of <see cref="Texture2D" /> class.</returns>
/// <msdn-id>ff476521</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short>
public static Texture2D New(GraphicsDevice device, int width, int height, MipMapCount mipCount, PixelFormat format, DataBox[] textureData, TextureFlags flags = TextureFlags.ShaderResource, int arraySize = 1, ResourceUsage usage = ResourceUsage.Default)
{
return new Texture2D(device, NewDescription(width, height, format, flags, mipCount, arraySize, usage), textureData);
}
/// <summary>
/// Creates a new <see cref="Texture2D" /> directly from an <see cref="Image"/>.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="image">An image in CPU memory.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="usage">The usage.</param>
/// <returns>A new instance of <see cref="Texture2D" /> class.</returns>
/// <msdn-id>ff476521</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short>
public static Texture2D New(GraphicsDevice device, Image image, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable)
{
if (image == null) throw new ArgumentNullException("image");
if (image.Description.Dimension != TextureDimension.Texture2D)
throw new ArgumentException("Invalid image. Must be 2D", "image");
return new Texture2D(device, CreateTextureDescriptionFromImage(image, flags, usage), image.ToDataBox());
}
/// <summary>
/// Loads a 2D texture from a stream.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="stream">The stream to load the texture from.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="usage">Usage of the resource. Default is <see cref="ResourceUsage.Immutable"/> </param>
/// <exception cref="ArgumentException">If the texture is not of type 2D</exception>
/// <returns>A texture</returns>
public static new Texture2D Load(GraphicsDevice device, Stream stream, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable)
{
var texture = Texture.Load(device, stream, flags, usage);
if (!(texture is Texture2D))
throw new ArgumentException(string.Format("Texture is not type of [Texture2D] but [{0}]", texture.GetType().Name));
return (Texture2D)texture;
}
/// <summary>
/// Loads a 2D texture from a stream.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="filePath">The file to load the texture from.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="usage">Usage of the resource. Default is <see cref="ResourceUsage.Immutable"/> </param>
/// <exception cref="ArgumentException">If the texture is not of type 2D</exception>
/// <returns>A texture</returns>
public static new Texture2D Load(GraphicsDevice device, string filePath, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable)
{
using (var stream = new NativeFileStream(filePath, NativeFileMode.Open, NativeFileAccess.Read))
return Load(device, stream, flags, usage);
}
/// <summary>
/// Implicit casting operator to <see cref="Direct3D11.Resource"/>
/// </summary>
/// <param name="from">The GraphicsResource to convert from.</param>
public static implicit operator Resource(Texture2D from)
{
return from == null ? null : (Resource)from.Resource;
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Management.Automation;
using Microsoft.Azure.Commands.RecoveryServices.SiteRecovery.Properties;
using Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models;
using Job = Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models.Job;
namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery
{
/// <summary>
/// Set Protection Entity protection state.
/// </summary>
[Cmdlet(
VerbsCommon.New,
"AzureRmRecoveryServicesAsrReplicationProtectedItem",
DefaultParameterSetName = ASRParameterSets.DisableDR,
SupportsShouldProcess = true)]
[Alias("New-ASRReplicationProtectedItem")]
[OutputType(typeof(ASRJob))]
public class NewAzureRmRecoveryServicesAsrReplicationProtectedItem : SiteRecoveryCmdletBase
{
private Job jobResponse;
/// <summary>
/// Job response.
/// </summary>
private PSSiteRecoveryLongRunningOperation response;
/// <summary>
/// Gets or sets Replication Protected Item.
/// </summary>
[Parameter(
ParameterSetName = ASRParameterSets.EnterpriseToEnterprise,
Mandatory = true,
ValueFromPipeline = true)]
[Parameter(
ParameterSetName = ASRParameterSets.EnterpriseToAzure,
Mandatory = true,
ValueFromPipeline = true)]
[Parameter(
ParameterSetName = ASRParameterSets.HyperVSiteToAzure,
Mandatory = true,
ValueFromPipeline = true)]
[ValidateNotNullOrEmpty]
public ASRProtectableItem ProtectableItem { get; set; }
/// <summary>
/// Gets or sets Replication Protected Item Name.
/// </summary>
[Parameter(
ParameterSetName = ASRParameterSets.EnterpriseToEnterprise,
Mandatory = true)]
[Parameter(
ParameterSetName = ASRParameterSets.EnterpriseToAzure,
Mandatory = true)]
[Parameter(
ParameterSetName = ASRParameterSets.HyperVSiteToAzure,
Mandatory = true)]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
/// <summary>
/// Gets or sets Policy.
/// </summary>
[Parameter(
ParameterSetName = ASRParameterSets.EnterpriseToEnterprise,
Mandatory = true)]
[Parameter(
ParameterSetName = ASRParameterSets.EnterpriseToAzure,
Mandatory = true)]
[Parameter(
ParameterSetName = ASRParameterSets.HyperVSiteToAzure,
Mandatory = true)]
[ValidateNotNullOrEmpty]
public ASRProtectionContainerMapping ProtectionContainerMapping { get; set; }
/// <summary>
/// Gets or sets Recovery Azure Storage Account Name of the Policy for E2A and B2A scenarios.
/// </summary>
[Parameter(
ParameterSetName = ASRParameterSets.EnterpriseToAzure,
Mandatory = true)]
[Parameter(
ParameterSetName = ASRParameterSets.HyperVSiteToAzure,
Mandatory = true)]
[ValidateNotNullOrEmpty]
public string RecoveryAzureStorageAccountId { get; set; }
/// <summary>
/// Gets or sets OS disk name.
/// </summary>
[Parameter(
ParameterSetName = ASRParameterSets.HyperVSiteToAzure,
Mandatory = true)]
[ValidateNotNullOrEmpty]
public string OSDiskName { get; set; }
/// <summary>
/// Gets or sets OS Type
/// </summary>
[Parameter(
ParameterSetName = ASRParameterSets.HyperVSiteToAzure,
Mandatory = true)]
[ValidateNotNullOrEmpty]
[ValidateSet(
Constants.OSWindows,
Constants.OSLinux)]
public string OS { get; set; }
/// <summary>
/// Gets or sets Recovery Resource Group Id.
/// </summary>
[Parameter(
ParameterSetName = ASRParameterSets.EnterpriseToAzure,
Mandatory = true)]
[Parameter(
ParameterSetName = ASRParameterSets.HyperVSiteToAzure,
Mandatory = true)]
[ValidateNotNullOrEmpty]
public string RecoveryResourceGroupId { get; set; }
/// <summary>
/// Gets or sets switch parameter. On passing, command waits till completion.
/// </summary>
[Parameter]
public SwitchParameter WaitForCompletion { get; set; }
/// <summary>
/// ProcessRecord of the command.
/// </summary>
public override void ExecuteSiteRecoveryCmdlet()
{
base.ExecuteSiteRecoveryCmdlet();
if (this.ShouldProcess(
this.Name,
VerbsCommon.New))
{
var policy = this.RecoveryServicesClient.GetAzureSiteRecoveryPolicy(
Utilities.GetValueFromArmId(
this.ProtectionContainerMapping.PolicyId,
ARMResourceTypeConstants.ReplicationPolicies));
var policyInstanceType = policy.Properties.ProviderSpecificDetails;
switch (this.ParameterSetName)
{
case ASRParameterSets.EnterpriseToEnterprise:
if (!(policyInstanceType is HyperVReplicaPolicyDetails) &&
!(policyInstanceType is HyperVReplicaBluePolicyDetails))
{
throw new PSArgumentException(
string.Format(
Resources.ContainerMappingParameterSetMismatch,
this.ProtectionContainerMapping.Name,
policyInstanceType));
}
break;
case ASRParameterSets.EnterpriseToAzure:
case ASRParameterSets.HyperVSiteToAzure:
if (!(policyInstanceType is HyperVReplicaAzurePolicyDetails))
{
throw new PSArgumentException(
string.Format(
Resources.ContainerMappingParameterSetMismatch,
this.ProtectionContainerMapping.Name,
policyInstanceType));
}
break;
default:
break;
}
var enableProtectionProviderSpecificInput =
new EnableProtectionProviderSpecificInput();
var inputProperties = new EnableProtectionInputProperties
{
PolicyId = this.ProtectionContainerMapping.PolicyId,
ProtectableItemId = this.ProtectableItem.ID,
ProviderSpecificDetails = enableProtectionProviderSpecificInput
};
var input = new EnableProtectionInput { Properties = inputProperties };
// E2A and B2A.
if ((0 ==
string.Compare(
this.ParameterSetName,
ASRParameterSets.EnterpriseToAzure,
StringComparison.OrdinalIgnoreCase)) ||
(0 ==
string.Compare(
this.ParameterSetName,
ASRParameterSets.HyperVSiteToAzure,
StringComparison.OrdinalIgnoreCase)))
{
var providerSettings = new HyperVReplicaAzureEnableProtectionInput();
providerSettings.HvHostVmId = this.ProtectableItem.FabricObjectId;
providerSettings.VmName = this.ProtectableItem.FriendlyName;
providerSettings.TargetAzureVmName = this.ProtectableItem.FriendlyName;
// Id disk details are missing in input PE object, get the latest PE.
if (string.IsNullOrEmpty(this.ProtectableItem.OS))
{
// Just checked for OS to see whether the disk details got filled up or not
var protectableItemResponse = this.RecoveryServicesClient
.GetAzureSiteRecoveryProtectableItem(
Utilities.GetValueFromArmId(
this.ProtectableItem.ID,
ARMResourceTypeConstants.ReplicationFabrics),
this.ProtectableItem.ProtectionContainerId,
this.ProtectableItem.Name);
this.ProtectableItem = new ASRProtectableItem(protectableItemResponse);
}
if (string.IsNullOrWhiteSpace(this.OS))
{
providerSettings.OsType = (string.Compare(
this.ProtectableItem.OS,
Constants.OSWindows,
StringComparison.OrdinalIgnoreCase) ==
0) ||
(string.Compare(
this.ProtectableItem.OS,
Constants.OSLinux) ==
0) ? this.ProtectableItem.OS
: Constants.OSWindows;
}
else
{
providerSettings.OsType = this.OS;
}
if (string.IsNullOrWhiteSpace(this.OSDiskName))
{
providerSettings.VhdId = this.ProtectableItem.OSDiskId;
}
else
{
foreach (var disk in this.ProtectableItem.Disks)
{
if (0 ==
string.Compare(
disk.Name,
this.OSDiskName,
true))
{
providerSettings.VhdId = disk.Id;
break;
}
}
}
if (this.RecoveryAzureStorageAccountId != null)
{
providerSettings.TargetStorageAccountId =
this.RecoveryAzureStorageAccountId;
}
var deploymentType = Utilities.GetValueFromArmId(
this.RecoveryAzureStorageAccountId,
ARMResourceTypeConstants.Providers);
if (deploymentType.ToLower()
.Contains(Constants.Classic.ToLower()))
{
providerSettings.TargetAzureV1ResourceGroupId =
this.RecoveryResourceGroupId;
providerSettings.TargetAzureV2ResourceGroupId = null;
}
else
{
providerSettings.TargetAzureV1ResourceGroupId = null;
providerSettings.TargetAzureV2ResourceGroupId =
this.RecoveryResourceGroupId;
}
input.Properties.ProviderSpecificDetails = providerSettings;
}
this.response = this.RecoveryServicesClient.EnableProtection(
Utilities.GetValueFromArmId(
this.ProtectableItem.ID,
ARMResourceTypeConstants.ReplicationFabrics),
Utilities.GetValueFromArmId(
this.ProtectableItem.ID,
ARMResourceTypeConstants.ReplicationProtectionContainers),
this.Name,
input);
this.jobResponse = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails(
PSRecoveryServicesClient.GetJobIdFromReponseLocation(this.response.Location));
this.WriteObject(new ASRJob(this.jobResponse));
if (this.WaitForCompletion.IsPresent)
{
this.WaitForJobCompletion(this.jobResponse.Name);
this.jobResponse = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails(
PSRecoveryServicesClient
.GetJobIdFromReponseLocation(this.response.Location));
this.WriteObject(new ASRJob(this.jobResponse));
}
}
}
/// <summary>
/// Writes Job.
/// </summary>
/// <param name="job">JOB object</param>
private void WriteJob(
Job job)
{
this.WriteObject(new ASRJob(job));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: A collection of methods for manipulating Files.
**
** April 09,2000 (some design refactorization)
**
===========================================================*/
using System.Security.Permissions;
using Win32Native = Microsoft.Win32.Win32Native;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.IO
{
// Class for creating FileStream objects, and some basic file management
// routines such as Delete, etc.
[ComVisible(true)]
public static class File
{
private const int ERROR_INVALID_PARAMETER = 87;
internal const int GENERIC_READ = unchecked((int)0x80000000);
private const int GetFileExInfoStandard = 0;
// Tests if a file exists. The result is true if the file
// given by the specified path exists; otherwise, the result is
// false. Note that if path describes a directory,
// Exists will return true.
public static bool Exists(String path)
{
return InternalExistsHelper(path);
}
private static bool InternalExistsHelper(String path)
{
try
{
if (path == null)
return false;
if (path.Length == 0)
return false;
path = Path.GetFullPath(path);
// After normalizing, check whether path ends in directory separator.
// Otherwise, FillAttributeInfo removes it and we may return a false positive.
// GetFullPath should never return null
Debug.Assert(path != null, "File.Exists: GetFullPath returned null");
if (path.Length > 0 && PathInternal.IsDirectorySeparator(path[path.Length - 1]))
{
return false;
}
return InternalExists(path);
}
catch (ArgumentException) { }
catch (NotSupportedException) { } // Security can throw this on ":"
catch (SecurityException) { }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
return false;
}
internal static bool InternalExists(String path) {
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(path, ref data, false, true);
return (dataInitialised == 0) && (data.fileAttributes != -1)
&& ((data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) == 0);
}
public static byte[] ReadAllBytes(String path)
{
byte[] bytes;
using(FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
FileStream.DefaultBufferSize, FileOptions.None)) {
// Do a blocking read
int index = 0;
long fileLength = fs.Length;
if (fileLength > Int32.MaxValue)
throw new IOException(Environment.GetResourceString("IO.IO_FileTooLong2GB"));
int count = (int) fileLength;
bytes = new byte[count];
while(count > 0) {
int n = fs.Read(bytes, index, count);
if (n == 0)
__Error.EndOfFile();
index += n;
count -= n;
}
}
return bytes;
}
public static String[] ReadAllLines(String path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
return InternalReadAllLines(path, Encoding.UTF8);
}
private static String[] InternalReadAllLines(String path, Encoding encoding)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length != 0);
String line;
List<String> lines = new List<String>();
using (StreamReader sr = new StreamReader(path, encoding))
while ((line = sr.ReadLine()) != null)
lines.Add(line);
return lines.ToArray();
}
// Returns 0 on success, otherwise a Win32 error code. Note that
// classes should use -1 as the uninitialized state for dataInitialized.
internal static int FillAttributeInfo(String path, ref Win32Native.WIN32_FILE_ATTRIBUTE_DATA data, bool tryagain, bool returnErrorOnNotFound)
{
int dataInitialised = 0;
if (tryagain) // someone has a handle to the file open, or other error
{
Win32Native.WIN32_FIND_DATA findData;
findData = new Win32Native.WIN32_FIND_DATA ();
// Remove trialing slash since this can cause grief to FindFirstFile. You will get an invalid argument error
String tempPath = path.TrimEnd(new char [] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar});
// For floppy drives, normally the OS will pop up a dialog saying
// there is no disk in drive A:, please insert one. We don't want that.
// SetErrorMode will let us disable this, but we should set the error
// mode back, since this may have wide-ranging effects.
int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
try {
bool error = false;
SafeFindHandle handle = Win32Native.FindFirstFile(tempPath,findData);
try {
if (handle.IsInvalid) {
error = true;
dataInitialised = Marshal.GetLastWin32Error();
if (dataInitialised == Win32Native.ERROR_FILE_NOT_FOUND ||
dataInitialised == Win32Native.ERROR_PATH_NOT_FOUND ||
dataInitialised == Win32Native.ERROR_NOT_READY) // floppy device not ready
{
if (!returnErrorOnNotFound) {
// Return default value for backward compatibility
dataInitialised = 0;
data.fileAttributes = -1;
}
}
return dataInitialised;
}
}
finally {
// Close the Win32 handle
try {
handle.Close();
}
catch {
// if we're already returning an error, don't throw another one.
if (!error) {
Debug.Assert(false, "File::FillAttributeInfo - FindClose failed!");
__Error.WinIOError();
}
}
}
}
finally {
Win32Native.SetErrorMode(oldMode);
}
// Copy the information to data
data.PopulateFrom(findData);
}
else
{
// For floppy drives, normally the OS will pop up a dialog saying
// there is no disk in drive A:, please insert one. We don't want that.
// SetErrorMode will let us disable this, but we should set the error
// mode back, since this may have wide-ranging effects.
bool success = false;
int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
try {
success = Win32Native.GetFileAttributesEx(path, GetFileExInfoStandard, ref data);
}
finally {
Win32Native.SetErrorMode(oldMode);
}
if (!success) {
dataInitialised = Marshal.GetLastWin32Error();
if (dataInitialised != Win32Native.ERROR_FILE_NOT_FOUND &&
dataInitialised != Win32Native.ERROR_PATH_NOT_FOUND &&
dataInitialised != Win32Native.ERROR_NOT_READY) // floppy device not ready
{
// In case someone latched onto the file. Take the perf hit only for failure
return FillAttributeInfo(path, ref data, true, returnErrorOnNotFound);
}
else {
if (!returnErrorOnNotFound) {
// Return default value for backward compbatibility
dataInitialised = 0;
data.fileAttributes = -1;
}
}
}
}
return dataInitialised;
}
}
}
| |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace StatsViewer {
public partial class StatsViewer : Form {
/// <summary>
/// Create a StatsViewer.
/// </summary>
public StatsViewer() {
InitializeComponent();
}
#region Protected Methods
/// <summary>
/// Callback when the form loads.
/// </summary>
/// <param name="e"></param>
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
timer_ = new Timer();
timer_.Interval = kPollInterval;
timer_.Tick += new EventHandler(PollTimerTicked);
timer_.Start();
}
#endregion
#region Private Methods
/// <summary>
/// Attempt to open the stats file.
/// Return true on success, false otherwise.
/// </summary>
private bool OpenStatsFile() {
StatsTable table = new StatsTable();
if (table.Open(kStatsTableName)) {
stats_table_ = table;
return true;
}
return false;
}
/// <summary>
/// Close the open stats file.
/// </summary>
private void CloseStatsFile() {
if (this.stats_table_ != null)
{
this.stats_table_.Close();
this.stats_table_ = null;
this.listViewCounters.Items.Clear();
}
}
/// <summary>
/// Updates the process list in the UI.
/// </summary>
private void UpdateProcessList() {
int current_pids = comboBoxFilter.Items.Count;
int table_pids = stats_table_.Processes.Count;
if (current_pids != table_pids + 1) // Add one because of the "all" entry.
{
int selected_index = this.comboBoxFilter.SelectedIndex;
this.comboBoxFilter.Items.Clear();
this.comboBoxFilter.Items.Add(kStringAllProcesses);
foreach (int pid in stats_table_.Processes)
this.comboBoxFilter.Items.Add(kStringProcess + pid.ToString());
this.comboBoxFilter.SelectedIndex = selected_index;
}
}
/// <summary>
/// Updates the UI for a counter.
/// </summary>
/// <param name="counter"></param>
private void UpdateCounter(IStatsCounter counter) {
ListView view;
// Figure out which list this counter goes into.
if (counter is StatsCounterRate)
view = listViewRates;
else if (counter is StatsCounter || counter is StatsTimer)
view = listViewCounters;
else
return; // Counter type not supported yet.
// See if the counter is already in the list.
ListViewItem item = view.Items[counter.name];
if (item != null)
{
// Update an existing counter.
Debug.Assert(item is StatsCounterListViewItem);
StatsCounterListViewItem counter_item = item as StatsCounterListViewItem;
counter_item.Update(counter, filter_pid_);
}
else
{
// Create a new counter
StatsCounterListViewItem new_item = null;
if (counter is StatsCounterRate)
new_item = new RateListViewItem(counter, filter_pid_);
else if (counter is StatsCounter || counter is StatsTimer)
new_item = new CounterListViewItem(counter, filter_pid_);
Debug.Assert(new_item != null);
view.Items.Add(new_item);
}
}
/// <summary>
/// Sample the data and update the UI
/// </summary>
private void SampleData() {
// If the table isn't open, try to open it again.
if (stats_table_ == null)
if (!OpenStatsFile())
return;
if (stats_counters_ == null)
stats_counters_ = stats_table_.Counters();
if (pause_updates_)
return;
stats_counters_.Update();
UpdateProcessList();
foreach (IStatsCounter counter in stats_counters_)
UpdateCounter(counter);
}
/// <summary>
/// Set the background color based on the value
/// </summary>
/// <param name="item"></param>
/// <param name="value"></param>
private void ColorItem(ListViewItem item, int value)
{
if (value < 0)
item.ForeColor = Color.Red;
else if (value > 0)
item.ForeColor = Color.DarkGreen;
else
item.ForeColor = Color.Black;
}
/// <summary>
/// Called when the timer fires.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void PollTimerTicked(object sender, EventArgs e) {
SampleData();
}
/// <summary>
/// Called when the interval is changed by the user.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void interval_changed(object sender, EventArgs e) {
int interval = 1;
if (int.TryParse(comboBoxInterval.Text, out interval)) {
if (timer_ != null) {
timer_.Stop();
timer_.Interval = interval * 1000;
timer_.Start();
}
} else {
comboBoxInterval.Text = timer_.Interval.ToString();
}
}
/// <summary>
/// Called when the user changes the filter
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void filter_changed(object sender, EventArgs e) {
// While in this event handler, don't allow recursive events!
this.comboBoxFilter.SelectedIndexChanged -= new System.EventHandler(this.filter_changed);
if (this.comboBoxFilter.Text == kStringAllProcesses)
filter_pid_ = 0;
else
int.TryParse(comboBoxFilter.Text.Substring(kStringProcess.Length), out filter_pid_);
SampleData();
this.comboBoxFilter.SelectedIndexChanged += new System.EventHandler(this.filter_changed);
}
/// <summary>
/// Callback when the mouse enters a control
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void mouse_Enter(object sender, EventArgs e) {
// When the dropdown is expanded, we pause
// updates, as it messes with the UI.
pause_updates_ = true;
}
/// <summary>
/// Callback when the mouse leaves a control
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void mouse_Leave(object sender, EventArgs e) {
pause_updates_ = false;
}
/// <summary>
/// Called when the user clicks the zero-stats button.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonZero_Click(object sender, EventArgs e) {
this.stats_table_.Zero();
SampleData();
}
/// <summary>
/// Called when the user clicks a column heading.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void column_Click(object sender, ColumnClickEventArgs e) {
if (e.Column != sort_column_) {
sort_column_ = e.Column;
this.listViewCounters.Sorting = SortOrder.Ascending;
} else {
if (this.listViewCounters.Sorting == SortOrder.Ascending)
this.listViewCounters.Sorting = SortOrder.Descending;
else
this.listViewCounters.Sorting = SortOrder.Ascending;
}
this.listViewCounters.ListViewItemSorter =
new ListViewItemComparer(e.Column, this.listViewCounters.Sorting);
this.listViewCounters.Sort();
}
/// <summary>
/// Called when the user clicks the button "Export".
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonExport_Click(object sender, EventArgs e) {
//Have to pick a textfile to export to.
//Saves what is shown in listViewStats in the format: function value
//(with a tab in between), so that it is easy to copy paste into a spreadsheet.
//(Does not save the delta values.)
TextWriter tw = null;
try {
saveFileDialogExport.CheckFileExists = false;
saveFileDialogExport.ShowDialog();
tw = new StreamWriter(saveFileDialogExport.FileName);
for (int i = 0; i < listViewCounters.Items.Count; i++) {
tw.Write(listViewCounters.Items[i].SubItems[0].Text + "\t");
tw.WriteLine(listViewCounters.Items[i].SubItems[1].Text);
}
}
catch (IOException ex) {
MessageBox.Show(string.Format("There was an error while saving your results file. The results might not have been saved correctly.: {0}", ex.Message));
}
finally{
if (tw != null) tw.Close();
}
}
#endregion
class ListViewItemComparer : IComparer {
public ListViewItemComparer() {
this.col_ = 0;
this.order_ = SortOrder.Ascending;
}
public ListViewItemComparer(int column, SortOrder order) {
this.col_ = column;
this.order_ = order;
}
public int Compare(object x, object y) {
int return_value = -1;
object x_tag = ((ListViewItem)x).SubItems[col_].Tag;
object y_tag = ((ListViewItem)y).SubItems[col_].Tag;
if (Comparable(x_tag, y_tag))
return_value = ((IComparable)x_tag).CompareTo(y_tag);
else
return_value = String.Compare(((ListViewItem)x).SubItems[col_].Text,
((ListViewItem)y).SubItems[col_].Text);
if (order_ == SortOrder.Descending)
return_value *= -1;
return return_value;
}
#region Private Methods
private bool Comparable(object x, object y) {
if (x == null || y == null)
return false;
return x is IComparable && y is IComparable;
}
#endregion
#region Private Members
private int col_;
private SortOrder order_;
#endregion
}
#region Private Members
private const string kStringAllProcesses = "All Processes";
private const string kStringProcess = "Process ";
private const int kPollInterval = 1000; // 1 second
private const string kStatsTableName = "ChromeStats";
private StatsTable stats_table_;
private StatsTableCounters stats_counters_;
private Timer timer_;
private int filter_pid_;
private bool pause_updates_;
private int sort_column_ = -1;
#endregion
#region Private Event Callbacks
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenDialog dialog = new OpenDialog();
dialog.ShowDialog();
CloseStatsFile();
StatsTable table = new StatsTable();
bool rv = table.Open(dialog.FileName);
if (!rv)
{
MessageBox.Show("Could not open statsfile: " + dialog.FileName);
}
else
{
stats_table_ = table;
}
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
CloseStatsFile();
}
private void quitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
#endregion
}
/// <summary>
/// Base class for counter list view items.
/// </summary>
internal class StatsCounterListViewItem : ListViewItem
{
/// <summary>
/// Create the ListViewItem
/// </summary>
/// <param name="text"></param>
public StatsCounterListViewItem(string text) : base(text) { }
/// <summary>
/// Update the ListViewItem given a new counter value.
/// </summary>
/// <param name="counter"></param>
/// <param name="filter_pid"></param>
public virtual void Update(IStatsCounter counter, int filter_pid) { }
/// <summary>
/// Set the background color based on the value
/// </summary>
/// <param name="value"></param>
protected void ColorItem(int value)
{
if (value < 0)
ForeColor = Color.Red;
else if (value > 0)
ForeColor = Color.DarkGreen;
else
ForeColor = Color.Black;
}
/// <summary>
/// Create a new subitem with a zeroed Tag.
/// </summary>
/// <returns></returns>
protected ListViewSubItem NewSubItem()
{
ListViewSubItem item = new ListViewSubItem();
item.Tag = -1; // Arbitrarily initialize to -1.
return item;
}
/// <summary>
/// Set the value for a subitem.
/// </summary>
/// <param name="item"></param>
/// <param name="val"></param>
/// <returns>True if the value changed, false otherwise</returns>
protected bool SetSubItem(ListViewSubItem item, int val)
{
// The reason for doing this extra compare is because
// we introduce flicker if we unnecessarily update the
// subitems. The UI is much less likely to cause you
// a seizure when we do this.
if (val != (int)item.Tag)
{
item.Text = val.ToString();
item.Tag = val;
return true;
}
return false;
}
}
/// <summary>
/// A listview item which contains a rate.
/// </summary>
internal class RateListViewItem : StatsCounterListViewItem
{
public RateListViewItem(IStatsCounter ctr, int filter_pid) :
base(ctr.name)
{
StatsCounterRate rate = ctr as StatsCounterRate;
Name = rate.name;
SubItems.Add(NewSubItem());
SubItems.Add(NewSubItem());
SubItems.Add(NewSubItem());
Update(ctr, filter_pid);
}
public override void Update(IStatsCounter counter, int filter_pid)
{
Debug.Assert(counter is StatsCounterRate);
StatsCounterRate new_rate = counter as StatsCounterRate;
int new_count = new_rate.GetCount(filter_pid);
int new_time = new_rate.GetTime(filter_pid);
int old_avg = Tag != null ? (int)Tag : 0;
int new_avg = new_count > 0 ? (new_time / new_count) : 0;
int delta = new_avg - old_avg;
SetSubItem(SubItems[column_count_index], new_count);
SetSubItem(SubItems[column_time_index], new_time);
if (SetSubItem(SubItems[column_avg_index], new_avg))
ColorItem(delta);
Tag = new_avg;
}
private const int column_count_index = 1;
private const int column_time_index = 2;
private const int column_avg_index = 3;
}
/// <summary>
/// A listview item which contains a counter.
/// </summary>
internal class CounterListViewItem : StatsCounterListViewItem
{
public CounterListViewItem(IStatsCounter ctr, int filter_pid) :
base(ctr.name)
{
Name = ctr.name;
SubItems.Add(NewSubItem());
SubItems.Add(NewSubItem());
Update(ctr, filter_pid);
}
public override void Update(IStatsCounter counter, int filter_pid) {
Debug.Assert(counter is StatsCounter || counter is StatsTimer);
int new_value = 0;
if (counter is StatsCounter)
new_value = ((StatsCounter)counter).GetValue(filter_pid);
else if (counter is StatsTimer)
new_value = ((StatsTimer)counter).GetValue(filter_pid);
int old_value = Tag != null ? (int)Tag : 0;
int delta = new_value - old_value;
SetSubItem(SubItems[column_value_index], new_value);
if (SetSubItem(SubItems[column_delta_index], delta))
ColorItem(delta);
Tag = new_value;
}
private const int column_value_index = 1;
private const int column_delta_index = 2;
}
}
| |
#region Copyright (c) 2003-2005, Luke T. Maxon
/********************************************************************************************************************
'
' Copyright (c) 2003-2005, Luke T. Maxon
' All rights reserved.
'
' Redistribution and use in source and binary forms, with or without modification, are permitted provided
' that the following conditions are met:
'
' * Redistributions of source code must retain the above copyright notice, this list of conditions and the
' following disclaimer.
'
' * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
' the following disclaimer in the documentation and/or other materials provided with the distribution.
'
' * Neither the name of the author nor the names of its contributors may be used to endorse or
' promote products derived from this software without specific prior written permission.
'
' THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
' WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
' PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
' ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
' LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
' INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
' OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
' IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'
'*******************************************************************************************************************/
#endregion
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace Xunit.Extensions.Forms.TestApplications
{
/// <summary>
/// Summary description for ContextMenuTestForm.
/// </summary>
public class ContextMenuTestForm : Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
private MenuItem menuItem1;
private MenuItem menuItem2;
private MenuItem menuItem3;
private MenuItem menuItem4;
private MenuItem menuItem5;
private MenuItem menuItem6;
private MenuItem menuItem7;
private MenuItem menuItem8;
private Label myCounterLabel;
private MenuItem myFirstMenuItem;
private Label myLabel;
private ContextMenu myLabelContextMenu;
private ContextMenu secondMenu;
public ContextMenuTestForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
private void myFirstMenuItem_Click(object sender, EventArgs e)
{
int i = int.Parse(myCounterLabel.Text) + 1;
myCounterLabel.Text = i.ToString();
}
#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.myLabel = new Label();
this.myLabelContextMenu = new ContextMenu();
this.myFirstMenuItem = new MenuItem();
this.menuItem1 = new MenuItem();
this.menuItem2 = new MenuItem();
this.menuItem3 = new MenuItem();
this.menuItem5 = new MenuItem();
this.menuItem4 = new MenuItem();
this.menuItem6 = new MenuItem();
this.myCounterLabel = new Label();
this.secondMenu = new ContextMenu();
this.menuItem7 = new MenuItem();
this.menuItem8 = new MenuItem();
this.SuspendLayout();
//
// myLabel
//
this.myLabel.ContextMenu = this.myLabelContextMenu;
this.myLabel.Location = new Point(32, 40);
this.myLabel.Name = "myLabel";
this.myLabel.Size = new Size(100, 48);
this.myLabel.TabIndex = 0;
this.myLabel.Text = "Right click me for a context menu";
//
// myLabelContextMenu
//
this.myLabelContextMenu.MenuItems.AddRange(
new MenuItem[]
{this.myFirstMenuItem, this.menuItem1, this.menuItem2, this.menuItem3, this.menuItem4});
//
// myFirstMenuItem
//
this.myFirstMenuItem.Index = 0;
this.myFirstMenuItem.Text = "Click To Count";
this.myFirstMenuItem.Click += new EventHandler(this.myFirstMenuItem_Click);
//
// menuItem1
//
this.menuItem1.Index = 1;
this.menuItem1.Text = "Ambiguous";
//
// menuItem2
//
this.menuItem2.Index = 2;
this.menuItem2.Text = "Ambiguous";
//
// menuItem3
//
this.menuItem3.Index = 3;
this.menuItem3.MenuItems.AddRange(new MenuItem[] {this.menuItem5});
this.menuItem3.Text = "Test 1";
//
// menuItem5
//
this.menuItem5.Index = 0;
this.menuItem5.Text = "Not Ambiguous";
//
// menuItem4
//
this.menuItem4.Index = 4;
this.menuItem4.MenuItems.AddRange(new MenuItem[] {this.menuItem6});
this.menuItem4.Text = "Test 2";
//
// menuItem6
//
this.menuItem6.Index = 0;
this.menuItem6.Text = "Not Ambiguous";
//
// myCounterLabel
//
this.myCounterLabel.ContextMenu = this.secondMenu;
this.myCounterLabel.Location = new Point(184, 48);
this.myCounterLabel.Name = "myCounterLabel";
this.myCounterLabel.TabIndex = 1;
this.myCounterLabel.Text = "0";
//
// secondMenu
//
this.secondMenu.MenuItems.AddRange(new MenuItem[] {this.menuItem7});
//
// menuItem7
//
this.menuItem7.Index = 0;
this.menuItem7.MenuItems.AddRange(new MenuItem[] {this.menuItem8});
this.menuItem7.Text = "Test 2";
//
// menuItem8
//
this.menuItem8.Index = 0;
this.menuItem8.Text = "Not Ambiguous";
//
// ContextMenuTestForm
//
this.AutoScaleDimensions = new SizeF(5, 13);
this.ClientSize = new Size(336, 149);
this.Controls.Add(this.myCounterLabel);
this.Controls.Add(this.myLabel);
this.Name = "ContextMenuTestForm";
this.Text = "ContextMenuTestForm";
this.ResumeLayout(false);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orleans.Runtime;
using Orleans.Streams.Core;
namespace Orleans.Streams
{
internal class StreamConsumer<T> : IInternalAsyncObservable<T>
{
internal bool IsRewindable { get; private set; }
private readonly StreamImpl<T> stream;
private readonly string streamProviderName;
[NonSerialized]
private readonly IStreamProviderRuntime providerRuntime;
[NonSerialized]
private readonly IStreamPubSub pubSub;
private StreamConsumerExtension myExtension;
private IStreamConsumerExtension myGrainReference;
[NonSerialized]
private readonly AsyncLock bindExtLock;
[NonSerialized]
private readonly Logger logger;
public StreamConsumer(StreamImpl<T> stream, string streamProviderName, IStreamProviderRuntime providerUtilities, IStreamPubSub pubSub, bool isRewindable)
{
if (stream == null) throw new ArgumentNullException("stream");
if (providerUtilities == null) throw new ArgumentNullException("providerUtilities");
if (pubSub == null) throw new ArgumentNullException("pubSub");
logger = LogManager.GetLogger(string.Format("StreamConsumer<{0}>-{1}", typeof(T).Name, stream), LoggerType.Runtime);
this.stream = stream;
this.streamProviderName = streamProviderName;
providerRuntime = providerUtilities;
this.pubSub = pubSub;
IsRewindable = isRewindable;
myExtension = null;
myGrainReference = null;
bindExtLock = new AsyncLock();
}
public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncObserver<T> observer)
{
return SubscribeAsync(observer, null);
}
public async Task<StreamSubscriptionHandle<T>> SubscribeAsync(
IAsyncObserver<T> observer,
StreamSequenceToken token,
StreamFilterPredicate filterFunc = null,
object filterData = null)
{
if (token != null && !IsRewindable)
throw new ArgumentNullException("token", "Passing a non-null token to a non-rewindable IAsyncObservable.");
if (observer is GrainReference)
throw new ArgumentException("On-behalf subscription via grain references is not supported. Only passing of object references is allowed.", "observer");
if (logger.IsVerbose) logger.Verbose("Subscribe Observer={0} Token={1}", observer, token);
await BindExtensionLazy();
IStreamFilterPredicateWrapper filterWrapper = null;
if (filterFunc != null)
filterWrapper = new FilterPredicateWrapperData(filterData, filterFunc);
if (logger.IsVerbose) logger.Verbose("Subscribe - Connecting to Rendezvous {0} My GrainRef={1} Token={2}",
pubSub, myGrainReference, token);
GuidId subscriptionId = pubSub.CreateSubscriptionId(stream.StreamId, myGrainReference);
// Optimistic Concurrency:
// In general, we should first register the subsription with the pubsub (pubSub.RegisterConsumer)
// and only if it succeeds store it locally (myExtension.SetObserver).
// Basicaly, those 2 operations should be done as one atomic transaction - either both or none and isolated from concurrent reads.
// BUT: there is a distributed race here: the first msg may arrive before the call is awaited
// (since the pubsub notifies the producer that may immideately produce)
// and will thus not find the subriptionHandle in the extension, basically violating "isolation".
// Therefore, we employ Optimistic Concurrency Control here to guarantee isolation:
// we optimisticaly store subscriptionId in the handle first before calling pubSub.RegisterConsumer
// and undo it in the case of failure.
// There is no problem with that we call myExtension.SetObserver too early before the handle is registered in pub sub,
// since this subscriptionId is unique (random Guid) and no one knows it anyway, unless successfully subscribed in the pubsub.
var subriptionHandle = myExtension.SetObserver(subscriptionId, stream, observer, token, filterWrapper);
try
{
await pubSub.RegisterConsumer(subscriptionId, stream.StreamId, streamProviderName, myGrainReference, filterWrapper);
return subriptionHandle;
} catch(Exception)
{
// Undo the previous call myExtension.SetObserver.
myExtension.RemoveObserver(subscriptionId);
throw;
}
}
public async Task<StreamSubscriptionHandle<T>> ResumeAsync(
StreamSubscriptionHandle<T> handle,
IAsyncObserver<T> observer,
StreamSequenceToken token = null)
{
StreamSubscriptionHandleImpl<T> oldHandleImpl = CheckHandleValidity(handle);
if (token != null && !IsRewindable)
throw new ArgumentNullException("token", "Passing a non-null token to a non-rewindable IAsyncObservable.");
if (logger.IsVerbose) logger.Verbose("Resume Observer={0} Token={1}", observer, token);
await BindExtensionLazy();
if (logger.IsVerbose) logger.Verbose("Resume - Connecting to Rendezvous {0} My GrainRef={1} Token={2}",
pubSub, myGrainReference, token);
StreamSubscriptionHandle<T> newHandle = myExtension.SetObserver(oldHandleImpl.SubscriptionId, stream, observer, token, null);
// On failure caller should be able to retry using the original handle, so invalidate old handle only if everything succeeded.
oldHandleImpl.Invalidate();
return newHandle;
}
public async Task UnsubscribeAsync(StreamSubscriptionHandle<T> handle)
{
await BindExtensionLazy();
StreamSubscriptionHandleImpl<T> handleImpl = CheckHandleValidity(handle);
if (logger.IsVerbose) logger.Verbose("Unsubscribe StreamSubscriptionHandle={0}", handle);
myExtension.RemoveObserver(handleImpl.SubscriptionId);
// UnregisterConsumer from pubsub even if does not have this handle localy, to allow UnsubscribeAsync retries.
if (logger.IsVerbose) logger.Verbose("Unsubscribe - Disconnecting from Rendezvous {0} My GrainRef={1}",
pubSub, myGrainReference);
await pubSub.UnregisterConsumer(handleImpl.SubscriptionId, stream.StreamId, streamProviderName);
handleImpl.Invalidate();
}
public async Task<IList<StreamSubscriptionHandle<T>>> GetAllSubscriptions()
{
await BindExtensionLazy();
List<StreamSubscription> subscriptions= await pubSub.GetAllSubscriptions(stream.StreamId, myGrainReference);
return subscriptions.Select(sub => new StreamSubscriptionHandleImpl<T>(GuidId.GetGuidId(sub.SubscriptionId), stream))
.ToList<StreamSubscriptionHandle<T>>();
}
public async Task Cleanup()
{
if (logger.IsVerbose) logger.Verbose("Cleanup() called");
if (myExtension == null)
return;
var allHandles = myExtension.GetAllStreamHandles<T>();
var tasks = new List<Task>();
foreach (var handle in allHandles)
{
myExtension.RemoveObserver(handle.SubscriptionId);
tasks.Add(pubSub.UnregisterConsumer(handle.SubscriptionId, stream.StreamId, streamProviderName));
}
try
{
await Task.WhenAll(tasks);
} catch (Exception exc)
{
logger.Warn(ErrorCode.StreamProvider_ConsumerFailedToUnregister,
"Ignoring unhandled exception during PubSub.UnregisterConsumer", exc);
}
myExtension = null;
}
// Used in test.
internal bool InternalRemoveObserver(StreamSubscriptionHandle<T> handle)
{
return myExtension != null && myExtension.RemoveObserver(((StreamSubscriptionHandleImpl<T>)handle).SubscriptionId);
}
internal Task<int> DiagGetConsumerObserversCount()
{
return Task.FromResult(myExtension.DiagCountStreamObservers<T>(stream.StreamId));
}
private async Task BindExtensionLazy()
{
if (myExtension == null)
{
using (await bindExtLock.LockAsync())
{
if (myExtension == null)
{
if (logger.IsVerbose) logger.Verbose("BindExtensionLazy - Binding local extension to stream runtime={0}", providerRuntime);
var tup = await providerRuntime.BindExtension<StreamConsumerExtension, IStreamConsumerExtension>(
() => new StreamConsumerExtension(providerRuntime));
myExtension = tup.Item1;
myGrainReference = tup.Item2;
if (logger.IsVerbose) logger.Verbose("BindExtensionLazy - Connected Extension={0} GrainRef={1}", myExtension, myGrainReference);
}
}
}
}
private StreamSubscriptionHandleImpl<T> CheckHandleValidity(StreamSubscriptionHandle<T> handle)
{
if (handle == null)
throw new ArgumentNullException("handle");
if (!handle.StreamIdentity.Equals(stream))
throw new ArgumentException("Handle is not for this stream.", "handle");
var handleImpl = handle as StreamSubscriptionHandleImpl<T>;
if (handleImpl == null)
throw new ArgumentException("Handle type not supported.", "handle");
if (!handleImpl.IsValid)
throw new ArgumentException("Handle is no longer valid. It has been used to unsubscribe or resume.", "handle");
return handleImpl;
}
}
}
| |
'From Squeak 2.2 of Sept 23, 1998 on 13 October 1998 at 10:58:16 pm'!
!Number methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:38'!
zeroDivideError
^ self error: 'Cannot divide by zero'! !
!Float methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:34'!
differenceFromFloat: aFloat
^ self primitiveFailed!
]style[(21 6 25)f1b,f1cgreen;b,f1! !
!Float methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:35'!
differenceFromFraction: aFraction
^ aFraction asFloat - self!
]style[(24 9 5 9 15)f1b,f1cgreen;b,f1,f1cblue;,f1! !
!Float methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:35'!
differenceFromInteger: anInteger
^ anInteger asFloat - self!
]style[(23 9 5 9 15)f1b,f1cgreen;b,f1,f1cblue;,f1! !
!Float methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:35'!
productFromFloat: aFloat
^ self primitiveFailed!
]style[(18 6 25)f1b,f1cgreen;b,f1! !
!Float methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:35'!
productFromFraction: aFraction
^ aFraction asFloat * self!
]style[(21 9 5 9 15)f1b,f1cgreen;b,f1,f1cblue;,f1! !
!Float methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:35'!
productFromInteger: anInteger
^ anInteger asFloat * self!
]style[(20 9 5 9 15)f1b,f1cgreen;b,f1,f1cblue;,f1! !
!Float methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:35'!
quotientFromFloat: aFloat
^ self = 0.0
ifTrue: [self zeroDivideError]
ifFalse: [self primitiveFailed]!
]style[(19 6 82)f1b,f1cgreen;b,f1! !
!Float methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:35'!
quotientFromFraction: aFraction
^ aFraction asFloat / self!
]style[(22 9 5 9 15)f1b,f1cgreen;b,f1,f1cblue;,f1! !
!Float methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:35'!
quotientFromInteger: anInteger
^ anInteger asFloat / self!
]style[(21 9 5 9 15)f1b,f1cgreen;b,f1,f1cblue;,f1! !
!Float methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:35'!
sumFromFloat: aFloat
^ self primitiveFailed!
]style[(14 6 25)f1b,f1cgreen;b,f1! !
!Float methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:35'!
sumFromFraction: aFraction
^ aFraction asFloat + self!
]style[(17 9 5 9 15)f1b,f1cgreen;b,f1,f1cblue;,f1! !
!Float methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:35'!
sumFromInteger: anInteger
^ anInteger asFloat + self!
]style[(16 9 5 9 15)f1b,f1cgreen;b,f1,f1cblue;,f1! !
!Fraction methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:36'!
differenceFromFloat: aFloat
^ aFloat - self asFloat!
]style[(21 6 5 6 15)f1b,f1cgreen;b,f1,f1cblue;,f1! !
!Fraction methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:36'!
differenceFromFraction: aFraction
^ aFraction numerator * denominator - (numerator * aFraction denominator) / (aFraction denominator * denominator)!
]style[(24 9 5 9 40 9 17 9 27)f1b,f1cgreen;b,f1,f1cblue;,f1,f1cblue;,f1,f1cblue;,f1! !
!Fraction methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:36'!
differenceFromInteger: anInteger
^ anInteger * denominator - numerator / denominator!
]style[(23 9 5 9 40)f1b,f1cgreen;b,f1,f1cblue;,f1! !
!Fraction methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:36'!
productFromFloat: aFloat
^ aFloat * self asFloat!
]style[(18 6 5 6 15)f1b,f1cgreen;b,f1,f1cblue;,f1! !
!Fraction methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:36'!
productFromFraction: aFraction
^ aFraction numerator * numerator / (aFraction denominator * denominator)!
]style[(21 9 5 9 26 9 27)f1b,f1cgreen;b,f1,f1cblue;,f1,f1cblue;,f1! !
!Fraction methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:36'!
productFromInteger: anInteger
^ anInteger * numerator / denominator!
]style[(20 9 5 9 26)f1b,f1cgreen;b,f1,f1cblue;,f1! !
!Fraction methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:36'!
quotientFromFloat: aFloat
^ aFloat / self asFloat!
]style[(19 6 5 6 15)f1b,f1cgreen;b,f1,f1cblue;,f1! !
!Fraction methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:36'!
quotientFromFraction: aFraction
^ aFraction numerator * denominator / (aFraction denominator * numerator)!
]style[(22 9 5 9 28 9 25)f1b,f1cgreen;b,f1,f1cblue;,f1,f1cblue;,f1! !
!Fraction methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:36'!
quotientFromInteger: anInteger
^ anInteger * denominator / numerator!
]style[(21 9 5 9 26)f1b,f1cgreen;b,f1,f1cblue;,f1! !
!Fraction methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:36'!
sumFromFloat: aFloat
^ aFloat + self asFloat!
]style[(14 6 5 6 15)f1b,f1cgreen;b,f1,f1cblue;,f1! !
!Fraction methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:36'!
sumFromFraction: aFraction
^ aFraction numerator * denominator + (numerator * aFraction denominator) / (aFraction denominator * denominator)!
]style[(17 9 5 9 40 9 17 9 27)f1b,f1cgreen;b,f1,f1cblue;,f1,f1cblue;,f1,f1cblue;,f1! !
!Fraction methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:36'!
sumFromInteger: anInteger
^ anInteger * denominator + numerator / denominator!
]style[(16 9 5 9 40)f1b,f1cgreen;b,f1,f1cblue;,f1! !
!Integer methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:37'!
differenceFromFloat: aFloat
^ aFloat - self asFloat!
]style[(21 6 5 6 15)f1b,f1cgreen;b,f1,f1cblue;,f1! !
!Integer methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:37'!
differenceFromFraction: aFraction
^ aFraction numerator - (self * aFraction denominator) / aFraction denominator!
]style[(24 9 5 9 21 9 16 9 12)f1b,f1cgreen;b,f1,f1cblue;,f1,f1cblue;,f1,f1cblue;,f1! !
!Integer methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:37'!
differenceFromInteger: anInteger
^ self negative == anInteger negative
ifTrue: [anInteger digitSubtract: self]
ifFalse: [(anInteger digitAdd: self) normalize]!
]style[(23 9 22 9 21 9 35 9 27)f1b,f1cgreen;b,f1,f1cblue;,f1,f1cblue;,f1,f1cblue;,f1! !
!Integer methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:37'!
productFromFloat: aFloat
^ aFloat * self asFloat!
]style[(18 6 5 6 15)f1b,f1cgreen;b,f1,f1cblue;,f1! !
!Integer methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:37'!
productFromFraction: aFraction
^ aFraction numerator * self / aFraction denominator!
]style[(21 9 5 9 20 9 12)f1b,f1cgreen;b,f1,f1cblue;,f1,f1cblue;,f1! !
!Integer methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:37'!
productFromInteger: anInteger
^ self digitMultiply: anInteger neg: self negative ~~ anInteger negative!
]style[(20 9 25 9 23 9 9)f1b,f1cgreen;b,f1,f1cblue;,f1,f1cblue;,f1! !
!Integer methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:37'!
quotientFromFloat: aFloat
^ aFloat / self asFloat!
]style[(19 6 5 6 15)f1b,f1cgreen;b,f1,f1cblue;,f1! !
!Integer methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:37'!
quotientFromFraction: aFraction
^ aFraction numerator / (aFraction denominator * self)!
]style[(22 9 5 9 14 9 20)f1b,f1cgreen;b,f1,f1cblue;,f1,f1cblue;,f1! !
!Integer methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:37'!
quotientFromInteger: anInteger
| quoRem |
quoRem _ anInteger abs digitDiv: self abs neg: self negative ~~ anInteger negative.
^ (quoRem at: 2)
= 0
ifTrue: [(quoRem at: 1) normalize]
ifFalse: [(Fraction numerator: anInteger denominator: self) reduced]!
]style[(21 9 5 7 3 6 3 9 46 9 15 6 26 6 52 9 28)f1b,f1cgreen;b,f1,f1cgreen;,f1,f1cblue;,f1,f1cblue;,f1,f1cblue;,f1,f1cblue;,f1,f1cblue;,f1,f1cblue;,f1! !
!Integer methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:38'!
sumFromFloat: aFloat
^ aFloat + self asFloat!
]style[(14 6 5 6 15)f1b,f1cgreen;b,f1,f1cblue;,f1! !
!Integer methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:38'!
sumFromFraction: aFraction
^ aFraction numerator + (self * aFraction denominator) / aFraction denominator!
]style[(17 9 5 9 21 9 16 9 12)f1b,f1cgreen;b,f1,f1cblue;,f1,f1cblue;,f1,f1cblue;,f1! !
!Integer methodsFor: 'arithmetic-DD' stamp: 'TAG 10/13/1998 22:38'!
sumFromInteger: anInteger
^ self negative == anInteger negative
ifTrue: [(self digitAdd: anInteger) normalize]
ifFalse: [self digitSubtract: anInteger]!
]style[(16 9 22 9 37 9 45 9 1)f1b,f1cgreen;b,f1,f1cblue;,f1,f1cblue;,f1,f1cblue;,f1! !
| |
using Microsoft.Azure.Management.NetApp;
using Microsoft.Azure.Management.NetApp.Models;
using System;
using System.Collections.Generic;
using System.Threading;
using Xunit;
namespace NetApp.Tests.Helpers
{
public class ResourceUtils
{
public const long gibibyte = 1024L * 1024L * 1024L;
private const string remoteSuffix = "-R";
//public const string vnet = "sdknettestqa2vnet464";
public const string vnet = "sdknettestqa2vnet464";
public const string backupVnet = "sdknettestqa2vnet464euap";
public const string repVnet = "sdktestqa2vnet464";
//public const string remoteVnet = repVnet + remoteSuffix;
public const string remoteVnet = "sdktestqa2vnet464east-R";
//public const string subsId = "8f38cfec-0ecd-413a-892e-2494f77a3b56";
//public const string subsId = "0661B131-4A11-479B-96BF-2F95ACCA2F73";
public const string subsId = "69a75bda-882e-44d5-8431-63421204132a";
public const string location = "westus2";
//public const string location = "eastus2euap";
//public const string remoteLocation = "southcentralus";
public const string remoteLocation = "eastus";
//public const string backupLocation = "westus2";
//public const string backupLocation = "westus2"; //"westusstage";
public const string backupLocation = "eastus2euap"; //"westusstage";
public const string resourceGroup = "sdk-net-test-qa2";
//public const string resourceGroup = "ab_sdk_test_rg";
public const string repResourceGroup = "sdk-test-qa2";
public const string remoteResourceGroup = repResourceGroup + remoteSuffix;
public const string accountName1 = "sdk-net-tests-acc-212";
public const string accountName1Repl = "sdk-net-tests-acc-21b";
public const string remoteAccountName1 = accountName1Repl + remoteSuffix;
public const string accountName2 = "sdk-net-tests-acc-23";
public const string poolName1 = "sdk-net-tests-pool-205";
public const string poolName1Repl = "sdk-net-tests-pool-11b";
public const string remotePoolName1 = poolName1Repl + remoteSuffix;
public const string poolName2 = "sdk-net-tests-pool-211";
public const string volumeName1 = "sdk-net-tests-vol-2105";
public const string volumeBackupAccountName1 = "sdk-net-tests-acc-213v";
public const string backupVolumeName1 = "sdk-net-tests-vol-2109";
public const string volumeName1ReplSource = "sdk-net-tests-vol-1001b-source";
public const string volumeName1ReplDest = volumeName1ReplSource + remoteSuffix+"dest";
public const string volumeName2 = "sdk-net-tests-vol-1001";
public const string snapshotName1 = "sdk-net-tests-snap-11";
public const string snapshotName2 = "sdk-net-tests-snap-12";
public const string snapshotPolicyName1 = "sdk-net-tests-snapshotPolicy-1";
public const string snapshotPolicyName2 = "sdk-net-tests-snapshotPolicy-2";
public const string backupPolicyName1 = "sdk-net-tests-backupPolicy-105a";
public const string backupPolicyName2 = "sdk-net-tests-backupPolicy-105b";
//public const string backupVaultId = "cbsvault";
public static ActiveDirectory activeDirectory = new ActiveDirectory()
{
Username = "sdkuser",
Password = "sdkpass",
Domain = "sdkdomain",
Dns = "192.0.2.2",
SmbServerName = "SDKSMBSeNa",
};
public static ActiveDirectory activeDirectory2 = new ActiveDirectory()
{
Username = "sdkuser1",
Password = "sdkpass1",
Domain = "sdkdomain",
Dns = "192.0.2.1",
SmbServerName = "SDKSMBSeNa",
};
public static ExportPolicyRule defaultExportPolicyRule = new ExportPolicyRule()
{
RuleIndex = 1,
UnixReadOnly = false,
UnixReadWrite = true,
Cifs = false,
Nfsv3 = true,
Nfsv41 = false,
AllowedClients = "0.0.0.0/0"
};
public static IList<ExportPolicyRule> defaultExportPolicyRuleList = new List<ExportPolicyRule>()
{
defaultExportPolicyRule
};
public static VolumePropertiesExportPolicy defaultExportPolicy = new VolumePropertiesExportPolicy()
{
Rules = defaultExportPolicyRuleList
};
private const int delay = 5000;
private const int retryAttempts = 4;
public static NetAppAccount CreateAccount(AzureNetAppFilesManagementClient netAppMgmtClient, string accountName = accountName1, string resourceGroup = resourceGroup, string location = location, IDictionary<string, string> tags = default(IDictionary<string, string>), ActiveDirectory activeDirectory = null)
{
// request reference example
// az netappfiles account update -g --account-name cli-lf-acc2 --active-directories '[{"username": "aduser", "password": "aduser", "smbservername": "SMBSERVER", "dns": "1.2.3.4", "domain": "westcentralus"}]' -l westus2
var activeDirectories = activeDirectory != null ? new List <ActiveDirectory> { activeDirectory } : new List<ActiveDirectory>();
var netAppAccount = new NetAppAccount()
{
Location = location,
Tags = tags,
ActiveDirectories = activeDirectories
};
var resource = netAppMgmtClient.Accounts.CreateOrUpdate(netAppAccount, resourceGroup, accountName);
Assert.Equal(resource.Name, accountName);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay); // some robustness against ARM caching
}
return resource;
}
public static CapacityPool CreatePool(AzureNetAppFilesManagementClient netAppMgmtClient, string poolName = poolName1, string accountName = accountName1, string resourceGroup = resourceGroup, string location = location, IDictionary<string, string> tags = default(IDictionary<string, string>), bool poolOnly = false, string serviceLevel = "Premium")
{
if (!poolOnly)
{
CreateAccount(netAppMgmtClient, accountName, resourceGroup: resourceGroup, location: location, tags: tags);
}
var pool = new CapacityPool
{
Location = location,
Size = 4398046511104,
ServiceLevel = serviceLevel,
Tags = tags
};
CapacityPool resource;
try
{
resource = netAppMgmtClient.Pools.CreateOrUpdate(pool, resourceGroup, accountName, poolName);
}
catch
{
// try one more time
resource = netAppMgmtClient.Pools.CreateOrUpdate(pool, resourceGroup, accountName, poolName);
}
Assert.Equal(resource.Name, accountName + '/' + poolName);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay); // some robustness against ARM caching
}
return resource;
}
public static Volume CreateVolume(AzureNetAppFilesManagementClient netAppMgmtClient, string volumeName = volumeName1, string poolName = poolName1, string accountName = accountName1, string resourceGroup = resourceGroup, string location = location, List<string> protocolTypes = null, IDictionary<string, string> tags = default(IDictionary<string, string>), VolumePropertiesExportPolicy exportPolicy = null, string vnet = vnet, bool volumeOnly = false, string snapshotId = null, string snapshotPolicyId = null)
{
if (!volumeOnly)
{
CreatePool(netAppMgmtClient, poolName, accountName, resourceGroup: resourceGroup, location: location);
}
var defaultProtocolType = new List<string>() { "NFSv3" };
var volumeProtocolTypes = protocolTypes == null ? defaultProtocolType : protocolTypes;
var volume = new Volume
{
Location = location,
UsageThreshold = 100 * gibibyte,
ProtocolTypes = volumeProtocolTypes,
CreationToken = volumeName,
SubnetId = "/subscriptions/" + netAppMgmtClient.SubscriptionId + "/resourceGroups/" + resourceGroup + "/providers/Microsoft.Network/virtualNetworks/" + vnet + "/subnets/default",
Tags = tags,
ExportPolicy = exportPolicy,
SnapshotId = snapshotId,
};
if (snapshotPolicyId != null)
{
var volumDataProtection = new VolumePropertiesDataProtection
{
Snapshot = new VolumeSnapshotProperties(snapshotPolicyId)
};
volume.DataProtection = volumDataProtection;
}
var resource = netAppMgmtClient.Volumes.CreateOrUpdate(volume, resourceGroup, accountName, poolName, volumeName);
Assert.Equal(resource.Name, accountName + '/' + poolName + '/' + volumeName);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay); // some robustness against ARM caching
}
return resource;
}
public static Volume CreateDpVolume(AzureNetAppFilesManagementClient netAppMgmtClient, Volume sourceVolume, string volumeName = volumeName1ReplDest, string poolName = remotePoolName1, string accountName = remoteAccountName1, string resourceGroup = remoteResourceGroup, string location = location, List<string> protocolTypes = null, IDictionary<string, string> tags = default(IDictionary<string, string>), VolumePropertiesExportPolicy exportPolicy = null, bool volumeOnly = false, string snapshotId = null)
{
if (!volumeOnly)
{
CreatePool(netAppMgmtClient, poolName, accountName, resourceGroup: resourceGroup, location: remoteLocation);
}
var defaultProtocolType = new List<string>() { "NFSv3" };
var volumeProtocolTypes = protocolTypes == null ? defaultProtocolType : protocolTypes;
var replication = new ReplicationObject
{
EndpointType = "dst",
RemoteVolumeResourceId = sourceVolume.Id,
ReplicationSchedule = "_10minutely"
};
var dataProtection = new VolumePropertiesDataProtection
{
Replication = replication
};
var volume = new Volume
{
Location = remoteLocation,
UsageThreshold = 100 * gibibyte,
ProtocolTypes = volumeProtocolTypes,
CreationToken = volumeName,
//SubnetId = "/subscriptions/" + subsId + "/resourceGroups/" + resourceGroup + "/providers/Microsoft.Network/virtualNetworks/" + remoteVnet + "/subnets/default",
SubnetId = "/subscriptions/" + netAppMgmtClient.SubscriptionId + "/resourceGroups/" + resourceGroup + "/providers/Microsoft.Network/virtualNetworks/" + remoteVnet + "/subnets/default",
Tags = tags,
ExportPolicy = exportPolicy,
SnapshotId = snapshotId,
VolumeType = "DataProtection",
DataProtection = dataProtection
};
var resource = netAppMgmtClient.Volumes.CreateOrUpdate(volume, resourceGroup, accountName, poolName, volumeName);
Assert.Equal(resource.Name, accountName + '/' + poolName + '/' + volumeName);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay); // some robustness against ARM caching
}
return resource;
}
public static Volume CreateBackedupVolume(AzureNetAppFilesManagementClient netAppMgmtClient, string volumeName = volumeName1, string poolName = poolName1, string accountName = volumeBackupAccountName1, string resourceGroup = resourceGroup, string location = backupLocation, List<string> protocolTypes = null, IDictionary<string, string> tags = default(IDictionary<string, string>), VolumePropertiesExportPolicy exportPolicy = null, bool volumeOnly = false, string vnet = backupVnet, string backupPolicyId = null, string backupVaultId = null)
{
if (!volumeOnly)
{
CreatePool(netAppMgmtClient, poolName, accountName, resourceGroup: resourceGroup, location: location);
}
var defaultProtocolType = new List<string>() { "NFSv3" };
var volumeProtocolTypes = protocolTypes == null ? defaultProtocolType : protocolTypes;
var dataProtection = new VolumePropertiesDataProtection
{
Backup = new VolumeBackupProperties {BackupEnabled = true, BackupPolicyId = backupPolicyId, VaultId = backupVaultId }
};
var volume = new Volume
{
Location = location,
UsageThreshold = 100 * gibibyte,
ProtocolTypes = volumeProtocolTypes,
CreationToken = volumeName,
SubnetId = "/subscriptions/" + netAppMgmtClient.SubscriptionId + "/resourceGroups/" + resourceGroup + "/providers/Microsoft.Network/virtualNetworks/" + backupVnet + "/subnets/default",
Tags = tags,
ExportPolicy = exportPolicy,
VolumeType = "DataProtection",
DataProtection = dataProtection
};
var resource = netAppMgmtClient.Volumes.CreateOrUpdate(volume, resourceGroup, accountName, poolName, volumeName);
Assert.Equal(resource.Name, accountName + '/' + poolName + '/' + volumeName);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay); // some robustness against ARM caching
}
return resource;
}
public static void CreateSnapshot(AzureNetAppFilesManagementClient netAppMgmtClient, string snapshotName = snapshotName1, string volumeName = volumeName1, string poolName = poolName1, string accountName = accountName1, string resourceGroup = resourceGroup, string location = location, bool snapshotOnly = false)
{
Volume volume = null;
var snapshot = new Snapshot();
if (!snapshotOnly)
{
volume = CreateVolume(netAppMgmtClient, volumeName, poolName, accountName);
snapshot = new Snapshot
{
Location = location,
};
}
else
{
// for those tests where snapshotOnly is true, no filesystem id will be available
// use this opportunity to test snapshot creation with no filesystem id provided
// for these cases it should use the name in the resource id
snapshot = new Snapshot
{
Location = location,
};
}
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay); // some robustness against ARM caching
}
var resource = netAppMgmtClient.Snapshots.Create(snapshot, resourceGroup, accountName, poolName, volumeName, snapshotName);
Assert.Equal(resource.Name, accountName + '/' + poolName + '/' + volumeName + '/' + snapshotName);
}
public static void DeleteAccount(AzureNetAppFilesManagementClient netAppMgmtClient, string accountName = accountName1, string resourceGroup = resourceGroup, bool deep = false)
{
if (deep)
{
// find and delete all nested resources - not implemented
}
// now delete the account
netAppMgmtClient.Accounts.Delete(resourceGroup, accountName);
}
public static void DeletePool(AzureNetAppFilesManagementClient netAppMgmtClient, string poolName = poolName1, string accountName = accountName1, string resourceGroup = resourceGroup, bool deep = false)
{
bool retry = true;
int co = 0;
if (deep)
{
// find and delete all nested resources - not implemented
}
// now delete the pool - with retry for test robustness due to
// - ARM caching (ARM continues to tidy up even after the awaited async op
// has returned)
// - other async actions in RP/SDE/NRP
// e.g. snapshot deletion might not be complete and therefore pool has child resource
while (retry == true)
{
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay);
}
try
{
netAppMgmtClient.Pools.Delete(resourceGroup, accountName, poolName);
retry = false;
}
catch
{
co++;
if (co > retryAttempts)
{
retry = false;
}
}
}
}
public static void DeleteVolume(AzureNetAppFilesManagementClient netAppMgmtClient, string volumeName = volumeName1, string poolName = poolName1, string accountName = accountName1, string resourceGroup = resourceGroup, string location = location, bool deep = false)
{
bool retry = true;
int co = 0;
if (deep)
{
// find and delete all nested resources - not implemented
}
// now delete the volume - with retry for test robustness due to
// - ARM caching (ARM continues to tidy up even after the awaited async op
// has returned)
// - other async actions in RP/SDE/NRP
// e.g. snapshot deletion might not be complete and therefore volume has child resource
while (retry == true)
{
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay);
}
try
{
netAppMgmtClient.Volumes.Delete(resourceGroup, accountName, poolName, volumeName);
retry = false;
}
catch
{
co++;
if (co > retryAttempts)
{
retry = false;
}
}
}
}
public static void DeleteSnapshot(AzureNetAppFilesManagementClient netAppMgmtClient, string snapshotName = snapshotName1, string volumeName = volumeName1, string poolName = poolName1, string accountName = accountName1, string resourceGroup = resourceGroup, string location = location, bool deep = false)
{
bool retry = true;
int co = 0;
if (deep)
{
// find and delete all nested resources - not implemented
}
// now delete the snapshot - with retry for test robustness due to
// - ARM caching (ARM continues to tidy up even after the awaited async op
// has returned)
// - other async actions in RP/SDE/NRP
// e.g. snapshot deletion might fail if the actual creation is not complete at
// all levels
while (retry == true)
{
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay);
}
try
{
netAppMgmtClient.Snapshots.Delete(resourceGroup, accountName, poolName, volumeName, snapshotName);
retry = false;
}
catch
{
co++;
if (co > retryAttempts)
{
retry = false;
}
}
}
}
}
}
| |
using System;
using System.Buffers;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Orleans.Runtime.Messaging
{
/// <summary>
/// An <see cref="IBufferWriter{T}"/> that reserves some fixed size for a header.
/// </summary>
/// <typeparam name="T">The type of element written by this writer.</typeparam>
/// <typeparam name="TBufferWriter">The type of underlying buffer writer.</typeparam>
/// <remarks>
/// This type is used for inserting the length of list in the header when the length is not known beforehand.
/// It is optimized to minimize or avoid copying.
/// </remarks>
public class PrefixingBufferWriter<T, TBufferWriter> : IBufferWriter<T>, IDisposable where TBufferWriter : IBufferWriter<T>
{
private readonly MemoryPool<T> memoryPool;
/// <summary>
/// The length of the header.
/// </summary>
private readonly int expectedPrefixSize;
/// <summary>
/// A hint from our owner at the size of the payload that follows the header.
/// </summary>
private readonly int payloadSizeHint;
/// <summary>
/// The underlying buffer writer.
/// </summary>
private TBufferWriter innerWriter;
/// <summary>
/// The memory reserved for the header from the <see cref="innerWriter"/>.
/// This memory is not reserved until the first call from this writer to acquire memory.
/// </summary>
private Memory<T> prefixMemory;
/// <summary>
/// The memory acquired from <see cref="innerWriter"/>.
/// This memory is not reserved until the first call from this writer to acquire memory.
/// </summary>
private Memory<T> realMemory;
/// <summary>
/// The number of elements written to a buffer belonging to <see cref="innerWriter"/>.
/// </summary>
private int advanced;
/// <summary>
/// The fallback writer to use when the caller writes more than we allowed for given the <see cref="payloadSizeHint"/>
/// in anything but the initial call to <see cref="GetSpan(int)"/>.
/// </summary>
private Sequence privateWriter;
/// <summary>
/// Initializes a new instance of the <see cref="PrefixingBufferWriter{T, TBufferWriter}"/> class.
/// </summary>
/// <param name="prefixSize">The length of the header to reserve space for. Must be a positive number.</param>
/// <param name="payloadSizeHint">A hint at the expected max size of the payload. The real size may be more or less than this, but additional copying is avoided if it does not exceed this amount. If 0, a reasonable guess is made.</param>
/// <param name="memoryPool"></param>
public PrefixingBufferWriter(int prefixSize, int payloadSizeHint, MemoryPool<T> memoryPool)
{
if (prefixSize <= 0)
{
ThrowPrefixSize();
}
this.expectedPrefixSize = prefixSize;
this.payloadSizeHint = payloadSizeHint;
this.memoryPool = memoryPool;
void ThrowPrefixSize() => throw new ArgumentOutOfRangeException(nameof(prefixSize));
}
public int CommittedBytes { get; private set; }
/// <inheritdoc />
public void Advance(int count)
{
if (this.privateWriter != null)
{
this.privateWriter.Advance(count);
}
else
{
this.advanced += count;
}
this.CommittedBytes += count;
}
/// <inheritdoc />
public Memory<T> GetMemory(int sizeHint = 0)
{
this.EnsureInitialized(sizeHint);
if (this.privateWriter != null || sizeHint > this.realMemory.Length - this.advanced)
{
if (this.privateWriter == null)
{
this.privateWriter = new Sequence(this.memoryPool);
}
return this.privateWriter.GetMemory(sizeHint);
}
else
{
return this.realMemory.Slice(this.advanced);
}
}
/// <inheritdoc />
public Span<T> GetSpan(int sizeHint = 0)
{
this.EnsureInitialized(sizeHint);
if (this.privateWriter != null || sizeHint > this.realMemory.Length - this.advanced)
{
if (this.privateWriter == null)
{
this.privateWriter = new Sequence(this.memoryPool);
}
return this.privateWriter.GetSpan(sizeHint);
}
else
{
return this.realMemory.Span.Slice(this.advanced);
}
}
/// <summary>
/// Inserts the prefix and commits the payload to the underlying <see cref="IBufferWriter{T}"/>.
/// </summary>
/// <param name="prefix">The prefix to write in. The length must match the one given in the constructor.</param>
public void Complete(ReadOnlySpan<T> prefix)
{
if (prefix.Length != this.expectedPrefixSize)
{
ThrowPrefixLength();
void ThrowPrefixLength() => throw new ArgumentOutOfRangeException(nameof(prefix), "Prefix was not expected length.");
}
if (this.prefixMemory.Length == 0)
{
// No payload was actually written, and we never requested memory, so just write it out.
this.innerWriter.Write(prefix);
}
else
{
// Payload has been written, so write in the prefix then commit the payload.
prefix.CopyTo(this.prefixMemory.Span);
this.innerWriter.Advance(prefix.Length + this.advanced);
if (this.privateWriter != null)
{
// Try to minimize segments in the target writer by hinting at the total size.
this.innerWriter.GetSpan((int)this.privateWriter.Length);
foreach (var segment in this.privateWriter.AsReadOnlySequence)
{
this.innerWriter.Write(segment.Span);
}
}
}
}
/// <summary>
/// Resets this instance to a reusable state.
/// </summary>
/// <param name="writer">The underlying writer that should ultimately receive the prefix and payload.</param>
public void Reset(TBufferWriter writer)
{
this.advanced = 0;
this.CommittedBytes = 0;
this.privateWriter?.Dispose();
this.privateWriter = null;
this.prefixMemory = default;
this.realMemory = default;
if (writer.Equals(default(TBufferWriter))) ThrowInnerWriter();
void ThrowInnerWriter() => throw new ArgumentNullException(nameof(writer));
this.innerWriter = writer;
}
public void Dispose()
{
this.privateWriter?.Dispose();
}
/// <summary>
/// Makes the initial call to acquire memory from the underlying writer if it has not been done already.
/// </summary>
/// <param name="sizeHint">The size requested by the caller to either <see cref="GetMemory(int)"/> or <see cref="GetSpan(int)"/>.</param>
private void EnsureInitialized(int sizeHint)
{
if (this.prefixMemory.Length == 0)
{
int sizeToRequest = this.expectedPrefixSize + Math.Max(sizeHint, this.payloadSizeHint);
var memory = this.innerWriter.GetMemory(sizeToRequest);
this.prefixMemory = memory.Slice(0, this.expectedPrefixSize);
this.realMemory = memory.Slice(this.expectedPrefixSize);
}
}
/// <summary>
/// Manages a sequence of elements, readily castable as a <see cref="ReadOnlySequence{T}"/>.
/// </summary>
/// <remarks>
/// Instance members are not thread-safe.
/// </remarks>
[DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")]
public class Sequence : IBufferWriter<T>, IDisposable
{
private const int DefaultBufferSize = 4 * 1024;
private readonly Stack<SequenceSegment> segmentPool = new Stack<SequenceSegment>();
private readonly MemoryPool<T> memoryPool;
private SequenceSegment first;
private SequenceSegment last;
/// <summary>
/// Initializes a new instance of the <see cref="Sequence"/> class.
/// </summary>
/// <param name="memoryPool">The pool to use for recycling backing arrays.</param>
public Sequence(MemoryPool<T> memoryPool)
{
this.memoryPool = memoryPool ?? ThrowNull();
MemoryPool<T> ThrowNull() => throw new ArgumentNullException(nameof(memoryPool));
}
/// <summary>
/// Gets this sequence expressed as a <see cref="ReadOnlySequence{T}"/>.
/// </summary>
/// <returns>A read only sequence representing the data in this object.</returns>
public ReadOnlySequence<T> AsReadOnlySequence => this;
/// <summary>
/// Gets the length of the sequence.
/// </summary>
public long Length => this.AsReadOnlySequence.Length;
/// <summary>
/// Gets the value to display in a debugger datatip.
/// </summary>
private string DebuggerDisplay => $"Length: {AsReadOnlySequence.Length}";
/// <summary>
/// Expresses this sequence as a <see cref="ReadOnlySequence{T}"/>.
/// </summary>
/// <param name="sequence">The sequence to convert.</param>
public static implicit operator ReadOnlySequence<T>(Sequence sequence)
{
return sequence.first != null
? new ReadOnlySequence<T>(sequence.first, sequence.first.Start, sequence.last, sequence.last.End)
: ReadOnlySequence<T>.Empty;
}
/// <summary>
/// Removes all elements from the sequence from its beginning to the specified position,
/// considering that data to have been fully processed.
/// </summary>
/// <param name="position">
/// The position of the first element that has not yet been processed.
/// This is typically <see cref="ReadOnlySequence{T}.End"/> after reading all elements from that instance.
/// </param>
public void AdvanceTo(SequencePosition position)
{
var firstSegment = (SequenceSegment)position.GetObject();
int firstIndex = position.GetInteger();
// Before making any mutations, confirm that the block specified belongs to this sequence.
var current = this.first;
while (current != firstSegment && current != null)
{
current = current.Next;
}
if (current == null) ThrowCurrentNull();
void ThrowCurrentNull() => throw new ArgumentException("Position does not represent a valid position in this sequence.", nameof(position));
// Also confirm that the position is not a prior position in the block.
if (firstIndex < current.Start) ThrowEarlierPosition();
void ThrowEarlierPosition() => throw new ArgumentException("Position must not be earlier than current position.", nameof(position));
// Now repeat the loop, performing the mutations.
current = this.first;
while (current != firstSegment)
{
var next = current.Next;
current.ResetMemory();
current = next;
}
firstSegment.AdvanceTo(firstIndex);
if (firstSegment.Length == 0)
{
firstSegment = this.RecycleAndGetNext(firstSegment);
}
this.first = firstSegment;
if (this.first == null)
{
this.last = null;
}
}
/// <summary>
/// Advances the sequence to include the specified number of elements initialized into memory
/// returned by a prior call to <see cref="GetMemory(int)"/>.
/// </summary>
/// <param name="count">The number of elements written into memory.</param>
public void Advance(int count)
{
if (count < 0) ThrowNegative();
this.last.End += count;
void ThrowNegative() => throw new ArgumentOutOfRangeException(
nameof(count),
"Value must be greater than or equal to 0");
}
/// <summary>
/// Gets writable memory that can be initialized and added to the sequence via a subsequent call to <see cref="Advance(int)"/>.
/// </summary>
/// <param name="sizeHint">The size of the memory required, or 0 to just get a convenient (non-empty) buffer.</param>
/// <returns>The requested memory.</returns>
public Memory<T> GetMemory(int sizeHint)
{
if (sizeHint < 0) ThrowNegative();
if (sizeHint == 0)
{
if (this.last?.WritableBytes > 0)
{
sizeHint = this.last.WritableBytes;
}
else
{
sizeHint = DefaultBufferSize;
}
}
if (this.last == null || this.last.WritableBytes < sizeHint)
{
this.Append(this.memoryPool.Rent(Math.Min(sizeHint, this.memoryPool.MaxBufferSize)));
}
return this.last.TrailingSlack;
void ThrowNegative() => throw new ArgumentOutOfRangeException(
nameof(sizeHint),
"Value for must be greater than or equal to 0");
}
/// <summary>
/// Gets writable memory that can be initialized and added to the sequence via a subsequent call to <see cref="Advance(int)"/>.
/// </summary>
/// <param name="sizeHint">The size of the memory required, or 0 to just get a convenient (non-empty) buffer.</param>
/// <returns>The requested memory.</returns>
public Span<T> GetSpan(int sizeHint) => this.GetMemory(sizeHint).Span;
/// <summary>
/// Clears the entire sequence, recycles associated memory into pools,
/// and resets this instance for reuse.
/// This invalidates any <see cref="ReadOnlySequence{T}"/> previously produced by this instance.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public void Dispose() => this.Reset();
/// <summary>
/// Clears the entire sequence and recycles associated memory into pools.
/// This invalidates any <see cref="ReadOnlySequence{T}"/> previously produced by this instance.
/// </summary>
public void Reset()
{
var current = this.first;
while (current != null)
{
current = this.RecycleAndGetNext(current);
}
this.first = this.last = null;
}
private void Append(IMemoryOwner<T> array)
{
if (array == null) ThrowNull();
var segment = this.segmentPool.Count > 0 ? this.segmentPool.Pop() : new SequenceSegment();
segment.SetMemory(array, 0, 0);
if (this.last == null)
{
this.first = this.last = segment;
}
else
{
if (this.last.Length > 0)
{
// Add a new block.
this.last.SetNext(segment);
}
else
{
// The last block is completely unused. Replace it instead of appending to it.
var current = this.first;
if (this.first != this.last)
{
while (current.Next != this.last)
{
current = current.Next;
}
}
else
{
this.first = segment;
}
current.SetNext(segment);
this.RecycleAndGetNext(this.last);
}
this.last = segment;
}
void ThrowNull() => throw new ArgumentNullException(nameof(array));
}
private SequenceSegment RecycleAndGetNext(SequenceSegment segment)
{
var recycledSegment = segment;
segment = segment.Next;
recycledSegment.ResetMemory();
this.segmentPool.Push(recycledSegment);
return segment;
}
private class SequenceSegment : ReadOnlySequenceSegment<T>
{
/// <summary>
/// Backing field for the <see cref="End"/> property.
/// </summary>
private int end;
/// <summary>
/// Gets the index of the first element in <see cref="AvailableMemory"/> to consider part of the sequence.
/// </summary>
/// <remarks>
/// The <see cref="Start"/> represents the offset into <see cref="AvailableMemory"/> where the range of "active" bytes begins. At the point when the block is leased
/// the <see cref="Start"/> is guaranteed to be equal to 0. The value of <see cref="Start"/> may be assigned anywhere between 0 and
/// <see cref="AvailableMemory"/>.Length, and must be equal to or less than <see cref="End"/>.
/// </remarks>
internal int Start { get; private set; }
/// <summary>
/// Gets or sets the index of the element just beyond the end in <see cref="AvailableMemory"/> to consider part of the sequence.
/// </summary>
/// <remarks>
/// The <see cref="End"/> represents the offset into <see cref="AvailableMemory"/> where the range of "active" bytes ends. At the point when the block is leased
/// the <see cref="End"/> is guaranteed to be equal to <see cref="Start"/>. The value of <see cref="Start"/> may be assigned anywhere between 0 and
/// <see cref="AvailableMemory"/>.Length, and must be equal to or less than <see cref="End"/>.
/// </remarks>
internal int End
{
get => this.end;
set
{
if (value > this.AvailableMemory.Length) ThrowOutOfRange();
this.end = value;
// If we ever support creating these instances on existing arrays, such that
// this.Start isn't 0 at the beginning, we'll have to "pin" this.Start and remove
// Advance, forcing Sequence<T> itself to track it, the way Pipe does it internally.
this.Memory = this.AvailableMemory.Slice(0, value);
void ThrowOutOfRange() =>
throw new ArgumentOutOfRangeException(nameof(value), "Value must be less than or equal to AvailableMemory.Length");
}
}
internal Memory<T> TrailingSlack => this.AvailableMemory.Slice(this.End);
internal IMemoryOwner<T> MemoryOwner { get; private set; }
internal Memory<T> AvailableMemory { get; private set; }
internal int Length => this.End - this.Start;
/// <summary>
/// Gets the amount of writable bytes in this segment.
/// It is the amount of bytes between <see cref="Length"/> and <see cref="End"/>.
/// </summary>
internal int WritableBytes
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => this.AvailableMemory.Length - this.End;
}
internal new SequenceSegment Next
{
get => (SequenceSegment)base.Next;
set => base.Next = value;
}
internal void SetMemory(IMemoryOwner<T> memoryOwner)
{
this.SetMemory(memoryOwner, 0, memoryOwner.Memory.Length);
}
internal void SetMemory(IMemoryOwner<T> memoryOwner, int start, int end)
{
this.MemoryOwner = memoryOwner;
this.AvailableMemory = this.MemoryOwner.Memory;
this.RunningIndex = 0;
this.Start = start;
this.End = end;
this.Next = null;
}
internal void ResetMemory()
{
this.MemoryOwner.Dispose();
this.MemoryOwner = null;
this.AvailableMemory = default;
this.Memory = default;
this.Next = null;
this.Start = 0;
this.end = 0;
}
internal void SetNext(SequenceSegment segment)
{
if (segment == null) ThrowNull();
this.Next = segment;
segment.RunningIndex = this.RunningIndex + this.End;
SequenceSegment ThrowNull() => throw new ArgumentNullException(nameof(segment));
}
internal void AdvanceTo(int offset)
{
if (offset > this.End) ThrowOutOfRange();
this.Start = offset;
void ThrowOutOfRange() => throw new ArgumentOutOfRangeException(nameof(offset));
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using umbraco.cms.businesslogic.macro;
using System.Web;
namespace umbraco.presentation.templateControls
{
[DefaultProperty("Alias")]
[ToolboxData("<{0}:Macro runat=server></{0}:Macro>")]
[PersistChildren(false)]
[ParseChildren(true, "Text")]
public class Macro : WebControl, ITextControl
{
private Hashtable m_Attributes = new Hashtable();
private string m_Code = String.Empty;
public Hashtable MacroAttributes
{
get
{
// Hashtable attributes = (Hashtable)ViewState["Attributes"];
return m_Attributes;
}
set
{
m_Attributes = value;
}
}
[Bindable(true)]
[Category("Umbraco")]
[DefaultValue("")]
[Localizable(true)]
public string Alias
{
get
{
String s = (String)ViewState["Alias"];
return ((s == null) ? String.Empty : s);
}
set
{
ViewState["Alias"] = value;
}
}
[Bindable(true)]
[Category("Umbraco")]
[DefaultValue("")]
[Localizable(true)]
public string Language {
get {
var s = (String)ViewState["Language"];
return (s ?? String.Empty);
}
set {
ViewState["Language"] = value.ToLower();
}
}
[Bindable(true)]
[Category("Umbraco")]
[DefaultValue("")]
[Localizable(true)]
public string FileLocation {
get {
var s = (String)ViewState["FileLocation"];
return (s ?? String.Empty);
}
set {
ViewState["FileLocation"] = value.ToLower();
}
}
[Bindable(true)]
[Category("Umbraco")]
[DefaultValue(RenderEvents.Init)]
[Localizable(true)]
public RenderEvents RenderEvent
{
get
{
RenderEvents renderEvent = RenderEvents.Init;
if (ViewState["RenderEvent"] != null)
renderEvent = (RenderEvents)ViewState["RenderEvent"];
return renderEvent;
}
set
{
ViewState["RenderEvent"] = value;
}
}
// Indicates where to run EnsureChildControls and effectively render the macro
public enum RenderEvents
{
Init,
PreRender,
Render
}
public IList<Exception> Exceptions = new List<Exception>();
/// <summary>
/// Raises the <see cref="E:System.Web.UI.Control.Init"/> event.
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
protected override void OnInit(EventArgs e) {
base.OnInit(e);
// Create child controls when told to - this is the default
if (this.RenderEvent == RenderEvents.Init)
EnsureChildControls();
}
// Create child controls when told to - new option to render at PreRender
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (this.RenderEvent == RenderEvents.PreRender)
EnsureChildControls();
}
/// <summary>
/// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
/// </summary>
protected override void CreateChildControls() {
// collect all attributes set on the control
var keys = Attributes.Keys;
foreach (string key in keys)
MacroAttributes.Add(key.ToLower(), HttpUtility.HtmlDecode(Attributes[key]));
if (!MacroAttributes.ContainsKey("macroalias") && !MacroAttributes.ContainsKey("macroAlias"))
MacroAttributes.Add("macroalias", Alias);
// set pageId to int.MinValue if no pageID was found,
// e.g. if the macro was rendered on a custom (non-Umbraco) page
int pageId = Context.Items["pageID"] == null ? int.MinValue : int.Parse(Context.Items["pageID"].ToString());
if ((!String.IsNullOrEmpty(Language) && Text != "") || !string.IsNullOrEmpty(FileLocation)) {
var tempMacro = new macro();
tempMacro.GenerateMacroModelPropertiesFromAttributes(MacroAttributes);
if (string.IsNullOrEmpty(FileLocation)) {
tempMacro.Model.ScriptCode = Text;
tempMacro.Model.ScriptLanguage = Language;
} else {
tempMacro.Model.ScriptName = FileLocation;
}
tempMacro.Model.MacroType = MacroTypes.Script;
if (!String.IsNullOrEmpty(Attributes["Cache"])) {
var cacheDuration = 0;
if (int.TryParse(Attributes["Cache"], out cacheDuration))
tempMacro.Model.CacheDuration = cacheDuration;
else
System.Web.HttpContext.Current.Trace.Warn("Template", "Cache attribute is in incorect format (should be an integer).");
}
var c = tempMacro.renderMacro((Hashtable)Context.Items["pageElements"], pageId);
if (c != null)
{
Exceptions = tempMacro.Exceptions;
Controls.Add(c);
}
else
System.Web.HttpContext.Current.Trace.Warn("Template", "Result of inline macro scripting is null");
} else {
var tempMacro = macro.GetMacro(Alias);
if (tempMacro != null) {
try {
var c = tempMacro.renderMacro(MacroAttributes, (Hashtable)Context.Items["pageElements"], pageId);
if (c != null)
Controls.Add(c);
else
System.Web.HttpContext.Current.Trace.Warn("Template", "Result of macro " + tempMacro.Name + " is null");
} catch (Exception ee) {
System.Web.HttpContext.Current.Trace.Warn("Template", "Error adding macro " + tempMacro.Name, ee);
throw;
}
}
}
}
/// <summary>
/// Renders the control to the specified HTML writer.
/// </summary>
/// <param name="writer">The <see cref="T:System.Web.UI.HtmlTextWriter"/> object that receives the control content.</param>
protected override void Render(HtmlTextWriter writer)
{
// Create child controls when told to - do it here anyway as it has to be done
EnsureChildControls();
bool isDebug = GlobalSettings.DebugMode && (helper.Request("umbdebugshowtrace") != "" || helper.Request("umbdebug") != "");
if (isDebug)
{
writer.Write("<div title=\"Macro Tag: '{0}'\" style=\"border: 1px solid #009;\">", Alias);
}
base.RenderChildren(writer);
if (isDebug)
{
writer.Write("</div>");
}
}
public string Text
{
get { return m_Code; }
set { m_Code = value; }
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Xml;
using System.Net;
using System.IO;
namespace DMatlabIDE
{
/// <summary>
/// Summary description for MachineSettings.
/// </summary>
public class MachineSettings : System.Windows.Forms.Form
{
private System.Windows.Forms.ListView processorslist;
private System.Windows.Forms.ColumnHeader IpAddress;
private System.Windows.Forms.TextBox addipaddress;
private System.Windows.Forms.TextBox addport;
private System.Windows.Forms.Button b_add;
private System.Windows.Forms.Button b_remove;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.NumericUpDown matmemsize;
private System.Windows.Forms.NumericUpDown threadstacksize;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Button b_ok;
private System.Windows.Forms.Button b_cancel;
private System.Windows.Forms.ColumnHeader Port;
private System.Windows.Forms.Panel panel3;
private System.Windows.Forms.Panel panel4;
private System.Windows.Forms.Panel panel5;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.ListView deviceslist;
private System.Windows.Forms.Button b_rmdevice;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.ColumnHeader columnHeader2;
private System.Windows.Forms.Button adddevice;
private System.Windows.Forms.TextBox adddport;
private System.Windows.Forms.TextBox adddname;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public MachineSettings()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region 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.processorslist = new System.Windows.Forms.ListView();
this.IpAddress = new System.Windows.Forms.ColumnHeader();
this.Port = new System.Windows.Forms.ColumnHeader();
this.addipaddress = new System.Windows.Forms.TextBox();
this.addport = new System.Windows.Forms.TextBox();
this.b_add = new System.Windows.Forms.Button();
this.b_remove = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.matmemsize = new System.Windows.Forms.NumericUpDown();
this.threadstacksize = new System.Windows.Forms.NumericUpDown();
this.panel1 = new System.Windows.Forms.Panel();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.panel2 = new System.Windows.Forms.Panel();
this.b_ok = new System.Windows.Forms.Button();
this.b_cancel = new System.Windows.Forms.Button();
this.panel3 = new System.Windows.Forms.Panel();
this.panel4 = new System.Windows.Forms.Panel();
this.panel5 = new System.Windows.Forms.Panel();
this.adddport = new System.Windows.Forms.TextBox();
this.adddname = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.adddevice = new System.Windows.Forms.Button();
this.deviceslist = new System.Windows.Forms.ListView();
this.b_rmdevice = new System.Windows.Forms.Button();
this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
((System.ComponentModel.ISupportInitialize)(this.matmemsize)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.threadstacksize)).BeginInit();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
this.panel3.SuspendLayout();
this.panel4.SuspendLayout();
this.panel5.SuspendLayout();
this.SuspendLayout();
//
// processorslist
//
this.processorslist.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.IpAddress,
this.Port});
this.processorslist.FullRowSelect = true;
this.processorslist.Location = new System.Drawing.Point(8, 8);
this.processorslist.Name = "processorslist";
this.processorslist.Size = new System.Drawing.Size(240, 104);
this.processorslist.TabIndex = 0;
this.processorslist.View = System.Windows.Forms.View.Details;
this.processorslist.SelectedIndexChanged += new System.EventHandler(this.processorslist_SelectedIndexChanged);
//
// IpAddress
//
this.IpAddress.Text = "Ip Address";
this.IpAddress.Width = 143;
//
// Port
//
this.Port.Text = "Port";
//
// addipaddress
//
this.addipaddress.Location = new System.Drawing.Point(67, 6);
this.addipaddress.Name = "addipaddress";
this.addipaddress.Size = new System.Drawing.Size(109, 20);
this.addipaddress.TabIndex = 3;
this.addipaddress.Text = "";
//
// addport
//
this.addport.Location = new System.Drawing.Point(217, 6);
this.addport.Name = "addport";
this.addport.Size = new System.Drawing.Size(64, 20);
this.addport.TabIndex = 4;
this.addport.Text = "";
//
// b_add
//
this.b_add.Location = new System.Drawing.Point(293, 6);
this.b_add.Name = "b_add";
this.b_add.Size = new System.Drawing.Size(56, 20);
this.b_add.TabIndex = 5;
this.b_add.Text = "Add";
this.b_add.Click += new System.EventHandler(this.b_add_Click);
//
// b_remove
//
this.b_remove.Location = new System.Drawing.Point(264, 24);
this.b_remove.Name = "b_remove";
this.b_remove.Size = new System.Drawing.Size(72, 72);
this.b_remove.TabIndex = 6;
this.b_remove.Text = "Remove";
this.b_remove.Click += new System.EventHandler(this.b_remove_Click);
//
// label1
//
this.label1.Location = new System.Drawing.Point(7, 12);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(104, 20);
this.label1.TabIndex = 7;
this.label1.Text = "Matrix Memory Size";
//
// label2
//
this.label2.Location = new System.Drawing.Point(183, 12);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(104, 20);
this.label2.TabIndex = 8;
this.label2.Text = "Thread Stack Size";
//
// matmemsize
//
this.matmemsize.Location = new System.Drawing.Point(111, 12);
this.matmemsize.Maximum = new System.Decimal(new int[] {
500,
0,
0,
0});
this.matmemsize.Minimum = new System.Decimal(new int[] {
10,
0,
0,
0});
this.matmemsize.Name = "matmemsize";
this.matmemsize.Size = new System.Drawing.Size(64, 20);
this.matmemsize.TabIndex = 9;
this.matmemsize.Value = new System.Decimal(new int[] {
10,
0,
0,
0});
//
// threadstacksize
//
this.threadstacksize.Location = new System.Drawing.Point(287, 12);
this.threadstacksize.Maximum = new System.Decimal(new int[] {
200,
0,
0,
0});
this.threadstacksize.Minimum = new System.Decimal(new int[] {
20,
0,
0,
0});
this.threadstacksize.Name = "threadstacksize";
this.threadstacksize.Size = new System.Drawing.Size(64, 20);
this.threadstacksize.TabIndex = 10;
this.threadstacksize.Value = new System.Decimal(new int[] {
21,
0,
0,
0});
//
// panel1
//
this.panel1.Controls.Add(this.matmemsize);
this.panel1.Controls.Add(this.label2);
this.panel1.Controls.Add(this.threadstacksize);
this.panel1.Controls.Add(this.label1);
this.panel1.Location = new System.Drawing.Point(8, 8);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(352, 40);
this.panel1.TabIndex = 11;
//
// label3
//
this.label3.Location = new System.Drawing.Point(186, 8);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(48, 16);
this.label3.TabIndex = 12;
this.label3.Text = "Port";
//
// label4
//
this.label4.Location = new System.Drawing.Point(6, 8);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(72, 16);
this.label4.TabIndex = 13;
this.label4.Text = "Ip Address";
//
// panel2
//
this.panel2.Controls.Add(this.addport);
this.panel2.Controls.Add(this.addipaddress);
this.panel2.Controls.Add(this.label4);
this.panel2.Controls.Add(this.label3);
this.panel2.Controls.Add(this.b_add);
this.panel2.Location = new System.Drawing.Point(0, 112);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(352, 32);
this.panel2.TabIndex = 14;
//
// b_ok
//
this.b_ok.Location = new System.Drawing.Point(192, 376);
this.b_ok.Name = "b_ok";
this.b_ok.Size = new System.Drawing.Size(72, 20);
this.b_ok.TabIndex = 15;
this.b_ok.Text = "OK";
this.b_ok.Click += new System.EventHandler(this.b_ok_Click);
//
// b_cancel
//
this.b_cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.b_cancel.Location = new System.Drawing.Point(272, 376);
this.b_cancel.Name = "b_cancel";
this.b_cancel.Size = new System.Drawing.Size(72, 20);
this.b_cancel.TabIndex = 16;
this.b_cancel.Text = "Cancel";
this.b_cancel.Click += new System.EventHandler(this.b_cancel_Click);
//
// panel3
//
this.panel3.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.panel3.Controls.Add(this.panel2);
this.panel3.Controls.Add(this.processorslist);
this.panel3.Controls.Add(this.b_remove);
this.panel3.Location = new System.Drawing.Point(8, 56);
this.panel3.Name = "panel3";
this.panel3.Size = new System.Drawing.Size(360, 152);
this.panel3.TabIndex = 17;
//
// panel4
//
this.panel4.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.panel4.Controls.Add(this.panel5);
this.panel4.Controls.Add(this.deviceslist);
this.panel4.Controls.Add(this.b_rmdevice);
this.panel4.Location = new System.Drawing.Point(8, 216);
this.panel4.Name = "panel4";
this.panel4.Size = new System.Drawing.Size(360, 152);
this.panel4.TabIndex = 18;
//
// panel5
//
this.panel5.Controls.Add(this.adddport);
this.panel5.Controls.Add(this.adddname);
this.panel5.Controls.Add(this.label5);
this.panel5.Controls.Add(this.label6);
this.panel5.Controls.Add(this.adddevice);
this.panel5.Location = new System.Drawing.Point(0, 112);
this.panel5.Name = "panel5";
this.panel5.Size = new System.Drawing.Size(352, 32);
this.panel5.TabIndex = 14;
//
// adddport
//
this.adddport.Location = new System.Drawing.Point(224, 6);
this.adddport.Name = "adddport";
this.adddport.Size = new System.Drawing.Size(48, 20);
this.adddport.TabIndex = 4;
this.adddport.Text = "";
//
// adddname
//
this.adddname.Location = new System.Drawing.Point(80, 6);
this.adddname.Name = "adddname";
this.adddname.Size = new System.Drawing.Size(96, 20);
this.adddname.TabIndex = 3;
this.adddname.Text = "";
//
// label5
//
this.label5.Location = new System.Drawing.Point(6, 8);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(72, 16);
this.label5.TabIndex = 13;
this.label5.Text = "Device Name";
//
// label6
//
this.label6.Location = new System.Drawing.Point(192, 8);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(48, 16);
this.label6.TabIndex = 12;
this.label6.Text = "Port";
//
// adddevice
//
this.adddevice.Location = new System.Drawing.Point(293, 6);
this.adddevice.Name = "adddevice";
this.adddevice.Size = new System.Drawing.Size(56, 20);
this.adddevice.TabIndex = 5;
this.adddevice.Text = "Add";
this.adddevice.Click += new System.EventHandler(this.adddevice_Click);
//
// deviceslist
//
this.deviceslist.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1,
this.columnHeader2});
this.deviceslist.FullRowSelect = true;
this.deviceslist.Location = new System.Drawing.Point(8, 8);
this.deviceslist.Name = "deviceslist";
this.deviceslist.Size = new System.Drawing.Size(240, 104);
this.deviceslist.TabIndex = 0;
this.deviceslist.View = System.Windows.Forms.View.Details;
this.deviceslist.SelectedIndexChanged += new System.EventHandler(this.deviceslist_SelectedIndexChanged);
//
// b_rmdevice
//
this.b_rmdevice.Location = new System.Drawing.Point(264, 24);
this.b_rmdevice.Name = "b_rmdevice";
this.b_rmdevice.Size = new System.Drawing.Size(72, 72);
this.b_rmdevice.TabIndex = 6;
this.b_rmdevice.Text = "Remove";
this.b_rmdevice.Click += new System.EventHandler(this.b_rmdevice_Click);
//
// columnHeader1
//
this.columnHeader1.Text = "Device Name";
this.columnHeader1.Width = 143;
//
// columnHeader2
//
this.columnHeader2.Text = "Port";
//
// MachineSettings
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(374, 404);
this.ControlBox = false;
this.Controls.Add(this.panel4);
this.Controls.Add(this.panel3);
this.Controls.Add(this.panel1);
this.Controls.Add(this.b_ok);
this.Controls.Add(this.b_cancel);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "MachineSettings";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "LocalMachine Settings";
this.Load += new System.EventHandler(this.MachineSettings_Load);
((System.ComponentModel.ISupportInitialize)(this.matmemsize)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.threadstacksize)).EndInit();
this.panel1.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.panel3.ResumeLayout(false);
this.panel4.ResumeLayout(false);
this.panel5.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void MachineSettings_Load(object sender, System.EventArgs e)
{
LoadConfigs(Application.StartupPath + "\\Config.xml");
}
private void LoadConfigs(string filename){
XmlDocument doc = new XmlDocument();
doc.Load(filename);
// MessageBox.Show( doc.SelectSingleNode("Configurations").NodeType.ToString());
try
{
matmemsize.Value = int.Parse((doc.SelectSingleNode("Configurations/MatrixMemorySize").InnerText));
}
catch(Exception e)
{
matmemsize.Value=20;
MessageBox.Show("There are some errors in config file.","Settings",
MessageBoxButtons.OK,MessageBoxIcon.Information);
}
try
{
threadstacksize.Value = int.Parse((doc.SelectSingleNode("Configurations/ThreadStackSize").InnerText));
}
catch(Exception e)
{
threadstacksize.Value=20;
MessageBox.Show("There are some errors in config file.","Settings",
MessageBoxButtons.OK,MessageBoxIcon.Information);
}
XmlNodeList prs = doc.SelectNodes("Configurations/RemoteProcessor");
processorslist.Items.Clear();
foreach(XmlNode tmpnode in prs){
try
{
ListViewItem tmpitm = processorslist.Items.Add(
tmpnode.SelectSingleNode("IPAddress").InnerText);
tmpitm.SubItems.Add(tmpnode.SelectSingleNode("Port").InnerText);
}
catch(Exception e){
MessageBox.Show(e.Message ,"Settings",
MessageBoxButtons.OK,MessageBoxIcon.Information);
}
}
prs = doc.SelectNodes("Configurations/ExternalDevice");
deviceslist.Items.Clear();
foreach(XmlNode tmpnode in prs)
{
try
{
ListViewItem tmpitm = deviceslist.Items.Add(
tmpnode.SelectSingleNode("Name").InnerText);
tmpitm.SubItems.Add(tmpnode.SelectSingleNode("Port").InnerText);
}
catch(Exception e)
{
MessageBox.Show(e.Message ,"Settings",
MessageBoxButtons.OK,MessageBoxIcon.Information);
}
}
}
private void b_cancel_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void b_add_Click(object sender, System.EventArgs e)
{
addport.Text =addport.Text.Trim();
addipaddress.Text =addipaddress.Text.Trim();
if(addport.Text!= "" && addipaddress.Text!="")
{
try
{
IPAddress.Parse(addipaddress.Text);
addport.Text= uint.Parse(addport.Text).ToString();
ListViewItem tmp= processorslist.Items.Add(addipaddress.Text);
tmp.SubItems.Add(addport.Text);
}
catch(Exception exc)
{
MessageBox.Show("Invalid IpAddress or port number.","Settings",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
}
private void b_remove_Click(object sender, System.EventArgs e)
{
foreach(ListViewItem itm in processorslist.SelectedItems){
processorslist.Items.Remove(itm);
}
}
private void b_ok_Click(object sender, System.EventArgs e)
{
string s;
s = "<Configurations>\n";
s +="<MatrixMemorySize>" + matmemsize.Value.ToString() + "</MatrixMemorySize>\n";
s +="<ThreadStackSize>" + threadstacksize.Value.ToString() + "</ThreadStackSize>\n";
foreach(ListViewItem itm in processorslist.Items){
s +="<RemoteProcessor><IPAddress>" + itm.Text + "</IPAddress>";
s +="<Port>" + itm.SubItems[1].Text + "</Port></RemoteProcessor>\n";
}
foreach(ListViewItem itm in deviceslist.Items)
{
s +="<ExternalDevice><Name>" + itm.Text + "</Name>";
s +="<Port>" + itm.SubItems[1].Text + "</Port></ExternalDevice>\n";
}
s += "</Configurations>";
//FileStream fs = File.Open(,FileMode.Create,FileAccess.Write);
StreamWriter stm = new StreamWriter(Application.StartupPath + "\\Config.xml",false);
stm.Write(s);
stm.Close();
this.Close();
}
private void processorslist_SelectedIndexChanged(object sender, System.EventArgs e)
{
if(processorslist.SelectedItems.Count>0){
addipaddress.Text = processorslist.SelectedItems[0].Text;
addport.Text = processorslist.SelectedItems[0].SubItems[1].Text;
}
}
private void deviceslist_SelectedIndexChanged(object sender, System.EventArgs e)
{
if(deviceslist.SelectedItems.Count>0)
{
adddname.Text =deviceslist.SelectedItems[0].Text;
adddport.Text = deviceslist.SelectedItems[0].SubItems[1].Text;
}
}
private void adddevice_Click(object sender, System.EventArgs e)
{
adddport.Text =adddport.Text.Trim();
adddname.Text =adddname.Text.Trim();
if(adddport.Text!= "" && adddname.Text!="")
{
adddport.Text= uint.Parse(adddport.Text).ToString();
ListViewItem tmp= deviceslist.Items.Add(adddname.Text);
tmp.SubItems.Add(adddport.Text);
}
}
private void b_rmdevice_Click(object sender, System.EventArgs e)
{
foreach(ListViewItem itm in deviceslist.SelectedItems)
{
deviceslist.Items.Remove(itm);
}
}
}
}
| |
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
Licensed under the Oculus Utilities SDK License Version 1.31 (the "License"); you may not use
the Utilities SDK except in compliance with the License, which is provided at the time of installation
or download, or which otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/utilities-1.31
Unless required by applicable law or agreed to in writing, the Utilities SDK distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
ANY KIND, either express or implied. See the License for the specific language governing
permissions and limitations under the License.
************************************************************************************/
#if USING_XR_MANAGEMENT && USING_XR_SDK_OCULUS
#define USING_XR_SDK
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_2017_2_OR_NEWER
using InputTracking = UnityEngine.XR.InputTracking;
using Node = UnityEngine.XR.XRNode;
#else
using InputTracking = UnityEngine.VR.InputTracking;
using Node = UnityEngine.VR.VRNode;
#endif
/// <summary>
/// A head-tracked stereoscopic virtual reality camera rig.
/// </summary>
[ExecuteInEditMode]
public class OVRCameraRig : MonoBehaviour
{
/// <summary>
/// The left eye camera.
/// </summary>
public Camera leftEyeCamera { get { return (usePerEyeCameras) ? _leftEyeCamera : _centerEyeCamera; } }
/// <summary>
/// The right eye camera.
/// </summary>
public Camera rightEyeCamera { get { return (usePerEyeCameras) ? _rightEyeCamera : _centerEyeCamera; } }
/// <summary>
/// Provides a root transform for all anchors in tracking space.
/// </summary>
public Transform trackingSpace { get; private set; }
/// <summary>
/// Always coincides with the pose of the left eye.
/// </summary>
public Transform leftEyeAnchor { get; private set; }
/// <summary>
/// Always coincides with average of the left and right eye poses.
/// </summary>
public Transform centerEyeAnchor { get; private set; }
/// <summary>
/// Always coincides with the pose of the right eye.
/// </summary>
public Transform rightEyeAnchor { get; private set; }
/// <summary>
/// Always coincides with the pose of the left hand.
/// </summary>
public Transform leftHandAnchor { get; private set; }
/// <summary>
/// Always coincides with the pose of the right hand.
/// </summary>
public Transform rightHandAnchor { get; private set; }
/// <summary>
/// Anchors controller pose to fix offset issues for the left hand.
/// </summary>
public Transform leftControllerAnchor { get; private set; }
/// <summary>
/// Anchors controller pose to fix offset issues for the right hand.
/// </summary>
public Transform rightControllerAnchor { get; private set; }
/// <summary>
/// Always coincides with the pose of the sensor.
/// </summary>
public Transform trackerAnchor { get; private set; }
/// <summary>
/// Occurs when the eye pose anchors have been set.
/// </summary>
public event System.Action<OVRCameraRig> UpdatedAnchors;
/// <summary>
/// If true, separate cameras will be used for the left and right eyes.
/// </summary>
public bool usePerEyeCameras = false;
/// <summary>
/// If true, all tracked anchors are updated in FixedUpdate instead of Update to favor physics fidelity.
/// \note: If the fixed update rate doesn't match the rendering framerate (OVRManager.display.appFramerate), the anchors will visibly judder.
/// </summary>
public bool useFixedUpdateForTracking = false;
/// <summary>
/// If true, the cameras on the eyeAnchors will be disabled.
/// \note: The main camera of the game will be used to provide VR rendering. And the tracking space anchors will still be updated to provide reference poses.
/// </summary>
public bool disableEyeAnchorCameras = false;
protected bool _skipUpdate = false;
protected readonly string trackingSpaceName = "TrackingSpace";
protected readonly string trackerAnchorName = "TrackerAnchor";
protected readonly string leftEyeAnchorName = "LeftEyeAnchor";
protected readonly string centerEyeAnchorName = "CenterEyeAnchor";
protected readonly string rightEyeAnchorName = "RightEyeAnchor";
protected readonly string leftHandAnchorName = "LeftHandAnchor";
protected readonly string rightHandAnchorName = "RightHandAnchor";
protected readonly string leftControllerAnchorName = "LeftControllerAnchor";
protected readonly string rightControllerAnchorName = "RightControllerAnchor";
protected Camera _centerEyeCamera;
protected Camera _leftEyeCamera;
protected Camera _rightEyeCamera;
#region Unity Messages
protected virtual void Awake()
{
_skipUpdate = true;
EnsureGameObjectIntegrity();
}
protected virtual void Start()
{
UpdateAnchors(true, true);
Application.onBeforeRender += OnBeforeRenderCallback;
}
protected virtual void FixedUpdate()
{
if (useFixedUpdateForTracking)
UpdateAnchors(true, true);
}
protected virtual void Update()
{
_skipUpdate = false;
if (!useFixedUpdateForTracking)
UpdateAnchors(true, true);
}
protected virtual void OnDestroy()
{
Application.onBeforeRender -= OnBeforeRenderCallback;
}
#endregion
protected virtual void UpdateAnchors(bool updateEyeAnchors, bool updateHandAnchors)
{
if (!OVRManager.OVRManagerinitialized)
return;
EnsureGameObjectIntegrity();
if (!Application.isPlaying)
return;
if (_skipUpdate)
{
centerEyeAnchor.FromOVRPose(OVRPose.identity, true);
leftEyeAnchor.FromOVRPose(OVRPose.identity, true);
rightEyeAnchor.FromOVRPose(OVRPose.identity, true);
return;
}
bool monoscopic = OVRManager.instance.monoscopic;
bool hmdPresent = OVRNodeStateProperties.IsHmdPresent();
OVRPose tracker = OVRManager.tracker.GetPose();
trackerAnchor.localRotation = tracker.orientation;
Quaternion emulatedRotation = Quaternion.Euler(-OVRManager.instance.headPoseRelativeOffsetRotation.x, -OVRManager.instance.headPoseRelativeOffsetRotation.y, OVRManager.instance.headPoseRelativeOffsetRotation.z);
//Note: in the below code, when using UnityEngine's API, we only update anchor transforms if we have a new, fresh value this frame.
//If we don't, it could mean that tracking is lost, etc. so the pose should not change in the virtual world.
//This can be thought of as similar to calling InputTracking GetLocalPosition and Rotation, but only for doing so when the pose is valid.
//If false is returned for any of these calls, then a new pose is not valid and thus should not be updated.
if (updateEyeAnchors)
{
if (hmdPresent)
{
Vector3 centerEyePosition = Vector3.zero;
Quaternion centerEyeRotation = Quaternion.identity;
if (OVRNodeStateProperties.GetNodeStatePropertyVector3(Node.CenterEye, NodeStatePropertyType.Position, OVRPlugin.Node.EyeCenter, OVRPlugin.Step.Render, out centerEyePosition))
centerEyeAnchor.localPosition = centerEyePosition;
if (OVRNodeStateProperties.GetNodeStatePropertyQuaternion(Node.CenterEye, NodeStatePropertyType.Orientation, OVRPlugin.Node.EyeCenter, OVRPlugin.Step.Render, out centerEyeRotation))
centerEyeAnchor.localRotation = centerEyeRotation;
}
else
{
centerEyeAnchor.localRotation = emulatedRotation;
centerEyeAnchor.localPosition = OVRManager.instance.headPoseRelativeOffsetTranslation;
}
if (!hmdPresent || monoscopic)
{
leftEyeAnchor.localPosition = centerEyeAnchor.localPosition;
rightEyeAnchor.localPosition = centerEyeAnchor.localPosition;
leftEyeAnchor.localRotation = centerEyeAnchor.localRotation;
rightEyeAnchor.localRotation = centerEyeAnchor.localRotation;
}
else
{
Vector3 leftEyePosition = Vector3.zero;
Vector3 rightEyePosition = Vector3.zero;
Quaternion leftEyeRotation = Quaternion.identity;
Quaternion rightEyeRotation = Quaternion.identity;
if (OVRNodeStateProperties.GetNodeStatePropertyVector3(Node.LeftEye, NodeStatePropertyType.Position, OVRPlugin.Node.EyeLeft, OVRPlugin.Step.Render, out leftEyePosition))
leftEyeAnchor.localPosition = leftEyePosition;
if (OVRNodeStateProperties.GetNodeStatePropertyVector3(Node.RightEye, NodeStatePropertyType.Position, OVRPlugin.Node.EyeRight, OVRPlugin.Step.Render, out rightEyePosition))
rightEyeAnchor.localPosition = rightEyePosition;
if (OVRNodeStateProperties.GetNodeStatePropertyQuaternion(Node.LeftEye, NodeStatePropertyType.Orientation, OVRPlugin.Node.EyeLeft, OVRPlugin.Step.Render, out leftEyeRotation))
leftEyeAnchor.localRotation = leftEyeRotation;
if (OVRNodeStateProperties.GetNodeStatePropertyQuaternion(Node.RightEye, NodeStatePropertyType.Orientation, OVRPlugin.Node.EyeRight, OVRPlugin.Step.Render, out rightEyeRotation))
rightEyeAnchor.localRotation = rightEyeRotation;
}
}
if (updateHandAnchors)
{
//Need this for controller offset because if we're on OpenVR, we want to set the local poses as specified by Unity, but if we're not, OVRInput local position is the right anchor
if (OVRManager.loadedXRDevice == OVRManager.XRDevice.OpenVR)
{
Vector3 leftPos = Vector3.zero;
Vector3 rightPos = Vector3.zero;
Quaternion leftQuat = Quaternion.identity;
Quaternion rightQuat = Quaternion.identity;
if (OVRNodeStateProperties.GetNodeStatePropertyVector3(Node.LeftHand, NodeStatePropertyType.Position, OVRPlugin.Node.HandLeft, OVRPlugin.Step.Render, out leftPos))
leftHandAnchor.localPosition = leftPos;
if (OVRNodeStateProperties.GetNodeStatePropertyVector3(Node.RightHand, NodeStatePropertyType.Position, OVRPlugin.Node.HandRight, OVRPlugin.Step.Render, out rightPos))
rightHandAnchor.localPosition = rightPos;
if (OVRNodeStateProperties.GetNodeStatePropertyQuaternion(Node.LeftHand, NodeStatePropertyType.Orientation, OVRPlugin.Node.HandLeft, OVRPlugin.Step.Render, out leftQuat))
leftHandAnchor.localRotation = leftQuat;
if (OVRNodeStateProperties.GetNodeStatePropertyQuaternion(Node.RightHand, NodeStatePropertyType.Orientation, OVRPlugin.Node.HandRight, OVRPlugin.Step.Render, out rightQuat))
rightHandAnchor.localRotation = rightQuat;
}
else
{
leftHandAnchor.localPosition = OVRInput.GetLocalControllerPosition(OVRInput.Controller.LTouch);
rightHandAnchor.localPosition = OVRInput.GetLocalControllerPosition(OVRInput.Controller.RTouch);
leftHandAnchor.localRotation = OVRInput.GetLocalControllerRotation(OVRInput.Controller.LTouch);
rightHandAnchor.localRotation = OVRInput.GetLocalControllerRotation(OVRInput.Controller.RTouch);
}
trackerAnchor.localPosition = tracker.position;
OVRPose leftOffsetPose = OVRPose.identity;
OVRPose rightOffsetPose = OVRPose.identity;
if (OVRManager.loadedXRDevice == OVRManager.XRDevice.OpenVR)
{
leftOffsetPose = OVRManager.GetOpenVRControllerOffset(Node.LeftHand);
rightOffsetPose = OVRManager.GetOpenVRControllerOffset(Node.RightHand);
//Sets poses of left and right nodes, local to the tracking space.
OVRManager.SetOpenVRLocalPose(trackingSpace.InverseTransformPoint(leftControllerAnchor.position),
trackingSpace.InverseTransformPoint(rightControllerAnchor.position),
Quaternion.Inverse(trackingSpace.rotation) * leftControllerAnchor.rotation,
Quaternion.Inverse(trackingSpace.rotation) * rightControllerAnchor.rotation);
}
rightControllerAnchor.localPosition = rightOffsetPose.position;
rightControllerAnchor.localRotation = rightOffsetPose.orientation;
leftControllerAnchor.localPosition = leftOffsetPose.position;
leftControllerAnchor.localRotation = leftOffsetPose.orientation;
}
RaiseUpdatedAnchorsEvent();
}
protected virtual void OnBeforeRenderCallback()
{
if (OVRManager.loadedXRDevice == OVRManager.XRDevice.Oculus) //Restrict late-update to only Oculus devices
{
bool controllersNeedUpdate = OVRManager.instance.LateControllerUpdate;
#if USING_XR_SDK
//For the XR SDK, we need to late update head pose, not just the controllers, because the functionality
//is no longer built-in to the Engine. Under legacy, late camera update is done by default. In the XR SDK, you must use
//Tracked Pose Driver to get this by default, which we do not use. So, we have to manually late update camera poses.
UpdateAnchors(true, controllersNeedUpdate);
#else
if (controllersNeedUpdate)
UpdateAnchors(false, true);
#endif
}
}
protected virtual void RaiseUpdatedAnchorsEvent()
{
if (UpdatedAnchors != null)
{
UpdatedAnchors(this);
}
}
public virtual void EnsureGameObjectIntegrity()
{
bool monoscopic = OVRManager.instance != null ? OVRManager.instance.monoscopic : false;
if (trackingSpace == null)
trackingSpace = ConfigureAnchor(null, trackingSpaceName);
if (leftEyeAnchor == null)
leftEyeAnchor = ConfigureAnchor(trackingSpace, leftEyeAnchorName);
if (centerEyeAnchor == null)
centerEyeAnchor = ConfigureAnchor(trackingSpace, centerEyeAnchorName);
if (rightEyeAnchor == null)
rightEyeAnchor = ConfigureAnchor(trackingSpace, rightEyeAnchorName);
if (leftHandAnchor == null)
leftHandAnchor = ConfigureAnchor(trackingSpace, leftHandAnchorName);
if (rightHandAnchor == null)
rightHandAnchor = ConfigureAnchor(trackingSpace, rightHandAnchorName);
if (trackerAnchor == null)
trackerAnchor = ConfigureAnchor(trackingSpace, trackerAnchorName);
if (leftControllerAnchor == null)
leftControllerAnchor = ConfigureAnchor(leftHandAnchor, leftControllerAnchorName);
if (rightControllerAnchor == null)
rightControllerAnchor = ConfigureAnchor(rightHandAnchor, rightControllerAnchorName);
if (_centerEyeCamera == null || _leftEyeCamera == null || _rightEyeCamera == null)
{
_centerEyeCamera = centerEyeAnchor.GetComponent<Camera>();
_leftEyeCamera = leftEyeAnchor.GetComponent<Camera>();
_rightEyeCamera = rightEyeAnchor.GetComponent<Camera>();
if (_centerEyeCamera == null)
{
_centerEyeCamera = centerEyeAnchor.gameObject.AddComponent<Camera>();
_centerEyeCamera.tag = "MainCamera";
}
if (_leftEyeCamera == null)
{
_leftEyeCamera = leftEyeAnchor.gameObject.AddComponent<Camera>();
_leftEyeCamera.tag = "MainCamera";
}
if (_rightEyeCamera == null)
{
_rightEyeCamera = rightEyeAnchor.gameObject.AddComponent<Camera>();
_rightEyeCamera.tag = "MainCamera";
}
_centerEyeCamera.stereoTargetEye = StereoTargetEyeMask.Both;
_leftEyeCamera.stereoTargetEye = StereoTargetEyeMask.Left;
_rightEyeCamera.stereoTargetEye = StereoTargetEyeMask.Right;
}
if (monoscopic && !OVRPlugin.EyeTextureArrayEnabled)
{
// Output to left eye only when in monoscopic mode
if (_centerEyeCamera.stereoTargetEye != StereoTargetEyeMask.Left)
{
_centerEyeCamera.stereoTargetEye = StereoTargetEyeMask.Left;
}
}
else
{
if (_centerEyeCamera.stereoTargetEye != StereoTargetEyeMask.Both)
{
_centerEyeCamera.stereoTargetEye = StereoTargetEyeMask.Both;
}
}
if (disableEyeAnchorCameras)
{
_centerEyeCamera.enabled = false;
_leftEyeCamera.enabled = false;
_rightEyeCamera.enabled = false;
}
else
{
// disable the right eye camera when in monoscopic mode
if (_centerEyeCamera.enabled == usePerEyeCameras ||
_leftEyeCamera.enabled == !usePerEyeCameras ||
_rightEyeCamera.enabled == !(usePerEyeCameras && (!monoscopic || OVRPlugin.EyeTextureArrayEnabled)))
{
_skipUpdate = true;
}
_centerEyeCamera.enabled = !usePerEyeCameras;
_leftEyeCamera.enabled = usePerEyeCameras;
_rightEyeCamera.enabled = (usePerEyeCameras && (!monoscopic || OVRPlugin.EyeTextureArrayEnabled));
}
}
protected virtual Transform ConfigureAnchor(Transform root, string name)
{
Transform anchor = (root != null) ? root.Find(name) : null;
if (anchor == null)
{
anchor = transform.Find(name);
}
if (anchor == null)
{
anchor = new GameObject(name).transform;
}
anchor.name = name;
anchor.parent = (root != null) ? root : transform;
anchor.localScale = Vector3.one;
anchor.localPosition = Vector3.zero;
anchor.localRotation = Quaternion.identity;
return anchor;
}
public virtual Matrix4x4 ComputeTrackReferenceMatrix()
{
if (centerEyeAnchor == null)
{
Debug.LogError("centerEyeAnchor is required");
return Matrix4x4.identity;
}
// The ideal approach would be using UnityEngine.VR.VRNode.TrackingReference, then we would not have to depend on the OVRCameraRig. Unfortunately, it is not available in Unity 5.4.3
OVRPose headPose = OVRPose.identity;
Vector3 pos;
Quaternion rot;
if (OVRNodeStateProperties.GetNodeStatePropertyVector3(Node.Head, NodeStatePropertyType.Position, OVRPlugin.Node.Head, OVRPlugin.Step.Render, out pos))
headPose.position = pos;
if (OVRNodeStateProperties.GetNodeStatePropertyQuaternion(Node.Head, NodeStatePropertyType.Orientation, OVRPlugin.Node.Head, OVRPlugin.Step.Render, out rot))
headPose.orientation = rot;
OVRPose invHeadPose = headPose.Inverse();
Matrix4x4 invHeadMatrix = Matrix4x4.TRS(invHeadPose.position, invHeadPose.orientation, Vector3.one);
Matrix4x4 ret = centerEyeAnchor.localToWorldMatrix * invHeadMatrix;
return ret;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.Azure.Management.Network;
using Microsoft.Azure.Management.Network.Models;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Compute.Tests
{
public class VMScaleSetNetworkProfileTests : VMScaleSetTestsBase
{
/// <summary>
/// Associates a VMScaleSet to an Application gateway
/// </summary>
[Fact]
public void TestVMScaleSetWithApplciationGateway()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
// Create resource group
string rgName = TestUtilities.GenerateName(TestPrefix) + 1;
var vmssName = TestUtilities.GenerateName("vmss");
string storageAccountName = TestUtilities.GenerateName(TestPrefix);
VirtualMachineScaleSet inputVMScaleSet;
bool passed = false;
try
{
var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);
var vnetResponse = CreateVNETWithSubnets(rgName, 2);
var gatewaySubnet = vnetResponse.Subnets[0];
var vmssSubnet = vnetResponse.Subnets[1];
ApplicationGateway appgw = CreateApplicationGateway(rgName, gatewaySubnet);
Microsoft.Azure.Management.Compute.Models.SubResource backendAddressPool = new Microsoft.Azure.Management.Compute.Models.SubResource()
{
Id = appgw.BackendAddressPools[0].Id
};
VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking(
rgName: rgName,
vmssName: vmssName,
storageAccount: storageAccountOutput,
imageRef: imageRef,
inputVMScaleSet: out inputVMScaleSet,
vmScaleSetCustomizer:
(virtualMachineScaleSet) =>
virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile
.NetworkInterfaceConfigurations[0].IpConfigurations[0]
.ApplicationGatewayBackendAddressPools.Add(backendAddressPool),
createWithPublicIpAddress: false,
subnet: vmssSubnet);
var getGwResponse = m_NrpClient.ApplicationGateways.Get(rgName, appgw.Name);
Assert.True(2 == getGwResponse.BackendAddressPools[0].BackendIPConfigurations.Count);
passed = true;
}
finally
{
m_ResourcesClient.ResourceGroups.DeleteIfExists(rgName);
}
Assert.True(passed);
}
}
/// <summary>
/// Associates a VMScaleSet with DnsSettings
/// </summary>
[Fact]
public void TestVMScaleSetWithDnsSettings()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
// Create resource group
string rgName = TestUtilities.GenerateName(TestPrefix) + 1;
var vmssName = TestUtilities.GenerateName("vmss");
string storageAccountName = TestUtilities.GenerateName(TestPrefix);
VirtualMachineScaleSet inputVMScaleSet;
bool passed = false;
try
{
var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);
var vnetResponse = CreateVNETWithSubnets(rgName, 2);
var vmssSubnet = vnetResponse.Subnets[1];
var nicDnsSettings = new VirtualMachineScaleSetNetworkConfigurationDnsSettings();
nicDnsSettings.DnsServers = new List<string>() { "10.0.0.5", "10.0.0.6" };
VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking(
rgName: rgName,
vmssName: vmssName,
storageAccount: storageAccountOutput,
imageRef: imageRef,
inputVMScaleSet: out inputVMScaleSet,
vmScaleSetCustomizer:
(virtualMachineScaleSet) =>
virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile
.NetworkInterfaceConfigurations[0].DnsSettings = nicDnsSettings,
createWithPublicIpAddress: false,
subnet: vmssSubnet);
var vmss = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName);
Assert.NotNull(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].DnsSettings);
Assert.NotNull(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].DnsSettings.DnsServers);
Assert.Equal(2, vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].DnsSettings.DnsServers.Count);
Assert.Contains(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].DnsSettings.DnsServers, ip => string.Equals("10.0.0.5", ip));
Assert.Contains(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].DnsSettings.DnsServers, ip => string.Equals("10.0.0.6", ip));
passed = true;
}
finally
{
m_ResourcesClient.ResourceGroups.DeleteIfExists(rgName);
}
Assert.True(passed);
}
}
/// <summary>
/// Associates a VMScaleSet with PublicIp
/// </summary>
[Fact]
public void TestVMScaleSetWithPublicIP()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
// Create resource group
string rgName = TestUtilities.GenerateName(TestPrefix) + 1;
var vmssName = TestUtilities.GenerateName("vmss");
var dnsname = TestUtilities.GenerateName("dnsname");
string storageAccountName = TestUtilities.GenerateName(TestPrefix);
VirtualMachineScaleSet inputVMScaleSet;
bool passed = false;
try
{
// Hard code the location to "westcentralus".
// This is because NRP is still deploying to other regions and is not available worldwide.
// Before changing the default location, we have to save it to be reset it at the end of the test.
// Since ComputeManagementTestUtilities.DefaultLocation is a static variable and can affect other tests if it is not reset.
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2");
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);
var vnetResponse = CreateVNETWithSubnets(rgName, 2);
var vmssSubnet = vnetResponse.Subnets[1];
var publicipConfiguration = new VirtualMachineScaleSetPublicIPAddressConfiguration();
publicipConfiguration.Name = "pip1";
publicipConfiguration.IdleTimeoutInMinutes = 10;
publicipConfiguration.DnsSettings = new VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettings();
publicipConfiguration.DnsSettings.DomainNameLabel = dnsname;
VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking(
rgName: rgName,
vmssName: vmssName,
storageAccount: storageAccountOutput,
imageRef: imageRef,
inputVMScaleSet: out inputVMScaleSet,
vmScaleSetCustomizer:
(virtualMachineScaleSet) =>
virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile
.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration = publicipConfiguration,
createWithPublicIpAddress: false,
subnet: vmssSubnet);
var vmss = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName);
Assert.NotNull(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration);
Assert.Equal("pip1", vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.Name);
Assert.Equal(10, vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.IdleTimeoutInMinutes);
Assert.NotNull(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.DnsSettings);
Assert.Equal(dnsname, vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.DnsSettings.DomainNameLabel);
passed = true;
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
m_ResourcesClient.ResourceGroups.DeleteIfExists(rgName);
}
Assert.True(passed);
}
}
/// <summary>
/// Associates a VMScaleSet with PublicIp
/// </summary>
[Fact]
public void TestFlexVMScaleSetWithPublicIP()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
// Create resource group
string rgName = TestUtilities.GenerateName(TestPrefix) + 1;
var vmssName = TestUtilities.GenerateName("vmss");
var dnsname = TestUtilities.GenerateName("dnsname");
string storageAccountName = TestUtilities.GenerateName(TestPrefix);
VirtualMachineScaleSet inputVMScaleSet;
bool passed = false;
try
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2euap");
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);
var vnetResponse = CreateVNETWithSubnets(rgName, 2);
var vmssSubnet = vnetResponse.Subnets[1];
var publicipConfiguration = new VirtualMachineScaleSetPublicIPAddressConfiguration();
publicipConfiguration.Name = "pip1";
publicipConfiguration.IdleTimeoutInMinutes = 10;
publicipConfiguration.DnsSettings = new VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettings();
publicipConfiguration.DnsSettings.DomainNameLabel = dnsname;
publicipConfiguration.DeleteOption = DeleteOptions.Detach.ToString();
VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking(
rgName: rgName,
vmssName: vmssName,
storageAccount: null,
imageRef: imageRef,
inputVMScaleSet: out inputVMScaleSet,
singlePlacementGroup: false,
createWithManagedDisks: true,
vmScaleSetCustomizer:
(virtualMachineScaleSet) => {
virtualMachineScaleSet.UpgradePolicy = null;
virtualMachineScaleSet.Overprovision = null;
virtualMachineScaleSet.PlatformFaultDomainCount = 1;
virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile.NetworkApiVersion = NetworkApiVersion.TwoZeroTwoZeroHyphenMinusOneOneHyphenMinusZeroOne;
virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile
.NetworkInterfaceConfigurations[0].DeleteOption = DeleteOptions.Delete.ToString();
virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile
.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration = publicipConfiguration;
virtualMachineScaleSet.OrchestrationMode = OrchestrationMode.Flexible.ToString();
virtualMachineScaleSet.VirtualMachineProfile.StorageProfile.DataDisks = null;
},
createWithPublicIpAddress: false,
subnet: vmssSubnet);
var vmss = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName);
Assert.NotNull(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration);
Assert.Equal("pip1", vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.Name);
Assert.Equal(10, vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.IdleTimeoutInMinutes);
Assert.NotNull(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.DnsSettings);
Assert.Equal(dnsname, vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.DnsSettings.DomainNameLabel);
passed = true;
m_CrpClient.VirtualMachineScaleSets.Delete(rgName, vmssName);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
m_ResourcesClient.ResourceGroups.DeleteIfExists(rgName);
}
Assert.True(passed);
}
}
/// <summary>
/// Associates a VMScaleSet with PublicIp with Ip tags
/// </summary>
[Fact]
public void TestVMScaleSetWithPublicIPAndIPTags()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
// Create resource group
string rgName = TestUtilities.GenerateName(TestPrefix) + 1;
var vmssName = TestUtilities.GenerateName("vmss");
var dnsname = TestUtilities.GenerateName("dnsname");
string storageAccountName = TestUtilities.GenerateName(TestPrefix);
VirtualMachineScaleSet inputVMScaleSet;
bool passed = false;
try
{
// Hard code the location to "westcentralus".
// This is because NRP is still deploying to other regions and is not available worldwide.
// Before changing the default location, we have to save it to be reset it at the end of the test.
// Since ComputeManagementTestUtilities.DefaultLocation is a static variable and can affect other tests if it is not reset.
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2");
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);
var vnetResponse = CreateVNETWithSubnets(rgName, 2);
var vmssSubnet = vnetResponse.Subnets[1];
var publicipConfiguration = new VirtualMachineScaleSetPublicIPAddressConfiguration();
publicipConfiguration.Name = "pip1";
publicipConfiguration.IdleTimeoutInMinutes = 10;
publicipConfiguration.DnsSettings = new VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettings();
publicipConfiguration.DnsSettings.DomainNameLabel = dnsname;
publicipConfiguration.IpTags = new List<VirtualMachineScaleSetIpTag>
{
new VirtualMachineScaleSetIpTag("FirstPartyUsage", "/Sql")
};
VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking(
rgName: rgName,
vmssName: vmssName,
storageAccount: storageAccountOutput,
imageRef: imageRef,
inputVMScaleSet: out inputVMScaleSet,
vmScaleSetCustomizer:
(virtualMachineScaleSet) =>
virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile
.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration = publicipConfiguration,
createWithPublicIpAddress: false,
subnet: vmssSubnet);
var vmss = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName);
Assert.NotNull(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration);
Assert.Equal("pip1", vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.Name);
Assert.Equal(10, vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.IdleTimeoutInMinutes);
Assert.NotNull(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.DnsSettings);
Assert.Equal(dnsname, vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.DnsSettings.DomainNameLabel);
Assert.NotNull(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.IpTags);
Assert.Equal("FirstPartyUsage", vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.IpTags[0].IpTagType);
Assert.Equal("/Sql", vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.IpTags[0].Tag);
passed = true;
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
m_ResourcesClient.ResourceGroups.DeleteIfExists(rgName);
}
Assert.True(passed);
}
}
/// <summary>
/// Associates a VMScaleSet with PublicIp with Ip prefix
/// </summary>
[Fact]
public void TestVMScaleSetWithPublicIPAndPublicIPPrefix()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
if (originalTestLocation == null)
{
originalTestLocation = String.Empty;
}
// Create resource group
string rgName = TestUtilities.GenerateName(TestPrefix) + 1;
var vmssName = TestUtilities.GenerateName("vmss");
var dnsname = TestUtilities.GenerateName("dnsname");
string storageAccountName = TestUtilities.GenerateName(TestPrefix);
VirtualMachineScaleSet inputVMScaleSet;
bool passed = false;
try
{
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);
var vnetResponse = CreateVNETWithSubnets(rgName, 2);
var vmssSubnet = vnetResponse.Subnets[1];
var publicIpPrefix = CreatePublicIPPrefix(rgName, 30);
var publicipConfiguration = new VirtualMachineScaleSetPublicIPAddressConfiguration();
publicipConfiguration.Name = "pip1";
publicipConfiguration.IdleTimeoutInMinutes = 10;
publicipConfiguration.DnsSettings = new VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettings();
publicipConfiguration.DnsSettings.DomainNameLabel = dnsname;
publicipConfiguration.PublicIPPrefix = new Microsoft.Azure.Management.Compute.Models.SubResource();
publicipConfiguration.PublicIPPrefix.Id = publicIpPrefix.Id;
VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking(
rgName: rgName,
vmssName: vmssName,
storageAccount: storageAccountOutput,
imageRef: imageRef,
inputVMScaleSet: out inputVMScaleSet,
vmScaleSetCustomizer:
(virtualMachineScaleSet) =>
virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile
.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration = publicipConfiguration,
createWithPublicIpAddress: false,
subnet: vmssSubnet);
var vmss = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName);
Assert.NotNull(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration);
Assert.Equal("pip1", vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.Name);
Assert.Equal(10, vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.IdleTimeoutInMinutes);
Assert.NotNull(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.DnsSettings);
Assert.Equal(dnsname, vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.DnsSettings.DomainNameLabel);
Assert.Equal(publicIpPrefix.Id, vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].PublicIPAddressConfiguration.PublicIPPrefix.Id);
passed = true;
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
m_ResourcesClient.ResourceGroups.DeleteIfExists(rgName);
}
Assert.True(passed);
}
}
/// <summary>
/// Associates a VMScaleSet with Nsg
/// </summary>
[Fact]
public void TestVMScaleSetWithnNsg()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
// Create resource group
string rgName = TestUtilities.GenerateName(TestPrefix) + 1;
var vmssName = TestUtilities.GenerateName("vmss");
var dnsname = TestUtilities.GenerateName("dnsname");
var nsgname = TestUtilities.GenerateName("nsg");
string storageAccountName = TestUtilities.GenerateName(TestPrefix);
VirtualMachineScaleSet inputVMScaleSet;
bool passed = false;
try
{
var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);
var vnetResponse = CreateVNETWithSubnets(rgName, 2);
var vmssSubnet = vnetResponse.Subnets[1];
var nsg = CreateNsg(rgName, nsgname);
Microsoft.Azure.Management.Compute.Models.SubResource nsgId = new Microsoft.Azure.Management.Compute.Models.SubResource()
{
Id = nsg.Id
};
VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking(
rgName: rgName,
vmssName: vmssName,
storageAccount: storageAccountOutput,
imageRef: imageRef,
inputVMScaleSet: out inputVMScaleSet,
vmScaleSetCustomizer:
(virtualMachineScaleSet) =>
virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile
.NetworkInterfaceConfigurations[0].NetworkSecurityGroup = nsgId,
createWithPublicIpAddress: false,
subnet: vmssSubnet);
var vmss = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName);
Assert.NotNull(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].NetworkSecurityGroup);
Assert.Equal(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].NetworkSecurityGroup.Id, nsg.Id, StringComparer.OrdinalIgnoreCase);
var getNsgResponse = m_NrpClient.NetworkSecurityGroups.Get(rgName, nsg.Name);
Assert.Equal(2, getNsgResponse.NetworkInterfaces.Count);
passed = true;
}
finally
{
m_ResourcesClient.ResourceGroups.DeleteIfExists(rgName);
}
Assert.True(passed);
}
}
/// <summary>
/// Associates a VMScaleSet with ipv6
/// </summary>
[Fact]
public void TestVMScaleSetWithnIpv6()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
// Create resource group
string rgName = TestUtilities.GenerateName(TestPrefix) + 1;
var vmssName = TestUtilities.GenerateName("vmss");
var dnsname = TestUtilities.GenerateName("dnsname");
string storageAccountName = TestUtilities.GenerateName(TestPrefix);
VirtualMachineScaleSet inputVMScaleSet;
bool passed = false;
try
{
var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);
var vnetResponse = CreateVNETWithSubnets(rgName, 2);
var vmssSubnet = vnetResponse.Subnets[1];
var ipv6ipconfig = new VirtualMachineScaleSetIPConfiguration();
ipv6ipconfig.Name = "ipv6";
ipv6ipconfig.PrivateIPAddressVersion = Microsoft.Azure.Management.Compute.Models.IPVersion.IPv6;
VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking(
rgName: rgName,
vmssName: vmssName,
storageAccount: storageAccountOutput,
imageRef: imageRef,
inputVMScaleSet: out inputVMScaleSet,
vmScaleSetCustomizer:
(virtualMachineScaleSet) =>
{
virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile
.NetworkInterfaceConfigurations[0].IpConfigurations[0].PrivateIPAddressVersion = Microsoft.Azure.Management.Compute.Models.IPVersion.IPv4;
virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile
.NetworkInterfaceConfigurations[0].IpConfigurations.Add(ipv6ipconfig);
},
createWithPublicIpAddress: false,
subnet: vmssSubnet);
var vmss = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName);
Assert.Equal(2, vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations.Count);
passed = true;
}
finally
{
m_ResourcesClient.ResourceGroups.DeleteIfExists(rgName);
}
Assert.True(passed);
}
}
/// <summary>
/// Associates a VMScaleSet with multiple IPConfigurations on a single NIC
/// </summary>
[Fact]
public void TestVMSSWithMultiCA()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
// Create resource group
string rgName = TestUtilities.GenerateName(TestPrefix) + 1;
var vmssName = TestUtilities.GenerateName("vmss");
string storageAccountName = TestUtilities.GenerateName(TestPrefix);
VirtualMachineScaleSet inputVMScaleSet;
bool passed = false;
try
{
var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);
var vnetResponse = CreateVNETWithSubnets(rgName, 2);
var vmssSubnet = vnetResponse.Subnets[1];
var secondaryCA =
new VirtualMachineScaleSetIPConfiguration(
name: TestUtilities.GenerateName("vmsstestnetconfig"),
subnet: new ApiEntityReference() { Id = vmssSubnet.Id });
VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking(
rgName: rgName,
vmssName: vmssName,
storageAccount: storageAccountOutput,
imageRef: imageRef,
inputVMScaleSet: out inputVMScaleSet,
vmScaleSetCustomizer:
(virtualMachineScaleSet) =>
{
virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations[0].Primary = true;
virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations.Add(secondaryCA);
},
createWithPublicIpAddress: false,
subnet: vmssSubnet);
var vmss = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName);
Assert.Equal(2, vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations.Count);
Assert.True(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].IpConfigurations.Count(ip => ip.Primary == true) == 1);
passed = true;
}
finally
{
m_ResourcesClient.ResourceGroups.DeleteIfExists(rgName);
}
Assert.True(passed);
}
}
/// <summary>
/// Associates a VMScaleSet with a NIC that has accelerated networking enabled.
/// </summary>
[Fact]
public void TestVMSSAccelNtwkng()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
// Create resource group
string rgName = TestUtilities.GenerateName(TestPrefix) + 1;
var vmssName = TestUtilities.GenerateName("vmss");
string storageAccountName = TestUtilities.GenerateName(TestPrefix);
VirtualMachineScaleSet inputVMScaleSet;
bool passed = false;
try
{
var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);
var vnetResponse = CreateVNETWithSubnets(rgName, 2);
var vmssSubnet = vnetResponse.Subnets[1];
VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking(
rgName: rgName,
vmssName: vmssName,
storageAccount: storageAccountOutput,
imageRef: imageRef,
inputVMScaleSet: out inputVMScaleSet,
vmScaleSetCustomizer:
(virtualMachineScaleSet) =>
{
virtualMachineScaleSet.Sku.Name = VirtualMachineSizeTypes.StandardDS11V2;
virtualMachineScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].EnableAcceleratedNetworking = true;
},
createWithPublicIpAddress: false,
subnet: vmssSubnet);
var vmss = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName);
Assert.True(vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].EnableAcceleratedNetworking == true);
passed = true;
}
finally
{
m_ResourcesClient.ResourceGroups.DeleteIfExists(rgName);
}
Assert.True(passed);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Xml;
using System.IO;
using System.Text;
using System.Reflection;
using System.Globalization;
using System.Threading;
using System.Management.Automation;
using Microsoft.Win32;
#if CORECLR
// Some APIs are missing from System.Environment. We use System.Management.Automation.Environment as a proxy type:
// - for missing APIs, System.Management.Automation.Environment has extension implementation.
// - for existing APIs, System.Management.Automation.Environment redirect the call to System.Environment.
using Environment = System.Management.Automation.Environment;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
#endif
namespace System.Management.Automation
{
/// <summary>
/// Leverages the strategy pattern to abstract away the details of gathering properties from outside sources.
/// Note: This is a class so that it can be internal.
/// </summary>
internal abstract class ConfigPropertyAccessor
{
#region Statics
/// <summary>
/// Static constructor to instantiate an instance
/// </summary>
static ConfigPropertyAccessor()
{
#if CORECLR
Instance = Platform.IsInbox
? (ConfigPropertyAccessor) new RegistryAccessor()
: new JsonConfigFileAccessor();
#else
Instance = new RegistryAccessor();
#endif
}
/// <summary>
/// The instance of the ConfigPropertyAccessor to use to iteract with properties.
/// Derived classes should not be directly instantiated.
/// </summary>
internal static readonly ConfigPropertyAccessor Instance;
#endregion // Statics
#region Enums
/// <summary>
/// Describes the scope of the property query.
/// SystemWide properties apply to all users.
/// CurrentUser properties apply to the current user that is impersonated.
/// </summary>
internal enum PropertyScope
{
SystemWide = 0,
CurrentUser = 1
}
#endregion // Enums
#region Interface Methods
/// <summary>
/// Existing Key = HKLM:\System\CurrentControlSet\Control\Session Manager\Environment
/// Proposed value = %ProgramFiles%\PowerShell\Modules by default
///
/// Note: There is no setter because this value is immutable.
/// </summary>
/// <returns>Module path values from the config file.</returns>
internal abstract string GetModulePath(PropertyScope scope);
/// <summary>
/// Existing Key = HKCU and HKLM\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell
/// Proposed value = Existing default execution policy if not already specified
/// </summary>
/// <param name="scope">Where it should check for the value.</param>
/// <param name="shellId">The shell associated with this policy. Typically, it is "Microsoft.PowerShell"</param>
/// <returns></returns>
internal abstract string GetExecutionPolicy(PropertyScope scope, string shellId);
internal abstract void RemoveExecutionPolicy(PropertyScope scope, string shellId);
internal abstract void SetExecutionPolicy(PropertyScope scope, string shellId, string executionPolicy);
/// <summary>
/// Existing Key = HKLM\SOFTWARE\Microsoft\PowerShell\1\ShellIds
/// Proposed value = existing default. Probably "1"
/// </summary>
/// <returns>Whether console prompting should happen.</returns>
internal abstract bool GetConsolePrompting();
internal abstract void SetConsolePrompting(bool shouldPrompt);
/// <summary>
/// Existing Key = HKLM\SOFTWARE\Microsoft\PowerShell
/// Proposed value = Existing default. Probably "0"
/// </summary>
/// <returns>Boolean indicating whether Update-Help should prompt</returns>
internal abstract bool GetDisablePromptToUpdateHelp();
internal abstract void SetDisablePromptToUpdateHelp(bool prompt);
/// <summary>
/// Existing Key = HKCU and HKLM\Software\Policies\Microsoft\Windows\PowerShell\UpdatableHelp
/// Proposed value = blank.This should be supported though
/// </summary>
/// <returns></returns>
internal abstract string GetDefaultSourcePath();
internal abstract void SetDefaultSourcePath(string defaultPath);
#endregion // Interface Methods
}
#if CORECLR
/// <summary>
/// JSON configuration file accessor
///
/// Reads from and writes to configuration files. The values stored were
/// originally stored in the Windows registry.
/// </summary>
internal class JsonConfigFileAccessor : ConfigPropertyAccessor
{
private string psHomeConfigDirectory;
private string appDataConfigDirectory;
private const string configFileName = "PowerShellProperties.json";
/// <summary>
/// Lock used to enable multiple concurrent readers and singular write locks within a
/// single process.
/// TODO: This solution only works for IO from a single process. A more robust solution is needed to enable ReaderWriterLockSlim behavior between proceses.
/// </summary>
private ReaderWriterLockSlim fileLock = new ReaderWriterLockSlim();
internal JsonConfigFileAccessor()
{
//
// Sets the system-wide configuration directory
//
Assembly assembly = typeof(PSObject).GetTypeInfo().Assembly;
psHomeConfigDirectory = Path.GetDirectoryName(assembly.Location);
//
// Sets the per-user configuration directory
//
appDataConfigDirectory = Utils.GetUserSettingsDirectory();
if (!Directory.Exists(appDataConfigDirectory))
{
try
{
Directory.CreateDirectory(appDataConfigDirectory);
}
catch (UnauthorizedAccessException)
{
// Do nothing now. This failure shouldn't block initialization
appDataConfigDirectory = null;
}
}
}
/// <summary>
/// Enables delayed creation of the user settings directory so it does
/// not interfere with PowerShell initialization
/// </summary>
/// <returns>Returns the directory if present or creatable. Throws otherwise.</returns>
private string GetAppDataConfigDirectory()
{
if (null == appDataConfigDirectory)
{
string tempAppDataConfigDir = Utils.GetUserSettingsDirectory();
if (!Directory.Exists(tempAppDataConfigDir))
{
Directory.CreateDirectory(tempAppDataConfigDir);
// Only assign it if creation succeeds. It will throw if it fails.
appDataConfigDirectory = tempAppDataConfigDir;
}
// Do not catch exceptions here. Let them flow up.
}
return appDataConfigDirectory;
}
/// <summary>
/// This value is not writable via the API and must be set using a text editor.
/// </summary>
/// <param name="scope"></param>
/// <returns>Value if found, null otherwise. The behavior matches ModuleIntrinsics.GetExpandedEnvironmentVariable().</returns>
internal override string GetModulePath(PropertyScope scope)
{
string scopeDirectory = psHomeConfigDirectory;
// Defaults to system wide.
if (PropertyScope.CurrentUser == scope)
{
scopeDirectory = GetAppDataConfigDirectory();
}
string fileName = Path.Combine(scopeDirectory, configFileName);
string modulePath = ReadValueFromFile<string>(fileName, "PsModulePath");
if (!string.IsNullOrEmpty(modulePath))
{
modulePath = Environment.ExpandEnvironmentVariables(modulePath);
}
return modulePath;
}
/// <summary>
/// Existing Key = HKCU and HKLM\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell
/// Proposed value = Existing default execution policy if not already specified
///
/// Schema:
/// {
/// "shell ID string","ExecutionPolicy" : "execution policy string"
/// }
///
/// TODO: In a single config file, it might be better to nest this. It is unnecessary complexity until a need arises for more nested values.
/// </summary>
/// <param name="scope">Whether this is a system-wide or per-user setting.</param>
/// <param name="shellId">The shell associated with this policy. Typically, it is "Microsoft.PowerShell"</param>
/// <returns>The execution policy if found. Null otherwise.</returns>
internal override string GetExecutionPolicy(PropertyScope scope, string shellId)
{
string execPolicy = null;
string scopeDirectory = psHomeConfigDirectory;
// Defaults to system wide.
if(PropertyScope.CurrentUser == scope)
{
scopeDirectory = GetAppDataConfigDirectory();
}
string fileName = Path.Combine(scopeDirectory, configFileName);
string valueName = string.Concat(shellId, ":", "ExecutionPolicy");
string rawExecPolicy = ReadValueFromFile<string>(fileName, valueName);
if (!String.IsNullOrEmpty(rawExecPolicy))
{
execPolicy = rawExecPolicy;
}
return execPolicy;
}
internal override void RemoveExecutionPolicy(PropertyScope scope, string shellId)
{
string scopeDirectory = psHomeConfigDirectory;
// Defaults to system wide.
if (PropertyScope.CurrentUser == scope)
{
scopeDirectory = GetAppDataConfigDirectory();
}
string fileName = Path.Combine(scopeDirectory, configFileName);
string valueName = string.Concat(shellId, ":", "ExecutionPolicy");
RemoveValueFromFile<string>(fileName, valueName);
}
internal override void SetExecutionPolicy(PropertyScope scope, string shellId, string executionPolicy)
{
string scopeDirectory = psHomeConfigDirectory;
// Defaults to system wide.
if (PropertyScope.CurrentUser == scope)
{
scopeDirectory = GetAppDataConfigDirectory();
}
string fileName = Path.Combine(scopeDirectory, configFileName);
string valueName = string.Concat(shellId, ":", "ExecutionPolicy");
WriteValueToFile<string>(fileName, valueName, executionPolicy);
}
/// <summary>
/// Existing Key = HKLM\SOFTWARE\Microsoft\PowerShell\1\ShellIds
/// Proposed value = existing default. Probably "1"
///
/// Schema:
/// {
/// "ConsolePrompting" : bool
/// }
/// </summary>
/// <returns>Whether console prompting should happen. If the value cannot be read it defaults to false.</returns>
internal override bool GetConsolePrompting()
{
string fileName = Path.Combine(psHomeConfigDirectory, configFileName);
return ReadValueFromFile<bool>(fileName, "ConsolePrompting");
}
internal override void SetConsolePrompting(bool shouldPrompt)
{
string fileName = Path.Combine(psHomeConfigDirectory, configFileName);
WriteValueToFile<bool>(fileName, "ConsolePrompting", shouldPrompt);
}
/// <summary>
/// Existing Key = HKLM\SOFTWARE\Microsoft\PowerShell
/// Proposed value = Existing default. Probably "0"
///
/// Schema:
/// {
/// "DisablePromptToUpdateHelp" : bool
/// }
/// </summary>
/// <returns>Boolean indicating whether Update-Help should prompt. If the value cannot be read, it defaults to false.</returns>
internal override bool GetDisablePromptToUpdateHelp()
{
string fileName = Path.Combine(psHomeConfigDirectory, configFileName);
return ReadValueFromFile<bool>(fileName, "DisablePromptToUpdateHelp");
}
internal override void SetDisablePromptToUpdateHelp(bool prompt)
{
string fileName = Path.Combine(psHomeConfigDirectory, configFileName);
WriteValueToFile<bool>(fileName, "DisablePromptToUpdateHelp", prompt);
}
/// <summary>
/// Existing Key = HKCU and HKLM\Software\Policies\Microsoft\Windows\PowerShell\UpdatableHelp
/// Proposed value = blank.This should be supported though
///
/// Schema:
/// {
/// "DefaultSourcePath" : "path to local updatable help location"
/// }
/// </summary>
/// <returns>The source path if found, null otherwise.</returns>
internal override string GetDefaultSourcePath()
{
string fileName = Path.Combine(psHomeConfigDirectory, configFileName);
string rawExecPolicy = ReadValueFromFile<string>(fileName, "DefaultSourcePath");
if (!String.IsNullOrEmpty(rawExecPolicy))
{
return rawExecPolicy;
}
return null;
}
internal override void SetDefaultSourcePath(string defaultPath)
{
string fileName = Path.Combine(psHomeConfigDirectory, configFileName);
WriteValueToFile<string>(fileName, "DefaultSourcePath", defaultPath);
}
private T ReadValueFromFile<T>(string fileName, string key)
{
fileLock.EnterReadLock();
try
{
// Open file for reading, but allow multiple readers
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
using (StreamReader streamRdr = new StreamReader(fs))
using (JsonTextReader jsonReader = new JsonTextReader(streamRdr))
{
JObject jsonObject = (JObject) JToken.ReadFrom(jsonReader);
JToken value = jsonObject.GetValue(key);
if (null != value)
{
return value.ToObject<T>();
}
}
}
catch (FileNotFoundException)
{
// The file doesn't exist. Treat this the same way as if the
// key was not present in the file.
}
finally
{
fileLock.ExitReadLock();
}
return default(T);
}
/// <summary>
/// TODO: Should this return success fail or throw?
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fileName"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="addValue">Whether the key-value pair should be added to or removed from the file</param>
private void UpdateValueInFile<T>(string fileName, string key, T value, bool addValue)
{
fileLock.EnterWriteLock();
try
{
// Since multiple properties can be in a single file, replacement
// is required instead of overwrite if a file already exists.
// Handling the read and write operations within a single FileStream
// prevents other processes from reading or writing the file while
// the update is in progress. It also locks out readers during write
// operations.
using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
JObject jsonObject = null;
// UTF8, BOM detection, and bufferSize are the same as the basic stream constructor.
// The most important parameter here is the last one, which keeps the StreamReader
// (and FileStream) open during Dispose so that it can be reused for the write
// operation.
using (StreamReader streamRdr = new StreamReader(fs, Encoding.UTF8, true, 1024, true))
using (JsonTextReader jsonReader = new JsonTextReader(streamRdr))
{
// Safely determines whether there is content to read from the file
bool isReadSuccess = jsonReader.Read();
if (isReadSuccess)
{
// Read the stream into a root JObject for manipulation
jsonObject = (JObject) JToken.ReadFrom(jsonReader);
JProperty propertyToModify = jsonObject.Property(key);
if (null == propertyToModify)
{
// The property doesn't exist, so add it
if (addValue)
{
jsonObject.Add(new JProperty(key, value));
}
// else the property doesn't exist so there is nothing to remove
}
// The property exists
else
{
if (addValue)
{
propertyToModify.Replace(new JProperty(key, value));
}
else
{
propertyToModify.Remove();
}
}
}
else
{
// The file doesn't already exist and we want to write to it
// or it exists with no content.
// A new file will be created that contains only this value.
// If the file doesn't exist and a we don't want to write to it, no
// action is necessary.
if (addValue)
{
jsonObject = new JObject(new JProperty(key, value));
}
else
{
return;
}
}
}
// Reset the stream position to the beginning so that the
// changes to the file can be written to disk
fs.Seek(0, SeekOrigin.Begin);
// Update the file with new content
using (StreamWriter streamWriter = new StreamWriter(fs))
using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
{
// The entire document exists within the root JObject.
// I just need to write that object to produce the document.
jsonObject.WriteTo(jsonWriter);
// This trims the file if the file shrank. If the file grew,
// it is a no-op. The purpose is to trim extraneous characters
// from the file stream when the resultant JObject is smaller
// than the input JObject.
fs.SetLength(fs.Position);
}
}
}
finally
{
fileLock.ExitWriteLock();
}
}
/// <summary>
/// TODO: Should this return success, fail, or throw?
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fileName"></param>
/// <param name="key"></param>
/// <param name="value"></param>
private void WriteValueToFile<T>(string fileName, string key, T value)
{
UpdateValueInFile<T>(fileName, key, value, true);
}
/// <summary>
/// TODO: Should this return success, fail, or throw?
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fileName"></param>
/// <param name="key"></param>
private void RemoveValueFromFile<T>(string fileName, string key)
{
UpdateValueInFile<T>(fileName, key, default(T), false);
}
}
#endif // CORECLR
internal class RegistryAccessor : ConfigPropertyAccessor
{
private const string DisablePromptToUpdateHelpRegPath = "Software\\Microsoft\\PowerShell";
private const string DisablePromptToUpdateHelpRegPath32 = "Software\\Wow6432Node\\Microsoft\\PowerShell";
private const string DisablePromptToUpdateHelpRegKey = "DisablePromptToUpdateHelp";
private const string DefaultSourcePathRegPath = "Software\\Policies\\Microsoft\\Windows\\PowerShell\\UpdatableHelp";
private const string DefaultSourcePathRegKey = "DefaultSourcePath";
internal RegistryAccessor()
{
}
/// <summary>
/// Gets the specified module path from the appropriate Environment entry in the registry.
/// </summary>
/// <param name="scope"></param>
/// <returns>The specified module path. Null if not present.</returns>
internal override string GetModulePath(PropertyScope scope)
{
if (PropertyScope.CurrentUser == scope)
{
return ModuleIntrinsics.GetExpandedEnvironmentVariable("PSMODULEPATH", EnvironmentVariableTarget.User);
}
else
{
return ModuleIntrinsics.GetExpandedEnvironmentVariable("PSMODULEPATH", EnvironmentVariableTarget.Machine);
}
}
/// <summary>
///
/// </summary>
/// <param name="scope"></param>
/// <param name="shellId"></param>
/// <returns>The execution policy string if found, otherwise null.</returns>
internal override string GetExecutionPolicy(PropertyScope scope, string shellId)
{
string regKeyName = Utils.GetRegistryConfigurationPath(shellId);
RegistryKey scopedKey = Registry.LocalMachine;
// Override if set to another value;
if (PropertyScope.CurrentUser == scope)
{
scopedKey = Registry.CurrentUser;
}
return GetRegistryString(scopedKey, regKeyName, "ExecutionPolicy");
}
internal override void SetExecutionPolicy(PropertyScope scope, string shellId, string executionPolicy)
{
string regKeyName = Utils.GetRegistryConfigurationPath(shellId);
RegistryKey scopedKey = Registry.LocalMachine;
// Override if set to another value;
if (PropertyScope.CurrentUser == scope)
{
scopedKey = Registry.CurrentUser;
}
using (RegistryKey key = scopedKey.CreateSubKey(regKeyName))
{
if (null != key)
{
key.SetValue("ExecutionPolicy", executionPolicy, RegistryValueKind.String);
}
}
}
internal override void RemoveExecutionPolicy(PropertyScope scope, string shellId)
{
string regKeyName = Utils.GetRegistryConfigurationPath(shellId);
RegistryKey scopedKey = Registry.LocalMachine;
// Override if set to another value;
if (PropertyScope.CurrentUser == scope)
{
scopedKey = Registry.CurrentUser;
}
using (RegistryKey key = scopedKey.OpenSubKey(regKeyName, true))
{
if (key != null)
{
if (key.GetValue("ExecutionPolicy") != null)
key.DeleteValue("ExecutionPolicy");
}
}
}
/// <summary>
/// Existing Key = HKLM\SOFTWARE\Microsoft\PowerShell\1\ShellIds
/// Proposed value = existing default. Probably "1"
/// </summary>
/// <returns>Whether console prompting should happen.</returns>
internal override bool GetConsolePrompting()
{
string policyKeyName = Utils.GetRegistryConfigurationPrefix();
string tempPrompt = GetRegistryString(Registry.LocalMachine, policyKeyName, "ConsolePrompting");
if (null != tempPrompt)
{
return Convert.ToBoolean(tempPrompt, CultureInfo.InvariantCulture);
}
else
{
return false;
}
}
internal override void SetConsolePrompting(bool shouldPrompt)
{
string policyKeyName = Utils.GetRegistryConfigurationPrefix();
SetRegistryString(Registry.LocalMachine, policyKeyName, "ConsolePrompting", shouldPrompt.ToString());
}
/// <summary>
/// Existing Key = HKLM\SOFTWARE\Microsoft\PowerShell
/// Proposed value = Existing default. Probably "0"
/// </summary>
/// <returns>Boolean indicating whether Update-Help should prompt</returns>
internal override bool GetDisablePromptToUpdateHelp()
{
using (RegistryKey hklm = Registry.LocalMachine.OpenSubKey(DisablePromptToUpdateHelpRegPath))
{
if (hklm != null)
{
object disablePromptToUpdateHelp = hklm.GetValue(DisablePromptToUpdateHelpRegKey, null, RegistryValueOptions.None);
if (disablePromptToUpdateHelp == null)
{
return true;
}
else
{
int result;
if (LanguagePrimitives.TryConvertTo<int>(disablePromptToUpdateHelp, out result))
{
return (result != 1);
}
return true;
}
}
else
{
return true;
}
}
}
internal override void SetDisablePromptToUpdateHelp(bool prompt)
{
int valueToSet = prompt ? 1 : 0;
using (RegistryKey hklm = Registry.LocalMachine.OpenSubKey(DisablePromptToUpdateHelpRegPath, true))
{
if (hklm != null)
{
hklm.SetValue(DisablePromptToUpdateHelpRegKey, valueToSet, RegistryValueKind.DWord);
}
}
using (RegistryKey hklm = Registry.LocalMachine.OpenSubKey(DisablePromptToUpdateHelpRegPath32, true))
{
if (hklm != null)
{
hklm.SetValue(DisablePromptToUpdateHelpRegKey, valueToSet, RegistryValueKind.DWord);
}
}
}
/// <summary>
/// Existing Key = HKCU and HKLM\Software\Policies\Microsoft\Windows\PowerShell\UpdatableHelp
/// Proposed value = blank.This should be supported though
/// </summary>
/// <returns></returns>
internal override string GetDefaultSourcePath()
{
return GetRegistryString(Registry.LocalMachine, DefaultSourcePathRegPath, DefaultSourcePathRegKey);
}
internal override void SetDefaultSourcePath(string defaultPath)
{
SetRegistryString(Registry.LocalMachine, DefaultSourcePathRegPath, DefaultSourcePathRegKey, defaultPath);
}
/// <summary>
/// Reads a DWORD from the Registry. Excpetions are intentionally allowed to pass through to
/// the caller because different classes and methods within the code base handle Registry
/// exceptions differently. Some suppress exceptions and others pass them to the user.
/// </summary>
/// <param name="rootKey"></param>
/// <param name="pathToKey"></param>
/// <param name="valueName"></param>
/// <returns></returns>
private int? GetRegistryDword(RegistryKey rootKey, string pathToKey, string valueName)
{
using (RegistryKey regKey = rootKey.OpenSubKey(pathToKey))
{
if (null == regKey)
{
// Key not found
return null;
}
// verify the value kind as a string
RegistryValueKind kind = regKey.GetValueKind(valueName);
if (kind == RegistryValueKind.DWord)
{
return regKey.GetValue(valueName) as int?;
}
else
{
// The function expected a DWORD, but got another type. This is a coding error or a registry key typing error.
return null;
}
}
}
/// <summary>
/// Excpetions are intentionally allowed to pass through to
/// the caller because different classes and methods within the code base handle Registry
/// exceptions differently. Some suppress exceptions and others pass them to the user.
/// </summary>
/// <param name="rootKey"></param>
/// <param name="pathToKey"></param>
/// <param name="valueName"></param>
/// <param name="value"></param>
private void SetRegistryDword(RegistryKey rootKey, string pathToKey, string valueName, int value)
{
using (RegistryKey regKey = rootKey.OpenSubKey(pathToKey))
{
if (null != regKey)
{
regKey.SetValue(valueName, value, RegistryValueKind.DWord);
}
}
}
/// <summary>
/// Excpetions are intentionally allowed to pass through to
/// the caller because different classes and methods within the code base handle Registry
/// exceptions differently. Some suppress exceptions and others pass them to the user.
/// </summary>
/// <param name="rootKey"></param>
/// <param name="pathToKey"></param>
/// <param name="valueName"></param>
/// <returns></returns>
private string GetRegistryString(RegistryKey rootKey, string pathToKey, string valueName)
{
using (RegistryKey regKey = rootKey.OpenSubKey(pathToKey))
{
if (null == regKey)
{
// Key not found
return null;
}
object regValue = regKey.GetValue(valueName);
if (null != regValue)
{
// verify the value kind as a string
RegistryValueKind kind = regKey.GetValueKind(valueName);
if (kind == RegistryValueKind.ExpandString ||
kind == RegistryValueKind.String)
{
return regValue as string;
}
}
// The function expected a string, but got another type or the value doesn't exist.
return null;
}
}
/// <summary>
/// Excpetions are intentionally allowed to pass through to
/// the caller because different classes and methods within the code base handle Registry
/// exceptions differently. Some suppress exceptions and others pass them to the user.
/// </summary>
/// <param name="rootKey"></param>
/// <param name="pathToKey"></param>
/// <param name="valueName"></param>
/// <param name="value"></param>
/// <returns></returns>
private void SetRegistryString(RegistryKey rootKey, string pathToKey, string valueName, string value)
{
using (RegistryKey key = rootKey.CreateSubKey(pathToKey))
{
if (null != key)
{
key.SetValue(valueName, value, RegistryValueKind.String);
}
}
}
}
} // Namespace System.Management.Automation
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace GDGeek
{
public class VoxelRemoveFace
{
private List<Vertex> vertices;
public VoxelRemoveFace() {
}
/**
* do reduce faces number of product
*/
public void build(VoxelProduct product) {
if (product.sub != null) {
for (int i = 0; i < product.sub.Length; ++i) {
build (product.sub [i]);
}
} else {
build (product.main);
}
}
public void build(VoxelProduct.Product main) {
vertices = new List<Vertex>();
initVertices(main.draw);
removeFaces();
updateVerticesAndTriangleOfProduct(main);
}
//private
private void initVertices0(VoxelDrawData draw_data){
for (int i = 0, count = draw_data.vertices.Count; i < count; ++i) {
Vertex new_vertex = new Vertex(draw_data.vertices[i], i);
vertices.Add(new_vertex);
}
}
private void initVertices1(VoxelDrawData draw_data){
for (int i = 0, count = draw_data.triangles.Count; i < count; i += 3) {
Vertex v0 = vertices[draw_data.triangles[i]];
Vertex v1 = vertices[draw_data.triangles[i + 1]];
Vertex v2 = vertices[draw_data.triangles[i + 2]];
Triangle new_triangle = new Triangle(v0, v1, v2);
v0.neighbor_vertices.Add(v1);
v0.neighbor_vertices.Add(v2);
v0.adjacent_faces.Add(new_triangle);
v1.neighbor_vertices.Add(v2);
v1.neighbor_vertices.Add(v0);
v1.adjacent_faces.Add(new_triangle);
v2.neighbor_vertices.Add(v0);
v2.neighbor_vertices.Add(v1);
v2.adjacent_faces.Add(new_triangle);
}
}
private void initVertices2(){
for (int i = 0, count = vertices.Count; i < count; ++i) {
distinct(vertices[i].neighbor_vertices);
distinct(vertices[i].adjacent_faces);
}
}
private void initVertices3(){
float total_internal_angle = 0;
for (int i = 0, count = vertices.Count; i < count; ++i) {
if (vertices[i].neighbor_vertices.Count - vertices[i].adjacent_faces.Count > 1) {
vertices[i].is_continuous_polygon = false;
}
total_internal_angle = computeSumOfInternalAngle(vertices[i]);
if (!(Mathf.Approximately(total_internal_angle, 360f) || total_internal_angle < 180.01f) || Mathf.Approximately(total_internal_angle, 90f)) {
vertices[i].can_move = false;
}
}
}
private void initVertices4(){
for (int i = 0, count = vertices.Count; i < count; ++i) {
computeEdgeCollapseCostAtVertex(vertices[i]);
}
}
private void initVertices(VoxelDrawData draw_data) {
initVertices0 (draw_data);
initVertices1 (draw_data);
initVertices2 ();
initVertices3 ();
initVertices4 ();
}
private float computeSumOfInternalAngle(Vertex v) {
float sum_of_angle = 0;
for (int i = 0, count = v.adjacent_faces.Count; i < count; ++i) {
sum_of_angle += v.adjacent_faces[i].computeInternalAngle(v);
}
return sum_of_angle * Mathf.Rad2Deg;
}
private Task removeFacesTask() {
int can_collapse_index = 0;
TaskCircle tc = new TaskCircle ();
TaskManager.PushFront (tc, delegate {
can_collapse_index = getCanCollapseVertexIndex();
});
Task task = new Task ();
task.init = delegate() {
for (int i = 0; i < 200; ++i) {
collapse (vertices [can_collapse_index], vertices [can_collapse_index].collapse);
can_collapse_index = getCanCollapseVertexIndex ();
if (can_collapse_index == -1) {
break;
}
}
};
TaskManager.PushBack (task, delegate {
if(can_collapse_index == -1){
tc.forceQuit();
}
});
tc.push (task);
return tc;
}
private void removeFaces() {
int can_collapse_index = getCanCollapseVertexIndex();
while (can_collapse_index != -1) {
collapse(vertices[can_collapse_index], vertices[can_collapse_index].collapse);
can_collapse_index = getCanCollapseVertexIndex();
}
}
private int getCanCollapseVertexIndex() {
for (int i = 0, count = vertices.Count; i < count; ++i) {
if (vertices[i].cost < int.MaxValue) {
return i;
}
}
return -1;
}
private void updateVerticesAndTriangleOfProduct(VoxelProduct.Product main) {
List<VoxelDrawData.Vertice> temp_draw_vertices = new List<VoxelDrawData.Vertice>();
List<Triangle> temp_triangles_list = new List<Triangle>();
Dictionary<int, int> id_to_vertex_index = new Dictionary<int, int>();
for (int i = 0, vertices_count = vertices.Count; i < vertices_count; ++i) {
temp_draw_vertices.Add(main.draw.vertices[vertices[i].id]);
id_to_vertex_index[vertices[i].id] = i;
for (int j = 0, faces_count = vertices[i].adjacent_faces.Count; j < faces_count; ++j) {
temp_triangles_list.Add(vertices[i].adjacent_faces[j]);
}
}
main.draw.vertices = temp_draw_vertices;
distinct(temp_triangles_list);
List<int> triangles = new List<int>();
for (int i = 0, faces_count = temp_triangles_list.Count; i < faces_count; ++i) {
for (int j = 0; j < 3; ++j) {
triangles.Add(id_to_vertex_index[temp_triangles_list[i].triangle_vertices[j].id]);
}
}
main.draw.triangles = triangles;
}
/**
* compute collapse cost of u->{ neighbor_vertices_of_u }
*/
private void computeEdgeCollapseCostAtVertex(Vertex v) {
v.cost = int.MaxValue;
v.collapse = null;
if (!v.can_move) {
return;
}
if (v.neighbor_vertices.Count == 0) {
return;
}
for (int i = 0, count = v.neighbor_vertices.Count; i < count; ++i) {
float c = computeEdgeCollapseCostFromUToV(v, v.neighbor_vertices[i]);
if (c < v.cost) {
v.collapse = v.neighbor_vertices[i];
v.cost = c;
}
}
}
private float computeEdgeCollapseCostFromUToV(Vertex u, Vertex v) {
if (!u.is_continuous_polygon) {
return int.MaxValue;
}
if (willChangeShapeUToV(u, v)) {
return int.MaxValue;
}
return u.distance(v);
}
private bool willChangeShapeUToV(Vertex u, Vertex v) {
List<Triangle> temp_triangles_list = new List<Triangle>();
for (int i = 0, count = u.adjacent_faces.Count; i < count; ++i) {
if (!u.adjacent_faces[i].has(v)) {
Vertex[] t_vertices = u.adjacent_faces[i].triangle_vertices;
Triangle new_t = new Triangle(t_vertices[0], t_vertices[1], t_vertices[2]);
for (int j = 0; j < 3; ++j) {
if (new_t.triangle_vertices[j].Equals(u)) {
new_t.triangle_vertices[j] = v;
break;
}
}
temp_triangles_list.Add(new_t);
}
}
bool u_in_none_triangle = true;
for (int i = 0, count = temp_triangles_list.Count; i < count; ++i) {
if (vertexInTriangle(u, temp_triangles_list[i])) {
u_in_none_triangle = false;
break;
}
}
if (u_in_none_triangle) {
return true;
}
float before_area = computeVertexAdjacentFacesArea(u);
float after_area = 0;
for (int i = 0, count = temp_triangles_list.Count; i < count; ++i) {
after_area += temp_triangles_list[i].computeArea();
}
if (Mathf.Approximately(before_area, after_area)) {
return false;
}
return true;
}
private float computeVertexAdjacentFacesArea(Vertex v) {
float total_area = 0;
for (int i = 0, count = v.adjacent_faces.Count; i < count; ++i) {
total_area += v.adjacent_faces[i].computeArea();
}
return total_area;
}
private bool vertexInTriangle(Vertex v, Triangle t) {
Vector3 tv0 = t.triangle_vertices[0].position;
Vector3 tv1 = t.triangle_vertices[1].position;
Vector3 tv2 = t.triangle_vertices[2].position;
Vector3 vp = v.position;
float area = 0.5f * (Vector3.Cross(tv0 - vp, tv1 - vp).magnitude
+ Vector3.Cross(tv0 - vp, tv2 - vp).magnitude
+ Vector3.Cross(tv1 - vp, tv2 - vp).magnitude);
return Mathf.Approximately(area, t.computeArea());
}
/**
* collapse vertex u to vertex v
*/
private void collapse(Vertex u, Vertex v) {
// remove the adjacent face of both vertex u and vertex v
for (int i = 0; i < u.adjacent_faces.Count; ++i) {
if (u.adjacent_faces[i].has(v)) {
for (int j = 0; j < 3; ++j) {
Vertex v_temp = u.adjacent_faces[i].triangle_vertices[j];
if (!v_temp.Equals(u)) {
for (int k = 0; k < v_temp.adjacent_faces.Count; ++k) {
if (v_temp.adjacent_faces[k].Equals(u.adjacent_faces[i])) {
v_temp.adjacent_faces.RemoveAt(k);
break;
}
}
}
}
u.adjacent_faces.RemoveAt(i);
--i;
}
}
// replace vertex u with vertex v in adjacent faces of neighbor vertices of vertex u
for (int i = 0, i_count = u.neighbor_vertices.Count; i < i_count; ++i) {
Vertex v_temp = u.neighbor_vertices[i];
for (int j = 0, j_count = v_temp.adjacent_faces.Count; j < j_count; ++j) {
if (v_temp.adjacent_faces[j].has(u)) {
v_temp.adjacent_faces[j].replaceVertex(u, v);
}
}
}
// replace vertex u with vertex v in adjacent faces of vertex u
for (int i = 0, count = u.adjacent_faces.Count; i < count; ++i) {
u.adjacent_faces[i].replaceVertex(u, v);
}
// remove vertex u
vertices.RemoveAt(vertices.IndexOf(u));
// remove vertex u in neighbor vertices of vertex u
// add neighbor vertices of vertex u to vertex v
// add vertex v to neighbor vertices of vertex u
// update collapse cost at neighbor vertices of vertex u
for (int i = 0, count = u.neighbor_vertices.Count; i < count; ++i) {
u.neighbor_vertices[i].neighbor_vertices.Remove(u);
if (!u.neighbor_vertices[i].Equals(v)) {
v.neighbor_vertices.Add(u.neighbor_vertices[i]);
u.neighbor_vertices[i].neighbor_vertices.Add(v);
distinct(u.neighbor_vertices[i].neighbor_vertices);
}
computeEdgeCollapseCostAtVertex(u.neighbor_vertices[i]);
}
distinct(v.neighbor_vertices);
// add new faces to vertex v and update collapse cost of vertex v
for (int i = 0, count = u.adjacent_faces.Count; i < count; ++i) {
v.adjacent_faces.Add(u.adjacent_faces[i]);
}
computeEdgeCollapseCostAtVertex(v);
}
/**
* Vertex
*/
private class Vertex
{
public int id;
public Vector3 position;
public Color color;
public Vector3 normal;
public List<Vertex> neighbor_vertices;
public List<Triangle> adjacent_faces;
public float cost;
public Vertex collapse;
public bool is_continuous_polygon;
public bool can_move;
public Vertex() {}
public Vertex(VoxelDrawData.Vertice v, int input_id) {
id = input_id;
position = v.position;
color = v.color;
normal = v.normal;
neighbor_vertices = new List<Vertex>();
adjacent_faces = new List<Triangle>();
cost = int.MaxValue;
collapse = null;
is_continuous_polygon = true;
can_move = true;
}
public bool Equals(Vertex other) {
return (id == other.id);
}
public float distance(Vertex other) {
return Vector3.Distance(position, other.position);
}
}
/**
* Triangle
*/
private class Triangle
{
public Vertex[] triangle_vertices;
public Vector3 normal;
public Triangle() {}
public Triangle(Vertex v0, Vertex v1, Vertex v2) {
triangle_vertices = new Vertex[3] { v0, v1, v2 };
normal = v1.normal;
}
public bool Equals(Triangle other) {
return (has(other.triangle_vertices[0]) && has(other.triangle_vertices[1]) && has(other.triangle_vertices[2]));
}
public bool has(Vertex v) {
for (int i = 0; i < 3; ++i) {
if (triangle_vertices[i].Equals(v)) {
return true;
}
}
return false;
}
public void replaceVertex(Vertex u, Vertex v) {
for (int i = 0; i < 3; ++i) {
if (triangle_vertices[i].Equals(u)) {
triangle_vertices[i] = v;
return;
}
}
}
public float computeArea() {
Vector3 ab = triangle_vertices[1].position - triangle_vertices[0].position;
Vector3 ac = triangle_vertices[2].position - triangle_vertices[0].position;
return 0.5f * Vector3.Cross(ab, ac).magnitude;
}
public static float computeArea(Vector3 v0, Vector3 v1, Vector3 v2) {
Vector3 ab = v1 - v0;
Vector3 ac = v2 - v0;
return 0.5f * Vector3.Cross(ab, ac).magnitude;
}
public float computeInternalAngle(Vertex v) {
Vector3 a = triangle_vertices[0].position;
Vector3 b = triangle_vertices[1].position;
Vector3 c = triangle_vertices[2].position;
Vector3 side1 = new Vector3(0, 0, 0);
Vector3 side2 = new Vector3(0, 0, 0);
if (triangle_vertices[0].Equals(v)) {
side1 = b - a;
side2 = c - a;
}
else if (triangle_vertices[1].Equals(v)) {
side1 = a - b;
side2 = c - b;
}
else {
side1 = a - c;
side2 = b - c;
}
return Mathf.Acos(Vector3.Dot(side1, side2) / (side1.magnitude * side2.magnitude));
}
}
/**
* distinct list
*/
private void distinct(List<Vertex> vl) {
for (int i = 0, count = vl.Count; i < count; ++i) {
for (int j = i + 1; j < count; ++j) {
if (vl[i].Equals(vl[j])) {
vl.RemoveAt(j);
--j;
--count;
}
}
}
}
private void distinct(List<Triangle> tl) {
for (int i = 0, count = tl.Count; i < count; ++i) {
for (int j = i + 1; j < count; ++j) {
if (tl[i].Equals(tl[j])) {
tl.RemoveAt(j);
--j;
--count;
}
}
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using gagr = Google.Api.Gax.ResourceNames;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.ErrorReporting.V1Beta1
{
/// <summary>Settings for <see cref="ReportErrorsServiceClient"/> instances.</summary>
public sealed partial class ReportErrorsServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="ReportErrorsServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="ReportErrorsServiceSettings"/>.</returns>
public static ReportErrorsServiceSettings GetDefault() => new ReportErrorsServiceSettings();
/// <summary>Constructs a new <see cref="ReportErrorsServiceSettings"/> object with default settings.</summary>
public ReportErrorsServiceSettings()
{
}
private ReportErrorsServiceSettings(ReportErrorsServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
ReportErrorEventSettings = existing.ReportErrorEventSettings;
OnCopy(existing);
}
partial void OnCopy(ReportErrorsServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ReportErrorsServiceClient.ReportErrorEvent</c> and <c>ReportErrorsServiceClient.ReportErrorEventAsync</c>
/// .
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ReportErrorEventSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="ReportErrorsServiceSettings"/> object.</returns>
public ReportErrorsServiceSettings Clone() => new ReportErrorsServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="ReportErrorsServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
public sealed partial class ReportErrorsServiceClientBuilder : gaxgrpc::ClientBuilderBase<ReportErrorsServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public ReportErrorsServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public ReportErrorsServiceClientBuilder()
{
UseJwtAccessWithScopes = ReportErrorsServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref ReportErrorsServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ReportErrorsServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override ReportErrorsServiceClient Build()
{
ReportErrorsServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<ReportErrorsServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<ReportErrorsServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private ReportErrorsServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return ReportErrorsServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<ReportErrorsServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return ReportErrorsServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => ReportErrorsServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => ReportErrorsServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => ReportErrorsServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>ReportErrorsService client wrapper, for convenient use.</summary>
/// <remarks>
/// An API for reporting error events.
/// </remarks>
public abstract partial class ReportErrorsServiceClient
{
/// <summary>
/// The default endpoint for the ReportErrorsService service, which is a host of
/// "clouderrorreporting.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "clouderrorreporting.googleapis.com:443";
/// <summary>The default ReportErrorsService scopes.</summary>
/// <remarks>
/// The default ReportErrorsService scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="ReportErrorsServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use
/// <see cref="ReportErrorsServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="ReportErrorsServiceClient"/>.</returns>
public static stt::Task<ReportErrorsServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new ReportErrorsServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="ReportErrorsServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use
/// <see cref="ReportErrorsServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="ReportErrorsServiceClient"/>.</returns>
public static ReportErrorsServiceClient Create() => new ReportErrorsServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="ReportErrorsServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="ReportErrorsServiceSettings"/>.</param>
/// <returns>The created <see cref="ReportErrorsServiceClient"/>.</returns>
internal static ReportErrorsServiceClient Create(grpccore::CallInvoker callInvoker, ReportErrorsServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
ReportErrorsService.ReportErrorsServiceClient grpcClient = new ReportErrorsService.ReportErrorsServiceClient(callInvoker);
return new ReportErrorsServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC ReportErrorsService client</summary>
public virtual ReportErrorsService.ReportErrorsServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Report an individual error event and record the event to a log.
///
/// This endpoint accepts **either** an OAuth token,
/// **or** an [API key](https://support.google.com/cloud/answer/6158862)
/// for authentication. To use an API key, append it to the URL as the value of
/// a `key` parameter. For example:
///
/// `POST
/// https://clouderrorreporting.googleapis.com/v1beta1/{projectName}/events:report?key=123ABC456`
///
/// **Note:** [Error Reporting](/error-reporting) is a global service built
/// on Cloud Logging and doesn't analyze logs stored
/// in regional log buckets or logs routed to other Google Cloud projects.
///
/// For more information, see
/// [Using Error Reporting with regionalized
/// logs](/error-reporting/docs/regionalization).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ReportErrorEventResponse ReportErrorEvent(ReportErrorEventRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Report an individual error event and record the event to a log.
///
/// This endpoint accepts **either** an OAuth token,
/// **or** an [API key](https://support.google.com/cloud/answer/6158862)
/// for authentication. To use an API key, append it to the URL as the value of
/// a `key` parameter. For example:
///
/// `POST
/// https://clouderrorreporting.googleapis.com/v1beta1/{projectName}/events:report?key=123ABC456`
///
/// **Note:** [Error Reporting](/error-reporting) is a global service built
/// on Cloud Logging and doesn't analyze logs stored
/// in regional log buckets or logs routed to other Google Cloud projects.
///
/// For more information, see
/// [Using Error Reporting with regionalized
/// logs](/error-reporting/docs/regionalization).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ReportErrorEventResponse> ReportErrorEventAsync(ReportErrorEventRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Report an individual error event and record the event to a log.
///
/// This endpoint accepts **either** an OAuth token,
/// **or** an [API key](https://support.google.com/cloud/answer/6158862)
/// for authentication. To use an API key, append it to the URL as the value of
/// a `key` parameter. For example:
///
/// `POST
/// https://clouderrorreporting.googleapis.com/v1beta1/{projectName}/events:report?key=123ABC456`
///
/// **Note:** [Error Reporting](/error-reporting) is a global service built
/// on Cloud Logging and doesn't analyze logs stored
/// in regional log buckets or logs routed to other Google Cloud projects.
///
/// For more information, see
/// [Using Error Reporting with regionalized
/// logs](/error-reporting/docs/regionalization).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ReportErrorEventResponse> ReportErrorEventAsync(ReportErrorEventRequest request, st::CancellationToken cancellationToken) =>
ReportErrorEventAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Report an individual error event and record the event to a log.
///
/// This endpoint accepts **either** an OAuth token,
/// **or** an [API key](https://support.google.com/cloud/answer/6158862)
/// for authentication. To use an API key, append it to the URL as the value of
/// a `key` parameter. For example:
///
/// `POST
/// https://clouderrorreporting.googleapis.com/v1beta1/{projectName}/events:report?key=123ABC456`
///
/// **Note:** [Error Reporting](/error-reporting) is a global service built
/// on Cloud Logging and doesn't analyze logs stored
/// in regional log buckets or logs routed to other Google Cloud projects.
///
/// For more information, see
/// [Using Error Reporting with regionalized
/// logs](/error-reporting/docs/regionalization).
/// </summary>
/// <param name="projectName">
/// Required. The resource name of the Google Cloud Platform project. Written
/// as `projects/{projectId}`, where `{projectId}` is the
/// [Google Cloud Platform project
/// ID](https://support.google.com/cloud/answer/6158840).
///
/// Example: // `projects/my-project-123`.
/// </param>
/// <param name="event">
/// Required. The error event to be reported.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ReportErrorEventResponse ReportErrorEvent(string projectName, ReportedErrorEvent @event, gaxgrpc::CallSettings callSettings = null) =>
ReportErrorEvent(new ReportErrorEventRequest
{
ProjectName = gax::GaxPreconditions.CheckNotNullOrEmpty(projectName, nameof(projectName)),
Event = gax::GaxPreconditions.CheckNotNull(@event, nameof(@event)),
}, callSettings);
/// <summary>
/// Report an individual error event and record the event to a log.
///
/// This endpoint accepts **either** an OAuth token,
/// **or** an [API key](https://support.google.com/cloud/answer/6158862)
/// for authentication. To use an API key, append it to the URL as the value of
/// a `key` parameter. For example:
///
/// `POST
/// https://clouderrorreporting.googleapis.com/v1beta1/{projectName}/events:report?key=123ABC456`
///
/// **Note:** [Error Reporting](/error-reporting) is a global service built
/// on Cloud Logging and doesn't analyze logs stored
/// in regional log buckets or logs routed to other Google Cloud projects.
///
/// For more information, see
/// [Using Error Reporting with regionalized
/// logs](/error-reporting/docs/regionalization).
/// </summary>
/// <param name="projectName">
/// Required. The resource name of the Google Cloud Platform project. Written
/// as `projects/{projectId}`, where `{projectId}` is the
/// [Google Cloud Platform project
/// ID](https://support.google.com/cloud/answer/6158840).
///
/// Example: // `projects/my-project-123`.
/// </param>
/// <param name="event">
/// Required. The error event to be reported.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ReportErrorEventResponse> ReportErrorEventAsync(string projectName, ReportedErrorEvent @event, gaxgrpc::CallSettings callSettings = null) =>
ReportErrorEventAsync(new ReportErrorEventRequest
{
ProjectName = gax::GaxPreconditions.CheckNotNullOrEmpty(projectName, nameof(projectName)),
Event = gax::GaxPreconditions.CheckNotNull(@event, nameof(@event)),
}, callSettings);
/// <summary>
/// Report an individual error event and record the event to a log.
///
/// This endpoint accepts **either** an OAuth token,
/// **or** an [API key](https://support.google.com/cloud/answer/6158862)
/// for authentication. To use an API key, append it to the URL as the value of
/// a `key` parameter. For example:
///
/// `POST
/// https://clouderrorreporting.googleapis.com/v1beta1/{projectName}/events:report?key=123ABC456`
///
/// **Note:** [Error Reporting](/error-reporting) is a global service built
/// on Cloud Logging and doesn't analyze logs stored
/// in regional log buckets or logs routed to other Google Cloud projects.
///
/// For more information, see
/// [Using Error Reporting with regionalized
/// logs](/error-reporting/docs/regionalization).
/// </summary>
/// <param name="projectName">
/// Required. The resource name of the Google Cloud Platform project. Written
/// as `projects/{projectId}`, where `{projectId}` is the
/// [Google Cloud Platform project
/// ID](https://support.google.com/cloud/answer/6158840).
///
/// Example: // `projects/my-project-123`.
/// </param>
/// <param name="event">
/// Required. The error event to be reported.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ReportErrorEventResponse> ReportErrorEventAsync(string projectName, ReportedErrorEvent @event, st::CancellationToken cancellationToken) =>
ReportErrorEventAsync(projectName, @event, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Report an individual error event and record the event to a log.
///
/// This endpoint accepts **either** an OAuth token,
/// **or** an [API key](https://support.google.com/cloud/answer/6158862)
/// for authentication. To use an API key, append it to the URL as the value of
/// a `key` parameter. For example:
///
/// `POST
/// https://clouderrorreporting.googleapis.com/v1beta1/{projectName}/events:report?key=123ABC456`
///
/// **Note:** [Error Reporting](/error-reporting) is a global service built
/// on Cloud Logging and doesn't analyze logs stored
/// in regional log buckets or logs routed to other Google Cloud projects.
///
/// For more information, see
/// [Using Error Reporting with regionalized
/// logs](/error-reporting/docs/regionalization).
/// </summary>
/// <param name="projectName">
/// Required. The resource name of the Google Cloud Platform project. Written
/// as `projects/{projectId}`, where `{projectId}` is the
/// [Google Cloud Platform project
/// ID](https://support.google.com/cloud/answer/6158840).
///
/// Example: // `projects/my-project-123`.
/// </param>
/// <param name="event">
/// Required. The error event to be reported.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ReportErrorEventResponse ReportErrorEvent(gagr::ProjectName projectName, ReportedErrorEvent @event, gaxgrpc::CallSettings callSettings = null) =>
ReportErrorEvent(new ReportErrorEventRequest
{
ProjectNameAsProjectName = gax::GaxPreconditions.CheckNotNull(projectName, nameof(projectName)),
Event = gax::GaxPreconditions.CheckNotNull(@event, nameof(@event)),
}, callSettings);
/// <summary>
/// Report an individual error event and record the event to a log.
///
/// This endpoint accepts **either** an OAuth token,
/// **or** an [API key](https://support.google.com/cloud/answer/6158862)
/// for authentication. To use an API key, append it to the URL as the value of
/// a `key` parameter. For example:
///
/// `POST
/// https://clouderrorreporting.googleapis.com/v1beta1/{projectName}/events:report?key=123ABC456`
///
/// **Note:** [Error Reporting](/error-reporting) is a global service built
/// on Cloud Logging and doesn't analyze logs stored
/// in regional log buckets or logs routed to other Google Cloud projects.
///
/// For more information, see
/// [Using Error Reporting with regionalized
/// logs](/error-reporting/docs/regionalization).
/// </summary>
/// <param name="projectName">
/// Required. The resource name of the Google Cloud Platform project. Written
/// as `projects/{projectId}`, where `{projectId}` is the
/// [Google Cloud Platform project
/// ID](https://support.google.com/cloud/answer/6158840).
///
/// Example: // `projects/my-project-123`.
/// </param>
/// <param name="event">
/// Required. The error event to be reported.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ReportErrorEventResponse> ReportErrorEventAsync(gagr::ProjectName projectName, ReportedErrorEvent @event, gaxgrpc::CallSettings callSettings = null) =>
ReportErrorEventAsync(new ReportErrorEventRequest
{
ProjectNameAsProjectName = gax::GaxPreconditions.CheckNotNull(projectName, nameof(projectName)),
Event = gax::GaxPreconditions.CheckNotNull(@event, nameof(@event)),
}, callSettings);
/// <summary>
/// Report an individual error event and record the event to a log.
///
/// This endpoint accepts **either** an OAuth token,
/// **or** an [API key](https://support.google.com/cloud/answer/6158862)
/// for authentication. To use an API key, append it to the URL as the value of
/// a `key` parameter. For example:
///
/// `POST
/// https://clouderrorreporting.googleapis.com/v1beta1/{projectName}/events:report?key=123ABC456`
///
/// **Note:** [Error Reporting](/error-reporting) is a global service built
/// on Cloud Logging and doesn't analyze logs stored
/// in regional log buckets or logs routed to other Google Cloud projects.
///
/// For more information, see
/// [Using Error Reporting with regionalized
/// logs](/error-reporting/docs/regionalization).
/// </summary>
/// <param name="projectName">
/// Required. The resource name of the Google Cloud Platform project. Written
/// as `projects/{projectId}`, where `{projectId}` is the
/// [Google Cloud Platform project
/// ID](https://support.google.com/cloud/answer/6158840).
///
/// Example: // `projects/my-project-123`.
/// </param>
/// <param name="event">
/// Required. The error event to be reported.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ReportErrorEventResponse> ReportErrorEventAsync(gagr::ProjectName projectName, ReportedErrorEvent @event, st::CancellationToken cancellationToken) =>
ReportErrorEventAsync(projectName, @event, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>ReportErrorsService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// An API for reporting error events.
/// </remarks>
public sealed partial class ReportErrorsServiceClientImpl : ReportErrorsServiceClient
{
private readonly gaxgrpc::ApiCall<ReportErrorEventRequest, ReportErrorEventResponse> _callReportErrorEvent;
/// <summary>
/// Constructs a client wrapper for the ReportErrorsService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="ReportErrorsServiceSettings"/> used within this client.</param>
public ReportErrorsServiceClientImpl(ReportErrorsService.ReportErrorsServiceClient grpcClient, ReportErrorsServiceSettings settings)
{
GrpcClient = grpcClient;
ReportErrorsServiceSettings effectiveSettings = settings ?? ReportErrorsServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callReportErrorEvent = clientHelper.BuildApiCall<ReportErrorEventRequest, ReportErrorEventResponse>(grpcClient.ReportErrorEventAsync, grpcClient.ReportErrorEvent, effectiveSettings.ReportErrorEventSettings).WithGoogleRequestParam("project_name", request => request.ProjectName);
Modify_ApiCall(ref _callReportErrorEvent);
Modify_ReportErrorEventApiCall(ref _callReportErrorEvent);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_ReportErrorEventApiCall(ref gaxgrpc::ApiCall<ReportErrorEventRequest, ReportErrorEventResponse> call);
partial void OnConstruction(ReportErrorsService.ReportErrorsServiceClient grpcClient, ReportErrorsServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC ReportErrorsService client</summary>
public override ReportErrorsService.ReportErrorsServiceClient GrpcClient { get; }
partial void Modify_ReportErrorEventRequest(ref ReportErrorEventRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Report an individual error event and record the event to a log.
///
/// This endpoint accepts **either** an OAuth token,
/// **or** an [API key](https://support.google.com/cloud/answer/6158862)
/// for authentication. To use an API key, append it to the URL as the value of
/// a `key` parameter. For example:
///
/// `POST
/// https://clouderrorreporting.googleapis.com/v1beta1/{projectName}/events:report?key=123ABC456`
///
/// **Note:** [Error Reporting](/error-reporting) is a global service built
/// on Cloud Logging and doesn't analyze logs stored
/// in regional log buckets or logs routed to other Google Cloud projects.
///
/// For more information, see
/// [Using Error Reporting with regionalized
/// logs](/error-reporting/docs/regionalization).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override ReportErrorEventResponse ReportErrorEvent(ReportErrorEventRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ReportErrorEventRequest(ref request, ref callSettings);
return _callReportErrorEvent.Sync(request, callSettings);
}
/// <summary>
/// Report an individual error event and record the event to a log.
///
/// This endpoint accepts **either** an OAuth token,
/// **or** an [API key](https://support.google.com/cloud/answer/6158862)
/// for authentication. To use an API key, append it to the URL as the value of
/// a `key` parameter. For example:
///
/// `POST
/// https://clouderrorreporting.googleapis.com/v1beta1/{projectName}/events:report?key=123ABC456`
///
/// **Note:** [Error Reporting](/error-reporting) is a global service built
/// on Cloud Logging and doesn't analyze logs stored
/// in regional log buckets or logs routed to other Google Cloud projects.
///
/// For more information, see
/// [Using Error Reporting with regionalized
/// logs](/error-reporting/docs/regionalization).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<ReportErrorEventResponse> ReportErrorEventAsync(ReportErrorEventRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ReportErrorEventRequest(ref request, ref callSettings);
return _callReportErrorEvent.Async(request, callSettings);
}
}
}
| |
using System.Threading.Tasks;
using Abp.Authorization.Users;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Events.Bus.Entities;
using Abp.Events.Bus.Handlers;
using Abp.Runtime.Caching;
using Abp.Runtime.Security;
namespace Abp.MultiTenancy
{
public class TenantCache<TTenant, TUser> : ITenantCache, IEventHandler<EntityChangedEventData<TTenant>>
where TTenant : AbpTenant<TUser>
where TUser : AbpUserBase
{
private readonly ICacheManager _cacheManager;
private readonly IRepository<TTenant> _tenantRepository;
private readonly IUnitOfWorkManager _unitOfWorkManager;
public TenantCache(
ICacheManager cacheManager,
IRepository<TTenant> tenantRepository,
IUnitOfWorkManager unitOfWorkManager)
{
_cacheManager = cacheManager;
_tenantRepository = tenantRepository;
_unitOfWorkManager = unitOfWorkManager;
}
public virtual TenantCacheItem Get(int tenantId)
{
var cacheItem = GetOrNull(tenantId);
if (cacheItem == null)
{
throw new AbpException("There is no tenant with given id: " + tenantId);
}
return cacheItem;
}
public virtual TenantCacheItem Get(string tenancyName)
{
var cacheItem = GetOrNull(tenancyName);
if (cacheItem == null)
{
throw new AbpException("There is no tenant with given tenancy name: " + tenancyName);
}
return cacheItem;
}
public virtual TenantCacheItem GetOrNull(string tenancyName)
{
var tenantId = _cacheManager
.GetTenantByNameCache()
.Get(
tenancyName.ToLowerInvariant(),
() => GetTenantOrNull(tenancyName)?.Id
);
if (tenantId == null)
{
return null;
}
return Get(tenantId.Value);
}
public TenantCacheItem GetOrNull(int tenantId)
{
return _cacheManager
.GetTenantCache()
.Get(
tenantId,
() =>
{
var tenant = GetTenantOrNull(tenantId);
if (tenant == null)
{
return null;
}
return CreateTenantCacheItem(tenant);
}
);
}
public virtual async Task<TenantCacheItem> GetAsync(int tenantId)
{
var cacheItem = await GetOrNullAsync(tenantId);
if (cacheItem == null)
{
throw new AbpException("There is no tenant with given id: " + tenantId);
}
return cacheItem;
}
public virtual async Task<TenantCacheItem> GetAsync(string tenancyName)
{
var cacheItem = await GetOrNullAsync(tenancyName);
if (cacheItem == null)
{
throw new AbpException("There is no tenant with given tenancy name: " + tenancyName);
}
return cacheItem;
}
public virtual async Task<TenantCacheItem> GetOrNullAsync(string tenancyName)
{
var tenantId = await _cacheManager
.GetTenantByNameCache()
.GetAsync(
tenancyName.ToLowerInvariant(), async key => (await GetTenantOrNullAsync(tenancyName))?.Id
);
if (tenantId == null)
{
return null;
}
return await GetAsync(tenantId.Value);
}
public virtual async Task<TenantCacheItem> GetOrNullAsync(int tenantId)
{
return await _cacheManager
.GetTenantCache()
.GetAsync(
tenantId, async key =>
{
var tenant = await GetTenantOrNullAsync(tenantId);
if (tenant == null)
{
return null;
}
return CreateTenantCacheItem(tenant);
}
);
}
protected virtual TenantCacheItem CreateTenantCacheItem(TTenant tenant)
{
return new TenantCacheItem
{
Id = tenant.Id,
Name = tenant.Name,
TenancyName = tenant.TenancyName,
EditionId = tenant.EditionId,
ConnectionString = SimpleStringCipher.Instance.Decrypt(tenant.ConnectionString),
IsActive = tenant.IsActive
};
}
protected virtual TTenant GetTenantOrNull(int tenantId)
{
return _unitOfWorkManager.WithUnitOfWork(() =>
{
using (_unitOfWorkManager.Current.SetTenantId(null))
{
return _tenantRepository.FirstOrDefault(tenantId);
}
});
}
protected virtual TTenant GetTenantOrNull(string tenancyName)
{
return _unitOfWorkManager.WithUnitOfWork(() =>
{
using (_unitOfWorkManager.Current.SetTenantId(null))
{
return _tenantRepository.FirstOrDefault(t => t.TenancyName == tenancyName);
}
});
}
protected virtual async Task<TTenant> GetTenantOrNullAsync(int tenantId)
{
return await _unitOfWorkManager.WithUnitOfWorkAsync(async () =>
{
using (_unitOfWorkManager.Current.SetTenantId(null))
{
return await _tenantRepository.FirstOrDefaultAsync(tenantId);
}
});
}
protected virtual async Task<TTenant> GetTenantOrNullAsync(string tenancyName)
{
return await _unitOfWorkManager.WithUnitOfWorkAsync(async () =>
{
using (_unitOfWorkManager.Current.SetTenantId(null))
{
return await _tenantRepository.FirstOrDefaultAsync(t => t.TenancyName == tenancyName);
}
});
}
public virtual void HandleEvent(EntityChangedEventData<TTenant> eventData)
{
var existingCacheItem = _cacheManager.GetTenantCache().GetOrDefault(eventData.Entity.Id);
_cacheManager
.GetTenantByNameCache()
.Remove(
existingCacheItem != null
? existingCacheItem.TenancyName.ToLowerInvariant()
: eventData.Entity.TenancyName.ToLowerInvariant()
);
_cacheManager
.GetTenantCache()
.Remove(eventData.Entity.Id);
}
}
}
| |
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using Umbraco.Core.Configuration;
using Umbraco.Core.Models;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Strings;
using umbraco.interfaces;
namespace Umbraco.Core.Services
{
//TODO: Move the rest of the logic for the PackageService.Export methods to here!
/// <summary>
/// A helper class to serialize entities to XML
/// </summary>
internal class EntityXmlSerializer
{
/// <summary>
/// Exports an <see cref="IContent"/> item to xml as an <see cref="XElement"/>
/// </summary>
/// <param name="contentService"></param>
/// <param name="dataTypeService"></param>
/// <param name="content">Content to export</param>
/// <param name="deep">Optional parameter indicating whether to include descendents</param>
/// <returns><see cref="XElement"/> containing the xml representation of the Content object</returns>
public XElement Serialize(IContentService contentService, IDataTypeService dataTypeService, IContent content, bool deep = false)
{
//nodeName should match Casing.SafeAliasWithForcingCheck(content.ContentType.Alias);
var nodeName = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "node" : content.ContentType.Alias.ToSafeAliasWithForcingCheck();
var xml = Serialize(dataTypeService, content, nodeName);
xml.Add(new XAttribute("nodeType", content.ContentType.Id));
xml.Add(new XAttribute("creatorName", content.GetCreatorProfile().Name));
xml.Add(new XAttribute("writerName", content.GetWriterProfile().Name));
xml.Add(new XAttribute("writerID", content.WriterId));
xml.Add(new XAttribute("template", content.Template == null ? "0" : content.Template.Id.ToString(CultureInfo.InvariantCulture)));
xml.Add(new XAttribute("nodeTypeAlias", content.ContentType.Alias));
if (deep)
{
var descendants = contentService.GetDescendants(content).ToArray();
var currentChildren = descendants.Where(x => x.ParentId == content.Id);
AddChildXml(contentService, dataTypeService, descendants, currentChildren, xml);
}
return xml;
}
/// <summary>
/// Exports an <see cref="IMedia"/> item to xml as an <see cref="XElement"/>
/// </summary>
/// <param name="mediaService"></param>
/// <param name="dataTypeService"></param>
/// <param name="media">Media to export</param>
/// <param name="deep">Optional parameter indicating whether to include descendents</param>
/// <returns><see cref="XElement"/> containing the xml representation of the Media object</returns>
public XElement Serialize(IMediaService mediaService, IDataTypeService dataTypeService, IMedia media, bool deep = false)
{
//nodeName should match Casing.SafeAliasWithForcingCheck(content.ContentType.Alias);
var nodeName = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "node" : media.ContentType.Alias.ToSafeAliasWithForcingCheck();
var xml = Serialize(dataTypeService, media, nodeName);
xml.Add(new XAttribute("nodeType", media.ContentType.Id));
xml.Add(new XAttribute("writerName", media.GetCreatorProfile().Name));
xml.Add(new XAttribute("writerID", media.CreatorId));
xml.Add(new XAttribute("version", media.Version));
xml.Add(new XAttribute("template", 0));
xml.Add(new XAttribute("nodeTypeAlias", media.ContentType.Alias));
if (deep)
{
var descendants = mediaService.GetDescendants(media).ToArray();
var currentChildren = descendants.Where(x => x.ParentId == media.Id);
AddChildXml(mediaService, dataTypeService, descendants, currentChildren, xml);
}
return xml;
}
/// <summary>
/// Exports an <see cref="IMedia"/> item to xml as an <see cref="XElement"/>
/// </summary>
/// <param name="dataTypeService"></param>
/// <param name="member">Member to export</param>
/// <returns><see cref="XElement"/> containing the xml representation of the Member object</returns>
public XElement Serialize(IDataTypeService dataTypeService, IMember member)
{
//nodeName should match Casing.SafeAliasWithForcingCheck(content.ContentType.Alias);
var nodeName = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "node" : member.ContentType.Alias.ToSafeAliasWithForcingCheck();
var xml = Serialize(dataTypeService, member, nodeName);
xml.Add(new XAttribute("nodeType", member.ContentType.Id));
xml.Add(new XAttribute("nodeTypeAlias", member.ContentType.Alias));
xml.Add(new XAttribute("loginName", member.Username));
xml.Add(new XAttribute("email", member.Email));
xml.Add(new XAttribute("key", member.Key));
return xml;
}
public XElement Serialize(IDataTypeService dataTypeService, Property property)
{
var propertyType = property.PropertyType;
var nodeName = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "data" : property.Alias.ToSafeAlias();
var xElement = new XElement(nodeName);
//Add the property alias to the legacy schema
if (UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema)
{
var a = new XAttribute("alias", property.Alias.ToSafeAlias());
xElement.Add(a);
}
//Get the property editor for thsi property and let it convert it to the xml structure
var propertyEditor = PropertyEditorResolver.Current.GetByAlias(property.PropertyType.PropertyEditorAlias);
if (propertyEditor != null)
{
var xmlValue = propertyEditor.ValueEditor.ConvertDbToXml(property, propertyType, dataTypeService);
xElement.Add(xmlValue);
}
return xElement;
}
/// <summary>
/// Used by Media Export to recursively add children
/// </summary>
/// <param name="mediaService"></param>
/// <param name="dataTypeService"></param>
/// <param name="originalDescendants"></param>
/// <param name="currentChildren"></param>
/// <param name="currentXml"></param>
private void AddChildXml(IMediaService mediaService, IDataTypeService dataTypeService, IMedia[] originalDescendants, IEnumerable<IMedia> currentChildren, XElement currentXml)
{
foreach (var child in currentChildren)
{
//add the child's xml
var childXml = Serialize(mediaService, dataTypeService, child);
currentXml.Add(childXml);
//copy local (out of closure)
var c = child;
//get this item's children
var children = originalDescendants.Where(x => x.ParentId == c.Id);
//recurse and add it's children to the child xml element
AddChildXml(mediaService, dataTypeService, originalDescendants, children, childXml);
}
}
/// <summary>
/// Part of the export of IContent and IMedia and IMember which is shared
/// </summary>
/// <param name="dataTypeService"></param>
/// <param name="contentBase">Base Content or Media to export</param>
/// <param name="nodeName">Name of the node</param>
/// <returns><see cref="XElement"/></returns>
private XElement Serialize(IDataTypeService dataTypeService, IContentBase contentBase, string nodeName)
{
//NOTE: that one will take care of umbracoUrlName
var url = contentBase.GetUrlSegment();
var xml = new XElement(nodeName,
new XAttribute("id", contentBase.Id),
new XAttribute("parentID", contentBase.Level > 1 ? contentBase.ParentId : -1),
new XAttribute("level", contentBase.Level),
new XAttribute("creatorID", contentBase.CreatorId),
new XAttribute("sortOrder", contentBase.SortOrder),
new XAttribute("createDate", contentBase.CreateDate.ToString("s")),
new XAttribute("updateDate", contentBase.UpdateDate.ToString("s")),
new XAttribute("nodeName", contentBase.Name),
new XAttribute("urlName", url),
new XAttribute("path", contentBase.Path),
new XAttribute("isDoc", ""));
foreach (var property in contentBase.Properties.Where(p => p != null && p.Value != null && p.Value.ToString().IsNullOrWhiteSpace() == false))
{
xml.Add(Serialize(dataTypeService, property));
}
return xml;
}
/// <summary>
/// Used by Content Export to recursively add children
/// </summary>
/// <param name="contentService"></param>
/// <param name="dataTypeService"></param>
/// <param name="originalDescendants"></param>
/// <param name="currentChildren"></param>
/// <param name="currentXml"></param>
private void AddChildXml(IContentService contentService, IDataTypeService dataTypeService, IContent[] originalDescendants, IEnumerable<IContent> currentChildren, XElement currentXml)
{
foreach (var child in currentChildren)
{
//add the child's xml
var childXml = Serialize(contentService, dataTypeService, child);
currentXml.Add(childXml);
//copy local (out of closure)
var c = child;
//get this item's children
var children = originalDescendants.Where(x => x.ParentId == c.Id);
//recurse and add it's children to the child xml element
AddChildXml(contentService, dataTypeService, originalDescendants, children, childXml);
}
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// WorkspaceResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Taskrouter.V1
{
public class WorkspaceResource : Resource
{
public sealed class QueueOrderEnum : StringEnum
{
private QueueOrderEnum(string value) : base(value) {}
public QueueOrderEnum() {}
public static implicit operator QueueOrderEnum(string value)
{
return new QueueOrderEnum(value);
}
public static readonly QueueOrderEnum Fifo = new QueueOrderEnum("FIFO");
public static readonly QueueOrderEnum Lifo = new QueueOrderEnum("LIFO");
}
private static Request BuildFetchRequest(FetchWorkspaceOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Taskrouter,
"/v1/Workspaces/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Workspace parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Workspace </returns>
public static WorkspaceResource Fetch(FetchWorkspaceOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Workspace parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Workspace </returns>
public static async System.Threading.Tasks.Task<WorkspaceResource> FetchAsync(FetchWorkspaceOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// fetch
/// </summary>
/// <param name="pathSid"> The SID of the resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Workspace </returns>
public static WorkspaceResource Fetch(string pathSid, ITwilioRestClient client = null)
{
var options = new FetchWorkspaceOptions(pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="pathSid"> The SID of the resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Workspace </returns>
public static async System.Threading.Tasks.Task<WorkspaceResource> FetchAsync(string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchWorkspaceOptions(pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildUpdateRequest(UpdateWorkspaceOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Taskrouter,
"/v1/Workspaces/" + options.PathSid + "",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Workspace parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Workspace </returns>
public static WorkspaceResource Update(UpdateWorkspaceOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Workspace parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Workspace </returns>
public static async System.Threading.Tasks.Task<WorkspaceResource> UpdateAsync(UpdateWorkspaceOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// update
/// </summary>
/// <param name="pathSid"> The SID of the resource to update </param>
/// <param name="defaultActivitySid"> The SID of the Activity that will be used when new Workers are created in the
/// Workspace </param>
/// <param name="eventCallbackUrl"> The URL we should call when an event occurs </param>
/// <param name="eventsFilter"> The list of Workspace events for which to call event_callback_url </param>
/// <param name="friendlyName"> A string to describe the Workspace resource </param>
/// <param name="multiTaskEnabled"> Whether multi-tasking is enabled </param>
/// <param name="timeoutActivitySid"> The SID of the Activity that will be assigned to a Worker when a Task reservation
/// times out without a response </param>
/// <param name="prioritizeQueueOrder"> The type of TaskQueue to prioritize when Workers are receiving Tasks from both
/// types of TaskQueues </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Workspace </returns>
public static WorkspaceResource Update(string pathSid,
string defaultActivitySid = null,
Uri eventCallbackUrl = null,
string eventsFilter = null,
string friendlyName = null,
bool? multiTaskEnabled = null,
string timeoutActivitySid = null,
WorkspaceResource.QueueOrderEnum prioritizeQueueOrder = null,
ITwilioRestClient client = null)
{
var options = new UpdateWorkspaceOptions(pathSid){DefaultActivitySid = defaultActivitySid, EventCallbackUrl = eventCallbackUrl, EventsFilter = eventsFilter, FriendlyName = friendlyName, MultiTaskEnabled = multiTaskEnabled, TimeoutActivitySid = timeoutActivitySid, PrioritizeQueueOrder = prioritizeQueueOrder};
return Update(options, client);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="pathSid"> The SID of the resource to update </param>
/// <param name="defaultActivitySid"> The SID of the Activity that will be used when new Workers are created in the
/// Workspace </param>
/// <param name="eventCallbackUrl"> The URL we should call when an event occurs </param>
/// <param name="eventsFilter"> The list of Workspace events for which to call event_callback_url </param>
/// <param name="friendlyName"> A string to describe the Workspace resource </param>
/// <param name="multiTaskEnabled"> Whether multi-tasking is enabled </param>
/// <param name="timeoutActivitySid"> The SID of the Activity that will be assigned to a Worker when a Task reservation
/// times out without a response </param>
/// <param name="prioritizeQueueOrder"> The type of TaskQueue to prioritize when Workers are receiving Tasks from both
/// types of TaskQueues </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Workspace </returns>
public static async System.Threading.Tasks.Task<WorkspaceResource> UpdateAsync(string pathSid,
string defaultActivitySid = null,
Uri eventCallbackUrl = null,
string eventsFilter = null,
string friendlyName = null,
bool? multiTaskEnabled = null,
string timeoutActivitySid = null,
WorkspaceResource.QueueOrderEnum prioritizeQueueOrder = null,
ITwilioRestClient client = null)
{
var options = new UpdateWorkspaceOptions(pathSid){DefaultActivitySid = defaultActivitySid, EventCallbackUrl = eventCallbackUrl, EventsFilter = eventsFilter, FriendlyName = friendlyName, MultiTaskEnabled = multiTaskEnabled, TimeoutActivitySid = timeoutActivitySid, PrioritizeQueueOrder = prioritizeQueueOrder};
return await UpdateAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadWorkspaceOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Taskrouter,
"/v1/Workspaces",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Workspace parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Workspace </returns>
public static ResourceSet<WorkspaceResource> Read(ReadWorkspaceOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<WorkspaceResource>.FromJson("workspaces", response.Content);
return new ResourceSet<WorkspaceResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Workspace parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Workspace </returns>
public static async System.Threading.Tasks.Task<ResourceSet<WorkspaceResource>> ReadAsync(ReadWorkspaceOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<WorkspaceResource>.FromJson("workspaces", response.Content);
return new ResourceSet<WorkspaceResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="friendlyName"> The friendly_name of the Workspace resources to read </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Workspace </returns>
public static ResourceSet<WorkspaceResource> Read(string friendlyName = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadWorkspaceOptions(){FriendlyName = friendlyName, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="friendlyName"> The friendly_name of the Workspace resources to read </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Workspace </returns>
public static async System.Threading.Tasks.Task<ResourceSet<WorkspaceResource>> ReadAsync(string friendlyName = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadWorkspaceOptions(){FriendlyName = friendlyName, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<WorkspaceResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<WorkspaceResource>.FromJson("workspaces", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<WorkspaceResource> NextPage(Page<WorkspaceResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Taskrouter)
);
var response = client.Request(request);
return Page<WorkspaceResource>.FromJson("workspaces", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<WorkspaceResource> PreviousPage(Page<WorkspaceResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Taskrouter)
);
var response = client.Request(request);
return Page<WorkspaceResource>.FromJson("workspaces", response.Content);
}
private static Request BuildCreateRequest(CreateWorkspaceOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Taskrouter,
"/v1/Workspaces",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Workspace parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Workspace </returns>
public static WorkspaceResource Create(CreateWorkspaceOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Workspace parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Workspace </returns>
public static async System.Threading.Tasks.Task<WorkspaceResource> CreateAsync(CreateWorkspaceOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// create
/// </summary>
/// <param name="friendlyName"> A string to describe the Workspace resource </param>
/// <param name="eventCallbackUrl"> The URL we should call when an event occurs </param>
/// <param name="eventsFilter"> The list of Workspace events for which to call event_callback_url </param>
/// <param name="multiTaskEnabled"> Whether multi-tasking is enabled </param>
/// <param name="template"> An available template name </param>
/// <param name="prioritizeQueueOrder"> The type of TaskQueue to prioritize when Workers are receiving Tasks from both
/// types of TaskQueues </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Workspace </returns>
public static WorkspaceResource Create(string friendlyName,
Uri eventCallbackUrl = null,
string eventsFilter = null,
bool? multiTaskEnabled = null,
string template = null,
WorkspaceResource.QueueOrderEnum prioritizeQueueOrder = null,
ITwilioRestClient client = null)
{
var options = new CreateWorkspaceOptions(friendlyName){EventCallbackUrl = eventCallbackUrl, EventsFilter = eventsFilter, MultiTaskEnabled = multiTaskEnabled, Template = template, PrioritizeQueueOrder = prioritizeQueueOrder};
return Create(options, client);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="friendlyName"> A string to describe the Workspace resource </param>
/// <param name="eventCallbackUrl"> The URL we should call when an event occurs </param>
/// <param name="eventsFilter"> The list of Workspace events for which to call event_callback_url </param>
/// <param name="multiTaskEnabled"> Whether multi-tasking is enabled </param>
/// <param name="template"> An available template name </param>
/// <param name="prioritizeQueueOrder"> The type of TaskQueue to prioritize when Workers are receiving Tasks from both
/// types of TaskQueues </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Workspace </returns>
public static async System.Threading.Tasks.Task<WorkspaceResource> CreateAsync(string friendlyName,
Uri eventCallbackUrl = null,
string eventsFilter = null,
bool? multiTaskEnabled = null,
string template = null,
WorkspaceResource.QueueOrderEnum prioritizeQueueOrder = null,
ITwilioRestClient client = null)
{
var options = new CreateWorkspaceOptions(friendlyName){EventCallbackUrl = eventCallbackUrl, EventsFilter = eventsFilter, MultiTaskEnabled = multiTaskEnabled, Template = template, PrioritizeQueueOrder = prioritizeQueueOrder};
return await CreateAsync(options, client);
}
#endif
private static Request BuildDeleteRequest(DeleteWorkspaceOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.Taskrouter,
"/v1/Workspaces/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Workspace parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Workspace </returns>
public static bool Delete(DeleteWorkspaceOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Workspace parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Workspace </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteWorkspaceOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// delete
/// </summary>
/// <param name="pathSid"> The SID of the resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Workspace </returns>
public static bool Delete(string pathSid, ITwilioRestClient client = null)
{
var options = new DeleteWorkspaceOptions(pathSid);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="pathSid"> The SID of the resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Workspace </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathSid, ITwilioRestClient client = null)
{
var options = new DeleteWorkspaceOptions(pathSid);
return await DeleteAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a WorkspaceResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> WorkspaceResource object represented by the provided JSON </returns>
public static WorkspaceResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<WorkspaceResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was last updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The name of the default activity
/// </summary>
[JsonProperty("default_activity_name")]
public string DefaultActivityName { get; private set; }
/// <summary>
/// The SID of the Activity that will be used when new Workers are created in the Workspace
/// </summary>
[JsonProperty("default_activity_sid")]
public string DefaultActivitySid { get; private set; }
/// <summary>
/// The URL we call when an event occurs
/// </summary>
[JsonProperty("event_callback_url")]
public Uri EventCallbackUrl { get; private set; }
/// <summary>
/// The list of Workspace events for which to call event_callback_url
/// </summary>
[JsonProperty("events_filter")]
public string EventsFilter { get; private set; }
/// <summary>
/// The string that you assigned to describe the Workspace resource
/// </summary>
[JsonProperty("friendly_name")]
public string FriendlyName { get; private set; }
/// <summary>
/// Whether multi-tasking is enabled
/// </summary>
[JsonProperty("multi_task_enabled")]
public bool? MultiTaskEnabled { get; private set; }
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The name of the timeout activity
/// </summary>
[JsonProperty("timeout_activity_name")]
public string TimeoutActivityName { get; private set; }
/// <summary>
/// The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response
/// </summary>
[JsonProperty("timeout_activity_sid")]
public string TimeoutActivitySid { get; private set; }
/// <summary>
/// The type of TaskQueue to prioritize when Workers are receiving Tasks from both types of TaskQueues
/// </summary>
[JsonProperty("prioritize_queue_order")]
[JsonConverter(typeof(StringEnumConverter))]
public WorkspaceResource.QueueOrderEnum PrioritizeQueueOrder { get; private set; }
/// <summary>
/// The absolute URL of the Workspace resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
/// <summary>
/// The URLs of related resources
/// </summary>
[JsonProperty("links")]
public Dictionary<string, string> Links { get; private set; }
private WorkspaceResource()
{
}
}
}
| |
using Shouldly;
using System;
using System.Collections.Generic;
using Xunit;
namespace Handyman.DataContractValidator.Tests.Validation
{
public class ObjectTests
{
[Fact]
public void ShouldPassWhenTypesMatch()
{
var type = typeof(ClassWithIntNumberProperty);
var dataContract = new { Number = typeof(int) };
new DataContractValidator().Validate(type, dataContract, out _).ShouldBeTrue();
}
[Fact]
public void ShouldFailWhenTypesIsMissingExpectedProperty()
{
var type = typeof(object);
var dataContract = new { Number = typeof(int) };
new DataContractValidator().Validate(type, dataContract, out var errors).ShouldBeFalse();
errors.ShouldBe(new[] { "Number : expected property not found." });
}
[Fact]
public void ShouldFailWhenTypesHasUnexpectedProperty()
{
var type = typeof(ClassWithIntNumberProperty);
var dataContract = new { };
new DataContractValidator().Validate(type, dataContract, out var errors).ShouldBeFalse();
errors.ShouldBe(new[] { "Number : unexpected property." });
}
[Fact]
public void ShouldIgnorePropertiesDecoratedWithIgnoreAttribute()
{
var type = typeof(TypeWithIgnoredProperty);
var dataContract = new { };
new DataContractValidator().Validate(type, dataContract, out _).ShouldBeTrue();
}
[Fact]
public void ShouldFailWhenExpectedPropertyIsDecoratedWithIgnoreAttribute()
{
var type = typeof(TypeWithIgnoredProperty);
var dataContract = new { Number = typeof(int) };
new DataContractValidator().Validate(type, dataContract, out var errors).ShouldBeFalse();
errors.ShouldBe(new[] { "Number : expected property found but it is decorated with ignore attribute." });
}
private class ClassWithIntNumberProperty
{
public int Number { get; set; }
}
private class TypeWithIgnoredProperty
{
[AttributeWithIgnoreInTheName]
public int Number { get; set; }
}
private class AttributeWithIgnoreInTheNameAttribute : Attribute { }
[Theory, MemberData(nameof(ShouldValidateNullableReferenceTypesParams))]
public void ShouldAccountForNullableAnnotations(Type type, object dataContract, string expected)
{
var validator = new DataContractValidator();
if (expected == "pass")
{
validator.Validate(type, dataContract);
}
else
{
Should.Throw<ValidationException>(() => validator.Validate(type, dataContract))
.Message.ShouldBe(expected);
}
}
public static IEnumerable<object[]> ShouldValidateNullableReferenceTypesParams()
{
yield return new object[]
{
typeof(NullableEnabledWithNullable),
new
{
Text = CanBeNull.String
},
"pass"
};
yield return new object[]
{
typeof(NullableEnabledWithNullable),
new
{
Text = typeof(string)
},
"Text : type mismatch, expected 'string' but found 'string?'."
};
yield return new object[]
{
typeof(NullableEnabledWithoutNullable),
new
{
Text = typeof(string)
},
"pass"
};
yield return new object[]
{
typeof(NullableEnabledWithoutNullable),
new
{
Text = CanBeNull.String
},
"Text : type mismatch, expected 'string?' but found 'string'."
};
yield return new object[]
{
typeof(NullableDisabled),
new
{
Text = typeof(string)
},
"pass"
};
yield return new object[]
{
typeof(NullableDisabled),
new
{
Text = CanBeNull.String
},
"Text : type mismatch, expected 'string?' but found 'string'."
};
}
#nullable enable
private class NullableEnabledWithNullable
{
public string? Text { get; set; }
}
private class NullableEnabledWithoutNullable
{
public string Text { get; set; } = null!;
}
#nullable disable
private class NullableDisabled
{
public string Text { get; set; }
}
#nullable restore
[Theory, MemberData(nameof(ShouldValidateReferenceTypeNullabilityParams))]
public void ShouldValidateReferenceTypeNullability(Type type, object dataContract, bool shouldThrow)
{
var validator = new DataContractValidator();
if (shouldThrow)
{
Should.Throw<ValidationException>(() => validator.Validate(type, dataContract));
}
else
{
validator.Validate(type, dataContract);
}
}
public static IEnumerable<object[]> ShouldValidateReferenceTypeNullabilityParams()
{
return new[]
{
// only not null
new object[]
{
typeof(OnlyNotNull),
new
{
NotNull = new { }
},
false
},
new object[]
{
typeof(OnlyNotNull),
new
{
NotNull = new CanBeNull(new { })
},
true
},
// only null
new object[]
{
typeof(OnlyNull),
new
{
Null = new { }
},
true
},
new object[]
{
typeof(OnlyNull),
new
{
Null = new CanBeNull(new { })
},
false
},
// not null & null
new object[]
{
typeof(NullAndNotNull),
new
{
NotNull = new { },
Null = new { }
},
true
},
new object[]
{
typeof(NullAndNotNull),
new
{
NotNull = new { },
Null = new CanBeNull(new { })
},
false
},
new object[]
{
typeof(NullAndNotNull),
new
{
NotNull = new CanBeNull(new { }),
Null = new { }
},
true
},
new object[]
{
typeof(NullAndNotNull),
new
{
NotNull = new CanBeNull(new { }),
Null = new CanBeNull(new { })
},
true
}
};
}
private class OnlyNotNull
{
public object NotNull { get; set; }
}
private class OnlyNull
{
public object? Null { get; set; }
}
private class NullAndNotNull
{
public object NotNull { get; set; }
public object? Null { get; set; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using ComTypes = System.Runtime.InteropServices.ComTypes;
namespace Kavod.ComReflection
{
internal class ComHelper
{
[DllImport("oleaut32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
static extern IntPtr LoadTypeLib(string fileName, out ComTypes.ITypeLib typeLib);
internal static ComTypes.ITypeLib LoadTypeLibrary(string file)
{
ComTypes.ITypeLib typeLib = null;
var ptr = IntPtr.Zero;
if (!File.Exists(file))
{
throw new FileNotFoundException(file);
}
try
{
var hr = LoadTypeLib(file, out typeLib);
if (hr != IntPtr.Zero)
{
// A ComException may be thrown here anyway.
throw new Exception("COM Error...");
}
return typeLib;
}
finally
{
if (typeLib != null && ptr != IntPtr.Zero)
{
typeLib.ReleaseTLibAttr(ptr);
}
}
}
internal static ComTypes.ITypeLib GetContainingTypeLib(ComTypes.ITypeInfo info)
{
ComTypes.ITypeLib referencedTypeLib;
var index = -1;
info.GetContainingTypeLib(out referencedTypeLib, out index);
if (index == -1)
{
throw new Exception("it wasn't me");
}
return referencedTypeLib;
}
internal static string GetTypeLibName(ComTypes.ITypeLib refTypeInfo)
{
string refTypeName;
string strHelpFile;
int dwHelpContext;
string strDocString;
refTypeInfo.GetDocumentation(-1, out refTypeName, out strDocString, out dwHelpContext, out strHelpFile);
return refTypeName;
}
internal static ComTypes.ITypeInfo GetRefTypeInfo(ComTypes.TYPEDESC tdesc, ComTypes.ITypeInfo context)
{
int href;
unchecked
{
href = (int)(tdesc.lpValue.ToInt64() & 0xFFFFFFFF);
}
ComTypes.ITypeInfo refTypeInfo;
context.GetRefTypeInfo(href, out refTypeInfo);
return refTypeInfo;
}
internal static string GetTypeName(ComTypes.ITypeInfo refTypeInfo)
{
string refTypeName;
string strHelpFile;
int dwHelpContext;
string strDocString;
refTypeInfo.GetDocumentation(-1, out refTypeName, out strDocString, out dwHelpContext, out strHelpFile);
return refTypeName;
}
internal static ComTypes.TYPELIBATTR GetTypeLibAttr(ComTypes.ITypeLib typeLib)
{
IntPtr ptr;
typeLib.GetLibAttr(out ptr);
var typeLibAttr = (ComTypes.TYPELIBATTR) Marshal.PtrToStructure(ptr, typeof(ComTypes.TYPELIBATTR));
typeLib.ReleaseTLibAttr(ptr);
return typeLibAttr;
}
internal static IEnumerable<ComTypes.ITypeInfo> GetInheritedTypeInfos(TypeInfoAndTypeAttr infoAndAttr)
{
return GetInheritedTypeInfos(infoAndAttr.TypeInfo, infoAndAttr.TypeAttr);
}
internal static IEnumerable<ComTypes.ITypeInfo> GetInheritedTypeInfos(ComTypes.ITypeInfo typeInfo, ComTypes.TYPEATTR typeAttr)
{
for (var iImplType = 0; iImplType < typeAttr.cImplTypes; iImplType++)
{
int href;
typeInfo.GetRefTypeOfImplType(iImplType, out href);
ComTypes.ITypeInfo implTypeInfo;
typeInfo.GetRefTypeInfo(href, out implTypeInfo);
yield return implTypeInfo;
}
}
internal static IEnumerable<ComTypes.ITypeInfo> GetTypeInformation(ComTypes.ITypeLib typeLib)
{
var comTypeCount = typeLib.GetTypeInfoCount();
for (var typeIndex = 0; typeIndex < comTypeCount; typeIndex++)
{
ComTypes.ITypeInfo comTypeInfo;
typeLib.GetTypeInfo(typeIndex, out comTypeInfo);
yield return comTypeInfo;
}
}
internal static string GetMemberName(ComTypes.ITypeInfo typeInfo, ComTypes.FUNCDESC funcDesc)
{
// first element in the sequence is the name of the method.
return GetNames(typeInfo, funcDesc.memid).First();
}
internal static string GetMemberName(ComTypes.ITypeInfo typeInfo, ComTypes.VARDESC varDesc)
{
// first element in the sequence is the name of the method.
return GetNames(typeInfo, varDesc.memid).First();
}
internal static IEnumerable<string> GetParameterNames(ComTypes.ITypeInfo typeInfo, ComTypes.FUNCDESC funcDesc)
{
// skip the first in the sequence because it is the name of the method.
return GetNames(typeInfo, funcDesc.memid).Skip(1);
}
private static IEnumerable<string> GetNames(ComTypes.ITypeInfo typeInfo, int memberId)
{
const int maxNames = 255;
var names = new string[maxNames];
int pcNames;
typeInfo.GetNames(memberId, names, maxNames, out pcNames);
for (var i = 0; i < pcNames; i++)
{
yield return names[i];
}
}
internal static IEnumerable<ComTypes.FUNCDESC> GetFuncDescs(TypeInfoAndTypeAttr infoAndAttr)
{
return GetFuncDescs(infoAndAttr.TypeInfo, infoAndAttr.TypeAttr);
}
private static IEnumerable<ComTypes.FUNCDESC> GetFuncDescs(ComTypes.ITypeInfo typeInfo, ComTypes.TYPEATTR typeAttr)
{
for (var iFunc = 0; iFunc < typeAttr.cFuncs; iFunc++)
{
IntPtr pFuncDesc;
typeInfo.GetFuncDesc(iFunc, out pFuncDesc);
var funcDesc = (ComTypes.FUNCDESC) Marshal.PtrToStructure(pFuncDesc, typeof(ComTypes.FUNCDESC));
yield return funcDesc;
typeInfo.ReleaseFuncDesc(pFuncDesc);
}
}
internal static ComTypes.TYPEATTR GetTypeAttr(ComTypes.ITypeInfo typeInfo)
{
IntPtr pTypeAttr;
typeInfo.GetTypeAttr(out pTypeAttr);
var typeAttr = (ComTypes.TYPEATTR) Marshal.PtrToStructure(pTypeAttr, typeof(ComTypes.TYPEATTR));
typeInfo.ReleaseTypeAttr(pTypeAttr);
return typeAttr;
}
internal static IEnumerable<ComTypes.VARDESC> GetTypeVariables(TypeInfoAndTypeAttr info)
{
return GetTypeVariables(info.TypeInfo, info.TypeAttr);
}
internal static IEnumerable<ComTypes.VARDESC> GetTypeVariables(ComTypes.ITypeInfo typeInfo, ComTypes.TYPEATTR typeAttr)
{
for (var iVar = 0; iVar < typeAttr.cVars; iVar++)
{
IntPtr pVarDesc;
typeInfo.GetVarDesc(iVar, out pVarDesc);
var varDesc = (ComTypes.VARDESC) Marshal.PtrToStructure(pVarDesc, typeof(ComTypes.VARDESC));
yield return varDesc;
typeInfo.ReleaseVarDesc(pVarDesc);
}
}
internal static IEnumerable<ComTypes.ELEMDESC> GetElemDescs(ComTypes.FUNCDESC funcDesc)
{
for (var iParam = 0; iParam < funcDesc.cParams; iParam++)
{
yield return (ComTypes.ELEMDESC) Marshal.PtrToStructure(
new IntPtr(funcDesc.lprgelemdescParam.ToInt64() +
Marshal.SizeOf(typeof(ComTypes.ELEMDESC)) * iParam),
typeof(ComTypes.ELEMDESC));
}
}
internal static bool IsConstant(ComTypes.VARDESC varDesc)
{
return varDesc.varkind == ComTypes.VARKIND.VAR_CONST;
}
internal static object GetConstantValue(ComTypes.VARDESC varDesc)
{
if (varDesc.varkind == ComTypes.VARKIND.VAR_CONST)
{
try
{
var constantValue = varDesc.desc.lpvarValue;
return Marshal.GetObjectForNativeVariant(constantValue);
}
catch (Exception e)
{
return null;
}
}
return null;
}
internal static object GetDefaultValue(ComTypes.PARAMDESC paramDesc)
{
if (paramDesc.wParamFlags.HasFlag(ComTypes.PARAMFLAG.PARAMFLAG_FHASDEFAULT))
{
try
{
// http://stackoverflow.com/a/20610486
var defaultValue = new IntPtr((long)paramDesc.lpVarValue + 8);
return Marshal.GetObjectForNativeVariant(defaultValue);
}
catch (Exception e)
{
return null;
}
}
return null;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
namespace ConnectionsEducation.Redis {
/// <summary>
/// Connection state object. Does the heavy-lifting for the Redis protocol by implementing a state machine.
/// </summary>
public class ConnectionState {
/// <summary>
/// The plus as a byte representation in ASCII
/// </summary>
private const byte PLUS = 43;
/// <summary>
/// The colon as a byte representation in ASCII
/// </summary>
private const byte COLON = 58;
/// <summary>
/// The asterisk as a byte representation in ASCII
/// </summary>
private const byte ASTERISK = 42;
/// <summary>
/// The dollar as a byte representation in ASCII
/// </summary>
private const byte DOLLAR = 36;
/// <summary>
/// The minus as a byte representation in ASCII
/// </summary>
private const byte MINUS = 45;
/// <summary>
/// The carriage return as a byte representation in ASCII
/// </summary>
private const byte CR = 13;
/// <summary>
/// The line-feed as a byte representation in ASCII
/// </summary>
private const byte LF = 10;
/// <summary>
/// The buffer size
/// </summary>
public const int BUFFER_SIZE = 1000;
/// <summary>
/// The encoding
/// </summary>
private readonly Encoding _encoding;
/// <summary>
/// CR-LF as a byte array
/// </summary>
private static readonly byte[] CrLf = {CR, LF};
/// <summary>
/// The buffer
/// </summary>
public byte[] buffer = new byte[BUFFER_SIZE];
/// <summary>
/// The received data queue
/// </summary>
public Queue receivedData = new Queue();
/// <summary>
/// The operations stack
/// </summary>
public Stack operations = new Stack();
/// <summary>
/// The socket
/// </summary>
public Socket workSocket = null;
private Action<ObjectReceivedEventArgs> _onObjectReceived;
/// <summary>
/// A consumer of this <see cref="ConnectionState"/> instance will observe for objects received from the state.
/// </summary>
/// <param name="action">The outer scope action to perform. Set to null when finised.</param>
internal void setObjectReceivedAction(Action<ObjectReceivedEventArgs> action) {
_onObjectReceived = action;
}
/// <summary>
/// Initializes a new instance of the <see cref="ConnectionState"/> class.
/// </summary>
public ConnectionState() : this(Encoding.ASCII) {}
/// <summary>
/// Initializes a new instance of the <see cref="ConnectionState"/> class.
/// </summary>
/// <param name="encoding">The encoding.</param>
public ConnectionState(Encoding encoding) {
_encoding = encoding;
}
/// <summary>
/// Gets the encoding.
/// </summary>
/// <value>The encoding.</value>
public Encoding encoding {
get { return _encoding; }
}
/// <summary>
/// Updates the internal states based on the latest bytes read.
/// </summary>
/// <param name="bytesRead">The number of bytes read.</param>
/// <exception cref="System.NotImplementedException">
/// Operation not implemented for + encoding.GetString(buffer, bufferIndex, 1)
/// or
/// Don't know what to do.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// Protocol Violation. Expected CR-LF.
/// or
/// Protocol Violation. Expected CR.
/// or
/// Protocol Violation. Expected LF.
/// </exception>
public void update(int bytesRead) {
int bufferIndex = 0;
while (bufferIndex < buffer.Length && bufferIndex < bytesRead) {
if (operations.Count == 0)
operations.Push(new AwaitCommand());
object nextOp = operations.Peek();
if (nextOp is AwaitCommand) {
switch (buffer[bufferIndex]) {
case PLUS:
operations.Pop();
operations.Push(new AwaitSimpleString());
++bufferIndex;
continue;
case DOLLAR:
operations.Pop();
operations.Push(new AwaitString { readSize = false });
operations.Push(new AwaitSimpleString());
++bufferIndex;
continue;
case COLON:
operations.Pop();
operations.Push(new AwaitInt());
++bufferIndex;
continue;
case ASTERISK:
operations.Pop();
operations.Push(new AwaitList {readLength = false});
operations.Push(new AwaitSimpleString());
++bufferIndex;
continue;
case MINUS:
operations.Pop();
operations.Push(new AwaitError());
operations.Push(new AwaitSimpleString());
++bufferIndex;
continue;
default:
throw new NotImplementedException("Operation not implemented for " + encoding.GetString(buffer, bufferIndex, 1));
}
} else if (nextOp is AwaitCrLf) {
AwaitCrLf op = (AwaitCrLf)nextOp;
int availableLength = buffer.Length - bufferIndex;
if (availableLength < 1)
continue;
if (!op.cr) {
if (availableLength >= 2) {
if (buffer[bufferIndex] == CR && buffer[bufferIndex + 1] == LF) {
operations.Pop();
bufferIndex += 2;
} else {
throw new InvalidOperationException("Protocol Violation. Expected CR-LF.");
}
} else {
if (buffer[bufferIndex] == CR) {
op.cr = true;
++bufferIndex;
} else {
throw new InvalidOperationException("Protocol Violation. Expected CR.");
}
}
} else {
if (buffer[bufferIndex] == LF) {
operations.Pop();
++bufferIndex;
} else {
throw new InvalidOperationException("Protocol Violation. Expected LF.");
}
}
} else if (nextOp is AwaitSimpleString) {
AwaitSimpleString op = (AwaitSimpleString)nextOp;
IEnumerable<byte> partialBuffer = buffer.Skip(bufferIndex).Take(bytesRead - bufferIndex);
byte[] potential = op.data == null ? partialBuffer.ToArray() : op.data.Concat(partialBuffer).ToArray();
int indexCrLf = potential.indexOf(CrLf);
if (indexCrLf == -1) {
op.data = potential;
bufferIndex = buffer.Length;
} else {
byte[] stringData = potential.Take(indexCrLf).ToArray();
operations.Pop();
if (operations.Count > 0 && operations.Peek() is AwaitError) {
operations.Pop();
apply(new RedisErrorException(encoding.GetString(stringData)));
} else {
applyString(stringData);
}
bufferIndex += indexCrLf + CrLf.Length - (op.data == null ? 0 : op.data.Length);
}
} else if (nextOp is AwaitInt) {
AwaitInt op = (AwaitInt)nextOp;
IEnumerable<byte> partialBuffer = buffer.Skip(bufferIndex).Take(bytesRead - bufferIndex);
byte[] potential = op.data == null ? partialBuffer.ToArray() : op.data.Concat(partialBuffer).ToArray();
int indexCrLf = potential.indexOf(CrLf);
if (indexCrLf == -1) {
op.data = potential;
bufferIndex = buffer.Length;
} else {
byte[] stringData = potential.Take(indexCrLf).ToArray();
string valueLiteral = _encoding.GetString(stringData);
operations.Pop();
long value;
if (long.TryParse(valueLiteral, out value)) {
apply(value);
} else {
apply(new Exception(string.Format("Failed to parse {0} as an integer", valueLiteral)));
}
bufferIndex += indexCrLf + CrLf.Length - (op.data == null ? 0 : op.data.Length);
}
} else if (nextOp is AwaitString) {
AwaitString op = (AwaitString)nextOp;
int currentSize = op.data.Length;
int availableLength = buffer.Length - bufferIndex;
if (currentSize + availableLength >= op.size) {
int count = op.size - op.data.Length;
byte[] stringData = op.data.Concat(buffer.Skip(bufferIndex).Take(count)).ToArray();
operations.Pop();
applyString(stringData);
bufferIndex = bufferIndex + count;
operations.Push(new AwaitCrLf());
continue;
} else {
op.data = op.data.Concat(buffer.Skip(bufferIndex).Take(availableLength)).ToArray();
bufferIndex = bufferIndex + availableLength;
}
} else if (nextOp is AwaitList) {
AwaitList op = (AwaitList)nextOp;
if (op.objectsRead < op.length)
operations.Push(new AwaitCommand());
} else {
throw new NotImplementedException("Don't know what to do.");
}
nextOp = operations.Count > 0 ? operations.Peek() : null;
while (nextOp is AwaitList && ((AwaitList)nextOp).objectsRead >= ((AwaitList)nextOp).length) {
operations.Pop();
apply(((AwaitList)nextOp).data);
nextOp = operations.Count > 0 ? operations.Peek() : null;
}
if (operations.Count == 0) {
// Opportunity here to convert from "internal" state to "external" state.
Queue receivedObject = new Queue(receivedData.Count);
while (receivedData.Count > 0)
receivedObject.Enqueue(receivedData.Dequeue());
_onObjectReceived(new ObjectReceivedEventArgs(receivedObject));
}
}
}
/// <summary>
/// Applies the specified value.
/// </summary>
/// <param name="value">The value.</param>
private void apply(object[] value) {
if (operations.Count == 0 || !applyToList(value))
receivedData.Enqueue(value);
}
/// <summary>
/// Applies the specified value.
/// </summary>
/// <param name="value">The value.</param>
private void applyString(byte[] value) {
if (operations.Count == 0) {
receivedData.Enqueue(value);
return;
}
object nextOp = operations.Peek();
if (nextOp is AwaitString && !((AwaitString)nextOp).readSize) {
AwaitString op = (AwaitString)nextOp;
int size = Convert.ToInt32(Encoding.ASCII.GetString(value));
op.readSize = true;
op.size = size;
op.data = new byte[] {};
if (op.size < 0) {
operations.Pop();
applyString(null);
}
} else if (nextOp is AwaitList && !((AwaitList)nextOp).readLength) {
AwaitList op = (AwaitList)nextOp;
int length = Convert.ToInt32(Encoding.ASCII.GetString(value));
op.readLength = true;
op.length = length;
if (op.length < 0) {
operations.Pop();
applyString(null);
}
op.data = new object[length];
} else {
if (!applyToList(value)) {
receivedData.Enqueue(value);
operations.Push(new AwaitCrLf());
}
}
}
/// <summary>
/// Applies to list.
/// </summary>
/// <param name="value">The value.</param>
/// <returns><c>true</c> if the object was applied to a list, <c>false</c> if another application should be attempted.</returns>
private bool applyToList(object value) {
object nextOp = operations.Peek();
if (!(nextOp is AwaitList))
return false;
AwaitList op = (AwaitList)nextOp;
if (op.objectsRead >= op.length) {
return false;
} else {
op.data[op.objectsRead++] = value;
return true;
}
}
/// <summary>
/// Applies the specified value.
/// </summary>
/// <param name="value">The value.</param>
private void apply(long value) {
if (operations.Count == 0 || !applyToList(value)) {
receivedData.Enqueue(value);
}
}
/// <summary>
/// Applies the specified error.
/// </summary>
/// <param name="error">The error.</param>
private void apply(Exception error) {
if (operations.Count == 0 || !applyToList(error)) {
receivedData.Enqueue(error);
}
}
/// <summary>
/// Class AwaitSimpleString.
/// </summary>
private class AwaitSimpleString {
/// <summary>
/// Gets or sets the data.
/// </summary>
/// <value>The data.</value>
public byte[] data { get; set; }
}
/// <summary>
/// Class AwaitInt.
/// </summary>
private class AwaitInt {
/// <summary>
/// Gets or sets the data.
/// </summary>
/// <value>The data.</value>
public byte[] data { get; set; }
}
/// <summary>
/// Class AwaitString.
/// </summary>
private class AwaitString {
/// <summary>
/// Gets or sets a value indicating whether the object read the size.
/// </summary>
/// <value><c>true</c> if the object read the size; otherwise, <c>false</c>.</value>
public bool readSize { get; set; }
/// <summary>
/// Gets or sets the size.
/// </summary>
/// <value>The size.</value>
public int size { get; set; }
/// <summary>
/// Gets or sets the data.
/// </summary>
/// <value>The data.</value>
public byte[] data { get; set; }
}
/// <summary>
/// Class AwaitList.
/// </summary>
private class AwaitList {
/// <summary>
/// Gets or sets a value indicating whether the object read the length.
/// </summary>
/// <value><c>true</c> if the object read the length; otherwise, <c>false</c>.</value>
public bool readLength { get; set; }
/// <summary>
/// Gets or sets the length.
/// </summary>
/// <value>The length.</value>
public int length { get; set; }
/// <summary>
/// Gets or sets the objects read.
/// </summary>
/// <value>The objects read.</value>
public int objectsRead { get; set; }
/// <summary>
/// Gets or sets the data.
/// </summary>
/// <value>The data.</value>
public object[] data { get; set; }
}
/// <summary>
/// Class AwaitCommand.
/// </summary>
private class AwaitCommand {
}
/// <summary>
/// Class AwaitError.
/// </summary>
private class AwaitError {
}
/// <summary>
/// Class AwaitCrLf.
/// </summary>
private class AwaitCrLf {
/// <summary>
/// Gets or sets a value indicating whether a carriage return was read.
/// </summary>
/// <value><c>true</c> if CR was read; otherwise, <c>false</c>.</value>
public bool cr { get; set; }
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Text;
using error = Microsoft.Build.BuildEngine.Shared.ErrorUtilities;
using System.Globalization;
using System.Reflection;
using Microsoft.Build.BuildEngine.Shared;
namespace Microsoft.Build.BuildEngine
{
internal class ToolsetConfigurationReader : ToolsetReader
{
private ToolsetConfigurationSection configurationSection = null;
private ReadApplicationConfiguration readApplicationConfiguration = null;
private bool configurationReadAttempted = false;
/// <summary>
/// Default constructor
/// </summary>
internal ToolsetConfigurationReader()
: this(new ReadApplicationConfiguration(ToolsetConfigurationReader.ReadApplicationConfiguration))
{
}
/// <summary>
/// Constructor taking a delegate for unit test purposes only
/// </summary>
/// <param name="readApplicationConfiguration"></param>
internal ToolsetConfigurationReader(ReadApplicationConfiguration readApplicationConfiguration)
{
error.VerifyThrowArgumentNull(readApplicationConfiguration, "readApplicationConfiguration");
this.readApplicationConfiguration = readApplicationConfiguration;
}
/// <summary>
/// Returns the list of tools versions
/// </summary>
protected override IEnumerable<PropertyDefinition> ToolsVersions
{
get
{
if (ConfigurationSection != null)
{
foreach (ToolsetElement toolset in ConfigurationSection.Toolsets)
{
string location = ResourceUtilities.FormatResourceString
(
"ConfigFileLocation",
toolset.ElementInformation.Source,
toolset.ElementInformation.LineNumber
);
if (toolset.toolsVersion != null && toolset.toolsVersion.Length == 0)
{
InvalidToolsetDefinitionException.Throw("InvalidToolsetValueInConfigFileValue", location);
}
yield return new PropertyDefinition(toolset.toolsVersion, string.Empty, location);
}
}
else
{
yield break;
}
}
}
/// <summary>
/// Returns the default tools version, or null if none was specified
/// </summary>
protected override string DefaultToolsVersion
{
get
{
return (ConfigurationSection == null ? null : ConfigurationSection.Default);
}
}
/// <summary>
/// Provides an enumerator over property definitions for a specified tools version
/// </summary>
/// <param name="toolsVersion"></param>
/// <returns></returns>
protected override IEnumerable<PropertyDefinition> GetPropertyDefinitions(string toolsVersion)
{
ToolsetElement toolsetElement = ConfigurationSection.Toolsets.GetElement(toolsVersion);
if (toolsetElement == null)
{
yield break;
}
foreach (ToolsetElement.PropertyElement propertyElement in toolsetElement.PropertyElements)
{
string location = ResourceUtilities.FormatResourceString
(
"ConfigFileLocation",
propertyElement.ElementInformation.Source,
propertyElement.ElementInformation.LineNumber
);
if (propertyElement.Name != null && propertyElement.Name.Length == 0)
{
InvalidToolsetDefinitionException.Throw("InvalidToolsetValueInConfigFileValue", location);
}
yield return new PropertyDefinition(propertyElement.Name, propertyElement.Value, location);
}
}
/// <summary>
/// Reads the application configuration file.
/// NOTE: this is abstracted into a method to support unit testing GetToolsetDataFromConfiguration().
/// Unit tests wish to avoid reading (nunit.exe) application configuration file.
/// </summary>
private static Configuration ReadApplicationConfiguration()
{
return ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}
/// <summary>
/// Lazy getter for the ToolsetConfigurationSection
/// Returns null if the section is not present
/// </summary>
private ToolsetConfigurationSection ConfigurationSection
{
get
{
if (null == configurationSection && !configurationReadAttempted)
{
try
{
Configuration configuration = readApplicationConfiguration();
// This will be null if the application config file does not have the following section
// definition for the msbuildToolsets section as the first child element.
// <configSections>
// <section name=""msbuildToolsets"" type=""Microsoft.Build.BuildEngine.ToolsetConfigurationSection, Microsoft.Build.Engine"" />
// </configSections>";
// Note that the application config file may or may not contain an msbuildToolsets element.
// For example:
// If section definition is present and section is not present, this value is not null
// If section definition is not present and section is also not present, this value is null
// If the section definition is not present and section is present, then this value is null
if (null != configuration)
{
configurationSection = configuration.GetSection("msbuildToolsets") as ToolsetConfigurationSection;
}
}
// ConfigurationException is obsolete, but we catch it rather than
// ConfigurationErrorsException (which is what we throw below) because it is more
// general and we don't want to miss catching some other derived exception.
catch (ConfigurationException ex)
{
string location = ResourceUtilities.FormatResourceString
(
"ConfigFileLocation",
ex.Filename,
ex.Line
);
InvalidToolsetDefinitionException.Throw(ex, "ConfigFileReadError", location, ex.BareMessage);
}
finally
{
configurationReadAttempted = true;
}
}
return configurationSection;
}
}
}
/// <summary>
/// This class is used to programmatically read msbuildToolsets section
/// in from the configuration file. An example of application config file:
///
/// <configuration>
/// <msbuildToolsets default="2.0">
/// <toolset toolsVersion="2.0">
/// <property name="MSBuildBinPath" value="D:\windows\Microsoft.NET\Framework\v2.0.x86ret\"/>
/// <property name="SomeOtherProperty" value="SomeOtherPropertyValue"/>
/// </toolset>
/// <toolset toolsVersion="3.5">
/// <property name="MSBuildBinPath" value="D:\windows\Microsoft.NET\Framework\v3.5.x86ret\"/>
/// </toolset>
/// </msbuildToolsets>
/// </configuration>
///
/// </summary>
/// <remarks>
/// Internal for unit testing only
/// </remarks>
internal sealed class ToolsetConfigurationSection : ConfigurationSection
{
/// <summary>
/// toolsVersion element collection
/// </summary>
[ConfigurationProperty("", IsDefaultCollection = true)]
public ToolsetElementCollection Toolsets
{
get
{
return (ToolsetElementCollection)base[""];
}
}
/// <summary>
/// default attribute on msbuildToolsets element, specifying the default ToolsVersion
/// </summary>
[ConfigurationProperty("default")]
public string Default
{
get
{
// The ConfigurationPropertyAttribute constructor accepts a named parameter "DefaultValue"
// that doesn't seem to work if null is the desired default value. So here we return null
// whenever the base class gives us an empty string.
// Note this means we can't distinguish between the attribute being present but containing
// an empty string for its value and the attribute not being present at all.
string defaultValue = (string)base["default"];
return (String.IsNullOrEmpty(defaultValue) ? null : defaultValue);
}
set
{
base["default"] = value;
}
}
}
/// <summary>
/// Class representing the collection of toolset elements
/// </summary>
/// <remarks>
/// Internal for unit testing only
/// </remarks>
internal sealed class ToolsetElementCollection : ConfigurationElementCollection
{
/// <summary>
/// We use this dictionary to track whether or not we've seen a given
/// toolset definition before, since the .NET configuration classes
/// won't perform this check without respect for case.
/// </summary>
private Dictionary<string, string> previouslySeenToolsVersions = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Creates a new element of the collection
/// </summary>
/// <returns>Created element</returns>
protected override ConfigurationElement CreateNewElement()
{
return new ToolsetElement();
}
/// <summary>
/// overridden so we can track previously seen tools versions
/// </summary>
/// <param name="index"></param>
/// <param name="element"></param>
protected override void BaseAdd(int index, ConfigurationElement element)
{
UpdateToolsVersionMap(element);
base.BaseAdd(index, element);
}
/// <summary>
/// overridden so we can track previously seen tools versions
/// </summary>
/// <param name="element"></param>
protected override void BaseAdd(ConfigurationElement element)
{
UpdateToolsVersionMap(element);
base.BaseAdd(element);
}
/// <summary>
/// Stores the name of the tools version in a case-insensitive map
/// so we can detect if it is specified more than once but with
/// different case
/// </summary>
/// <param name="element"></param>
private void UpdateToolsVersionMap(ConfigurationElement element)
{
string toolsVersion = GetElementKey(element).ToString();
if (previouslySeenToolsVersions.ContainsKey(toolsVersion))
{
string message = ResourceUtilities.FormatResourceString("MultipleDefinitionsForSameToolset", toolsVersion);
throw new ConfigurationErrorsException(message, element.ElementInformation.Source, element.ElementInformation.LineNumber);
}
previouslySeenToolsVersions.Add(toolsVersion, string.Empty);
}
/// <summary>
/// Returns the key value for the given element
/// </summary>
/// <param name="element">element whose key is returned</param>
/// <returns>key</returns>
protected override object GetElementKey(ConfigurationElement element)
{
return ((ToolsetElement)element).toolsVersion;
}
/// <summary>
/// Throw exception if an element with a duplicate key is added to the collection
/// </summary>
protected override bool ThrowOnDuplicate
{
get
{
return false;
}
}
/// <summary>
/// Type of the collection
/// This has to be public as cannot change access modifier when overriding
/// </summary>
public override ConfigurationElementCollectionType CollectionType
{
get
{
return ConfigurationElementCollectionType.BasicMap;
}
}
/// <summary>
/// Name of the element
/// </summary>
protected override string ElementName
{
get
{
return "toolset";
}
}
/// <summary>
/// Gets an element with the specified name
/// </summary>
/// <param name="toolsVersion">toolsVersion of the element</param>
/// <returns>element</returns>
public ToolsetElement GetElement(string toolsVersion)
{
return (ToolsetElement)this.BaseGet(toolsVersion);
}
/// <summary>
/// Gets an element based at the specified position
/// </summary>
/// <param name="index">position</param>
/// <returns>element</returns>
public ToolsetElement GetElement(int index)
{
return (ToolsetElement)this.BaseGet(index);
}
}
/// <summary>
/// Class representing the Toolset element
/// </summary>
/// <remarks>
/// Internal for unit testing only
/// </remarks>
internal sealed class ToolsetElement : ConfigurationElement
{
/// <summary>
/// ToolsVersion attribute of the element
/// </summary>
[ConfigurationProperty("toolsVersion", IsKey = true, IsRequired = true)]
public string toolsVersion
{
get
{
return (string)base["toolsVersion"];
}
set
{
base["toolsVersion"] = value;
}
}
/// <summary>
/// Property element collection
/// </summary>
[ConfigurationProperty("", IsDefaultCollection = true)]
public PropertyElementCollection PropertyElements
{
get
{
return (PropertyElementCollection)base[""];
}
}
/// <summary>
/// Class representing collection of property elements
/// </summary>
internal sealed class PropertyElementCollection : ConfigurationElementCollection
{
/// <summary>
/// We use this dictionary to track whether or not we've seen a given
/// property definition before, since the .NET configuration classes
/// won't perform this check without respect for case.
/// </summary>
private Dictionary<string, string> previouslySeenPropertyNames = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Creates a new element
/// </summary>
/// <returns>element</returns>
protected override ConfigurationElement CreateNewElement()
{
return new PropertyElement();
}
/// <summary>
/// overridden so we can track previously seen property names
/// </summary>
/// <param name="index"></param>
/// <param name="element"></param>
protected override void BaseAdd(int index, ConfigurationElement element)
{
UpdatePropertyNameMap(element);
base.BaseAdd(index, element);
}
/// <summary>
/// overridden so we can track previously seen property names
/// </summary>
/// <param name="element"></param>
protected override void BaseAdd(ConfigurationElement element)
{
UpdatePropertyNameMap(element);
base.BaseAdd(element);
}
/// <summary>
/// Stores the name of the tools version in a case-insensitive map
/// so we can detect if it is specified more than once but with
/// different case
/// </summary>
/// <param name="element"></param>
private void UpdatePropertyNameMap(ConfigurationElement element)
{
string propertyName = GetElementKey(element).ToString();
if (previouslySeenPropertyNames.ContainsKey(propertyName))
{
string message = ResourceUtilities.FormatResourceString("MultipleDefinitionsForSameProperty", propertyName);
throw new ConfigurationErrorsException(message, element.ElementInformation.Source, element.ElementInformation.LineNumber);
}
previouslySeenPropertyNames.Add(propertyName, string.Empty);
}
/// <summary>
/// Gets the key for the element
/// </summary>
/// <param name="element">element</param>
/// <returns>key</returns>
protected override object GetElementKey(ConfigurationElement element)
{
return ((PropertyElement)element).Name;
}
/// <summary>
/// Collection type
/// This has to be public as cannot change access modifier when overriding
/// </summary>
public override ConfigurationElementCollectionType CollectionType
{
get
{
return ConfigurationElementCollectionType.BasicMap;
}
}
/// <summary>
/// Throw exception if an element with a duplicate is added
/// </summary>
protected override bool ThrowOnDuplicate
{
get
{
return false;
}
}
/// <summary>
/// name of the element
/// </summary>
protected override string ElementName
{
get
{
return "property";
}
}
/// <summary>
/// Gets an element with the specified name
/// </summary>
/// <param name="name">name of the element</param>
/// <returns>element</returns>
public PropertyElement GetElement(string name)
{
return (PropertyElement)this.BaseGet(name);
}
/// <summary>
/// Gets an element at the specified position
/// </summary>
/// <param name="index">position</param>
/// <returns>element</returns>
public PropertyElement GetElement(int index)
{
return (PropertyElement)this.BaseGet(index);
}
}
/// <summary>
/// This class represents property element
/// </summary>
internal sealed class PropertyElement : ConfigurationElement
{
/// <summary>
/// name attribute
/// </summary>
[ConfigurationProperty("name", IsKey = true, IsRequired = true)]
public string Name
{
get
{
return (string)base["name"];
}
set
{
base["name"] = value;
}
}
/// <summary>
/// value attribute
/// </summary>
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get
{
return (string)base["value"];
}
set
{
base["value"] = value;
}
}
}
}
/// <summary>
/// Delegate for unit test purposes only
/// </summary>
/// <returns></returns>
internal delegate Configuration ReadApplicationConfiguration();
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DefaultRegistry.cs" company="Web Advanced">
// Copyright 2012 Web Advanced (www.webadvanced.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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Configuration;
using System.Reflection;
using System.Web;
using FeatureToggle;
using FluentValidation;
using MediatR;
using SFA.DAS.Authorization.Context;
using SFA.DAS.Authorization.Handlers;
using SFA.DAS.Authorization.ProviderPermissions.Handlers;
using SFA.DAS.Configuration;
using SFA.DAS.Configuration.AzureTableStorage;
using SFA.DAS.CookieService;
using SFA.DAS.EAS.Account.Api.Client;
using SFA.DAS.Encoding;
using SFA.DAS.HashingService;
using SFA.DAS.Learners.Validators;
using SFA.DAS.NLog.Logger;
using SFA.DAS.ProviderApprenticeshipsService.Domain.Data;
using SFA.DAS.ProviderApprenticeshipsService.Domain.Interfaces;
using SFA.DAS.ProviderApprenticeshipsService.Infrastructure.Caching;
using SFA.DAS.ProviderApprenticeshipsService.Infrastructure.Configuration;
using SFA.DAS.ProviderApprenticeshipsService.Infrastructure.Data;
using SFA.DAS.ProviderApprenticeshipsService.Infrastructure.Logging;
using SFA.DAS.ProviderApprenticeshipsService.Infrastructure.Services;
using SFA.DAS.ProviderApprenticeshipsService.Web.Authorization;
using SFA.DAS.ProviderApprenticeshipsService.Web.Models;
using SFA.DAS.ProviderApprenticeshipsService.Web.Orchestrators.BulkUpload;
using SFA.DAS.ProviderApprenticeshipsService.Web.Validation;
using SFA.DAS.ProviderApprenticeshipsService.Web.Validation.Text;
using SFA.DAS.ProviderRelationships.Api.Client;
using StructureMap;
namespace SFA.DAS.ProviderApprenticeshipsService.Web.DependencyResolution
{
public class DefaultRegistry : Registry {
private const string ServiceName = "SFA.DAS.ProviderApprenticeshipsService";
private const string ServiceNamespace = "SFA.DAS";
public DefaultRegistry() {
Scan(
scan => {
scan.AssembliesFromApplicationBaseDirectory(a => a.GetName().Name.StartsWith(ServiceNamespace));
scan.ConnectImplementationsToTypesClosing(typeof(IValidator<>)).OnAddedPluginTypes(t => t.Singleton());
scan.ConnectImplementationsToTypesClosing(typeof(IRequestHandler<,>));
scan.ConnectImplementationsToTypesClosing(typeof(INotificationHandler<>));
scan.RegisterConcreteTypesAgainstTheFirstInterface();
});
var environment = GetAndStoreEnvironment();
var configurationRepository = GetConfigurationRepository();
For<IConfigurationRepository>().Use(configurationRepository);
var config = GetConfiguration(environment, configurationRepository);
#region uncomment to override the auto config of the ProviderRelationships Api Client
//var providerPermissionsReadStoreConfig = GetProviderPermissionsReadStoreConfiguration(environment, configurationRepository);
//For<ProviderRelationshipsReadStoreConfiguration>().ClearAll();
//For<ProviderRelationshipsReadStoreConfiguration>().Use(providerPermissionsReadStoreConfig);
//var providerRelationshipsApiClientConfiguration =
// GetProviderRelationshipsApiClientConfiguration(environment, configurationRepository);
//For<ProviderRelationshipsApiClientConfiguration>().ClearAll();
//For<ProviderRelationshipsApiClientConfiguration>().Use(providerRelationshipsApiClientConfiguration);
#endregion
ConfigureHashingService(config);
For<IProviderAgreementStatusConfiguration>().Use(config);
For<ProviderApprenticeshipsServiceConfiguration>().Use(config);
For<ICache>().Use<InMemoryCache>(); //RedisCache
For<IAgreementStatusQueryRepository>().Use<ProviderAgreementStatusRepository>();
For<IApprenticeshipValidationErrorText>().Use<WebApprenticeshipValidationText>();
For<IApprenticeshipCoreValidator>().Use<ApprenticeshipCoreValidator>().Singleton();
For<IApprovedApprenticeshipValidator>().Use<ApprovedApprenticeshipValidator>().Singleton();
For<IAccountApiClient>().Use<AccountApiClient>();
For<IAccountApiConfiguration>().Use<Domain.Configuration.AccountApiConfiguration>();
For<HttpContextBase>().Use(() => new HttpContextWrapper(HttpContext.Current));
For(typeof(ICookieService<>)).Use(typeof(HttpCookieService<>));
For(typeof(ICookieStorageService<>)).Use(typeof(CookieStorageService<>));
For<IAuthorizationContextProvider>().Use<AuthorizationContextProvider>();
For<IAuthorizationHandler>().Use<AuthorizationHandler>();
ConfigureFeatureToggle();
RegisterMediator();
ConfigureProviderRelationshipsApiClient();
ConfigureLogging();
ConfigureInstrumentedTypes();
For<EncodingConfig>().Use(x => GetEncodingConfig(environment, configurationRepository));
}
private void ConfigureFeatureToggle()
{
For<IBooleanToggleValueProvider>().Use<CloudConfigurationBooleanValueProvider>();
For<IFeatureToggleService>().Use<FeatureToggleService>();
}
private void ConfigureInstrumentedTypes()
{
For<IBulkUploadValidator>().Use(x => new InstrumentedBulkUploadValidator(x.GetInstance<ILog>(), x.GetInstance<BulkUploadValidator>(), x.GetInstance<IUlnValidator>(), x.GetInstance<IAcademicYearDateProvider>()));
For<IBulkUploadFileParser>().Use(x => new InstrumentedBulkUploadFileParser(x.GetInstance<ILog>(), x.GetInstance<BulkUploadFileParser>()));
}
private void ConfigureLogging()
{
For<ILoggingContext>().Use(x => new RequestContext(new HttpContextWrapper(HttpContext.Current)));
For<IProviderCommitmentsLogger>().Use(x => GetBaseLogger(x)).AlwaysUnique();
For<ILog>().Use(x => new NLogLogger(
x.ParentType,
x.GetInstance<ILoggingContext>(),
null)).AlwaysUnique();
}
private void ConfigureHashingService(ProviderApprenticeshipsServiceConfiguration config)
{
For<IHashingService>().Use(x => new HashingService.HashingService(config.AllowedHashstringCharacters, config.Hashstring));
For<IPublicHashingService>().Use(x => new PublicHashingService(config.PublicAllowedHashstringCharacters, config.PublicHashstring));
For<IAccountLegalEntityPublicHashingService>().Use(x => new PublicHashingService(config.PublicAllowedAccountLegalEntityHashstringCharacters, config.PublicAllowedAccountLegalEntityHashstringSalt));
}
private IProviderCommitmentsLogger GetBaseLogger(IContext x)
{
var parentType = x.ParentType;
return new ProviderCommitmentsLogger(new NLogLogger(parentType, x.GetInstance<ILoggingContext>()));
}
private string GetAndStoreEnvironment()
{
var environment = Environment.GetEnvironmentVariable("DASENV");
if (string.IsNullOrEmpty(environment))
{
environment = ConfigurationManager.AppSettings["EnvironmentName"];
}
if (environment.Equals("LOCAL") || environment.Equals("AT") || environment.Equals("TEST"))
{
PopulateSystemDetails(environment);
}
return environment;
}
private ProviderApprenticeshipsServiceConfiguration GetConfiguration(string environment, IConfigurationRepository configurationRepository)
{
var configurationService = new ConfigurationService(configurationRepository,
new ConfigurationOptions(ServiceName, environment, "1.0"));
return configurationService.Get<ProviderApprenticeshipsServiceConfiguration>();
}
private EncodingConfig GetEncodingConfig(string environment, IConfigurationRepository configurationRepository)
{
var configurationService = new ConfigurationService(configurationRepository,
new ConfigurationOptions("SFA.DAS.Encoding", environment, "1.0"));
return configurationService.Get<EncodingConfig>();
}
private static IConfigurationRepository GetConfigurationRepository()
{
return new AzureTableStorageConfigurationRepository(ConfigurationManager.AppSettings["ConfigurationStorageConnectionString"]);
}
private void RegisterMediator()
{
For<ServiceFactory>().Use<ServiceFactory>(ctx => ctx.GetInstance);
For<IMediator>().Use<Mediator>();
}
private void PopulateSystemDetails(string envName)
{
SystemDetails.EnvironmentName = envName;
SystemDetails.VersionNumber = Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
private void ConfigureProviderRelationshipsApiClient()
{
var useStub = GetUseStubProviderRelationshipsSetting();
if (useStub)
{
For<IProviderRelationshipsApiClient>().Use<StubProviderRelationshipsApiClient>();
}
}
private bool GetUseStubProviderRelationshipsSetting()
{
var value = ConfigurationManager.AppSettings["UseStubProviderRelationships"];
if (value == null)
{
return false;
}
if (!bool.TryParse(value, out var result))
{
return false;
}
return result;
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System;
using System.ServiceModel.Channels;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.ServiceModel.Security;
using System.Text;
using System.Xml;
using QName = System.ServiceModel.Dispatcher.EndpointAddressProcessor.QName;
using HeaderBit = System.ServiceModel.Dispatcher.EndpointAddressProcessor.HeaderBit;
public class EndpointAddressMessageFilter : MessageFilter
{
EndpointAddress address;
bool includeHostNameInComparison;
EndpointAddressMessageFilterHelper helper;
UriComparer comparer;
public EndpointAddressMessageFilter(EndpointAddress address)
: this(address, false)
{
}
public EndpointAddressMessageFilter(EndpointAddress address, bool includeHostNameInComparison)
{
if (address == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address");
}
this.address = address;
this.includeHostNameInComparison = includeHostNameInComparison;
this.helper = new EndpointAddressMessageFilterHelper(this.address);
if (includeHostNameInComparison)
{
this.comparer = HostUriComparer.Value;
}
else
{
this.comparer = NoHostUriComparer.Value;
}
}
public EndpointAddress Address
{
get
{
return this.address;
}
}
public bool IncludeHostNameInComparison
{
get { return this.includeHostNameInComparison; }
}
protected internal override IMessageFilterTable<FilterData> CreateFilterTable<FilterData>()
{
return new EndpointAddressMessageFilterTable<FilterData>();
}
public override bool Match(MessageBuffer messageBuffer)
{
if (messageBuffer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageBuffer");
}
Message msg = messageBuffer.CreateMessage();
try
{
return Match(msg);
}
finally
{
msg.Close();
}
}
public override bool Match(Message message)
{
if (message == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
}
// To
#pragma warning suppress 56506 // [....], Message.Headers can never be null
Uri to = message.Headers.To;
Uri actingAs = this.address.Uri;
if (to == null || !this.comparer.Equals(actingAs, to))
{
return false;
}
return this.helper.Match(message);
}
internal Dictionary<string, HeaderBit[]> HeaderLookup
{
get { return this.helper.HeaderLookup; }
}
internal bool ComparePort
{
set
{
comparer.ComparePort = value;
}
}
internal abstract class UriComparer : EqualityComparer<Uri>
{
protected UriComparer()
{
ComparePort = true;
}
protected abstract bool CompareHost { get; }
internal bool ComparePort
{
get;
set;
}
public override bool Equals(Uri u1, Uri u2)
{
return EndpointAddress.UriEquals(u1, u2, true /* ignoreCase */, CompareHost, ComparePort);
}
public override int GetHashCode(Uri uri)
{
return EndpointAddress.UriGetHashCode(uri, CompareHost, ComparePort);
}
}
internal sealed class HostUriComparer : UriComparer
{
internal static readonly UriComparer Value = new HostUriComparer();
HostUriComparer()
{
}
protected override bool CompareHost
{
get
{
return true;
}
}
}
internal sealed class NoHostUriComparer : UriComparer
{
internal static readonly UriComparer Value = new NoHostUriComparer();
NoHostUriComparer()
{
}
protected override bool CompareHost
{
get
{
return false;
}
}
}
}
internal class EndpointAddressMessageFilterHelper
{
EndpointAddress address;
WeakReference processorPool;
int size;
byte[] mask;
Dictionary<QName, int> qnameLookup;
Dictionary<string, HeaderBit[]> headerLookup;
internal EndpointAddressMessageFilterHelper(EndpointAddress address)
{
this.address = address;
if (this.address.Headers.Count > 0)
{
CreateMask();
this.processorPool = new WeakReference(null);
}
else
{
this.qnameLookup = null;
this.headerLookup = null;
this.size = 0;
this.mask = null;
}
}
void CreateMask()
{
int nextBit = 0;
string key;
HeaderBit[] bits;
QName qname;
this.qnameLookup = new Dictionary<QName, int>(EndpointAddressProcessor.QNameComparer);
this.headerLookup = new Dictionary<string, HeaderBit[]>();
StringBuilder builder = null;
for (int i = 0; i < this.address.Headers.Count; ++i)
{
if (builder == null)
builder = new StringBuilder();
else
builder.Remove(0, builder.Length);
key = this.address.Headers[i].GetComparableForm(builder);
if (this.headerLookup.TryGetValue(key, out bits))
{
Array.Resize(ref bits, bits.Length + 1);
bits[bits.Length - 1] = new HeaderBit(nextBit++);
this.headerLookup[key] = bits;
}
else
{
this.headerLookup.Add(key, new HeaderBit[] { new HeaderBit(nextBit++) });
AddressHeader parameter = this.address.Headers[i];
qname.name = parameter.Name;
qname.ns = parameter.Namespace;
this.qnameLookup[qname] = 1;
}
}
if (nextBit == 0)
{
this.size = 0;
}
else
{
this.size = (nextBit - 1) / 8 + 1;
}
if (this.size > 0)
{
this.mask = new byte[size];
for (int i = 0; i < this.size - 1; ++i)
{
this.mask[i] = 0xff;
}
if ((nextBit % 8) == 0)
{
this.mask[this.size - 1] = 0xff;
}
else
{
this.mask[this.size - 1] = (byte)((1 << (nextBit % 8)) - 1);
}
}
}
internal Dictionary<string, HeaderBit[]> HeaderLookup
{
get
{
if (this.headerLookup == null)
this.headerLookup = new Dictionary<string, HeaderBit[]>();
return this.headerLookup;
}
}
EndpointAddressProcessor CreateProcessor(int length)
{
if (this.processorPool.Target != null)
{
lock (this.processorPool)
{
object o = this.processorPool.Target;
if (o != null)
{
EndpointAddressProcessor p = (EndpointAddressProcessor)o;
this.processorPool.Target = p.Next;
p.Next = null;
p.Clear(length);
return p;
}
}
}
return new EndpointAddressProcessor(length);
}
internal bool Match(Message message)
{
if (this.size == 0)
{
return true;
}
EndpointAddressProcessor context = CreateProcessor(this.size);
context.ProcessHeaders(message, this.qnameLookup, this.headerLookup);
bool result = context.TestExact(this.mask);
ReleaseProcessor(context);
return result;
}
void ReleaseProcessor(EndpointAddressProcessor context)
{
lock (this.processorPool)
{
context.Next = this.processorPool.Target as EndpointAddressProcessor;
this.processorPool.Target = context;
}
}
}
}
| |
using Lucene.Net.Support;
using System.IO;
using System.Text;
namespace Lucene.Net.Search
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Encapsulates sort criteria for returned hits.
///
/// <para/>The fields used to determine sort order must be carefully chosen.
/// <see cref="Documents.Document"/>s must contain a single term in such a field,
/// and the value of the term should indicate the document's relative position in
/// a given sort order. The field must be indexed, but should not be tokenized,
/// and does not need to be stored (unless you happen to want it back with the
/// rest of your document data). In other words:
///
/// <para/><code>document.Add(new Field("byNumber", x.ToString(CultureInfo.InvariantCulture), Field.Store.NO, Field.Index.NOT_ANALYZED));</code>
///
///
/// <para/><h3>Valid Types of Values</h3>
///
/// <para/>There are four possible kinds of term values which may be put into
/// sorting fields: <see cref="int"/>s, <see cref="long"/>s, <see cref="float"/>s, or <see cref="string"/>s. Unless
/// <see cref="SortField"/> objects are specified, the type of value
/// in the field is determined by parsing the first term in the field.
///
/// <para/><see cref="int"/> term values should contain only digits and an optional
/// preceding negative sign. Values must be base 10 and in the range
/// <see cref="int.MinValue"/> and <see cref="int.MaxValue"/> inclusive.
/// Documents which should appear first in the sort
/// should have low value integers, later documents high values
/// (i.e. the documents should be numbered <c>1..n</c> where
/// <c>1</c> is the first and <c>n</c> the last).
///
/// <para/><see cref="long"/> term values should contain only digits and an optional
/// preceding negative sign. Values must be base 10 and in the range
/// <see cref="long.MinValue"/> and <see cref="long.MaxValue"/> inclusive.
/// Documents which should appear first in the sort
/// should have low value integers, later documents high values.
///
/// <para/><see cref="float"/> term values should conform to values accepted by
/// <see cref="float"/> (except that <c>NaN</c>
/// and <c>Infinity</c> are not supported).
/// <see cref="Documents.Document"/>s which should appear first in the sort
/// should have low values, later documents high values.
///
/// <para/><see cref="string"/> term values can contain any valid <see cref="string"/>, but should
/// not be tokenized. The values are sorted according to their
/// comparable natural order (<see cref="System.StringComparer.Ordinal"/>). Note that using this type
/// of term value has higher memory requirements than the other
/// two types.
///
/// <para/><h3>Object Reuse</h3>
///
/// <para/>One of these objects can be
/// used multiple times and the sort order changed between usages.
///
/// <para/>This class is thread safe.
///
/// <para/><h3>Memory Usage</h3>
///
/// <para/>Sorting uses of caches of term values maintained by the
/// internal HitQueue(s). The cache is static and contains an <see cref="int"/>
/// or <see cref="float"/> array of length <c>IndexReader.MaxDoc</c> for each field
/// name for which a sort is performed. In other words, the size of the
/// cache in bytes is:
///
/// <para/><code>4 * IndexReader.MaxDoc * (# of different fields actually used to sort)</code>
///
/// <para/>For <see cref="string"/> fields, the cache is larger: in addition to the
/// above array, the value of every term in the field is kept in memory.
/// If there are many unique terms in the field, this could
/// be quite large.
///
/// <para/>Note that the size of the cache is not affected by how many
/// fields are in the index and <i>might</i> be used to sort - only by
/// the ones actually used to sort a result set.
///
/// <para/>Created: Feb 12, 2004 10:53:57 AM
/// <para/>
/// @since lucene 1.4
/// </summary>
public class Sort
{
/// <summary>
/// Represents sorting by computed relevance. Using this sort criteria returns
/// the same results as calling
/// <see cref="IndexSearcher.Search(Query, int)"/>without a sort criteria,
/// only with slightly more overhead.
/// </summary>
public static readonly Sort RELEVANCE = new Sort();
/// <summary>
/// Represents sorting by index order. </summary>
public static readonly Sort INDEXORDER = new Sort(SortField.FIELD_DOC);
// internal representation of the sort criteria
internal SortField[] fields;
/// <summary>
/// Sorts by computed relevance. This is the same sort criteria as calling
/// <see cref="IndexSearcher.Search(Query, int)"/> without a sort criteria,
/// only with slightly more overhead.
/// </summary>
public Sort()
: this(SortField.FIELD_SCORE)
{
}
/// <summary>
/// Sorts by the criteria in the given <see cref="SortField"/>. </summary>
public Sort(SortField field)
{
SetSort(field);
}
/// <summary>
/// Sorts in succession by the criteria in each <see cref="SortField"/>. </summary>
public Sort(params SortField[] fields)
{
SetSort(fields);
}
/// <summary>Sets the sort to the given criteria. </summary>
public virtual void SetSort(SortField field)
{
this.fields = new SortField[] { field };
}
/// <summary>Sets the sort to the given criteria in succession. </summary>
public virtual void SetSort(params SortField[] fields)
{
this.fields = fields;
}
/// <summary> Representation of the sort criteria.</summary>
/// <returns> Array of <see cref="SortField"/> objects used in this sort criteria
/// </returns>
[WritableArray]
public virtual SortField[] GetSort()
{
return fields;
}
/// <summary>
/// Rewrites the <see cref="SortField"/>s in this <see cref="Sort"/>, returning a new <see cref="Sort"/> if any of the fields
/// changes during their rewriting.
/// <para/>
/// @lucene.experimental
/// </summary>
/// <param name="searcher"> <see cref="IndexSearcher"/> to use in the rewriting </param>
/// <returns> <c>this</c> if the Sort/Fields have not changed, or a new <see cref="Sort"/> if there
/// is a change </returns>
/// <exception cref="IOException"> Can be thrown by the rewriting</exception>
public virtual Sort Rewrite(IndexSearcher searcher)
{
bool changed = false;
SortField[] rewrittenSortFields = new SortField[fields.Length];
for (int i = 0; i < fields.Length; i++)
{
rewrittenSortFields[i] = fields[i].Rewrite(searcher);
if (fields[i] != rewrittenSortFields[i])
{
changed = true;
}
}
return (changed) ? new Sort(rewrittenSortFields) : this;
}
public override string ToString()
{
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < fields.Length; i++)
{
buffer.Append(fields[i].ToString());
if ((i + 1) < fields.Length)
{
buffer.Append(',');
}
}
return buffer.ToString();
}
/// <summary>
/// Returns <c>true</c> if <paramref name="o"/> is equal to this. </summary>
public override bool Equals(object o)
{
if (this == o)
{
return true;
}
if (!(o is Sort))
{
return false;
}
Sort other = (Sort)o;
return Arrays.Equals(this.fields, other.fields);
}
/// <summary>
/// Returns a hash code value for this object. </summary>
public override int GetHashCode()
{
return 0x45aaf665 + Arrays.GetHashCode(fields);
}
/// <summary>
/// Returns <c>true</c> if the relevance score is needed to sort documents. </summary>
public virtual bool NeedsScores
{
get
{
foreach (SortField sortField in fields)
{
if (sortField.NeedsScores)
{
return true;
}
}
return false;
}
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* 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
#region Imports
using System;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
#endregion
namespace Spring.Web.UI.Controls
{
#if !NET_2_0
/// <summary>
/// This controls provides MultiView introduced with ASP.NET 2.0 for NET 1.1 Platform
/// </summary>
/// <author>Erich Eichinger</author>
[
DefaultEvent("ActiveViewChanged")
, ToolboxData("<{0}:MultiView runat=\"server\"></{0}:MultiView>")
, ParseChildren(false, null)
, AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)
, AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)]
public class MultiView : Control
{
#region Constants
/// <summary>
/// Represents the command name associated with the next View control to display in a MultiView control. This field is read-only.
/// </summary>
public static readonly string NextViewCommandName = "NextView";
/// <summary>
/// Represents the command name associated with the previous View control to display in a MultiView control. This field is read-only.
/// </summary>
public static readonly string PreviousViewCommandName = "PrevView";
/// <summary>
/// Represents the command name associated with changing the active View control in a MultiView control, based on a specified View id. This field is read-only.
/// </summary>
public static readonly string SwitchViewByIDCommandName = "SwitchViewByID";
/// <summary>
/// Represents the command name associated with changing the active View control in a MultiView control based on a specified View index. This field is read-only.
/// </summary>
public static readonly string SwitchViewByIndexCommandName = "SwitchViewByIndex";
#endregion
#region Fields
private static readonly FieldInfo s_fiControlState =
typeof(Control).GetField("_controlState", BindingFlags.Instance | BindingFlags.NonPublic);
private int _activeViewIndex = -1;
private int _cachedActiveViewIndex = -1;
private bool _controlStateApplied;
private static readonly object _eventActiveViewChanged = new object();
private bool _ignoreBubbleEvents;
#endregion
#region Construction
/// <summary>
/// Initializes a new instance of the <see cref="MultiView"/> class.
/// </summary>
public MultiView()
{
// intentionally left empty
}
#endregion
#region Events
/// <summary>
/// Occurs when the active View control of a MultiView control changes between posts to the server.
/// </summary>
public event EventHandler ActiveViewChanged
{
add { base.Events.AddHandler(_eventActiveViewChanged, value); }
remove { base.Events.RemoveHandler(_eventActiveViewChanged, value); }
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the index of the active View control within a MultiView control.
/// </summary>
[DefaultValue(-1)]
public virtual int ActiveViewIndex
{
get
{
if (_cachedActiveViewIndex > -1)
{
return _cachedActiveViewIndex;
}
return _activeViewIndex;
}
set
{
if (value < -1)
{
throw new ArgumentOutOfRangeException("value",
string.Format(
"MultiView_ActiveViewIndex_less_than_minus_one",
new object[] {value}));
}
if ((Views.Count == 0) && (ControlState < ControlState.ChildrenInitialized))
{
_cachedActiveViewIndex = value;
}
else
{
if (value >= Views.Count)
{
throw new ArgumentOutOfRangeException("value",
string.Format(
"MultiView_ActiveViewIndex_equal_or_greater_than_count",
new object[] {value, Views.Count}));
}
int num = (_cachedActiveViewIndex != -1) ? -1 : _activeViewIndex;
_activeViewIndex = value;
_cachedActiveViewIndex = -1;
if (((num != value) && (num != -1)) && (num < Views.Count))
{
Views[num].Active = false;
if (ShouldTriggerViewEvent)
{
Views[num].OnDeactivate(EventArgs.Empty);
}
}
if (((num != value) && (Views.Count != 0)) && (value != -1))
{
Views[value].Active = true;
if (ShouldTriggerViewEvent)
{
Views[value].OnActivate(EventArgs.Empty);
OnActiveViewChanged(EventArgs.Empty);
}
}
}
}
}
/// <summary>
/// Gets the collection of View controls in the MultiView control.
/// </summary>
[
PersistenceMode(PersistenceMode.InnerDefaultProperty)
, Browsable(false)
]
public virtual ViewCollection Views
{
get { return (ViewCollection) Controls; }
}
/// <summary>
/// Return the current lifecycle state of this control.
/// </summary>
private ControlState ControlState
{
get { return (ControlState) s_fiControlState.GetValue(this); }
}
#endregion
/// <summary>
/// Sets the specified View control to the active view within a MultiView control.
/// </summary>
/// <param name="view">A View control to set as the active view within a MultiView control.</param>
public void SetActiveView(View view)
{
int index = Views.IndexOf(view);
if (index < 0)
{
throw new HttpException(
string.Format("MultiView_view_not_found", new object[] {(view == null) ? "null" : view.ID, ID}));
}
ActiveViewIndex = index;
}
/// <summary>
/// Returns the current active View control within a MultiView control.
/// </summary>
/// <returns>A View control that represents the active view within a MultiView control.</returns>
public View GetActiveView()
{
int activeViewIndex = ActiveViewIndex;
if (activeViewIndex >= Views.Count)
{
throw new Exception("MultiView_ActiveViewIndex_out_of_range");
}
if (activeViewIndex < 0)
{
return null;
}
View view = Views[activeViewIndex];
if (!view.Active)
{
UpdateActiveView(activeViewIndex);
}
return view;
}
/// <summary>
/// Mark this control to ignore <see cref="OnBubbleEvent"/>
/// </summary>
internal void IgnoreBubbleEvents()
{
_ignoreBubbleEvents = true;
}
/// <summary>
/// Adds the element to the collection of child controls.
/// </summary>
protected override void AddParsedSubObject(object obj)
{
if (obj is View)
{
Controls.Add((Control) obj);
}
else if (!(obj is LiteralControl))
{
throw new HttpException(
string.Format("MultiView_cannot_have_children_of_type", new object[] {obj.GetType().Name}));
}
}
/// <summary>
/// Creates a new <see cref="ViewCollection"/> instance.
/// </summary>
/// <returns></returns>
protected override ControlCollection CreateControlCollection()
{
return new ViewCollection(this);
}
/// <summary>
/// Restores view-state information from a previous page request.
/// </summary>
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
ActiveViewIndex = (int) ViewState["_activeViewIndex"];
_controlStateApplied = true;
}
/// <summary>
/// Saves view-state information to the page response.
/// </summary>
protected override object SaveViewState()
{
ViewState["_activeViewIndex"] = ActiveViewIndex;
return base.SaveViewState();
}
/// <summary>
/// Raises the <see cref="ActiveViewChanged"/> event.
/// </summary>
protected virtual void OnActiveViewChanged(EventArgs e)
{
EventHandler handler = (EventHandler) base.Events[_eventActiveViewChanged];
if (handler != null)
{
handler(this, e);
}
}
/// <summary>
/// Captures know commands.
/// </summary>
protected override bool OnBubbleEvent(object source, EventArgs e)
{
if (!_ignoreBubbleEvents && (e is CommandEventArgs))
{
CommandEventArgs args = (CommandEventArgs) e;
string commandName = args.CommandName;
if (commandName == NextViewCommandName)
{
if (ActiveViewIndex < (Views.Count - 1))
{
ActiveViewIndex++;
}
else
{
ActiveViewIndex = -1;
}
return true;
}
if (commandName == PreviousViewCommandName)
{
if (ActiveViewIndex > -1)
{
ActiveViewIndex--;
}
return true;
}
if (commandName == SwitchViewByIDCommandName)
{
View view = FindControl((string) args.CommandArgument) as View;
if ((view == null) || (view.Parent != this))
{
throw new HttpException(
string.Format("MultiView_invalid_view_id",
new object[]
{ID, (string) args.CommandArgument, SwitchViewByIDCommandName}));
}
SetActiveView(view);
return true;
}
if (commandName == SwitchViewByIndexCommandName)
{
int num;
try
{
num = int.Parse((string) args.CommandArgument, CultureInfo.InvariantCulture);
}
catch (FormatException)
{
throw new FormatException(
string.Format("MultiView_invalid_view_index_format",
new object[] {(string) args.CommandArgument, SwitchViewByIndexCommandName}));
}
ActiveViewIndex = num;
return true;
}
}
return false;
}
/// <summary>
/// Initialize this control.
/// </summary>
/// <param name="e"></param>
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (_cachedActiveViewIndex > -1)
{
ActiveViewIndex = _cachedActiveViewIndex;
_cachedActiveViewIndex = -1;
GetActiveView();
}
}
/// <summary>
/// Handle removal of a view.
/// </summary>
/// <param name="ctl"></param>
protected override void RemovedControl(Control ctl)
{
if (((View) ctl).Active && (ActiveViewIndex < Views.Count))
{
GetActiveView();
}
base.RemovedControl(ctl);
}
/// <summary>
/// Render the currently active view.
/// </summary>
/// <param name="writer"></param>
protected override void Render(HtmlTextWriter writer)
{
View activeView = GetActiveView();
if (activeView != null)
{
activeView.RenderControl(writer);
}
}
/// <summary>
/// Switches from the currently active view to the specified view.
/// </summary>
/// <param name="activeViewIndex"></param>
private void UpdateActiveView(int activeViewIndex)
{
for (int i = 0; i < Views.Count; i++)
{
View view = Views[i];
if (i == activeViewIndex)
{
view.Active = true;
if (ShouldTriggerViewEvent)
{
view.OnActivate(EventArgs.Empty);
}
}
else if (view.Active)
{
view.Active = false;
if (ShouldTriggerViewEvent)
{
view.OnDeactivate(EventArgs.Empty);
}
}
}
}
/// <summary>
/// Indicates if view events are ready to be raised.
/// </summary>
private bool ShouldTriggerViewEvent
{
get
{
if (_controlStateApplied)
{
return true;
}
if (this.Page != null)
{
return !this.Page.IsPostBack;
}
return false;
}
}
}
#endif // !NET_2_0
}
| |
// 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.Drawing;
using System.Xml;
using Gallio.Common.Collections;
using Gallio.Common.Messaging;
using Gallio.Common.Messaging.MessageSinks;
using Gallio.Loader;
using Gallio.Model;
using Gallio.Common.Reflection;
using Gallio.Model.Messages.Exploration;
using Gallio.Model.Schema;
using Gallio.ReSharperRunner.Properties;
using Gallio.ReSharperRunner.Provider.Facade;
using Gallio.ReSharperRunner.Reflection;
using Gallio.Runtime;
using Gallio.Runtime.Logging;
using Gallio.Runtime.ProgressMonitoring;
using JetBrains.Metadata.Reader.API;
using JetBrains.ProjectModel;
#if RESHARPER_61_OR_NEWER
using JetBrains.ReSharper.Feature.Services.UnitTesting;
#endif
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Impl.Caches2;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.ReSharper.TaskRunnerFramework;
using JetBrains.ReSharper.UnitTestFramework;
using JetBrains.Application;
using JetBrains.Application.Progress;
namespace Gallio.ReSharperRunner.Provider
{
/// <summary>
/// This is the main entry point into the Gallio test runner for ReSharper.
/// </summary>
[UnitTestProvider]
public class GallioTestProvider : IUnitTestProvider
#if RESHARPER_61_OR_NEWER
, IUnitTestingCategoriesAttributeProvider
#endif
{
public const string ProviderId = "Gallio";
private readonly Shim shim;
private static readonly IClrTypeName CategoryAttribute = new ClrTypeName("MbUnit.Framework.CategoryAttribute");
#if RESHARPER_60
private UnitTestManager unitTestManager;
#endif
static GallioTestProvider()
{
LoaderManager.InitializeAndSetupRuntimeIfNeeded();
}
#if RESHARPER_60
public GallioTestProvider(ISolution solution, PsiModuleManager psiModuleManager, CacheManagerEx cacheManager)
#else
public GallioTestProvider()
#endif
{
#if RESHARPER_60
Solution = solution;
PsiModuleManager = psiModuleManager;
CacheManager = cacheManager;
#endif
shim = new Shim(this);
}
public CacheManagerEx CacheManager { get; set; }
#if RESHARPER_60
public UnitTestManager UnitTestManager
{
get { return unitTestManager ?? (unitTestManager = Solution.GetComponent<UnitTestManager>()); }
}
#else
public IUnitTestProvidersManager UnitTestProvidersManager { get; set; }
#endif
public void ExploreExternal(UnitTestElementConsumer consumer)
{
}
public void ExploreSolution(ISolution solution, UnitTestElementConsumer consumer)
{
}
public void ExploreAssembly(IMetadataAssembly assembly, IProject project, UnitTestElementConsumer consumer)
{
shim.ExploreAssembly(assembly, project, consumer);
}
public void ExploreFile(IFile psiFile, UnitTestElementLocationConsumer consumer, CheckForInterrupt interrupted)
{
shim.ExploreFile(psiFile, consumer, interrupted);
}
public bool IsElementOfKind(IDeclaredElement element, UnitTestElementKind kind)
{
return shim.IsElementOfKind(element, kind);
}
public bool IsElementOfKind(IUnitTestElement element, UnitTestElementKind kind)
{
return shim.IsElementOfKind(element, kind);
}
public bool IsSupported(IHostProvider hostProvider)
{
return true;
}
public IUnitTestElement DeserializeElement(XmlElement parent, IUnitTestElement parentElement)
{
return GallioTestElement.Deserialize(parent, parentElement, this);
}
public RemoteTaskRunnerInfo GetTaskRunnerInfo()
{
return shim.GetTaskRunnerInfo();
}
public int CompareUnitTestElements(IUnitTestElement x, IUnitTestElement y)
{
return shim.CompareUnitTestElements(x, y);
}
public void SerializeElement(XmlElement parent, IUnitTestElement element)
{
var gallioTestElement = element as GallioTestElement;
if (gallioTestElement != null)
{
gallioTestElement.Serialize(parent);
}
}
public string ID
{
get { return ProviderId; }
}
public Image Icon
{
get { return shim.Icon; }
}
public string Name
{
get { return shim.Name; }
}
public ISolution Solution { get; private set; }
public PsiModuleManager PsiModuleManager { get; set; }
private sealed class Shim
{
private static readonly MultiMap<string, string> IncompatibleProviders = new MultiMap<string, string>
{
{ "nUnit", new[] { "NUnitAdapter248.TestFramework", "NUnitAdapter25.TestFramework" } },
{ "MSTest", new[] { "MSTestAdapter.TestFramework" } }
};
private readonly GallioTestProvider provider;
private readonly ITestFrameworkManager testFrameworkManager;
private readonly ILogger logger;
/// <summary>
/// Initializes the provider.
/// </summary>
public Shim(GallioTestProvider provider)
{
this.provider = provider;
testFrameworkManager = RuntimeAccessor.ServiceLocator.Resolve<ITestFrameworkManager>();
logger = new FacadeLoggerWrapper(new AdapterFacadeLogger());
RuntimeAccessor.Instance.AddLogListener(logger);
}
/// <summary>
/// Explores given compiled project.
/// </summary>
public void ExploreAssembly(IMetadataAssembly assembly, IProject project, UnitTestElementConsumer consumer)
{
if (assembly == null)
throw new ArgumentNullException("assembly");
if (project == null)
throw new ArgumentNullException("project");
if (consumer == null)
throw new ArgumentNullException("consumer");
try
{
#if RESHARPER_60
var reflectionPolicy = new MetadataReflectionPolicy(assembly, project);
#else
var reflectionPolicy = new MetadataReflectionPolicy(assembly, project, provider.CacheManager);
#endif
IAssemblyInfo assemblyInfo = reflectionPolicy.Wrap(assembly);
if (assemblyInfo != null)
{
var consumerAdapter = new ConsumerAdapter(provider, consumer);
Describe(reflectionPolicy, new ICodeElementInfo[] {assemblyInfo}, consumerAdapter);
}
}
catch (Exception ex)
{
HandleEmbeddedProcessCancelledException(ex);
throw;
}
}
/// <summary>
/// Explores given PSI file.
/// </summary>
public void ExploreFile(ITreeNode psiFile, UnitTestElementLocationConsumer consumer, CheckForInterrupt interrupted)
{
if (psiFile == null)
throw new ArgumentNullException("psiFile");
if (consumer == null)
throw new ArgumentNullException("consumer");
if (!psiFile.IsValid())
return;
try
{
#if RESHARPER_60
var reflectionPolicy = new PsiReflectionPolicy(psiFile.GetPsiServices().PsiManager);
#else
var reflectionPolicy = new PsiReflectionPolicy(psiFile.GetPsiServices().PsiManager, provider.CacheManager);
#endif
var consumerAdapter = new ConsumerAdapter(provider, consumer, psiFile);
var codeElements = new List<ICodeElementInfo>();
psiFile.ProcessDescendants(new OneActionProcessorWithoutVisit(delegate(ITreeNode element)
{
var declaration = element as ITypeDeclaration;
if (declaration != null)
PopulateCodeElementsFromTypeDeclaration(codeElements, reflectionPolicy, declaration);
}, delegate(ITreeNode element)
{
if (interrupted())
throw new ProcessCancelledException();
// Stop recursing at the first type declaration found.
return element is ITypeDeclaration;
}));
Describe(reflectionPolicy, codeElements, consumerAdapter);
ProjectFileState.SetFileState(psiFile.GetSourceFile().ToProjectFile(), consumerAdapter.CreateProjectFileState());
}
catch (Exception ex)
{
HandleEmbeddedProcessCancelledException(ex);
throw;
}
}
private static void PopulateCodeElementsFromTypeDeclaration(ICollection<ICodeElementInfo> codeElements, PsiReflectionPolicy reflectionPolicy, ITypeDeclaration declaration)
{
if (! declaration.IsValid())
return;
ITypeInfo typeInfo = reflectionPolicy.Wrap(declaration.DeclaredElement);
if (typeInfo != null)
codeElements.Add(typeInfo);
foreach (ITypeDeclaration nestedDeclaration in declaration.NestedTypeDeclarations)
PopulateCodeElementsFromTypeDeclaration(codeElements, reflectionPolicy, nestedDeclaration);
}
private ITestDriver CreateTestDriver()
{
var excludedTestFrameworkIds = new List<string>();
#if RESHARPER_60
var unitTestManager = UnitTestManager.GetInstance(provider.Solution);
var unitTestProviders = unitTestManager.GetEnabledProviders();
#else
var unitTestProviders = provider.UnitTestProvidersManager.GetEnabledProviders();
#endif
foreach (var testProvider in unitTestProviders)
{
IList<string> frameworkIds;
if (IncompatibleProviders.TryGetValue(testProvider.ID, out frameworkIds))
excludedTestFrameworkIds.AddRange(frameworkIds);
}
var testFrameworkSelector = new TestFrameworkSelector
{
Filter = testFrameworkHandle => !excludedTestFrameworkIds.Contains(testFrameworkHandle.Id),
FallbackMode = TestFrameworkFallbackMode.Approximate
};
return testFrameworkManager.GetTestDriver(testFrameworkSelector, logger);
}
private void Describe(IReflectionPolicy reflectionPolicy, IList<ICodeElementInfo> codeElements, IMessageSink consumerAdapter)
{
var testDriver = CreateTestDriver();
var testExplorationOptions = new TestExplorationOptions();
testDriver.Describe(reflectionPolicy, codeElements, testExplorationOptions, consumerAdapter,
NullProgressMonitor.CreateInstance());
}
public bool IsElementOfKind(IDeclaredElement element, UnitTestElementKind kind)
{
if (element == null)
throw new ArgumentNullException("element");
return EvalTestPartPredicate(element, testPart =>
{
switch (kind)
{
case UnitTestElementKind.Unknown:
return false;
case UnitTestElementKind.Test:
return testPart.IsTest;
case UnitTestElementKind.TestContainer:
return testPart.IsTestContainer;
case UnitTestElementKind.TestStuff:
return testPart.IsTestContribution;
default:
throw new ArgumentOutOfRangeException("kind");
}
});
}
public bool IsElementOfKind(IUnitTestElement element, UnitTestElementKind kind)
{
if (element == null)
throw new ArgumentNullException("element");
var gallioTestElement = element as GallioTestElement;
if (gallioTestElement == null)
return false;
switch (kind)
{
case UnitTestElementKind.Unknown:
case UnitTestElementKind.TestStuff:
return false;
case UnitTestElementKind.Test:
return gallioTestElement.IsTestCase;
case UnitTestElementKind.TestContainer:
return ! gallioTestElement.IsTestCase;
default:
throw new ArgumentOutOfRangeException("kind");
}
}
private bool EvalTestPartPredicate(IDeclaredElement element, Predicate<TestPart> predicate)
{
if (!element.IsValid())
return false;
try
{
#if RESHARPER_60
var reflectionPolicy = new PsiReflectionPolicy(element.GetPsiServices().PsiManager);
#else
var reflectionPolicy = new PsiReflectionPolicy(element.GetPsiServices().PsiManager, provider.CacheManager);
#endif
var elementInfo = reflectionPolicy.Wrap(element);
if (elementInfo == null)
return false;
var driver = CreateTestDriver();
var testParts = driver.GetTestParts(reflectionPolicy, elementInfo);
return GenericCollectionUtils.Exists(testParts, predicate);
}
catch (Exception ex)
{
HandleEmbeddedProcessCancelledException(ex);
throw;
}
}
/// <summary>
/// Gets instance of <see cref="T:JetBrains.ReSharper.TaskRunnerFramework.RemoteTaskRunnerInfo" />.
/// </summary>
public RemoteTaskRunnerInfo GetTaskRunnerInfo()
{
return new RemoteTaskRunnerInfo(typeof(FacadeTaskRunner));
}
/// <summary>
/// Compares unit tests elements to determine relative sort order.
/// </summary>
public int CompareUnitTestElements(IUnitTestElement x, IUnitTestElement y)
{
if (x == null)
throw new ArgumentNullException("x");
if (y == null)
throw new ArgumentNullException("y");
var xe = (GallioTestElement)x;
var ye = (GallioTestElement)y;
return xe.CompareTo(ye);
}
/// <summary>
/// Gets the icon to display in the Options panel or null to use the default.
/// </summary>
public Image Icon
{
get { return Resources.ProviderIcon; }
}
/// <summary>
/// Gets the name to display in the Options panel.
/// </summary>
public string Name
{
get { return Resources.ProviderName; }
}
/// <summary>
/// ReSharper can throw ProcessCancelledException while we are performing reflection
/// over code elements. Gallio will then often wrap the exception as a ModelException
/// which ReSharper does not expect. So we check to see whether a ProcessCancelledException
/// was wrapped up and throw it again if needed.
/// </summary>
private static void HandleEmbeddedProcessCancelledException(Exception exception)
{
do
{
if (exception is ProcessCancelledException)
throw exception;
exception = exception.InnerException;
}
while (exception != null);
}
private sealed class ConsumerAdapter : IMessageSink
{
private readonly GallioTestProvider provider;
private readonly UnitTestElementConsumer consumer;
private readonly MessageConsumer messageConsumer;
private readonly Dictionary<string, GallioTestElement> tests = new Dictionary<string, GallioTestElement>();
private readonly List<AnnotationData> annotations = new List<AnnotationData>();
public ConsumerAdapter(GallioTestProvider provider, UnitTestElementConsumer consumer)
{
this.provider = provider;
this.consumer = consumer;
messageConsumer = new MessageConsumer()
.Handle<TestDiscoveredMessage>(HandleTestDiscoveredMessage)
.Handle<AnnotationDiscoveredMessage>(HandleAnnotationDiscoveredMessage);
}
public ConsumerAdapter(GallioTestProvider provider, UnitTestElementLocationConsumer consumer, ITreeNode psiFile)
: this(provider, delegate(IUnitTestElement element)
{
var projectFile = psiFile.GetSourceFile().ToProjectFile();
if (projectFile == null || !projectFile.IsValid())
return;
consumer(element.GetDisposition());
})
{
}
public void Publish(Message message)
{
messageConsumer.Consume(message);
}
private void HandleTestDiscoveredMessage(TestDiscoveredMessage message)
{
GallioTestElement element;
if (!tests.TryGetValue(message.Test.Id, out element))
{
if (ShouldTestBePresented(message.Test.CodeElement))
{
GallioTestElement parentElement;
tests.TryGetValue(message.ParentTestId, out parentElement);
element = GallioTestElement.CreateFromTest(message.Test, message.Test.CodeElement, provider, parentElement);
consumer(element);
}
tests.Add(message.Test.Id, element);
}
}
private void HandleAnnotationDiscoveredMessage(AnnotationDiscoveredMessage message)
{
annotations.Add(message.Annotation);
}
public ProjectFileState CreateProjectFileState()
{
return annotations.Count != 0
? ProjectFileState.CreateFromAnnotations(annotations)
: null;
}
/// <summary>
/// ReSharper does not know how to present tests with a granularity any
/// larger than a type.
/// </summary>
/// <remarks>
/// <para>
/// The tree it shows to users in such cases is
/// not very helpful because it appears that the root test is a child of the
/// project that resides in the root namespace. So we filter out
/// certain kinds of tests from view.
/// </para>
/// </remarks>
private static bool ShouldTestBePresented(ICodeElementInfo codeElement)
{
if (codeElement == null)
return false;
switch (codeElement.Kind)
{
case CodeElementKind.Assembly:
case CodeElementKind.Namespace:
return false;
default:
return true;
}
}
}
}
public IEnumerable<string> CategoryAttributes
{
get { yield return CategoryAttribute.FullName; }
}
}
}
| |
#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
// .NET Compact Framework 1.0 has no support for System.Web.Mail
// SSCLI 1.0 has no support for System.Web.Mail
#if !NETCF && !SSCLI
using System;
using System.IO;
#if NET_2_0
using System.Net.Mail;
#else
using System.Web.Mail;
#endif
using Ctrip.Layout;
using Ctrip.Core;
using Ctrip.Util;
namespace Ctrip.Appender
{
/// <summary>
/// Send an e-mail when a specific logging event occurs, typically on errors
/// or fatal errors.
/// </summary>
/// <remarks>
/// <para>
/// The number of logging events delivered in this e-mail depend on
/// the value of <see cref="BufferingAppenderSkeleton.BufferSize"/> option. The
/// <see cref="SmtpAppender"/> keeps only the last
/// <see cref="BufferingAppenderSkeleton.BufferSize"/> logging events in its
/// cyclic buffer. This keeps memory requirements at a reasonable level while
/// still delivering useful application context.
/// </para>
/// <note type="caution">
/// Authentication and setting the server Port are only available on the MS .NET 1.1 runtime.
/// For these features to be enabled you need to ensure that you are using a version of
/// the Ctrip assembly that is built against the MS .NET 1.1 framework and that you are
/// running the your application on the MS .NET 1.1 runtime. On all other platforms only sending
/// unauthenticated messages to a server listening on port 25 (the default) is supported.
/// </note>
/// <para>
/// Authentication is supported by setting the <see cref="Authentication"/> property to
/// either <see cref="SmtpAuthentication.Basic"/> or <see cref="SmtpAuthentication.Ntlm"/>.
/// If using <see cref="SmtpAuthentication.Basic"/> authentication then the <see cref="Username"/>
/// and <see cref="Password"/> properties must also be set.
/// </para>
/// <para>
/// To set the SMTP server port use the <see cref="Port"/> property. The default port is 25.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public class SmtpAppender : BufferingAppenderSkeleton
{
#region Public Instance Constructors
/// <summary>
/// Default constructor
/// </summary>
/// <remarks>
/// <para>
/// Default constructor
/// </para>
/// </remarks>
public SmtpAppender()
{
}
#endregion // Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses (use semicolon on .NET 1.1 and comma for later versions).
/// </summary>
/// <value>
/// <para>
/// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses.
/// </para>
/// <para>
/// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses.
/// </para>
/// </value>
/// <remarks>
/// <para>
/// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses.
/// </para>
/// <para>
/// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses.
/// </para>
/// </remarks>
public string To
{
get { return m_to; }
set { m_to = value; }
}
/// <summary>
/// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses
/// that will be carbon copied (use semicolon on .NET 1.1 and comma for later versions).
/// </summary>
/// <value>
/// <para>
/// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses.
/// </para>
/// <para>
/// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses.
/// </para>
/// </value>
/// <remarks>
/// <para>
/// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses.
/// </para>
/// <para>
/// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses.
/// </para>
/// </remarks>
public string Cc
{
get { return m_cc; }
set { m_cc = value; }
}
/// <summary>
/// Gets or sets a semicolon-delimited list of recipient e-mail addresses
/// that will be blind carbon copied.
/// </summary>
/// <value>
/// A semicolon-delimited list of e-mail addresses.
/// </value>
/// <remarks>
/// <para>
/// A semicolon-delimited list of recipient e-mail addresses.
/// </para>
/// </remarks>
public string Bcc
{
get { return m_bcc; }
set { m_bcc = value; }
}
/// <summary>
/// Gets or sets the e-mail address of the sender.
/// </summary>
/// <value>
/// The e-mail address of the sender.
/// </value>
/// <remarks>
/// <para>
/// The e-mail address of the sender.
/// </para>
/// </remarks>
public string From
{
get { return m_from; }
set { m_from = value; }
}
/// <summary>
/// Gets or sets the subject line of the e-mail message.
/// </summary>
/// <value>
/// The subject line of the e-mail message.
/// </value>
/// <remarks>
/// <para>
/// The subject line of the e-mail message.
/// </para>
/// </remarks>
public string Subject
{
get { return m_subject; }
set { m_subject = value; }
}
/// <summary>
/// Gets or sets the name of the SMTP relay mail server to use to send
/// the e-mail messages.
/// </summary>
/// <value>
/// The name of the e-mail relay server. If SmtpServer is not set, the
/// name of the local SMTP server is used.
/// </value>
/// <remarks>
/// <para>
/// The name of the e-mail relay server. If SmtpServer is not set, the
/// name of the local SMTP server is used.
/// </para>
/// </remarks>
public string SmtpHost
{
get { return m_smtpHost; }
set { m_smtpHost = value; }
}
/// <summary>
/// Obsolete
/// </summary>
/// <remarks>
/// Use the BufferingAppenderSkeleton Fix methods instead
/// </remarks>
/// <remarks>
/// <para>
/// Obsolete property.
/// </para>
/// </remarks>
[Obsolete("Use the BufferingAppenderSkeleton Fix methods")]
public bool LocationInfo
{
get { return false; }
set { ; }
}
/// <summary>
/// The mode to use to authentication with the SMTP server
/// </summary>
/// <remarks>
/// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note>
/// <para>
/// Valid Authentication mode values are: <see cref="SmtpAuthentication.None"/>,
/// <see cref="SmtpAuthentication.Basic"/>, and <see cref="SmtpAuthentication.Ntlm"/>.
/// The default value is <see cref="SmtpAuthentication.None"/>. When using
/// <see cref="SmtpAuthentication.Basic"/> you must specify the <see cref="Username"/>
/// and <see cref="Password"/> to use to authenticate.
/// When using <see cref="SmtpAuthentication.Ntlm"/> the Windows credentials for the current
/// thread, if impersonating, or the process will be used to authenticate.
/// </para>
/// </remarks>
public SmtpAuthentication Authentication
{
get { return m_authentication; }
set { m_authentication = value; }
}
/// <summary>
/// The username to use to authenticate with the SMTP server
/// </summary>
/// <remarks>
/// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note>
/// <para>
/// A <see cref="Username"/> and <see cref="Password"/> must be specified when
/// <see cref="Authentication"/> is set to <see cref="SmtpAuthentication.Basic"/>,
/// otherwise the username will be ignored.
/// </para>
/// </remarks>
public string Username
{
get { return m_username; }
set { m_username = value; }
}
/// <summary>
/// The password to use to authenticate with the SMTP server
/// </summary>
/// <remarks>
/// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note>
/// <para>
/// A <see cref="Username"/> and <see cref="Password"/> must be specified when
/// <see cref="Authentication"/> is set to <see cref="SmtpAuthentication.Basic"/>,
/// otherwise the password will be ignored.
/// </para>
/// </remarks>
public string Password
{
get { return m_password; }
set { m_password = value; }
}
/// <summary>
/// The port on which the SMTP server is listening
/// </summary>
/// <remarks>
/// <note type="caution">Server Port is only available on the MS .NET 1.1 runtime.</note>
/// <para>
/// The port on which the SMTP server is listening. The default
/// port is <c>25</c>. The Port can only be changed when running on
/// the MS .NET 1.1 runtime.
/// </para>
/// </remarks>
public int Port
{
get { return m_port; }
set { m_port = value; }
}
/// <summary>
/// Gets or sets the priority of the e-mail message
/// </summary>
/// <value>
/// One of the <see cref="MailPriority"/> values.
/// </value>
/// <remarks>
/// <para>
/// Sets the priority of the e-mails generated by this
/// appender. The default priority is <see cref="MailPriority.Normal"/>.
/// </para>
/// <para>
/// If you are using this appender to report errors then
/// you may want to set the priority to <see cref="MailPriority.High"/>.
/// </para>
/// </remarks>
public MailPriority Priority
{
get { return m_mailPriority; }
set { m_mailPriority = value; }
}
#if NET_2_0
/// <summary>
/// Enable or disable use of SSL when sending e-mail message
/// </summary>
/// <remarks>
/// This is available on MS .NET 2.0 runtime and higher
/// </remarks>
public bool EnableSsl
{
get { return m_enableSsl; }
set { m_enableSsl = value; }
}
/// <summary>
/// Gets or sets the reply-to e-mail address.
/// </summary>
/// <remarks>
/// This is available on MS .NET 2.0 runtime and higher
/// </remarks>
public string ReplyTo
{
get { return m_replyTo; }
set { m_replyTo = value; }
}
#endif
#endregion // Public Instance Properties
#region Override implementation of BufferingAppenderSkeleton
/// <summary>
/// Sends the contents of the cyclic buffer as an e-mail message.
/// </summary>
/// <param name="events">The logging events to send.</param>
override protected void SendBuffer(LoggingEvent[] events)
{
// Note: this code already owns the monitor for this
// appender. This frees us from needing to synchronize again.
try
{
StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture);
string t = Layout.Header;
if (t != null)
{
writer.Write(t);
}
for(int i = 0; i < events.Length; i++)
{
// Render the event and append the text to the buffer
RenderLoggingEvent(writer, events[i]);
}
t = Layout.Footer;
if (t != null)
{
writer.Write(t);
}
SendEmail(writer.ToString());
}
catch(Exception e)
{
ErrorHandler.Error("Error occurred while sending e-mail notification.", e);
}
}
#endregion // Override implementation of BufferingAppenderSkeleton
#region Override implementation of AppenderSkeleton
/// <summary>
/// This appender requires a <see cref="Layout"/> to be set.
/// </summary>
/// <value><c>true</c></value>
/// <remarks>
/// <para>
/// This appender requires a <see cref="Layout"/> to be set.
/// </para>
/// </remarks>
override protected bool RequiresLayout
{
get { return true; }
}
#endregion // Override implementation of AppenderSkeleton
#region Protected Methods
/// <summary>
/// Send the email message
/// </summary>
/// <param name="messageBody">the body text to include in the mail</param>
virtual protected void SendEmail(string messageBody)
{
#if NET_2_0
// .NET 2.0 has a new API for SMTP email System.Net.Mail
// This API supports credentials and multiple hosts correctly.
// The old API is deprecated.
// Create and configure the smtp client
SmtpClient smtpClient = new SmtpClient();
if (!String.IsNullOrEmpty(m_smtpHost))
{
smtpClient.Host = m_smtpHost;
}
smtpClient.Port = m_port;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = m_enableSsl;
if (m_authentication == SmtpAuthentication.Basic)
{
// Perform basic authentication
smtpClient.Credentials = new System.Net.NetworkCredential(m_username, m_password);
}
else if (m_authentication == SmtpAuthentication.Ntlm)
{
// Perform integrated authentication (NTLM)
smtpClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
}
using (MailMessage mailMessage = new MailMessage())
{
mailMessage.Body = messageBody;
mailMessage.From = new MailAddress(m_from);
mailMessage.To.Add(m_to);
if (!String.IsNullOrEmpty(m_cc))
{
mailMessage.CC.Add(m_cc);
}
if (!String.IsNullOrEmpty(m_bcc))
{
mailMessage.Bcc.Add(m_bcc);
}
if (!String.IsNullOrEmpty(m_replyTo))
{
// .NET 4.0 warning CS0618: 'System.Net.Mail.MailMessage.ReplyTo' is obsolete:
// 'ReplyTo is obsoleted for this type. Please use ReplyToList instead which can accept multiple addresses. http://go.microsoft.com/fwlink/?linkid=14202'
#if !NET_4_0
mailMessage.ReplyTo = new MailAddress(m_replyTo);
#else
mailMessage.ReplyToList.Add(new MailAddress(m_replyTo));
#endif
}
mailMessage.Subject = m_subject;
mailMessage.Priority = m_mailPriority;
// TODO: Consider using SendAsync to send the message without blocking. This would be a change in
// behaviour compared to .NET 1.x. We would need a SendCompletedCallback to log errors.
smtpClient.Send(mailMessage);
}
#else
// .NET 1.x uses the System.Web.Mail API for sending Mail
MailMessage mailMessage = new MailMessage();
mailMessage.Body = messageBody;
mailMessage.From = m_from;
mailMessage.To = m_to;
if (m_cc != null && m_cc.Length > 0)
{
mailMessage.Cc = m_cc;
}
if (m_bcc != null && m_bcc.Length > 0)
{
mailMessage.Bcc = m_bcc;
}
mailMessage.Subject = m_subject;
mailMessage.Priority = m_mailPriority;
#if NET_1_1
// The Fields property on the MailMessage allows the CDO properties to be set directly.
// This property is only available on .NET Framework 1.1 and the implementation must understand
// the CDO properties. For details of the fields available in CDO see:
//
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdosys/html/_cdosys_configuration_coclass.asp
//
try
{
if (m_authentication == SmtpAuthentication.Basic)
{
// Perform basic authentication
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", m_username);
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", m_password);
}
else if (m_authentication == SmtpAuthentication.Ntlm)
{
// Perform integrated authentication (NTLM)
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 2);
}
// Set the port if not the default value
if (m_port != 25)
{
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", m_port);
}
}
catch(MissingMethodException missingMethodException)
{
// If we were compiled against .NET 1.1 but are running against .NET 1.0 then
// we will get a MissingMethodException when accessing the MailMessage.Fields property.
ErrorHandler.Error("SmtpAppender: Authentication and server Port are only supported when running on the MS .NET 1.1 framework", missingMethodException);
}
#else
if (m_authentication != SmtpAuthentication.None)
{
ErrorHandler.Error("SmtpAppender: Authentication is only supported on the MS .NET 1.1 or MS .NET 2.0 builds of Ctrip");
}
if (m_port != 25)
{
ErrorHandler.Error("SmtpAppender: Server Port is only supported on the MS .NET 1.1 or MS .NET 2.0 builds of Ctrip");
}
#endif // if NET_1_1
if (m_smtpHost != null && m_smtpHost.Length > 0)
{
SmtpMail.SmtpServer = m_smtpHost;
}
SmtpMail.Send(mailMessage);
#endif // if NET_2_0
}
#endregion // Protected Methods
#region Private Instance Fields
private string m_to;
private string m_cc;
private string m_bcc;
private string m_from;
private string m_subject;
private string m_smtpHost;
// authentication fields
private SmtpAuthentication m_authentication = SmtpAuthentication.None;
private string m_username;
private string m_password;
// server port, default port 25
private int m_port = 25;
private MailPriority m_mailPriority = MailPriority.Normal;
#if NET_2_0
private bool m_enableSsl = false;
private string m_replyTo;
#endif
#endregion // Private Instance Fields
#region SmtpAuthentication Enum
/// <summary>
/// Values for the <see cref="SmtpAppender.Authentication"/> property.
/// </summary>
/// <remarks>
/// <para>
/// SMTP authentication modes.
/// </para>
/// </remarks>
public enum SmtpAuthentication
{
/// <summary>
/// No authentication
/// </summary>
None,
/// <summary>
/// Basic authentication.
/// </summary>
/// <remarks>
/// Requires a username and password to be supplied
/// </remarks>
Basic,
/// <summary>
/// Integrated authentication
/// </summary>
/// <remarks>
/// Uses the Windows credentials from the current thread or process to authenticate.
/// </remarks>
Ntlm
}
#endregion // SmtpAuthentication Enum
}
}
#endif // !NETCF && !SSCLI
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Threading;
namespace Apache.Geode.Client.UnitTests
{
using Apache.Geode.DUnitFramework;
class TallyWriter : Apache.Geode.Client.CacheWriterAdapter<Object, Object>
{
#region Private members
private int m_creates = 0;
private int m_updates = 0;
private int m_invalidates = 0;
private int m_destroys = 0;
private Apache.Geode.Client.ISerializable m_callbackArg = null;
private int m_clears = 0;
private Apache.Geode.Client.ISerializable m_lastKey = null;
private Apache.Geode.Client.ISerializable m_lastValue = null;
private bool isWriterFailed = false;
private bool isWriterInvoke = false;
private bool isCallbackCalled = false;
#endregion
#region Public accessors
public int Creates
{
get
{
return m_creates;
}
}
public int Clears
{
get
{
return m_clears;
}
}
public int Updates
{
get
{
return m_updates;
}
}
public int Invalidates
{
get
{
return m_invalidates;
}
}
public int Destroys
{
get
{
return m_destroys;
}
}
public Apache.Geode.Client.ISerializable LastKey
{
get
{
return m_lastKey;
}
}
public Apache.Geode.Client.ISerializable CallbackArgument
{
get
{
return m_callbackArg;
}
}
public Apache.Geode.Client.ISerializable LastValue
{
get
{
return m_lastValue;
}
}
public void SetWriterFailed( )
{
isWriterFailed = true;
}
public void SetCallBackArg( Apache.Geode.Client.ISerializable callbackArg )
{
m_callbackArg = callbackArg;
}
public void ResetWriterInvokation()
{
isWriterInvoke = false;
isCallbackCalled = false;
}
public bool IsWriterInvoked
{
get
{
return isWriterInvoke;
}
}
public bool IsCallBackArgCalled
{
get
{
return isCallbackCalled;
}
}
#endregion
public int ExpectCreates(int expected)
{
int tries = 0;
while ((m_creates < expected) && (tries < 200))
{
Thread.Sleep(100);
tries++;
}
return m_creates;
}
public int ExpectUpdates(int expected)
{
int tries = 0;
while ((m_updates < expected) && (tries < 200))
{
Thread.Sleep(100);
tries++;
}
return m_updates;
}
public void ShowTallies()
{
Util.Log("TallyWriter state: (updates = {0}, creates = {1}, invalidates = {2}, destroys = {3})",
Updates, Creates, Invalidates, Destroys);
}
public void CheckcallbackArg(Apache.Geode.Client.EntryEvent<Object, Object> ev)
{
if(!isWriterInvoke)
isWriterInvoke = true;
if (m_callbackArg != null)
{
Apache.Geode.Client.ISerializable callbkArg = (Apache.Geode.Client.ISerializable)ev.CallbackArgument;
if (m_callbackArg.Equals(callbkArg))
isCallbackCalled = true;
}
}
public static TallyWriter Create()
{
return new TallyWriter();
}
#region ICacheWriter Members
public override bool BeforeCreate(Apache.Geode.Client.EntryEvent<Object, Object> ev)
{
m_creates++;
Util.Log("TallyWriter::BeforeCreate");
CheckcallbackArg(ev);
return !isWriterFailed;
}
public override bool BeforeDestroy(Apache.Geode.Client.EntryEvent<Object, Object> ev)
{
m_destroys++;
Util.Log("TallyWriter::BeforeDestroy");
CheckcallbackArg(ev);
return !isWriterFailed;
}
public override bool BeforeRegionClear(Apache.Geode.Client.RegionEvent<Object, Object> ev)
{
m_clears++;
Util.Log("TallyWriter::BeforeRegionClear");
return true;
}
public override bool BeforeUpdate(Apache.Geode.Client.EntryEvent<Object, Object> ev)
{
m_updates++;
Util.Log("TallyWriter::BeforeUpdate");
CheckcallbackArg(ev);
return !isWriterFailed;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using org.ncore.Common;
using org.ncore.Diagnostics;
using org.ncore.Extensions;
namespace _unittests.org.ncore.Diagnostics
{
/// <summary>
/// Summary description for LogWriterTests
/// </summary>
[TestClass]
public class LogWriterTests
{
// TODO: There are definitely some unit tests missing from this TestFixture. For the sake of expediency we have NOT
// implemented all possible unit tests for the LogWriter class. For example, not all overloads of the Write() method
// are exercised. Additionally, most tests focus on the file logging output and do not examine the EventLog or
// other Console targets. These alternative targets are tested only superficially to ensure that basic functionality
// for their respective logging is working. Obviously this issue should be addressed as soon as possible to ensure
// full unit test coverage for this assembly.
// TODO: Need to write unit tests to ensure thread saftey and proper concurrency behavior. I.e. writers on multiple threads writing to the same log at the same time. See Write_MultiThreaded() unit test below (currently commented out.)
// TODO: Should have a unit test that ensures proper behavior when writing to multiple LogWriter instances from the same caller.
private static string[] _parseLineFromFile( string fileName, int targetLineNumber = 1 )
{
if( File.Exists( fileName ) )
{
FileStream fileStream = File.Open( fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read,
System.IO.FileShare.ReadWrite );
string targetLine = _readLineFromStream( fileStream, targetLineNumber );
fileStream.Close();
return targetLine.Split( '\x1F' );
}
else
{
throw new ApplicationException( "Could not read file because the file does not exist. File name: " + fileName );
}
}
private static string _readLineFromStream( Stream stream, int targetLineNumber )
{
Condition.Assert( targetLineNumber > 0, new ArgumentException( "Value must be greater than 0.", "targetLineNumber" ) );
StreamReader streamReader = new StreamReader( stream );
streamReader.BaseStream.Seek( 0, SeekOrigin.Begin );
string targetLine = string.Empty;
string currentLine;
int currentLineNumber = 0;
do
{
currentLineNumber++;
currentLine = streamReader.ReadLine();
if( currentLineNumber == targetLineNumber )
{
targetLine = currentLine;
break;
}
} while( currentLine != null );
return targetLine;
}
private static void _deleteFile( string fileName )
{
if( File.Exists( fileName ) )
{
File.Delete( fileName );
}
}
private LogWriter _log;
private static string _eventLogSource = "NCoreUnitTests";
public LogWriterTests()
{
//
// TODO: Add constructor logic here
//
}
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
// TODO: Need to deal with changes (as of Vista) that prevent an event log source being created on the fly and used right away.
// See below comments in sample at: http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx JF
// "An event log source should not be created and immediately used.
// There is a latency time to enable the source, it should be created
// prior to executing the application that uses the source.
// Execute this sample a second time to use the new source."
// UPDATE: Seems to have been addressed by putting source creation here in TestFixture setup/teardown. Verify? JF
// TODO: Also need to deal with the issue when attempting to create the new source:
// "The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security."
// for more info see http://social.msdn.microsoft.com/Forums/en-US/windowsgeneraldevelopmentissues/thread/416098a4-4183-4711-a53b-e10966c9801d/
// and here's the (concise) permissions fix in the registry: http://support.microsoft.com/kb/842795
// Simple enough, but a *very* manual user action (as is setting up the EventLog source that is to be written to)
// This isn't really something we can do in a unit test setup so the question is how we deal with this
// so that tests will just run all green when someone runs them for the first time? JF
[ClassInitialize()]
public static void MyClassInitialize( TestContext testContext )
{
try
{
// NOTE: This is an auxilliary step that needs to happen just once to create
// the EventLog source on the machine, then never again. Unfortunately,
// without manually setting permissions on the event log hive in the registry
// for the executing user this will fail (as will all the event logging unit
// tests.) Most unfortunate. JF
if( !EventLog.SourceExists( _eventLogSource ) )
{
EventLog.CreateEventSource( _eventLogSource, "Application" );
}
}
catch
{
// NOTE: See above comments for explanation of issues with EventLog testing.
// Empty try-catch is a neccessary evil here. JF
}
}
[ClassCleanup()]
public static void MyClassCleanup()
{
// NOTE: See comments in MyClassInitialize() for explanation of issues around EventLog testing. JF
try
{
if( !EventLog.SourceExists( _eventLogSource ) )
{
EventLog.DeleteEventSource( _eventLogSource, "Application" );
}
}
catch
{
// NOTE: See above comments for explanation of issues with EventLog testing.
// Empty try-catch is a neccessary evil here. JF
}
}
[TestInitialize()]
public void MyTestInitialize()
{
_log = new LogWriter();
_deleteFile( _log.FileLocation );
}
[TestCleanup()]
public void MyTestCleanup()
{
if( _log != null )
{
_log.Dispose();
_log = null;
}
}
#endregion
[TestMethod]
public void Write()
{
using( _log )
{
_log.Write( "First entry" );
_log.Write( "Second entry" );
_log.Write( "Third (and last) entry" );
}
string[] fields = LogWriterTests._parseLineFromFile( _log.FileLocation, 1 );
DateTime.Parse( fields[ 0 ] ); // Test the date/time is at least valid (it's tough to actually check the date/time value)
Assert.AreEqual( fields[ 1 ], "First entry" );
Assert.AreEqual( fields[ 2 ], "_unittests.org.ncore.Diagnostics.LogWriterTests->Write()" );
Assert.AreEqual( fields[ 3 ], "Information" );
Assert.AreEqual( fields[ 4 ], "0" );
fields = LogWriterTests._parseLineFromFile( _log.FileLocation, 2 );
DateTime.Parse( fields[ 0 ] ); // Test the date/time is at least valid (it's tough to actually check the date/time value)
Assert.AreEqual( fields[ 1 ], "Second entry" );
Assert.AreEqual( fields[ 2 ], "_unittests.org.ncore.Diagnostics.LogWriterTests->Write()" );
Assert.AreEqual( fields[ 3 ], "Information" );
Assert.AreEqual( fields[ 4 ], "0" );
fields = LogWriterTests._parseLineFromFile( _log.FileLocation, 3 );
DateTime.Parse( fields[ 0 ] ); // Test the date/time is at least valid (it's tough to actually check the date/time value)
Assert.AreEqual( fields[ 1 ], "Third (and last) entry" );
Assert.AreEqual( fields[ 2 ], "_unittests.org.ncore.Diagnostics.LogWriterTests->Write()" );
Assert.AreEqual( fields[ 3 ], "Information" );
Assert.AreEqual( fields[ 4 ], "0" );
// NOTE: Normally, if you're just writing a single line to the log you can do this:
// __log.Write( ...
// Instead of embedding in the 'using' block. Just remember to do this:
// __log.Dipsose();
// __log = null;
// If you do use it outside of a 'using' block. Of course, you probably just want to do this once when your app shuts down.
// Regardless, the LogWriter will handle it correctly.
}
[TestMethod]
public void Write_WithAdditionalEntryData()
{
_log.Write( "Write_WithAdditionalEntryData", "A=1", "B=2", "C=3" );
string[] fields = LogWriterTests._parseLineFromFile( _log.FileLocation );
DateTime.Parse( fields[ 0 ] ); // NOTE: Test the date/time is at least valid (it's tough to actually check the date/time value)
Assert.AreEqual( fields[ 1 ], "Write_WithAdditionalEntryData" );
Assert.AreEqual( fields[ 2 ], "_unittests.org.ncore.Diagnostics.LogWriterTests->Write_WithAdditionalEntryData()" );
Assert.AreEqual( fields[ 3 ], "Information" );
Assert.AreEqual( fields[ 4 ], "0" );
Assert.AreEqual( fields[ 5 ], "A=1" );
Assert.AreEqual( fields[ 6 ], "B=2" );
Assert.AreEqual( fields[ 7 ], "C=3" );
}
[TestMethod]
public void Write_WithEntryType()
{
_log.Write( "Write_WithEntryType", LogWriter.EntryTypeEnum.Warning );
string[] fields = LogWriterTests._parseLineFromFile( _log.FileLocation );
DateTime.Parse( fields[ 0 ] ); // NOTE: Test the date/time is at least valid (it's tough to actually check the date/time value)
Assert.AreEqual( fields[ 1 ], "Write_WithEntryType" );
Assert.AreEqual( fields[ 2 ], "_unittests.org.ncore.Diagnostics.LogWriterTests->Write_WithEntryType()" );
Assert.AreEqual( fields[ 3 ], "Warning" );
Assert.AreEqual( fields[ 4 ], "0" );
}
[TestMethod]
public void Write_WithEntryTypeAndEventNumber()
{
_log.Write( "Write_WithEntryTypeAndEventNumber", LogWriter.EntryTypeEnum.Warning, 123 );
string[] fields = LogWriterTests._parseLineFromFile( _log.FileLocation );
DateTime.Parse( fields[ 0 ] ); // NOTE: Test the date/time is at least valid (it's tough to actually check the date/time value)
Assert.AreEqual( fields[ 1 ], "Write_WithEntryTypeAndEventNumber" );
Assert.AreEqual( fields[ 2 ], "_unittests.org.ncore.Diagnostics.LogWriterTests->Write_WithEntryTypeAndEventNumber()" );
Assert.AreEqual( fields[ 3 ], "Warning" );
Assert.AreEqual( fields[ 4 ], "123" );
}
[TestMethod]
public void Write_WithSource()
{
_log.Write( "Write_WithSource", "Custom Source", LogWriter.EntryTypeEnum.Information );
string[] fields = LogWriterTests._parseLineFromFile( _log.FileLocation );
DateTime.Parse( fields[ 0 ] ); // NOTE: Test the date/time is at least valid (it's tough to actually check the date/time value)
Assert.AreEqual( fields[ 1 ], "Write_WithSource" );
Assert.AreEqual( fields[ 2 ], "Custom Source" );
Assert.AreEqual( fields[ 3 ], "Information" );
Assert.AreEqual( fields[ 4 ], "0" );
}
[TestMethod]
public void Write_WithException()
{
_log.LogTarget = _log.LogTarget | LogWriter.LogTargetEnum.EventLog;
try
{
throw new ApplicationException( "An exception was thrown." );
}
catch( Exception exception )
{
_log.Write( exception );
}
string[] fields = LogWriterTests._parseLineFromFile( _log.FileLocation );
DateTime.Parse( fields[ 0 ] ); // NOTE: Test the date/time is at least valid (it's tough to actually check the date/time value)
// NOTE: The following ensures that the exception expression at least starts the same as we expect. The reason we can't compare
// the entire string is because the debug symbols will vary depending on where the source was built.
Assert.IsTrue( fields[ 1 ].StartsWith( "System.ApplicationException: An exception was thrown.\x1A at _unittests.org.ncore.Diagnostics.LogWriterTests.Write_WithException()" ) );
Assert.AreEqual( fields[ 2 ], "_unittests.org.ncore.Diagnostics.LogWriterTests->Write_WithException()" );
Assert.AreEqual( fields[ 3 ], "Exception" );
Assert.AreEqual( fields[ 4 ], "0" );
}
[TestMethod]
public void Write_WithExceptionAndEntryType()
{
_log.LogTarget = _log.LogTarget | LogWriter.LogTargetEnum.EventLog;
try
{
throw new ApplicationException( "An exception was thrown." );
}
catch( Exception exception )
{
_log.Write( exception, LogWriter.EntryTypeEnum.Information );
}
string[] fields = LogWriterTests._parseLineFromFile( _log.FileLocation );
DateTime.Parse( fields[ 0 ] ); // NOTE: Test the date/time is at least valid (it's tough to actually check the date/time value)
// NOTE: The following ensures that the exception expression at least starts the same as we expect. The reason we can't compare
// the entire string is because the debug symbols will vary depending on where the source was built.
Assert.IsTrue( fields[ 1 ].StartsWith( "System.ApplicationException: An exception was thrown.\x1A at _unittests.org.ncore.Diagnostics.LogWriterTests.Write_WithExceptionAndEntryType()" ) );
Assert.AreEqual( fields[ 2 ], "_unittests.org.ncore.Diagnostics.LogWriterTests->Write_WithExceptionAndEntryType()" );
Assert.AreEqual( fields[ 3 ], "Information" );
Assert.AreEqual( fields[ 4 ], "0" );
}
[TestMethod]
public void Write_CustomizedLogFileDetails()
{
_log.FileExtension = "txt";
_log.FileNameDateFormat = "MM-dd-yyyy";
_log.FileNameSuffix = "_log";
_log.FileNamePrefix = "unit-test_";
_log.FilePath = System.Environment.CurrentDirectory + @"\testlog\";
using( _log )
{
_log.Write( "Write_CustomizedLogFileDetails" );
_log.Write( "Write_CustomizedLogFileDetails" );
_log.Write( "Write_CustomizedLogFileDetails" );
}
// UNDONE: Figure out this whole .FileName / .LogFileFullName - I mean seriously, WTF?!
string[] fields = LogWriterTests._parseLineFromFile( _log.FileLocation );
Assert.IsTrue( _log.FileName.StartsWith( "unit-test_" ) );
Assert.IsTrue( _log.FileName.EndsWith( "_log.txt" ) );
Assert.IsTrue( _log.FileName.Substring( 10, 10 ) == DateTime.Now.ToString( "MM-dd-yyyy" ) );
DateTime.Parse( fields[ 0 ] ); // Test the date/time is at least valid (it's tough to actually check the date/time value)
Assert.AreEqual( fields[ 1 ], "Write_CustomizedLogFileDetails" );
Assert.AreEqual( fields[ 2 ], "_unittests.org.ncore.Diagnostics.LogWriterTests->Write_CustomizedLogFileDetails()" );
Assert.AreEqual( fields[ 3 ], "Information" );
Assert.AreEqual( fields[ 4 ], "0" );
if( Directory.Exists( _log.FilePath ) )
{
Directory.Delete( _log.FilePath, true );
}
}
[TestMethod]
public void Write_ChangeLogFileDetailsBetweenEntries()
{
string initialLogFile = _log.FileLocation;
_log.Write( "Write_ChangeLogFileDetailsBetweenEntries" );
_log.FileExtension = "txt";
_log.FileNameDateFormat = "MM-dd-yyyy";
_log.FileNameSuffix = "_log";
_log.FileNamePrefix = "unit-test_";
_log.FilePath = System.Environment.CurrentDirectory + @"\testlog\";
_log.Write( "Write_ChangeLogFileDetailsBetweenEntries" );
// UNDONE: Figure out this whole .FileName / .LogFileFullName - I mean seriously, WTF?!
string[] fields = LogWriterTests._parseLineFromFile( _log.FileLocation );
Assert.IsTrue( _log.FileName.StartsWith( "unit-test_" ) );
Assert.IsTrue( _log.FileName.EndsWith( "_log.txt" ) );
Assert.IsTrue( _log.FileName.Substring( 10, 10 ) == DateTime.Now.ToString( "MM-dd-yyyy" ) );
DateTime.Parse( fields[ 0 ] ); // Test the date/time is at least valid (it's tough to actually check the date/time value)
Assert.AreEqual( fields[ 1 ], "Write_ChangeLogFileDetailsBetweenEntries" );
Assert.AreEqual( fields[ 2 ], "_unittests.org.ncore.Diagnostics.LogWriterTests->Write_ChangeLogFileDetailsBetweenEntries()" );
Assert.AreEqual( fields[ 3 ], "Information" );
Assert.AreEqual( fields[ 4 ], "0" );
if( Directory.Exists( _log.FilePath ) )
{
Directory.Delete( _log.FilePath, true );
}
fields = LogWriterTests._parseLineFromFile( initialLogFile );
DateTime.Parse( fields[ 0 ] ); // Test the date/time is at least valid (it's tough to actually check the date/time value)
Assert.AreEqual( fields[ 1 ], "Write_ChangeLogFileDetailsBetweenEntries" );
Assert.AreEqual( fields[ 2 ], "_unittests.org.ncore.Diagnostics.LogWriterTests->Write_ChangeLogFileDetailsBetweenEntries()" );
Assert.AreEqual( fields[ 3 ], "Information" );
Assert.AreEqual( fields[ 4 ], "0" );
}
// TODO: See comments on EventLog Source creation in TestFixture setup. JF
// TODO: The whole "Source" thing is a bit confusing as well since it means something different for the EventLog than it does for the LogWriter. JF
[TestMethod]
//[Ignore]
public void Write_ToEventLog()
{
_log.LogTarget = LogWriter.LogTargetEnum.EventLog;
_log.EventLogSource = _eventLogSource;
_log.Write( "Write_ToEventLog", LogWriter.EntryTypeEnum.Error );
EventLog eventLog = new EventLog( "Application" );
// HACK: Assumes that the entry we're interested in is the last one
// with this source in the list. Probably true but still hacky.
// I don't really know how to deal with this otherwise though. JF
// HACK: Oh, and btw, this approach of spinning through EVERYTHING
// in the event log to find our entry is SOOOO slow. Again, I'm
// stumped as to a better alternative. JF
List<EventLogEntry> entries = new List<EventLogEntry>();
foreach( EventLogEntry entry in eventLog.Entries )
{
if( entry.Source == _eventLogSource )
{
entries.Add( entry );
}
}
EventLogEntry targetEntry = entries.Last();
Assert.IsNotNull( targetEntry );
Assert.AreEqual( targetEntry.Message, "In _unittests.org.ncore.Diagnostics.LogWriterTests->Write_ToEventLog():\r\nWrite_ToEventLog" );
Assert.AreEqual( targetEntry.Source, _eventLogSource );
Assert.AreEqual( targetEntry.EntryType, EventLogEntryType.Error );
Assert.AreEqual( targetEntry.InstanceId, 0 );
}
// TODO: See event log issues mentioned above in Write_ToEventLog() test. JF
[TestMethod]
//[Ignore]
public void Write_ToEventLogWithAdditionalEntryData()
{
_log.LogTarget = LogWriter.LogTargetEnum.EventLog;
_log.EventLogSource = _eventLogSource;
_log.Write( "Write_ToEventLogWithAdditionalEntryData", LogWriter.EntryTypeEnum.Error, 0, "A=1", "B=2", "C=3" );
EventLog eventLog = new EventLog( "Application" );
List<EventLogEntry> entries = new List<EventLogEntry>();
foreach( EventLogEntry entry in eventLog.Entries )
{
if( entry.Source == _eventLogSource )
{
entries.Add( entry );
}
}
EventLogEntry targetEntry = entries.Last();
Assert.IsNotNull( targetEntry );
Assert.AreEqual( targetEntry.Message, "In _unittests.org.ncore.Diagnostics.LogWriterTests->Write_ToEventLogWithAdditionalEntryData():\r\nWrite_ToEventLogWithAdditionalEntryData" );
Assert.AreEqual( targetEntry.Source, _eventLogSource );
Assert.AreEqual( targetEntry.EntryType, EventLogEntryType.Error );
Assert.AreEqual( targetEntry.InstanceId, 0 );
string additionalEntryData = targetEntry.Data.ToText();
Assert.AreEqual( additionalEntryData, "A=1\u001FB=2\u001FC=3" );
}
[TestMethod]
public void Write_UsingDerivedLogWriter()
{
LogWriter log = new DerivedLogWriter();
using( log )
{
log.Write( "Write_UsingDerivedLogWriter" );
log.Write( "Write_UsingDerivedLogWriter" );
log.Write( "Write_UsingDerivedLogWriter" );
}
// UNDONE: Figure out this whole .FileName / .LogFileFullName - I mean seriously, WTF?!
string[] fields = LogWriterTests._parseLineFromFile( log.FileLocation );
Assert.IsTrue( log.FileName.StartsWith( "unit-test_" ) );
Assert.IsTrue( log.FileName.EndsWith( "_log.txt" ) );
Assert.IsTrue( log.FileName.Substring( 10, 10 ) == DateTime.Now.ToString( "MM-dd-yyyy" ) );
DateTime.Parse( fields[ 0 ] ); // Test the date/time is at least valid (it's tough to actually check the date/time value)
Assert.AreEqual( fields[ 1 ], "Write_UsingDerivedLogWriter" );
Assert.AreEqual( fields[ 2 ], "_unittests.org.ncore.Diagnostics.LogWriterTests->Write_UsingDerivedLogWriter()" );
Assert.AreEqual( fields[ 3 ], "Information" );
Assert.AreEqual( fields[ 4 ], "0" );
if( Directory.Exists( log.FilePath ) )
{
Directory.Delete( log.FilePath, true );
}
}
[TestMethod]
public void Write_ToConsole()
{
_log.LogTarget = LogWriter.LogTargetEnum.Console;
MemoryStream stream = new MemoryStream();
StreamWriter streamWriter = new StreamWriter( stream )
{
AutoFlush = true,
};
Console.SetOut( streamWriter );
using( _log )
{
_log.Write( "First entry" );
_log.Write( "Second entry" );
_log.Write( "Third (and last) entry" );
}
string line = LogWriterTests._readLineFromStream( stream, 1 );
// TODO: Implement regex for DateTime at the end of the line. JF
Assert.IsTrue( line.StartsWith( "First entry [ADDITIONAL DATA: ] [SOURCE: _unittests.org.ncore.Diagnostics.LogWriterTests->Write_ToConsole()] [ENTRY TYPE: Information] [EVENT NUMBER: 0] [DATETIME: " ) );
line = LogWriterTests._readLineFromStream( stream, 2 );
Assert.IsTrue( line.StartsWith( "Second entry [ADDITIONAL DATA: ] [SOURCE: _unittests.org.ncore.Diagnostics.LogWriterTests->Write_ToConsole()] [ENTRY TYPE: Information] [EVENT NUMBER: 0] [DATETIME: " ) );
line = LogWriterTests._readLineFromStream( stream, 3 );
Assert.IsTrue( line.StartsWith( "Third (and last) entry [ADDITIONAL DATA: ] [SOURCE: _unittests.org.ncore.Diagnostics.LogWriterTests->Write_ToConsole()] [ENTRY TYPE: Information] [EVENT NUMBER: 0] [DATETIME: " ) );
stream.Close();
}
[TestMethod]
public void Write_ToConsoleAndFile()
{
_log.LogTarget = _log.LogTarget | LogWriter.LogTargetEnum.Console;
// OR:
//_log.LogTarget = LogWriter.LogTargetEnum.File | LogWriter.LogTargetEnum.Console;
MemoryStream stream = new MemoryStream();
StreamWriter streamWriter = new StreamWriter( stream )
{
AutoFlush = true,
};
Console.SetOut( streamWriter );
using( _log )
{
_log.Write( "First entry" );
_log.Write( "Second entry" );
_log.Write( "Third (and last) entry" );
}
string line = LogWriterTests._readLineFromStream( stream, 1 );
// TODO: Implement regex for DateTime at the end of the line. JF
Assert.IsTrue( line.StartsWith( "First entry [ADDITIONAL DATA: ] [SOURCE: _unittests.org.ncore.Diagnostics.LogWriterTests->Write_ToConsoleAndFile()] [ENTRY TYPE: Information] [EVENT NUMBER: 0] [DATETIME: " ) );
line = LogWriterTests._readLineFromStream( stream, 2 );
Assert.IsTrue( line.StartsWith( "Second entry [ADDITIONAL DATA: ] [SOURCE: _unittests.org.ncore.Diagnostics.LogWriterTests->Write_ToConsoleAndFile()] [ENTRY TYPE: Information] [EVENT NUMBER: 0] [DATETIME: " ) );
line = LogWriterTests._readLineFromStream( stream, 3 );
Assert.IsTrue( line.StartsWith( "Third (and last) entry [ADDITIONAL DATA: ] [SOURCE: _unittests.org.ncore.Diagnostics.LogWriterTests->Write_ToConsoleAndFile()] [ENTRY TYPE: Information] [EVENT NUMBER: 0] [DATETIME: " ) );
stream.Close();
}
[TestMethod]
// TODO: How do we peek at the EventLog and ensure that we're NOT writing there. That's a bit of a unit testing trick, no? JF
public void Write_LogTargetNull()
{
_log.LogTarget = null;
MemoryStream stream = new MemoryStream();
StreamWriter streamWriter = new StreamWriter( stream )
{
AutoFlush = true,
};
Console.SetOut( streamWriter );
using( _log )
{
_log.Write( "First entry" );
_log.Write( "Second entry" );
_log.Write( "Third (and last) entry" );
}
Assert.AreEqual( 0, stream.Length );
Assert.IsFalse( File.Exists( _log.FileLocation ) );
stream.Close();
}
[TestMethod]
// TODO: How do we peek at the EventLog and ensure that we're NOT writing there. That's a bit of a unit testing trick, no? JF
public void Write_EntryTypesNull()
{
_log.LogTarget = _log.LogTarget | LogWriter.LogTargetEnum.Console;
_log.FileEntryTypes = null;
_log.ConsoleEntryTypes = null;
_log.EventLogEntryTypes = null;
MemoryStream stream = new MemoryStream();
StreamWriter streamWriter = new StreamWriter( stream )
{
AutoFlush = true,
};
Console.SetOut( streamWriter );
using( _log )
{
_log.Write( "Error", LogWriter.EntryTypeEnum.Error );
_log.Write( "FailureAudit", LogWriter.EntryTypeEnum.FailureAudit );
_log.Write( "Information", LogWriter.EntryTypeEnum.Information );
_log.Write( "SuccessAudit", LogWriter.EntryTypeEnum.SuccessAudit );
_log.Write( "Exception", LogWriter.EntryTypeEnum.Exception );
_log.Write( "Warning", LogWriter.EntryTypeEnum.Warning );
}
Assert.AreEqual( 0, stream.Length );
Assert.IsFalse( File.Exists( _log.FileLocation ) );
stream.Close();
}
// NOTE: See TODO above regarding multi-threaded unit tests for an explanation of why this is commented out.
/*
[TestMethod]
public void Write_MultiThreaded()
{
LogCaller logCaller = new LogCaller();
LogCallerDelegate altLogCaller = new LogCallerDelegate( logCaller.DoLogging );
IAsyncResult asyncResult = altLogCaller.BeginInvoke( __log, null, null );
for( int i = 0; i < 1000; i++ )
{
DateTime dt = DateTime.Now;
string ticks = dt.Ticks.ToString();
__log.Write( "Primary - logging #" + i.ToString() + " " + ticks );
}
asyncResult.AsyncWaitHandle.WaitOne( 10000, false );
if( asyncResult.IsCompleted )
{
altLogCaller.EndInvoke( asyncResult );
}
}
*/
}
// NOTE: Example of a simple derived "self-configuring" LogWriter. JF
public class DerivedLogWriter : LogWriter
{
protected override string defineFileExtension()
{
return "txt";
}
protected override string defineFileNameDateFormat()
{
return "MM-dd-yyyy";
}
protected override string defineFileNameSuffix()
{
return "_log";
}
protected override string defineFileNamePrefix()
{
return "unit-test_";
}
protected override string defineFilePath()
{
return System.Environment.CurrentDirectory + @"\derivedlog\";
}
}
// TODO: Hmm. Need to work this out. JF
// NOTE: See TODO above regarding multi-threaded unit tests and Write_MultiThreaded() for an explanation of why this is commented out.
/*
public delegate void LogCallerDelegate( LogWriter log );
public class LogCaller
{
public void DoLogging( LogWriter log )
{
for( int i = 0; i < 1000; i++ )
{
DateTime dt = DateTime.Now;
string ticks = dt.Ticks.ToString();
log.Write( "LogCaller - logging #" + i.ToString() + " " + ticks );
}
}
}
*/
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
namespace Omnius.Collections
{
public class SimpleLinkedList<T> : ICollection<T>, IEnumerable<T>, ICollection, IEnumerable
{
private Node _firstNode;
private int _count;
private int? _capacity;
private IEqualityComparer<T> _equalityComparer = EqualityComparer<T>.Default;
public SimpleLinkedList()
{
}
public SimpleLinkedList(int capacity)
{
_capacity = capacity;
}
public SimpleLinkedList(IEnumerable<T> collection)
{
foreach (var item in collection)
{
this.Add(item);
}
}
public int Capacity
{
get
{
return _capacity ?? -1;
}
set
{
_capacity = value;
}
}
protected virtual bool Filter(T item)
{
return false;
}
public void Add(T item)
{
if (_capacity != null && _count + 1 > _capacity.Value) throw new OverflowException();
if (this.Filter(item)) return;
var currentItem = new Node();
currentItem.Value = item;
currentItem.Next = _firstNode;
_firstNode = currentItem;
_count++;
}
public void Clear()
{
_firstNode = null;
_count = 0;
}
public bool Contains(T item)
{
for (var currentNode = _firstNode; currentNode != null; currentNode = currentNode.Next)
{
if (_equalityComparer.Equals(currentNode.Value, item)) return true;
}
return false;
}
public void CopyTo(T[] array, int arrayIndex)
{
for (var currentNode = _firstNode; currentNode != null; currentNode = currentNode.Next)
{
array[arrayIndex++] = currentNode.Value;
}
}
public int Count
{
get
{
return _count;
}
}
public bool Remove(T item)
{
var currentItem = _firstNode;
Node previousItem = null;
while (currentItem != null)
{
if (_equalityComparer.Equals(currentItem.Value, item))
{
if (previousItem == null)
{
_firstNode = _firstNode.Next;
_count--;
}
else
{
previousItem.Next = currentItem.Next;
_count--;
}
return true;
}
else
{
previousItem = currentItem;
currentItem = currentItem.Next;
}
}
return false;
}
public int RemoveAll(Predicate<T> match)
{
if (match == null) throw new ArgumentNullException(nameof(match));
int hitCount = 0;
var currentItem = _firstNode;
Node previousItem = null;
while (currentItem != null)
{
if (match(currentItem.Value))
{
if (previousItem == null)
{
_firstNode = _firstNode.Next;
_count--;
}
else
{
previousItem.Next = currentItem.Next;
_count--;
}
hitCount++;
}
else
{
previousItem = currentItem;
currentItem = currentItem.Next;
}
}
return hitCount;
}
bool ICollection<T>.IsReadOnly
{
get
{
return false;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
object ICollection.SyncRoot
{
get
{
return null;
}
}
void ICollection.CopyTo(Array array, int index)
{
for (var currentNode = _firstNode; currentNode != null; currentNode = currentNode.Next)
{
array.SetValue(currentNode.Value, index++);
}
}
public IEnumerator<T> GetEnumerator()
{
for (var currentNode = _firstNode; currentNode != null; currentNode = currentNode.Next)
{
yield return currentNode.Value;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
private sealed class Node
{
public T Value { get; set; }
public Node Next { get; set; }
}
}
}
| |
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 WebApi.Areas.HelpPage.ModelDescriptions;
using WebApi.Areas.HelpPage.Models;
namespace WebApi.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);
}
}
}
}
| |
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using YamlDotNet.Helpers;
using YamlDotNet.Serialization.Utilities;
namespace YamlDotNet.Serialization.ObjectGraphTraversalStrategies
{
/// <summary>
/// An implementation of <see cref="IObjectGraphTraversalStrategy"/> that traverses
/// readable properties, collections and dictionaries.
/// </summary>
public class FullObjectGraphTraversalStrategy : IObjectGraphTraversalStrategy
{
protected readonly Serializer serializer;
private readonly int maxRecursion;
private readonly ITypeInspector typeDescriptor;
private readonly ITypeResolver typeResolver;
private INamingConvention namingConvention;
public FullObjectGraphTraversalStrategy(Serializer serializer, ITypeInspector typeDescriptor, ITypeResolver typeResolver, int maxRecursion, INamingConvention namingConvention)
{
if (maxRecursion <= 0)
{
throw new ArgumentOutOfRangeException("maxRecursion", maxRecursion, "maxRecursion must be greater than 1");
}
this.serializer = serializer;
if (typeDescriptor == null)
{
throw new ArgumentNullException("typeDescriptor");
}
this.typeDescriptor = typeDescriptor;
if (typeResolver == null)
{
throw new ArgumentNullException("typeResolver");
}
this.typeResolver = typeResolver;
this.maxRecursion = maxRecursion;
this.namingConvention = namingConvention;
}
void IObjectGraphTraversalStrategy.Traverse(IObjectDescriptor graph, IObjectGraphVisitor visitor)
{
Traverse(graph, visitor, 0);
}
protected virtual void Traverse(IObjectDescriptor value, IObjectGraphVisitor visitor, int currentDepth)
{
if (++currentDepth > maxRecursion)
{
throw new InvalidOperationException("Too much recursion when traversing the object graph");
}
if (!visitor.Enter(value))
{
return;
}
var typeCode = value.Type.GetTypeCode();
switch (typeCode)
{
case TypeCode.Boolean:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.SByte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
case TypeCode.String:
case TypeCode.Char:
case TypeCode.DateTime:
visitor.VisitScalar(value);
break;
case TypeCode.DBNull:
visitor.VisitScalar(new ObjectDescriptor(null, typeof(object), typeof(object)));
break;
case TypeCode.Empty:
throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "TypeCode.{0} is not supported.", typeCode));
default:
if (value.Value == null || value.Type == typeof(TimeSpan))
{
visitor.VisitScalar(value);
break;
}
var underlyingType = Nullable.GetUnderlyingType(value.Type);
if (underlyingType != null)
{
// This is a nullable type, recursively handle it with its underlying type.
// Note that if it contains null, the condition above already took care of it
Traverse(new ObjectDescriptor(value.Value, underlyingType, value.Type, value.ScalarStyle), visitor, currentDepth);
}
else
{
TraverseObject(value, visitor, currentDepth);
}
break;
}
}
protected virtual void TraverseObject(IObjectDescriptor value, IObjectGraphVisitor visitor, int currentDepth)
{
if (typeof(IDictionary).IsAssignableFrom(value.Type))
{
TraverseDictionary(value, visitor, currentDepth, typeof(object), typeof(object));
return;
}
var genericDictionaryType = ReflectionUtility.GetImplementedGenericInterface(value.Type, typeof(IDictionary<,>));
if (genericDictionaryType != null)
{
var adaptedDictionary = new GenericDictionaryToNonGenericAdapter(value.Value, genericDictionaryType);
var genericArguments = genericDictionaryType.GetGenericArguments();
TraverseDictionary(new ObjectDescriptor(adaptedDictionary, value.Type, value.StaticType, value.ScalarStyle), visitor, currentDepth, genericArguments[0], genericArguments[1]);
return;
}
if (typeof(IEnumerable).IsAssignableFrom(value.Type))
{
TraverseList(value, visitor, currentDepth);
return;
}
TraverseProperties(value, visitor, currentDepth);
}
protected virtual void TraverseDictionary(IObjectDescriptor dictionary, IObjectGraphVisitor visitor, int currentDepth, Type keyType, Type valueType)
{
visitor.VisitMappingStart(dictionary, keyType, valueType);
var isDynamic = dictionary.Type.FullName.Equals("System.Dynamic.ExpandoObject");
foreach (DictionaryEntry entry in (IDictionary)dictionary.Value)
{
var keyString = isDynamic ? namingConvention.Apply(entry.Key.ToString()) : entry.Key.ToString();
var key = GetObjectDescriptor(keyString, keyType);
var value = GetObjectDescriptor(entry.Value, valueType);
if (visitor.EnterMapping(key, value))
{
Traverse(key, visitor, currentDepth);
Traverse(value, visitor, currentDepth);
}
}
visitor.VisitMappingEnd(dictionary);
}
private void TraverseList(IObjectDescriptor value, IObjectGraphVisitor visitor, int currentDepth)
{
var enumerableType = ReflectionUtility.GetImplementedGenericInterface(value.Type, typeof(IEnumerable<>));
var itemType = enumerableType != null ? enumerableType.GetGenericArguments()[0] : typeof(object);
visitor.VisitSequenceStart(value, itemType);
foreach (var item in (IEnumerable)value.Value)
{
Traverse(GetObjectDescriptor(item, itemType), visitor, currentDepth);
}
visitor.VisitSequenceEnd(value);
}
protected virtual void TraverseProperties(IObjectDescriptor value, IObjectGraphVisitor visitor, int currentDepth)
{
visitor.VisitMappingStart(value, typeof(string), typeof(object));
foreach (var propertyDescriptor in typeDescriptor.GetProperties(value.Type, value.Value))
{
var propertyValue = propertyDescriptor.Read(value.Value);
if (visitor.EnterMapping(propertyDescriptor, propertyValue))
{
Traverse(new ObjectDescriptor(propertyDescriptor.Name, typeof(string), typeof(string)), visitor, currentDepth);
Traverse(propertyValue, visitor, currentDepth);
}
}
visitor.VisitMappingEnd(value);
}
private IObjectDescriptor GetObjectDescriptor(object value, Type staticType)
{
return new ObjectDescriptor(value, typeResolver.Resolve(staticType, value), staticType);
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using TestCases.SS.UserModel;
using NUnit.Framework;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using System;
using System.Collections.Generic;
using TestCases.HSSF;
using NPOI.XSSF;
using NPOI.XSSF.UserModel;
namespace TestCases.XSSF.UserModel
{
[TestFixture]
public class TestXSSFFormulaEvaluation : BaseTestFormulaEvaluator
{
public TestXSSFFormulaEvaluation()
: base(XSSFITestDataProvider.instance)
{
}
[Test]
public void TestSharedFormulas()
{
BaseTestSharedFormulas("shared_formulas.xlsx");
}
[Test]
public void TestSharedFormulas_EvaluateInCell()
{
XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.OpenSampleWorkbook("49872.xlsx");
IFormulaEvaluator Evaluator = wb.GetCreationHelper().CreateFormulaEvaluator();
ISheet sheet = wb.GetSheetAt(0);
double result = 3.0;
// B3 is a master shared formula, C3 and D3 don't have the formula written in their f element.
// Instead, the attribute si for a particular cell is used to figure what the formula expression
// should be based on the cell's relative location to the master formula, e.g.
// B3: <f t="shared" ref="B3:D3" si="0">B1+B2</f>
// C3 and D3: <f t="shared" si="0"/>
// Get B3 and Evaluate it in the cell
ICell b3 = sheet.GetRow(2).GetCell(1);
Assert.AreEqual(result, Evaluator.EvaluateInCell(b3).NumericCellValue, 0);
//at this point the master formula is gone, but we are still able to Evaluate dependent cells
ICell c3 = sheet.GetRow(2).GetCell(2);
Assert.AreEqual(result, Evaluator.EvaluateInCell(c3).NumericCellValue, 0);
ICell d3 = sheet.GetRow(2).GetCell(3);
Assert.AreEqual(result, Evaluator.EvaluateInCell(d3).NumericCellValue, 0);
wb.Close();
}
/**
* Evaluation of cell references with column indexes greater than 255. See bugzilla 50096
*/
[Test]
public void TestEvaluateColumnGreaterThan255()
{
XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.OpenSampleWorkbook("50096.xlsx");
IFormulaEvaluator Evaluator = wb.GetCreationHelper().CreateFormulaEvaluator();
/**
* The first row simply Contains the numbers 1 - 300.
* The second row simply refers to the cell value above in the first row by a simple formula.
*/
for (int i = 245; i < 265; i++)
{
ICell cell_noformula = wb.GetSheetAt(0).GetRow(0).GetCell(i);
ICell cell_formula = wb.GetSheetAt(0).GetRow(1).GetCell(i);
CellReference ref_noformula = new CellReference(cell_noformula.RowIndex, cell_noformula.ColumnIndex);
CellReference ref_formula = new CellReference(cell_noformula.RowIndex, cell_noformula.ColumnIndex);
String fmla = cell_formula.CellFormula;
// assure that the formula refers to the cell above.
// the check below is 'deep' and involves conversion of the shared formula:
// in the sample file a shared formula in GN1 is spanned in the range GN2:IY2,
Assert.AreEqual(ref_noformula.FormatAsString(), fmla);
CellValue cv_noformula = Evaluator.Evaluate(cell_noformula);
CellValue cv_formula = Evaluator.Evaluate(cell_formula);
Assert.AreEqual(cv_noformula.NumberValue, cv_formula.NumberValue, 0, "Wrong Evaluation result in " + ref_formula.FormatAsString());
}
wb.Close();
}
/**
* Related to bugs #56737 and #56752 - XSSF workbooks which have
* formulas that refer to cells and named ranges in multiple other
* workbooks, both HSSF and XSSF ones
*/
[Test]
public void TestReferencesToOtherWorkbooks()
{
XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.OpenSampleWorkbook("ref2-56737.xlsx");
XSSFFormulaEvaluator evaluator = wb.GetCreationHelper().CreateFormulaEvaluator() as XSSFFormulaEvaluator;
XSSFSheet s = wb.GetSheetAt(0) as XSSFSheet;
// References to a .xlsx file
IRow rXSLX = s.GetRow(2);
ICell cXSLX_cell = rXSLX.GetCell(4);
ICell cXSLX_sNR = rXSLX.GetCell(6);
ICell cXSLX_gNR = rXSLX.GetCell(8);
Assert.AreEqual("[1]Uses!$A$1", cXSLX_cell.CellFormula);
Assert.AreEqual("[1]Defines!NR_To_A1", cXSLX_sNR.CellFormula);
Assert.AreEqual("[1]!NR_Global_B2", cXSLX_gNR.CellFormula);
Assert.AreEqual("Hello!", cXSLX_cell.StringCellValue);
Assert.AreEqual("Test A1", cXSLX_sNR.StringCellValue);
Assert.AreEqual(142.0, cXSLX_gNR.NumericCellValue, 0);
// References to a .xls file
IRow rXSL = s.GetRow(4);
ICell cXSL_cell = rXSL.GetCell(4);
ICell cXSL_sNR = rXSL.GetCell(6);
ICell cXSL_gNR = rXSL.GetCell(8);
Assert.AreEqual("[2]Uses!$C$1", cXSL_cell.CellFormula);
Assert.AreEqual("[2]Defines!NR_To_A1", cXSL_sNR.CellFormula);
Assert.AreEqual("[2]!NR_Global_B2", cXSL_gNR.CellFormula);
Assert.AreEqual("Hello!", cXSL_cell.StringCellValue);
Assert.AreEqual("Test A1", cXSL_sNR.StringCellValue);
Assert.AreEqual(142.0, cXSL_gNR.NumericCellValue, 0);
// Try to Evaluate without references, won't work
// (At least, not unit we fix bug #56752 that is1)
try
{
evaluator.Evaluate(cXSL_cell);
Assert.Fail("Without a fix for #56752, shouldn't be able to Evaluate a " +
"reference to a non-provided linked workbook");
}
catch (Exception)
{
}
// Setup the environment
Dictionary<String, IFormulaEvaluator> evaluators = new Dictionary<String, IFormulaEvaluator>();
evaluators.Add("ref2-56737.xlsx", evaluator);
evaluators.Add("56737.xlsx",
_testDataProvider.OpenSampleWorkbook("56737.xlsx").GetCreationHelper().CreateFormulaEvaluator());
evaluators.Add("56737.xls",
HSSFTestDataSamples.OpenSampleWorkbook("56737.xls").GetCreationHelper().CreateFormulaEvaluator());
evaluator.SetupReferencedWorkbooks(evaluators);
// Try Evaluating all of them, ensure we don't blow up
foreach (IRow r in s)
{
foreach (ICell c in r)
{
// TODO Fix and enable
evaluator.Evaluate(c);
}
}
// And evaluate the other way too
evaluator.EvaluateAll();
// Static evaluator won't work, as no references passed in
try
{
XSSFFormulaEvaluator.EvaluateAllFormulaCells(wb);
Assert.Fail("Static method lacks references, shouldn't work");
}
catch (Exception)
{
// expected here
}
// Evaluate specific cells and check results
Assert.AreEqual("\"Hello!\"", evaluator.Evaluate(cXSLX_cell).FormatAsString());
Assert.AreEqual("\"Test A1\"", evaluator.Evaluate(cXSLX_sNR).FormatAsString());
//Assert.AreEqual("142.0", evaluator.Evaluate(cXSLX_gNR).FormatAsString());
Assert.AreEqual("142", evaluator.Evaluate(cXSLX_gNR).FormatAsString());
Assert.AreEqual("\"Hello!\"", evaluator.Evaluate(cXSL_cell).FormatAsString());
Assert.AreEqual("\"Test A1\"", evaluator.Evaluate(cXSL_sNR).FormatAsString());
//Assert.AreEqual("142.0", evaluator.Evaluate(cXSL_gNR).FormatAsString());
Assert.AreEqual("142", evaluator.Evaluate(cXSL_gNR).FormatAsString());
// Add another formula referencing these workbooks
ICell cXSL_cell2 = rXSL.CreateCell(40);
cXSL_cell2.CellFormula = (/*setter*/"[56737.xls]Uses!$C$1");
// TODO Shouldn't it become [2] like the others?
Assert.AreEqual("[56737.xls]Uses!$C$1", cXSL_cell2.CellFormula);
Assert.AreEqual("\"Hello!\"", evaluator.Evaluate(cXSL_cell2).FormatAsString());
// Now add a formula that refers to yet another (different) workbook
// Won't work without the workbook being linked
ICell cXSLX_nw_cell = rXSLX.CreateCell(42);
try
{
cXSLX_nw_cell.CellFormula = (/*setter*/"[alt.xlsx]Sheet1!$A$1");
Assert.Fail("New workbook not linked, shouldn't be able to Add");
}
catch (Exception) { }
// Link and re-try
IWorkbook alt = new XSSFWorkbook();
try
{
alt.CreateSheet().CreateRow(0).CreateCell(0).SetCellValue("In another workbook");
// TODO Implement the rest of this, see bug #57184
/*
wb.linkExternalWorkbook("alt.xlsx", alt);
cXSLX_nw_cell.setCellFormula("[alt.xlsx]Sheet1!$A$1");
// Check it - TODO Is this correct? Or should it become [3]Sheet1!$A$1 ?
Assert.AreEqual("[alt.xlsx]Sheet1!$A$1", cXSLX_nw_cell.getCellFormula());
// Evaluate it, without a link to that workbook
try {
evaluator.evaluate(cXSLX_nw_cell);
fail("No cached value and no link to workbook, shouldn't evaluate");
} catch(Exception e) {}
// Add a link, check it does
evaluators.put("alt.xlsx", alt.getCreationHelper().createFormulaEvaluator());
evaluator.setupReferencedWorkbooks(evaluators);
evaluator.evaluate(cXSLX_nw_cell);
Assert.AreEqual("In another workbook", cXSLX_nw_cell.getStringCellValue());
*/
}
finally
{
alt.Close();
}
wb.Close();
}
/**
* If a formula references cells or named ranges in another workbook,
* but that isn't available at Evaluation time, the cached values
* should be used instead
* TODO Add the support then add a unit test
* See bug #56752
*/
[Test]
public void TestCachedReferencesToOtherWorkbooks()
{
// TODO
}
/**
* A handful of functions (such as SUM, COUNTA, MIN) support
* multi-sheet references (eg Sheet1:Sheet3!A1 = Cell A1 from
* Sheets 1 through Sheet 3).
* This test, based on common test files for HSSF and XSSF, Checks
* that we can correctly Evaluate these
*/
[Test]
public void TestMultiSheetReferencesHSSFandXSSF()
{
IWorkbook wb1 = HSSFTestDataSamples.OpenSampleWorkbook("55906-MultiSheetRefs.xls");
IWorkbook wb2 = XSSFTestDataSamples.OpenSampleWorkbook("55906-MultiSheetRefs.xlsx");
foreach (IWorkbook wb in new IWorkbook[] { wb1, wb2 })
{
IFormulaEvaluator Evaluator = wb.GetCreationHelper().CreateFormulaEvaluator();
ISheet s1 = wb.GetSheetAt(0);
// Simple SUM over numbers
ICell sumF = s1.GetRow(2).GetCell(0);
Assert.IsNotNull(sumF);
Assert.AreEqual("SUM(Sheet1:Sheet3!A1)", sumF.CellFormula);
Assert.AreEqual("66", Evaluator.Evaluate(sumF).FormatAsString(), "Failed for " + wb.GetType());
// Various Stats formulas on numbers
ICell avgF = s1.GetRow(2).GetCell(1);
Assert.IsNotNull(avgF);
Assert.AreEqual("AVERAGE(Sheet1:Sheet3!A1)", avgF.CellFormula);
Assert.AreEqual("22", Evaluator.Evaluate(avgF).FormatAsString());
ICell minF = s1.GetRow(3).GetCell(1);
Assert.IsNotNull(minF);
Assert.AreEqual("MIN(Sheet1:Sheet3!A$1)", minF.CellFormula);
Assert.AreEqual("11", Evaluator.Evaluate(minF).FormatAsString());
ICell maxF = s1.GetRow(4).GetCell(1);
Assert.IsNotNull(maxF);
Assert.AreEqual("MAX(Sheet1:Sheet3!A$1)", maxF.CellFormula);
Assert.AreEqual("33", Evaluator.Evaluate(maxF).FormatAsString());
ICell countF = s1.GetRow(5).GetCell(1);
Assert.IsNotNull(countF);
Assert.AreEqual("COUNT(Sheet1:Sheet3!A$1)", countF.CellFormula);
Assert.AreEqual("3", Evaluator.Evaluate(countF).FormatAsString());
// Various CountAs on Strings
ICell countA_1F = s1.GetRow(2).GetCell(2);
Assert.IsNotNull(countA_1F);
Assert.AreEqual("COUNTA(Sheet1:Sheet3!C1)", countA_1F.CellFormula);
Assert.AreEqual("3", Evaluator.Evaluate(countA_1F).FormatAsString());
ICell countA_2F = s1.GetRow(2).GetCell(3);
Assert.IsNotNull(countA_2F);
Assert.AreEqual("COUNTA(Sheet1:Sheet3!D1)", countA_2F.CellFormula);
Assert.AreEqual("0", Evaluator.Evaluate(countA_2F).FormatAsString());
ICell countA_3F = s1.GetRow(2).GetCell(4);
Assert.IsNotNull(countA_3F);
Assert.AreEqual("COUNTA(Sheet1:Sheet3!E1)", countA_3F.CellFormula);
Assert.AreEqual("3", Evaluator.Evaluate(countA_3F).FormatAsString());
}
wb2.Close();
wb1.Close();
}
/**
* A handful of functions (such as SUM, COUNTA, MIN) support
* multi-sheet areas (eg Sheet1:Sheet3!A1:B2 = Cell A1 to Cell B2,
* from Sheets 1 through Sheet 3).
* This test, based on common test files for HSSF and XSSF, checks
* that we can correctly evaluate these
*/
[Test]
public void TestMultiSheetAreasHSSFandXSSF()
{
IWorkbook wb1 = HSSFTestDataSamples.OpenSampleWorkbook("55906-MultiSheetRefs.xls");
IWorkbook wb2 = XSSFTestDataSamples.OpenSampleWorkbook("55906-MultiSheetRefs.xlsx");
foreach (IWorkbook wb in new IWorkbook[] { wb1, wb2 })
{
IFormulaEvaluator Evaluator = wb.GetCreationHelper().CreateFormulaEvaluator();
ISheet s1 = wb.GetSheetAt(0);
// SUM over a range
ICell sumFA = s1.GetRow(2).GetCell(7);
Assert.IsNotNull(sumFA);
Assert.AreEqual("SUM(Sheet1:Sheet3!A1:B2)", sumFA.CellFormula);
Assert.AreEqual("110", Evaluator.Evaluate(sumFA).FormatAsString(), "Failed for " + wb.GetType());
// Various Stats formulas on ranges of numbers
ICell avgFA = s1.GetRow(2).GetCell(8);
Assert.IsNotNull(avgFA);
Assert.AreEqual("AVERAGE(Sheet1:Sheet3!A1:B2)", avgFA.CellFormula);
Assert.AreEqual("27.5", Evaluator.Evaluate(avgFA).FormatAsString());
ICell minFA = s1.GetRow(3).GetCell(8);
Assert.IsNotNull(minFA);
Assert.AreEqual("MIN(Sheet1:Sheet3!A$1:B$2)", minFA.CellFormula);
Assert.AreEqual("11", Evaluator.Evaluate(minFA).FormatAsString());
ICell maxFA = s1.GetRow(4).GetCell(8);
Assert.IsNotNull(maxFA);
Assert.AreEqual("MAX(Sheet1:Sheet3!A$1:B$2)", maxFA.CellFormula);
Assert.AreEqual("44", Evaluator.Evaluate(maxFA).FormatAsString());
ICell countFA = s1.GetRow(5).GetCell(8);
Assert.IsNotNull(countFA);
Assert.AreEqual("COUNT(Sheet1:Sheet3!$A$1:$B$2)", countFA.CellFormula);
Assert.AreEqual("4", Evaluator.Evaluate(countFA).FormatAsString());
}
wb2.Close();
wb1.Close();
}
[Test]
public void TestMultisheetFormulaEval()
{
XSSFWorkbook wb = new XSSFWorkbook();
try
{
XSSFSheet sheet1 = wb.CreateSheet("Sheet1") as XSSFSheet;
XSSFSheet sheet2 = wb.CreateSheet("Sheet2") as XSSFSheet;
XSSFSheet sheet3 = wb.CreateSheet("Sheet3") as XSSFSheet;
// sheet1 A1
XSSFCell cell = sheet1.CreateRow(0).CreateCell(0) as XSSFCell;
cell.SetCellType(CellType.Numeric);
cell.SetCellValue(1.0);
// sheet2 A1
cell = sheet2.CreateRow(0).CreateCell(0) as XSSFCell;
cell.SetCellType(CellType.Numeric);
cell.SetCellValue(1.0);
// sheet2 B1
cell = sheet2.GetRow(0).CreateCell(1) as XSSFCell;
cell.SetCellType(CellType.Numeric);
cell.SetCellValue(1.0);
// sheet3 A1
cell = sheet3.CreateRow(0).CreateCell(0) as XSSFCell;
cell.SetCellType(CellType.Numeric);
cell.SetCellValue(1.0);
// sheet1 A2 formulae
cell = sheet1.CreateRow(1).CreateCell(0) as XSSFCell;
cell.SetCellType(CellType.Formula);
cell.CellFormula = (/*setter*/"SUM(Sheet1:Sheet3!A1)");
// sheet1 A3 formulae
cell = sheet1.CreateRow(2).CreateCell(0) as XSSFCell;
cell.SetCellType(CellType.Formula);
cell.CellFormula = (/*setter*/"SUM(Sheet1:Sheet3!A1:B1)");
wb.GetCreationHelper().CreateFormulaEvaluator().EvaluateAll();
cell = sheet1.GetRow(1).GetCell(0) as XSSFCell;
Assert.AreEqual(3.0, cell.NumericCellValue, 0);
cell = sheet1.GetRow(2).GetCell(0) as XSSFCell;
Assert.AreEqual(4.0, cell.NumericCellValue, 0);
}
finally
{
wb.Close();
}
}
[Test]
public void TestBug55843()
{
XSSFWorkbook wb = new XSSFWorkbook();
try
{
XSSFSheet sheet = wb.CreateSheet("test") as XSSFSheet;
XSSFRow row = sheet.CreateRow(0) as XSSFRow;
XSSFRow row2 = sheet.CreateRow(1) as XSSFRow;
XSSFCell cellA2 = row2.CreateCell(0, CellType.Formula) as XSSFCell;
XSSFCell cellB1 = row.CreateCell(1, CellType.Numeric) as XSSFCell;
cellB1.SetCellValue(10);
XSSFFormulaEvaluator formulaEvaluator = wb.GetCreationHelper().CreateFormulaEvaluator() as XSSFFormulaEvaluator;
cellA2.SetCellFormula("IF(B1=0,\"\",((ROW()-ROW(A$1))*12))");
CellValue Evaluate = formulaEvaluator.Evaluate(cellA2);
System.Console.WriteLine(Evaluate);
Assert.AreEqual("12", Evaluate.FormatAsString());
cellA2.CellFormula = (/*setter*/"IF(NOT(B1=0),((ROW()-ROW(A$1))*12),\"\")");
CellValue EvaluateN = formulaEvaluator.Evaluate(cellA2);
System.Console.WriteLine(EvaluateN);
Assert.AreEqual(Evaluate.ToString(), EvaluateN.ToString());
Assert.AreEqual("12", EvaluateN.FormatAsString());
}
finally
{
wb.Close();
}
}
[Test]
public void TestBug55843a()
{
XSSFWorkbook wb = new XSSFWorkbook();
try
{
XSSFSheet sheet = wb.CreateSheet("test") as XSSFSheet;
XSSFRow row = sheet.CreateRow(0) as XSSFRow;
XSSFRow row2 = sheet.CreateRow(1) as XSSFRow;
XSSFCell cellA2 = row2.CreateCell(0, CellType.Formula) as XSSFCell;
XSSFCell cellB1 = row.CreateCell(1, CellType.Numeric) as XSSFCell;
cellB1.SetCellValue(10);
XSSFFormulaEvaluator formulaEvaluator = wb.GetCreationHelper().CreateFormulaEvaluator() as XSSFFormulaEvaluator;
cellA2.SetCellFormula("IF(B1=0,\"\",((ROW(A$1))))");
CellValue Evaluate = formulaEvaluator.Evaluate(cellA2);
System.Console.WriteLine(Evaluate);
Assert.AreEqual("1", Evaluate.FormatAsString());
cellA2.CellFormula = (/*setter*/"IF(NOT(B1=0),((ROW(A$1))),\"\")");
CellValue EvaluateN = formulaEvaluator.Evaluate(cellA2);
System.Console.WriteLine(EvaluateN);
Assert.AreEqual(Evaluate.ToString(), EvaluateN.ToString());
Assert.AreEqual("1", EvaluateN.FormatAsString());
}
finally
{
wb.Close();
}
}
[Test]
public void TestBug55843b()
{
XSSFWorkbook wb = new XSSFWorkbook();
try
{
XSSFSheet sheet = wb.CreateSheet("test") as XSSFSheet;
XSSFRow row = sheet.CreateRow(0) as XSSFRow;
XSSFRow row2 = sheet.CreateRow(1) as XSSFRow;
XSSFCell cellA2 = row2.CreateCell(0, CellType.Formula) as XSSFCell;
XSSFCell cellB1 = row.CreateCell(1, CellType.Numeric) as XSSFCell;
cellB1.SetCellValue(10);
XSSFFormulaEvaluator formulaEvaluator = wb.GetCreationHelper().CreateFormulaEvaluator() as XSSFFormulaEvaluator;
cellA2.SetCellFormula("IF(B1=0,\"\",((ROW())))");
CellValue Evaluate = formulaEvaluator.Evaluate(cellA2);
System.Console.WriteLine(Evaluate);
Assert.AreEqual("2", Evaluate.FormatAsString());
cellA2.CellFormula = (/*setter*/"IF(NOT(B1=0),((ROW())),\"\")");
CellValue EvaluateN = formulaEvaluator.Evaluate(cellA2);
System.Console.WriteLine(EvaluateN);
Assert.AreEqual(Evaluate.ToString(), EvaluateN.ToString());
Assert.AreEqual("2", EvaluateN.FormatAsString());
}
finally
{
wb.Close();
}
}
[Test]
public void TestBug55843c()
{
XSSFWorkbook wb = new XSSFWorkbook();
try
{
XSSFSheet sheet = wb.CreateSheet("test") as XSSFSheet;
XSSFRow row = sheet.CreateRow(0) as XSSFRow;
XSSFRow row2 = sheet.CreateRow(1) as XSSFRow;
XSSFCell cellA2 = row2.CreateCell(0, CellType.Formula) as XSSFCell;
XSSFCell cellB1 = row.CreateCell(1, CellType.Numeric) as XSSFCell;
cellB1.SetCellValue(10);
XSSFFormulaEvaluator formulaEvaluator = wb.GetCreationHelper().CreateFormulaEvaluator() as XSSFFormulaEvaluator;
cellA2.CellFormula = (/*setter*/"IF(NOT(B1=0),((ROW())))");
CellValue EvaluateN = formulaEvaluator.Evaluate(cellA2);
System.Console.WriteLine(EvaluateN);
Assert.AreEqual("2", EvaluateN.FormatAsString());
}
finally
{
wb.Close();
}
}
[Test]
public void TestBug55843d()
{
XSSFWorkbook wb = new XSSFWorkbook();
try
{
XSSFSheet sheet = wb.CreateSheet("test") as XSSFSheet;
XSSFRow row = sheet.CreateRow(0) as XSSFRow;
XSSFRow row2 = sheet.CreateRow(1) as XSSFRow;
XSSFCell cellA2 = row2.CreateCell(0, CellType.Formula) as XSSFCell;
XSSFCell cellB1 = row.CreateCell(1, CellType.Numeric) as XSSFCell;
cellB1.SetCellValue(10);
XSSFFormulaEvaluator formulaEvaluator = wb.GetCreationHelper().CreateFormulaEvaluator() as XSSFFormulaEvaluator;
cellA2.CellFormula = (/*setter*/"IF(NOT(B1=0),((ROW())),\"\")");
CellValue EvaluateN = formulaEvaluator.Evaluate(cellA2);
System.Console.WriteLine(EvaluateN);
Assert.AreEqual("2", EvaluateN.FormatAsString());
}
finally
{
wb.Close();
}
}
[Test]
public void TestBug55843e()
{
XSSFWorkbook wb = new XSSFWorkbook();
try
{
XSSFSheet sheet = wb.CreateSheet("test") as XSSFSheet;
XSSFRow row = sheet.CreateRow(0) as XSSFRow;
XSSFRow row2 = sheet.CreateRow(1) as XSSFRow;
XSSFCell cellA2 = row2.CreateCell(0, CellType.Formula) as XSSFCell;
XSSFCell cellB1 = row.CreateCell(1, CellType.Numeric) as XSSFCell;
cellB1.SetCellValue(10);
XSSFFormulaEvaluator formulaEvaluator = wb.GetCreationHelper().CreateFormulaEvaluator() as XSSFFormulaEvaluator;
cellA2.SetCellFormula("IF(B1=0,\"\",((ROW())))");
CellValue Evaluate = formulaEvaluator.Evaluate(cellA2);
System.Console.WriteLine(Evaluate);
Assert.AreEqual("2", Evaluate.FormatAsString());
}
finally
{
wb.Close();
}
}
[Test]
public void TestBug55843f()
{
XSSFWorkbook wb = new XSSFWorkbook();
try
{
XSSFSheet sheet = wb.CreateSheet("test") as XSSFSheet;
XSSFRow row = sheet.CreateRow(0) as XSSFRow;
XSSFRow row2 = sheet.CreateRow(1) as XSSFRow;
XSSFCell cellA2 = row2.CreateCell(0, CellType.Formula) as XSSFCell;
XSSFCell cellB1 = row.CreateCell(1, CellType.Numeric) as XSSFCell;
cellB1.SetCellValue(10);
XSSFFormulaEvaluator formulaEvaluator = wb.GetCreationHelper().CreateFormulaEvaluator() as XSSFFormulaEvaluator;
cellA2.SetCellFormula("IF(B1=0,\"\",IF(B1=10,3,4))");
CellValue Evaluate = formulaEvaluator.Evaluate(cellA2);
System.Console.WriteLine(Evaluate);
Assert.AreEqual("3", Evaluate.FormatAsString());
}
finally
{
wb.Close();
}
}
[Test]
public void TestBug56655()
{
IWorkbook wb = new XSSFWorkbook();
ISheet sheet = wb.CreateSheet();
setCellFormula(sheet, 0, 0, "#VALUE!");
setCellFormula(sheet, 0, 1, "SUMIFS(A:A,A:A,#VALUE!)");
wb.GetCreationHelper().CreateFormulaEvaluator().EvaluateAll();
Assert.AreEqual(CellType.Error, getCell(sheet, 0, 0).CachedFormulaResultType);
Assert.AreEqual(FormulaError.VALUE.Code, getCell(sheet, 0, 0).ErrorCellValue);
Assert.AreEqual(CellType.Error, getCell(sheet, 0, 1).CachedFormulaResultType);
Assert.AreEqual(FormulaError.VALUE.Code, getCell(sheet, 0, 1).ErrorCellValue);
wb.Close();
}
[Test]
public void TestBug56655a()
{
IWorkbook wb = new XSSFWorkbook();
ISheet sheet = wb.CreateSheet();
setCellFormula(sheet, 0, 0, "B1*C1");
sheet.GetRow(0).CreateCell(1).SetCellValue("A");
setCellFormula(sheet, 1, 0, "B1*C1");
sheet.GetRow(1).CreateCell(1).SetCellValue("A");
setCellFormula(sheet, 0, 3, "SUMIFS(A:A,A:A,A2)");
wb.GetCreationHelper().CreateFormulaEvaluator().EvaluateAll();
Assert.AreEqual(CellType.Error, getCell(sheet, 0, 0).CachedFormulaResultType);
Assert.AreEqual(FormulaError.VALUE.Code, getCell(sheet, 0, 0).ErrorCellValue);
Assert.AreEqual(CellType.Error, getCell(sheet, 1, 0).CachedFormulaResultType);
Assert.AreEqual(FormulaError.VALUE.Code, getCell(sheet, 1, 0).ErrorCellValue);
Assert.AreEqual(CellType.Error, getCell(sheet, 0, 3).CachedFormulaResultType);
Assert.AreEqual(FormulaError.VALUE.Code, getCell(sheet, 0, 3).ErrorCellValue);
wb.Close();
}
// bug 57721
[Test]
public void structuredReferences()
{
verifyAllFormulasInWorkbookCanBeEvaluated("evaluate_formula_with_structured_table_references.xlsx");
}
// bug 57840
[Ignore("Takes over a minute to evaluate all formulas in this large workbook. Run this test when profiling for formula evaluation speed.")]
[Test]
public void TestLotsOfFormulasWithStructuredReferencesToCalculatedTableColumns()
{
verifyAllFormulasInWorkbookCanBeEvaluated("StructuredRefs-lots-with-lookups.xlsx");
}
// FIXME: use junit4 parameterization
private static void verifyAllFormulasInWorkbookCanBeEvaluated(String sampleWorkbook)
{
XSSFWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook(sampleWorkbook);
XSSFFormulaEvaluator.EvaluateAllFormulaCells(wb);
wb.Close();
}
/**
* @param row 0-based
* @param column 0-based
*/
private void setCellFormula(ISheet sheet, int row, int column, String formula)
{
IRow r = sheet.GetRow(row);
if (r == null)
{
r = sheet.CreateRow(row);
}
ICell cell = r.GetCell(column);
if (cell == null)
{
cell = r.CreateCell(column);
}
cell.SetCellType(CellType.Formula);
cell.CellFormula = (formula);
}
/**
* @param rowNo 0-based
* @param column 0-based
*/
private ICell getCell(ISheet sheet, int rowNo, int column)
{
return sheet.GetRow(rowNo).GetCell(column);
}
[Test]
public void Test59736()
{
IWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("59736.xlsx");
IFormulaEvaluator evaluator = wb.GetCreationHelper().CreateFormulaEvaluator();
ICell cell = wb.GetSheetAt(0).GetRow(0).GetCell(0);
Assert.AreEqual(1, cell.NumericCellValue, 0.001);
cell = wb.GetSheetAt(0).GetRow(1).GetCell(0);
CellValue value = evaluator.Evaluate(cell);
Assert.AreEqual(1, value.NumberValue, 0.001);
cell = wb.GetSheetAt(0).GetRow(2).GetCell(0);
value = evaluator.Evaluate(cell);
Assert.AreEqual(1, value.NumberValue, 0.001);
}
[Test]
public void EvaluateInCellReturnsSameDataType()
{
XSSFWorkbook wb = new XSSFWorkbook();
wb.CreateSheet().CreateRow(0).CreateCell(0);
XSSFFormulaEvaluator evaluator = wb.GetCreationHelper().CreateFormulaEvaluator() as XSSFFormulaEvaluator;
XSSFCell cell = wb.GetSheetAt(0).GetRow(0).GetCell(0) as XSSFCell;
XSSFCell same = evaluator.EvaluateInCell(cell) as XSSFCell;
//assertSame(cell, same);
Assert.AreSame(cell, same);
wb.Close();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests.LegacyTests
{
public class SkipTests
{
public class Skip008
{
private static int Skip001()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
var rst1 = q.Skip(0);
var rst2 = q.Skip(0);
return Verification.Allequal(rst1, rst2);
}
private static int Skip002()
{
var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty }
where !String.IsNullOrEmpty(x)
select x;
var rst1 = q.Skip(0);
var rst2 = q.Skip(0);
return Verification.Allequal(rst1, rst2);
}
public static int Main()
{
int ret = RunTest(Skip001) + RunTest(Skip002);
if (0 != ret)
Console.Write(s_errorMessage);
return ret;
}
private static string s_errorMessage = String.Empty;
private delegate int D();
private static int RunTest(D m)
{
int n = m();
if (0 != n)
s_errorMessage += m.ToString() + " - FAILED!\r\n";
return n;
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Skip1
{
// source is empty and count>0
public static int Test1()
{
int[] source = { };
int[] expected = { };
int count = 3;
var actual = source.Skip(count);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test1();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Skip2
{
// source is >0 and count=0
public static int Test2()
{
int[] source = { 3, 100, 4, 10 };
int[] expected = { 3, 100, 4, 10 };
int count = 0;
var actual = source.Skip(count);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test2();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Skip3
{
// source is >0 and count<0
public static int Test3()
{
int[] source = { 3, 100, 4, 10 };
int[] expected = { 3, 100, 4, 10 };
int count = -10;
var actual = source.Skip(count);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test3();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Skip4
{
// source is >1 and count=1
public static int Test4()
{
int?[] source = { 3, 100, 4, null, 10 };
int?[] expected = { 100, 4, null, 10 };
int count = 1;
var actual = source.Skip(count);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test4();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Skip5
{
// source is >0 and count=Number of elements in source
public static int Test5()
{
int[] source = { 3, 100, 4, 10 };
int[] expected = { };
int count = 4;
var actual = source.Skip(count);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test5();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Skip6
{
// source is >0 and count=Number of elements in source - 1
public static int Test6()
{
int?[] source = { 3, 100, null, 4, 10 };
int?[] expected = { 10 };
int count = 4;
var actual = source.Skip(count);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test6();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Skip7
{
// source is >0 and count=Number of elements in source + 1
public static int Test7()
{
int[] source = { 3, 100, 4, 10 };
int[] expected = { };
int count = 5;
var actual = source.Skip(count);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test7();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Net.Sockets.NetworkStream.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Net.Sockets
{
public partial class NetworkStream : Stream
{
#region Methods and constructors
public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state)
{
return default(IAsyncResult);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state)
{
return default(IAsyncResult);
}
public void Close(int timeout)
{
}
protected override void Dispose(bool disposing)
{
}
public override int EndRead(IAsyncResult asyncResult)
{
return default(int);
}
public override void EndWrite(IAsyncResult asyncResult)
{
}
public override void Flush()
{
}
public NetworkStream(Socket socket)
{
Contract.Ensures(socket.Blocking == true);
Contract.Ensures(socket.Connected == true);
Contract.Ensures(socket.SocketType == ((System.Net.Sockets.SocketType)(1)));
}
public NetworkStream(Socket socket, FileAccess access, bool ownsSocket)
{
Contract.Ensures(socket.Blocking == true);
Contract.Ensures(socket.Connected == true);
Contract.Ensures(socket.SocketType == ((System.Net.Sockets.SocketType)(1)));
}
public NetworkStream(Socket socket, bool ownsSocket)
{
Contract.Ensures(socket.Blocking == true);
Contract.Ensures(socket.Connected == true);
Contract.Ensures(socket.SocketType == ((System.Net.Sockets.SocketType)(1)));
}
public NetworkStream(Socket socket, FileAccess access)
{
Contract.Ensures(socket.Blocking == true);
Contract.Ensures(socket.Connected == true);
Contract.Ensures(socket.SocketType == ((System.Net.Sockets.SocketType)(1)));
}
public override int Read(byte[] buffer, int offset, int size)
{
return default(int);
}
public override long Seek(long offset, SeekOrigin origin)
{
return default(long);
}
public override void SetLength(long value)
{
}
public override void Write(byte[] buffer, int offset, int size)
{
}
#endregion
#region Properties and indexers
public override bool CanRead
{
get
{
return default(bool);
}
}
public override bool CanSeek
{
get
{
return default(bool);
}
}
public override bool CanTimeout
{
get
{
return default(bool);
}
}
public override bool CanWrite
{
get
{
return default(bool);
}
}
public virtual new bool DataAvailable
{
get
{
return default(bool);
}
}
public override long Length
{
get
{
return default(long);
}
}
public override long Position
{
get
{
return default(long);
}
set
{
}
}
protected bool Readable
{
get
{
return default(bool);
}
set
{
}
}
public override int ReadTimeout
{
get
{
return default(int);
}
set
{
}
}
protected Socket Socket
{
get
{
return default(Socket);
}
}
protected bool Writeable
{
get
{
return default(bool);
}
set
{
}
}
public override int WriteTimeout
{
get
{
return default(int);
}
set
{
}
}
#endregion
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using Mono.Collections.Generic;
using Mono.Cecil.Metadata;
using Mono.Cecil.PE;
using RVA = System.UInt32;
namespace Mono.Cecil.Cil {
sealed class CodeWriter : ByteBuffer {
readonly RVA code_base;
internal readonly MetadataBuilder metadata;
readonly Dictionary<uint, MetadataToken> standalone_signatures;
readonly Dictionary<ByteBuffer, RVA> tiny_method_bodies;
MethodBody body;
public CodeWriter (MetadataBuilder metadata)
: base (0)
{
this.code_base = metadata.text_map.GetNextRVA (TextSegment.CLIHeader);
this.metadata = metadata;
this.standalone_signatures = new Dictionary<uint, MetadataToken> ();
this.tiny_method_bodies = new Dictionary<ByteBuffer, RVA> (new ByteBufferEqualityComparer ());
}
public RVA WriteMethodBody (MethodDefinition method)
{
RVA rva;
if (IsUnresolved (method)) {
if (method.rva == 0)
return 0;
rva = WriteUnresolvedMethodBody (method);
} else {
if (IsEmptyMethodBody (method.Body))
return 0;
rva = WriteResolvedMethodBody (method);
}
return rva;
}
static bool IsEmptyMethodBody (MethodBody body)
{
return body.instructions.IsNullOrEmpty ()
&& body.variables.IsNullOrEmpty ();
}
static bool IsUnresolved (MethodDefinition method)
{
return method.HasBody && method.HasImage && method.body == null;
}
RVA WriteUnresolvedMethodBody (MethodDefinition method)
{
var code_reader = metadata.module.reader.code;
int code_size;
MetadataToken local_var_token;
var raw_body = code_reader.PatchRawMethodBody (method, this, out code_size, out local_var_token);
var fat_header = (raw_body.buffer [0] & 0x3) == 0x3;
if (fat_header)
Align (4);
var rva = BeginMethod ();
if (fat_header || !GetOrMapTinyMethodBody (raw_body, ref rva)) {
WriteBytes (raw_body);
}
if (method.debug_info == null)
return rva;
var symbol_writer = metadata.symbol_writer;
if (symbol_writer != null) {
method.debug_info.code_size = code_size;
method.debug_info.local_var_token = local_var_token;
symbol_writer.Write (method.debug_info);
}
return rva;
}
RVA WriteResolvedMethodBody(MethodDefinition method)
{
RVA rva;
body = method.Body;
ComputeHeader ();
if (RequiresFatHeader ()) {
Align (4);
rva = BeginMethod ();
WriteFatHeader ();
WriteInstructions ();
if (body.HasExceptionHandlers)
WriteExceptionHandlers ();
} else {
rva = BeginMethod ();
WriteByte ((byte) (0x2 | (body.CodeSize << 2))); // tiny
WriteInstructions ();
var start_position = (int) (rva - code_base);
var body_size = position - start_position;
var body_bytes = new byte [body_size];
Array.Copy (buffer, start_position, body_bytes, 0, body_size);
if (GetOrMapTinyMethodBody (new ByteBuffer (body_bytes), ref rva))
position = start_position;
}
var symbol_writer = metadata.symbol_writer;
if (symbol_writer != null && method.debug_info != null) {
method.debug_info.code_size = body.CodeSize;
method.debug_info.local_var_token = body.local_var_token;
symbol_writer.Write (method.debug_info);
}
return rva;
}
bool GetOrMapTinyMethodBody (ByteBuffer body, ref RVA rva)
{
RVA existing_rva;
if (tiny_method_bodies.TryGetValue (body, out existing_rva)) {
rva = existing_rva;
return true;
}
tiny_method_bodies.Add (body, rva);
return false;
}
void WriteFatHeader ()
{
var body = this.body;
byte flags = 0x3; // fat
if (body.InitLocals)
flags |= 0x10; // init locals
if (body.HasExceptionHandlers)
flags |= 0x8; // more sections
WriteByte (flags);
WriteByte (0x30);
WriteInt16 ((short) body.max_stack_size);
WriteInt32 (body.code_size);
body.local_var_token = body.HasVariables
? GetStandAloneSignature (body.Variables)
: MetadataToken.Zero;
WriteMetadataToken (body.local_var_token);
}
void WriteInstructions ()
{
var instructions = body.Instructions;
var items = instructions.items;
var size = instructions.size;
for (int i = 0; i < size; i++) {
var instruction = items [i];
WriteOpCode (instruction.opcode);
WriteOperand (instruction);
}
}
void WriteOpCode (OpCode opcode)
{
if (opcode.Size == 1) {
WriteByte (opcode.Op2);
} else {
WriteByte (opcode.Op1);
WriteByte (opcode.Op2);
}
}
void WriteOperand (Instruction instruction)
{
var opcode = instruction.opcode;
var operand_type = opcode.OperandType;
if (operand_type == OperandType.InlineNone)
return;
var operand = instruction.operand;
if (operand == null && !(operand_type == OperandType.InlineBrTarget || operand_type == OperandType.ShortInlineBrTarget)) {
throw new ArgumentException ();
}
switch (operand_type) {
case OperandType.InlineSwitch: {
var targets = (Instruction []) operand;
WriteInt32 (targets.Length);
var diff = instruction.Offset + opcode.Size + (4 * (targets.Length + 1));
for (int i = 0; i < targets.Length; i++)
WriteInt32 (GetTargetOffset (targets [i]) - diff);
break;
}
case OperandType.ShortInlineBrTarget: {
var target = (Instruction) operand;
var offset = target != null ? GetTargetOffset (target) : body.code_size;
WriteSByte ((sbyte) (offset - (instruction.Offset + opcode.Size + 1)));
break;
}
case OperandType.InlineBrTarget: {
var target = (Instruction) operand;
var offset = target != null ? GetTargetOffset (target) : body.code_size;
WriteInt32 (offset - (instruction.Offset + opcode.Size + 4));
break;
}
case OperandType.ShortInlineVar:
WriteByte ((byte) GetVariableIndex ((VariableDefinition) operand));
break;
case OperandType.ShortInlineArg:
WriteByte ((byte) GetParameterIndex ((ParameterDefinition) operand));
break;
case OperandType.InlineVar:
WriteInt16 ((short) GetVariableIndex ((VariableDefinition) operand));
break;
case OperandType.InlineArg:
WriteInt16 ((short) GetParameterIndex ((ParameterDefinition) operand));
break;
case OperandType.InlineSig:
WriteMetadataToken (GetStandAloneSignature ((CallSite) operand));
break;
case OperandType.ShortInlineI:
if (opcode == OpCodes.Ldc_I4_S)
WriteSByte ((sbyte) operand);
else
WriteByte ((byte) operand);
break;
case OperandType.InlineI:
WriteInt32 ((int) operand);
break;
case OperandType.InlineI8:
WriteInt64 ((long) operand);
break;
case OperandType.ShortInlineR:
WriteSingle ((float) operand);
break;
case OperandType.InlineR:
WriteDouble ((double) operand);
break;
case OperandType.InlineString:
WriteMetadataToken (
new MetadataToken (
TokenType.String,
GetUserStringIndex ((string) operand)));
break;
case OperandType.InlineType:
case OperandType.InlineField:
case OperandType.InlineMethod:
case OperandType.InlineTok:
WriteMetadataToken (metadata.LookupToken ((IMetadataTokenProvider) operand));
break;
default:
throw new ArgumentException ();
}
}
int GetTargetOffset (Instruction instruction)
{
if (instruction == null) {
var last = body.instructions [body.instructions.size - 1];
return last.offset + last.GetSize ();
}
return instruction.offset;
}
uint GetUserStringIndex (string @string)
{
if (@string == null)
return 0;
return metadata.user_string_heap.GetStringIndex (@string);
}
static int GetVariableIndex (VariableDefinition variable)
{
return variable.Index;
}
int GetParameterIndex (ParameterDefinition parameter)
{
if (body.method.HasThis) {
if (parameter == body.this_parameter)
return 0;
return parameter.Index + 1;
}
return parameter.Index;
}
bool RequiresFatHeader ()
{
var body = this.body;
return body.CodeSize >= 64
|| body.InitLocals
|| body.HasVariables
|| body.HasExceptionHandlers
|| body.MaxStackSize > 8;
}
void ComputeHeader ()
{
int offset = 0;
var instructions = body.instructions;
var items = instructions.items;
var count = instructions.size;
var stack_size = 0;
var max_stack = 0;
Dictionary<Instruction, int> stack_sizes = null;
if (body.HasExceptionHandlers)
ComputeExceptionHandlerStackSize (ref stack_sizes);
for (int i = 0; i < count; i++) {
var instruction = items [i];
instruction.offset = offset;
offset += instruction.GetSize ();
ComputeStackSize (instruction, ref stack_sizes, ref stack_size, ref max_stack);
}
body.code_size = offset;
body.max_stack_size = max_stack;
}
void ComputeExceptionHandlerStackSize (ref Dictionary<Instruction, int> stack_sizes)
{
var exception_handlers = body.ExceptionHandlers;
for (int i = 0; i < exception_handlers.Count; i++) {
var exception_handler = exception_handlers [i];
switch (exception_handler.HandlerType) {
case ExceptionHandlerType.Catch:
AddExceptionStackSize (exception_handler.HandlerStart, ref stack_sizes);
break;
case ExceptionHandlerType.Filter:
AddExceptionStackSize (exception_handler.FilterStart, ref stack_sizes);
AddExceptionStackSize (exception_handler.HandlerStart, ref stack_sizes);
break;
}
}
}
static void AddExceptionStackSize (Instruction handler_start, ref Dictionary<Instruction, int> stack_sizes)
{
if (handler_start == null)
return;
if (stack_sizes == null)
stack_sizes = new Dictionary<Instruction, int> ();
stack_sizes [handler_start] = 1;
}
static void ComputeStackSize (Instruction instruction, ref Dictionary<Instruction, int> stack_sizes, ref int stack_size, ref int max_stack)
{
int computed_size;
if (stack_sizes != null && stack_sizes.TryGetValue (instruction, out computed_size))
stack_size = computed_size;
max_stack = System.Math.Max (max_stack, stack_size);
ComputeStackDelta (instruction, ref stack_size);
max_stack = System.Math.Max (max_stack, stack_size);
CopyBranchStackSize (instruction, ref stack_sizes, stack_size);
ComputeStackSize (instruction, ref stack_size);
}
static void CopyBranchStackSize (Instruction instruction, ref Dictionary<Instruction, int> stack_sizes, int stack_size)
{
if (stack_size == 0)
return;
switch (instruction.opcode.OperandType) {
case OperandType.ShortInlineBrTarget:
case OperandType.InlineBrTarget:
CopyBranchStackSize (ref stack_sizes, (Instruction) instruction.operand, stack_size);
break;
case OperandType.InlineSwitch:
var targets = (Instruction []) instruction.operand;
for (int i = 0; i < targets.Length; i++)
CopyBranchStackSize (ref stack_sizes, targets [i], stack_size);
break;
}
}
static void CopyBranchStackSize (ref Dictionary<Instruction, int> stack_sizes, Instruction target, int stack_size)
{
if (stack_sizes == null)
stack_sizes = new Dictionary<Instruction, int> ();
int branch_stack_size = stack_size;
int computed_size;
if (stack_sizes.TryGetValue (target, out computed_size))
branch_stack_size = System.Math.Max (branch_stack_size, computed_size);
stack_sizes [target] = branch_stack_size;
}
static void ComputeStackSize (Instruction instruction, ref int stack_size)
{
switch (instruction.opcode.FlowControl) {
case FlowControl.Branch:
case FlowControl.Throw:
case FlowControl.Return:
stack_size = 0;
break;
}
}
static void ComputeStackDelta (Instruction instruction, ref int stack_size)
{
switch (instruction.opcode.FlowControl) {
case FlowControl.Call: {
var method = (IMethodSignature) instruction.operand;
// pop 'this' argument
if (method.HasImplicitThis() && instruction.opcode.Code != Code.Newobj)
stack_size--;
// pop normal arguments
if (method.HasParameters)
stack_size -= method.Parameters.Count;
// pop function pointer
if (instruction.opcode.Code == Code.Calli)
stack_size--;
// push return value
if (method.ReturnType.etype != ElementType.Void || instruction.opcode.Code == Code.Newobj)
stack_size++;
break;
}
default:
ComputePopDelta (instruction.opcode.StackBehaviourPop, ref stack_size);
ComputePushDelta (instruction.opcode.StackBehaviourPush, ref stack_size);
break;
}
}
static void ComputePopDelta (StackBehaviour pop_behavior, ref int stack_size)
{
switch (pop_behavior) {
case StackBehaviour.Popi:
case StackBehaviour.Popref:
case StackBehaviour.Pop1:
stack_size--;
break;
case StackBehaviour.Pop1_pop1:
case StackBehaviour.Popi_pop1:
case StackBehaviour.Popi_popi:
case StackBehaviour.Popi_popi8:
case StackBehaviour.Popi_popr4:
case StackBehaviour.Popi_popr8:
case StackBehaviour.Popref_pop1:
case StackBehaviour.Popref_popi:
stack_size -= 2;
break;
case StackBehaviour.Popi_popi_popi:
case StackBehaviour.Popref_popi_popi:
case StackBehaviour.Popref_popi_popi8:
case StackBehaviour.Popref_popi_popr4:
case StackBehaviour.Popref_popi_popr8:
case StackBehaviour.Popref_popi_popref:
stack_size -= 3;
break;
case StackBehaviour.PopAll:
stack_size = 0;
break;
}
}
static void ComputePushDelta (StackBehaviour push_behaviour, ref int stack_size)
{
switch (push_behaviour) {
case StackBehaviour.Push1:
case StackBehaviour.Pushi:
case StackBehaviour.Pushi8:
case StackBehaviour.Pushr4:
case StackBehaviour.Pushr8:
case StackBehaviour.Pushref:
stack_size++;
break;
case StackBehaviour.Push1_push1:
stack_size += 2;
break;
}
}
void WriteExceptionHandlers ()
{
Align (4);
var handlers = body.ExceptionHandlers;
if (handlers.Count < 0x15 && !RequiresFatSection (handlers))
WriteSmallSection (handlers);
else
WriteFatSection (handlers);
}
static bool RequiresFatSection (Collection<ExceptionHandler> handlers)
{
for (int i = 0; i < handlers.Count; i++) {
var handler = handlers [i];
if (IsFatRange (handler.TryStart, handler.TryEnd))
return true;
if (IsFatRange (handler.HandlerStart, handler.HandlerEnd))
return true;
if (handler.HandlerType == ExceptionHandlerType.Filter
&& IsFatRange (handler.FilterStart, handler.HandlerStart))
return true;
}
return false;
}
static bool IsFatRange (Instruction start, Instruction end)
{
if (start == null)
throw new ArgumentException ();
if (end == null)
return true;
return end.Offset - start.Offset > 255 || start.Offset > 65535;
}
void WriteSmallSection (Collection<ExceptionHandler> handlers)
{
const byte eh_table = 0x1;
WriteByte (eh_table);
WriteByte ((byte) (handlers.Count * 12 + 4));
WriteBytes (2);
WriteExceptionHandlers (
handlers,
i => WriteUInt16 ((ushort) i),
i => WriteByte ((byte) i));
}
void WriteFatSection (Collection<ExceptionHandler> handlers)
{
const byte eh_table = 0x1;
const byte fat_format = 0x40;
WriteByte (eh_table | fat_format);
int size = handlers.Count * 24 + 4;
WriteByte ((byte) (size & 0xff));
WriteByte ((byte) ((size >> 8) & 0xff));
WriteByte ((byte) ((size >> 16) & 0xff));
WriteExceptionHandlers (handlers, WriteInt32, WriteInt32);
}
void WriteExceptionHandlers (Collection<ExceptionHandler> handlers, Action<int> write_entry, Action<int> write_length)
{
for (int i = 0; i < handlers.Count; i++) {
var handler = handlers [i];
write_entry ((int) handler.HandlerType);
write_entry (handler.TryStart.Offset);
write_length (GetTargetOffset (handler.TryEnd) - handler.TryStart.Offset);
write_entry (handler.HandlerStart.Offset);
write_length (GetTargetOffset (handler.HandlerEnd) - handler.HandlerStart.Offset);
WriteExceptionHandlerSpecific (handler);
}
}
void WriteExceptionHandlerSpecific (ExceptionHandler handler)
{
switch (handler.HandlerType) {
case ExceptionHandlerType.Catch:
WriteMetadataToken (metadata.LookupToken (handler.CatchType));
break;
case ExceptionHandlerType.Filter:
WriteInt32 (handler.FilterStart.Offset);
break;
default:
WriteInt32 (0);
break;
}
}
public MetadataToken GetStandAloneSignature (Collection<VariableDefinition> variables)
{
var signature = metadata.GetLocalVariableBlobIndex (variables);
return GetStandAloneSignatureToken (signature);
}
public MetadataToken GetStandAloneSignature (CallSite call_site)
{
var signature = metadata.GetCallSiteBlobIndex (call_site);
var token = GetStandAloneSignatureToken (signature);
call_site.MetadataToken = token;
return token;
}
MetadataToken GetStandAloneSignatureToken (uint signature)
{
MetadataToken token;
if (standalone_signatures.TryGetValue (signature, out token))
return token;
token = new MetadataToken (TokenType.Signature, metadata.AddStandAloneSignature (signature));
standalone_signatures.Add (signature, token);
return token;
}
RVA BeginMethod ()
{
return (RVA)(code_base + position);
}
void WriteMetadataToken (MetadataToken token)
{
WriteUInt32 (token.ToUInt32 ());
}
void Align (int align)
{
align--;
WriteBytes (((position + align) & ~align) - position);
}
}
}
| |
using Acklann.Daterpillar.Serialization;
using ApprovalTests;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
namespace Acklann.Daterpillar.Tests
{
[TestClass]
public class ReflectionTest
{
[TestMethod]
[DynamicData(nameof(GetTypesToConvertToTable), DynamicDataSourceType.Method)]
public void Can_convert_type_to_table(Type type)
{
// Arrange
string name = type.Name;
using var scenario = ApprovalTests.Namers.ApprovalResults.ForScenario(type.Name);
using var stream = new MemoryStream();
var serializer = new XmlSerializer(typeof(Table));
// Act
var result = SchemaFactory.CreateFrom(type);
serializer.Serialize(stream, result);
stream.Seek(0, SeekOrigin.Begin);
using var reader = new StreamReader(stream);
string xml = reader.ReadToEnd();
// Assert
Approvals.VerifyXml(xml);
}
[TestMethod]
[DynamicData(nameof(GetTypesToConvertToTable), DynamicDataSourceType.Method)]
public void Can_enumerate_all_columns(Type type)
{
using var scenario = ApprovalTests.Namers.ApprovalResults.ForScenario(type.Name);
var columns = Acklann.Daterpillar.Serialization.Helper.GetColumns(type).Select(x => x.Name);
var results = string.Join("\r\n", columns);
Approvals.Verify(results);
}
#region Backing Members
private static IEnumerable<object[]> GetTypesToConvertToTable()
{
var cases = from t in typeof(ReflectionTest).GetNestedTypes()
//where t.Name == nameof(MultiKey)
select t;
foreach (var type in cases)
{
yield return new object[] { type };
}
}
#endregion Backing Members
#region Types To Convert
[Acklann.Daterpillar.Modeling.Attributes.Table]
public class Empty
{
}
[System.ComponentModel.DataAnnotations.Schema.Table("offset_table")]
public class OffsetTable
{
public string Id { get; set; }
public DateTimeOffset Date { get; set; }
}
[System.ComponentModel.DataAnnotations.Schema.Table("inffered-columns-table")]
public class InferredTable
{
public string Id { get; set; }
public string Name { get; set; }
public int IntValue { get; set; }
public decimal DecimalValue { get; set; }
public DateTime Date { get; set; }
public bool Boolean { get; set; }
public TimeSpan Time { get; set; }
public float FloatValue { get; set; }
public DayOfWeek EnumValue { get; set; }
public string ReadOnlyProp { get => Id; }
public int PublicField;
private string PrivateField;
}
[System.ComponentModel.DataAnnotations.Schema.Table("dataAnnotation")]
public class DataAnnotatedTable
{
[System.ComponentModel.DataAnnotations.Key]
public string Id { get; set; }
public string Name { get; set; }
[System.ComponentModel.DataAnnotations.MaxLength(123)]
[System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
public string Hash { get; set; }
}
[Modeling.Attributes.Table]
public class MultiKey
{
public string Name { get; set; }
[System.ComponentModel.DataAnnotations.Key]
public string Part1 { get; set; }
[Modeling.Attributes.Key]
public string Part2 { get; set; }
[Modeling.Attributes.Key]
public string Part3 { get; set; }
}
[Modeling.Attributes.Table]
public class MultiKey2
{
[System.ComponentModel.DataAnnotations.Key]
public string Name { get; set; }
[System.ComponentModel.DataAnnotations.Key]
[Modeling.Attributes.Index("name_unique_idx", IndexType.Index, Unique = true)]
public string Part1 { get; set; }
public string Part2 { get; set; }
[Modeling.Attributes.Index("name_unique_idx", IndexType.Index, Unique = true)]
public string Part3 { get; set; }
}
[Modeling.Attributes.Table]
public class UniqueIndex
{
public string Id { get; set; }
public string Name { get; set; }
[Modeling.Attributes.Index(Unique = true)]
public string Part2 { get; set; }
}
public class Parent
{
[Modeling.Attributes.Column("dln")]
public int Id { get; set; }
public string Name { get; set; }
}
public class Child
{
public int Id { get; set; }
public string Name { get; set; }
[Modeling.Attributes.ForeignKey(typeof(Parent))]
public int ParentId { get; set; }
}
[Modeling.Attributes.Table]
public class ComplexType
{
public int Id { get; set; }
public string Name { get; set; }
[Modeling.Attributes.Column(SchemaType.VARCHAR)]
public ReadonlyValue Value { get; }
}
public readonly struct ReadonlyValue
{
public ReadonlyValue(string value)
{
Value = value;
}
[Modeling.Attributes.Column]
public string Value { get; }
}
public class HiddenColumns
{
public int Id { get; set; }
public string Name { get; set; }
[Modeling.Attributes.Column(SchemaType.VARCHAR)]
private string _secret;
}
#endregion Types To Convert
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
namespace System.Runtime.InteropServices.WindowsRuntime
{
/// <summary><p>Provides factory methods to construct WinRT-compatible representations of asynchronous operations.</p>
/// <p>The factory methods take as inputs functions (delegates) that provide managed Task objects;
/// Different factory methods return different sub-interfaces of <code>Windows.Foundation.IAyncInfo</code>.
/// When an asynchronous operation created by this factory is actually started (by calling <code>Start()</code>),
/// the specified <code>Task</code>-provider delegate will be invoked to create the <code>Task</code> that will
/// be wrapped by the to-WinRT adapter.</p> </summary>
[CLSCompliant(false)]
public static class AsyncInfo
{
#region Factory methods for creating "normal" IAsyncInfo instances backed by a Task created by a pastProvider delegate
/// <summary>
/// Creates and starts an <see cref="Windows.Foundation.IAsyncAction"/> instance from a function that generates
/// a <see cref="System.Threading.Tasks.Task"/>.
/// Use this overload if your task supports cancellation in order to hook-up the <code>Cancel</code>
/// mechanism exposed by the created asynchronous action and the cancellation of your task.</summary>
/// <param name="taskProvider">The function to invoke to create the task when the IAsyncInfo is started.
/// The function is passed a <see cref="System.Threading.CancellationToken"/> that the task may monitor
/// to be notified of a cancellation request;
/// you may ignore the <code>CancellationToken</code> if your task does not support cancellation.</param>
/// <returns>An unstarted <see cref="Windows.Foundation.IAsyncAction"/> instance. </returns>
public static IAsyncAction Run(Func<CancellationToken, Task> taskProvider)
{
if (taskProvider == null)
throw new ArgumentNullException("taskProvider");
Contract.EndContractBlock();
return new TaskToAsyncActionAdapter(taskProvider);
}
/// <summary>
/// Creates and starts an <see cref="Windows.Foundation.IAsyncActionWithProgress{TProgress}"/> instance from a function
/// that generates a <see cref="System.Threading.Tasks.Task"/>.
/// Use this overload if your task supports cancellation and progress monitoring is order to:
/// (1) hook-up the <code>Cancel</code> mechanism of the created asynchronous action and the cancellation of your task,
/// and (2) hook-up the <code>Progress</code> update delegate exposed by the created async action and the progress updates
/// published by your task.</summary>
/// <param name="taskProvider">The function to invoke to create the task when the IAsyncInfo is started.
/// The function is passed a <see cref="System.Threading.CancellationToken"/> that the task may monitor
/// to be notified of a cancellation request;
/// you may ignore the <code>CancellationToken</code> if your task does not support cancellation.
/// It is also passed a <see cref="System.IProgress{TProgress}"/> instance to which progress updates may be published;
/// you may ignore the <code>IProgress</code> if your task does not support progress reporting.</param>
/// <returns>An unstarted <see cref="Windows.Foundation.IAsyncActionWithProgress{TProgress}"/> instance.</returns>
public static IAsyncActionWithProgress<TProgress> Run<TProgress>(Func<CancellationToken, IProgress<TProgress>, Task> taskProvider)
{
if (taskProvider == null)
throw new ArgumentNullException("taskProvider");
Contract.EndContractBlock();
return new TaskToAsyncActionWithProgressAdapter<TProgress>(taskProvider);
}
/// <summary>
/// Creates and starts an <see cref="Windows.Foundation.IAsyncOperation{TResult}"/> instance from a function
/// that generates a <see cref="System.Threading.Tasks.Task{TResult}"/>.
/// Use this overload if your task supports cancellation in order to hook-up the <code>Cancel</code>
/// mechanism exposed by the created asynchronous operation and the cancellation of your task.</summary>
/// <param name="taskProvider">The function to invoke to create the task when the IAsyncInfo is started.
/// The function is passed a <see cref="System.Threading.CancellationToken"/> that the task may monitor
/// to be notified of a cancellation request;
/// you may ignore the <code>CancellationToken</code> if your task does not support cancellation.</param>
/// <returns>An unstarted <see cref="Windows.Foundation.IAsyncOperation{TResult}"/> instance.</returns>
public static IAsyncOperation<TResult> Run<TResult>(Func<CancellationToken, Task<TResult>> taskProvider)
{
// This is only internal to reduce the number of public overloads.
// Code execution flows through this method when the method above is called. We can always make this public.
if (taskProvider == null)
throw new ArgumentNullException("taskProvider");
Contract.EndContractBlock();
return new TaskToAsyncOperationAdapter<TResult>(taskProvider);
}
/// <summary>
/// Creates and starts an <see cref="Windows.Foundation.IAsyncOperationWithProgress{TResult,TProgress}"/> instance
/// from a function that generates a <see cref="System.Threading.Tasks.Task{TResult}"/>.<br />
/// Use this overload if your task supports cancellation and progress monitoring is order to:
/// (1) hook-up the <code>Cancel</code> mechanism of the created asynchronous operation and the cancellation of your task,
/// and (2) hook-up the <code>Progress</code> update delegate exposed by the created async operation and the progress
/// updates published by your task.</summary>
/// <typeparam name="TResult">The result type of the task.</typeparam>
/// <typeparam name="TProgress">The type used for progress notifications.</typeparam>
/// <param name="taskProvider">The function to invoke to create the task when the IAsyncOperationWithProgress is started.<br />
/// The function is passed a <see cref="System.Threading.CancellationToken"/> that the task may monitor
/// to be notified of a cancellation request;
/// you may ignore the <code>CancellationToken</code> if your task does not support cancellation.
/// It is also passed a <see cref="System.IProgress{TProgress}"/> instance to which progress updates may be published;
/// you may ignore the <code>IProgress</code> if your task does not support progress reporting.</param>
/// <returns>An unstarted <see cref="Windows.Foundation.IAsyncOperationWithProgress{TResult,TProgress}"/> instance.</returns>
public static IAsyncOperationWithProgress<TResult, TProgress> Run<TResult, TProgress>(
Func<CancellationToken, IProgress<TProgress>, Task<TResult>> taskProvider)
{
if (taskProvider == null)
throw new ArgumentNullException("taskProvider");
Contract.EndContractBlock();
return new TaskToAsyncOperationWithProgressAdapter<TResult, TProgress>(taskProvider);
}
#endregion Factory methods for creating "normal" IAsyncInfo instances backed by a Task created by a pastProvider delegate
#region Factory methods for creating IAsyncInfo instances that have already completed synchronously
internal static IAsyncAction CreateCompletedAction()
{
var asyncInfo = new TaskToAsyncActionAdapter(isCanceled: false);
return asyncInfo;
}
internal static IAsyncActionWithProgress<TProgress> CreateCompletedAction<TProgress>()
{
var asyncInfo = new TaskToAsyncActionWithProgressAdapter<TProgress>(isCanceled: false);
return asyncInfo;
}
internal static IAsyncOperation<TResult> CreateCompletedOperation<TResult>(TResult synchronousResult)
{
var asyncInfo = new TaskToAsyncOperationAdapter<TResult>(synchronousResult);
return asyncInfo;
}
internal static IAsyncOperationWithProgress<TResult, TProgress> CreateCompletedOperation<TResult, TProgress>(TResult synchronousResult)
{
var asyncInfo = new TaskToAsyncOperationWithProgressAdapter<TResult, TProgress>(synchronousResult);
return asyncInfo;
}
#endregion Factory methods for creating IAsyncInfo instances that have already completed synchronously
#region Factory methods for creating IAsyncInfo instances that have already completed synchronously with an error
internal static IAsyncAction CreateFaultedAction(Exception error)
{
if (error == null)
throw new ArgumentNullException("error");
Contract.EndContractBlock();
var asyncInfo = new TaskToAsyncActionAdapter(isCanceled: false);
asyncInfo.DangerousSetError(error);
Debug.Assert(asyncInfo.Status == AsyncStatus.Error);
return asyncInfo;
}
internal static IAsyncActionWithProgress<TProgress> CreateFaultedAction<TProgress>(Exception error)
{
if (error == null)
throw new ArgumentNullException("error");
Contract.EndContractBlock();
var asyncInfo = new TaskToAsyncActionWithProgressAdapter<TProgress>(isCanceled: false);
asyncInfo.DangerousSetError(error);
Debug.Assert(asyncInfo.Status == AsyncStatus.Error);
return asyncInfo;
}
internal static IAsyncOperation<TResult> CreateFaultedOperation<TResult>(Exception error)
{
if (error == null)
throw new ArgumentNullException("error");
Contract.EndContractBlock();
var asyncInfo = new TaskToAsyncOperationAdapter<TResult>(default(TResult));
asyncInfo.DangerousSetError(error);
Debug.Assert(asyncInfo.Status == AsyncStatus.Error);
return asyncInfo;
}
internal static IAsyncOperationWithProgress<TResult, TProgress> CreateFaultedOperation<TResult, TProgress>(Exception error)
{
if (error == null)
throw new ArgumentNullException("error");
Contract.EndContractBlock();
var asyncInfo = new TaskToAsyncOperationWithProgressAdapter<TResult, TProgress>(default(TResult));
asyncInfo.DangerousSetError(error);
Debug.Assert(asyncInfo.Status == AsyncStatus.Error);
return asyncInfo;
}
#endregion Factory methods for creating IAsyncInfo instances that have already completed synchronously with an error
} // class AsyncInfo
} // namespace
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using log4net;
using PacketDotNet.MiscUtil.Conversion;
using PacketDotNet.Utils;
namespace PacketDotNet
{
/// <summary>
/// An ICMP packet
/// See http://en.wikipedia.org/wiki/Internet_Control_Message_Protocol
/// </summary>
[Serializable]
public class ICMPv4Packet : InternetPacket
{
#if DEBUG
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
#else
// NOTE: No need to warn about lack of use, the compiler won't
// put any calls to 'log' here but we need 'log' to exist to compile
#pragma warning disable 0169, 0649
private static readonly ILogInactive log;
#pragma warning restore 0169, 0649
#endif
/// <value>
/// The Type/Code enum value
/// </value>
public virtual ICMPv4TypeCodes TypeCode
{
get
{
var val = EndianBitConverter.Big.ToUInt16(this.header.Bytes, this.header.Offset + ICMPv4Fields.TypeCodePosition);
//TODO: how to handle a mismatch in the mapping? maybe throw here?
if(Enum.IsDefined(typeof(ICMPv4TypeCodes), val)) { return (ICMPv4TypeCodes) val; }
throw new NotImplementedException("TypeCode of " + val + " is not defined in ICMPv4TypeCode");
}
set
{
var theValue = (UInt16) value;
EndianBitConverter.Big.CopyBytes(theValue, this.header.Bytes, this.header.Offset + ICMPv4Fields.TypeCodePosition);
}
}
/// <value>
/// Checksum value
/// </value>
public ushort Checksum
{
get { return EndianBitConverter.Big.ToUInt16(this.header.Bytes, this.header.Offset + ICMPv4Fields.ChecksumPosition); }
set
{
var theValue = value;
EndianBitConverter.Big.CopyBytes(theValue, this.header.Bytes, this.header.Offset + ICMPv4Fields.ChecksumPosition);
}
}
/// <summary>
/// ID field
/// </summary>
public ushort ID
{
get { return EndianBitConverter.Big.ToUInt16(this.header.Bytes, this.header.Offset + ICMPv4Fields.IDPosition); }
set
{
var theValue = value;
EndianBitConverter.Big.CopyBytes(theValue, this.header.Bytes, this.header.Offset + ICMPv4Fields.IDPosition);
}
}
/// <summary>
/// Sequence field
/// </summary>
public ushort Sequence
{
get { return EndianBitConverter.Big.ToUInt16(this.header.Bytes, this.header.Offset + ICMPv4Fields.SequencePosition); }
set { EndianBitConverter.Big.CopyBytes(value, this.header.Bytes, this.header.Offset + ICMPv4Fields.SequencePosition); }
}
/// <summary>
/// Contents of the ICMP packet
/// </summary>
public byte[] Data
{
get { return this.payloadPacketOrData.TheByteArraySegment.ActualBytes(); }
set { this.payloadPacketOrData.TheByteArraySegment = new ByteArraySegment(value, 0, value.Length); }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="bas">
/// A <see cref="ByteArraySegment" />
/// </param>
public ICMPv4Packet(ByteArraySegment bas)
{
log.Debug("");
this.header = new ByteArraySegment(bas);
this.header.Length = ICMPv4Fields.HeaderLength;
// store the payload bytes
this.payloadPacketOrData = new PacketOrByteArraySegment();
this.payloadPacketOrData.TheByteArraySegment = this.header.EncapsulatedBytes();
}
/// <summary>
/// Construct with parent packet
/// </summary>
/// <param name="bas">
/// A <see cref="ByteArraySegment" />
/// </param>
/// <param name="ParentPacket">
/// A <see cref="Packet" />
/// </param>
public ICMPv4Packet(ByteArraySegment bas, Packet ParentPacket) : this(bas) { this.ParentPacket = ParentPacket; }
/// <summary> Fetch ascii escape sequence of the color associated with this packet type.</summary>
public override String Color
{
get { return AnsiEscapeSequences.LightBlue; }
}
/// <summary cref="Packet.ToString(StringOutputType)" />
public override string ToString(StringOutputType outputFormat)
{
var buffer = new StringBuilder();
var color = "";
var colorEscape = "";
if(outputFormat == StringOutputType.Colored || outputFormat == StringOutputType.VerboseColored)
{
color = this.Color;
colorEscape = AnsiEscapeSequences.Reset;
}
if(outputFormat == StringOutputType.Normal || outputFormat == StringOutputType.Colored)
{
// build the output string
buffer.AppendFormat("{0}[ICMPPacket: TypeCode={2}]{1}", color, colorEscape, this.TypeCode);
}
if(outputFormat == StringOutputType.Verbose || outputFormat == StringOutputType.VerboseColored)
{
// collect the properties and their value
var properties = new Dictionary<string, string>();
properties.Add("type/code", this.TypeCode + " (0x" + this.TypeCode.ToString("x") + ")");
// TODO: Implement checksum verification for ICMPv4
properties.Add("checksum", this.Checksum.ToString("x"));
properties.Add("identifier", "0x" + this.ID.ToString("x"));
properties.Add("sequence number", this.Sequence + " (0x" + this.Sequence.ToString("x") + ")");
// calculate the padding needed to right-justify the property names
var padLength = RandomUtils.LongestStringLength(new List<string>(properties.Keys));
// build the output string
buffer.AppendLine("ICMP: ******* ICMPv4 - \"Internet Control Message Protocol (Version 4)\" - offset=? length=" + this.TotalPacketLength);
buffer.AppendLine("ICMP:");
foreach(var property in properties) { buffer.AppendLine("ICMP: " + property.Key.PadLeft(padLength) + " = " + property.Value); }
buffer.AppendLine("ICMP:");
}
// append the base string output
buffer.Append(base.ToString(outputFormat));
return buffer.ToString();
}
/// <summary>
/// Returns the ICMPv4Packet inside of Packet p or null if
/// there is no encapsulated ICMPv4Packet
/// </summary>
/// <param name="p">
/// A <see cref="Packet" />
/// </param>
/// <returns>
/// A <see cref="ICMPv4Packet" />
/// </returns>
[Obsolete("Use Packet.Extract() instead")]
public static ICMPv4Packet GetEncapsulated(Packet p)
{
log.Debug("");
if(p is InternetLinkLayerPacket)
{
var payload = InternetLinkLayerPacket.GetInnerPayload((InternetLinkLayerPacket) p);
if(payload is IpPacket)
{
var payload2 = payload.PayloadPacket;
if(payload2 is ICMPv4Packet) { return (ICMPv4Packet) payload2; }
}
}
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.Security.Permissions;
namespace Aga.Controls.Tree
{
[Serializable]
public sealed class TreeNodeAdv : ISerializable
{
#region NodeCollection
private class NodeCollection : Collection<TreeNodeAdv>
{
private TreeNodeAdv _owner;
public NodeCollection(TreeNodeAdv owner)
{
_owner = owner;
}
protected override void ClearItems()
{
while (this.Count != 0)
this.RemoveAt(this.Count - 1);
}
protected override void InsertItem(int index, TreeNodeAdv item)
{
if (item == null)
throw new ArgumentNullException("item");
if (item.Parent != _owner)
{
if (item.Parent != null)
item.Parent.Nodes.Remove(item);
item._parent = _owner;
item._index = index;
for (int i = index; i < Count; i++)
this[i]._index++;
base.InsertItem(index, item);
}
if (_owner.Tree != null && _owner.Tree.Model == null)
{
_owner.Tree.SmartFullUpdate();
}
}
protected override void RemoveItem(int index)
{
TreeNodeAdv item = this[index];
item._parent = null;
item._index = -1;
for (int i = index + 1; i < Count; i++)
this[i]._index--;
base.RemoveItem(index);
if (_owner.Tree != null && _owner.Tree.Model == null)
{
_owner.Tree.UpdateSelection();
_owner.Tree.SmartFullUpdate();
}
}
protected override void SetItem(int index, TreeNodeAdv item)
{
if (item == null)
throw new ArgumentNullException("item");
RemoveAt(index);
InsertItem(index, item);
}
}
#endregion
#region Events
public event EventHandler<TreeViewAdvEventArgs> Collapsing;
internal void OnCollapsing()
{
if (Collapsing != null)
Collapsing(this, new TreeViewAdvEventArgs(this));
}
public event EventHandler<TreeViewAdvEventArgs> Collapsed;
internal void OnCollapsed()
{
if (Collapsed != null)
Collapsed(this, new TreeViewAdvEventArgs(this));
}
public event EventHandler<TreeViewAdvEventArgs> Expanding;
internal void OnExpanding()
{
if (Expanding != null)
Expanding(this, new TreeViewAdvEventArgs(this));
}
public event EventHandler<TreeViewAdvEventArgs> Expanded;
internal void OnExpanded()
{
if (Expanded != null)
Expanded(this, new TreeViewAdvEventArgs(this));
}
#endregion
#region Properties
private TreeViewAdv _tree;
public TreeViewAdv Tree
{
get { return _tree; }
}
private int _row;
public int Row
{
get { return _row; }
internal set { _row = value; }
}
private int _index = -1;
public int Index
{
get
{
return _index;
}
}
private bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set
{
if (_isSelected != value)
{
if (Tree.IsMyNode(this))
{
//_tree.OnSelectionChanging
if (value)
{
if (!_tree.Selection.Contains(this))
_tree.Selection.Add(this);
if (_tree.Selection.Count == 1)
_tree.CurrentNode = this;
}
else
_tree.Selection.Remove(this);
_tree.UpdateView();
_tree.OnSelectionChanged();
}
_isSelected = value;
}
}
}
internal void SetSelectedInternal(bool value)
{
_isSelected = value;
}
/// <summary>
/// Returns true if all parent nodes of this node are expanded.
/// </summary>
internal bool IsUnwrapped
{
get
{
TreeNodeAdv node = _parent;
while (node != null)
{
if (!node.IsExpanded)
return false;
node = node.Parent;
}
return true;
}
}
private bool _isLeaf;
public bool IsLeaf
{
get { return _isLeaf; }
internal set { _isLeaf = value; }
}
private bool _isExpandedOnce;
public bool IsExpandedOnce
{
get { return _isExpandedOnce; }
internal set { _isExpandedOnce = value; }
}
private bool _isExpanded;
public bool IsExpanded
{
get { return _isExpanded; }
set
{
if (value)
Expand();
else
Collapse();
}
}
private bool _isHidden;
public bool IsHidden
{
get { return this._isHidden || (_tag is Node && (_tag as Node).IsHidden); }
set
{
if (this._isHidden != value)
{
this._isHidden = value;
this._tree.SmartFullUpdate();
}
}
}
internal void AssignIsExpanded(bool value)
{
_isExpanded = value;
}
private TreeNodeAdv _parent;
public TreeNodeAdv Parent
{
get { return _parent; }
}
public int Level
{
get
{
if (_parent == null)
return 0;
else
return _parent.Level + 1;
}
}
public TreeNodeAdv PreviousNode
{
get
{
if (_parent != null)
{
int index = Index;
if (index > 0)
return _parent.Nodes[index - 1];
}
return null;
}
}
public TreeNodeAdv NextNode
{
get
{
if (_parent != null)
{
int index = Index;
if (index < _parent.Nodes.Count - 1)
return _parent.Nodes[index + 1];
}
return null;
}
}
internal TreeNodeAdv BottomNode
{
get
{
TreeNodeAdv parent = this.Parent;
if (parent != null)
{
if (parent.NextNode != null)
return parent.NextNode;
else
return parent.BottomNode;
}
return null;
}
}
internal TreeNodeAdv NextVisibleNode
{
get
{
if (IsExpanded && Nodes.Count > 0)
return Nodes[0];
else
{
TreeNodeAdv nn = NextNode;
if (nn != null)
return nn;
else
return BottomNode;
}
}
}
public bool CanExpand
{
get
{
return (Nodes.Count > 0 || (!IsExpandedOnce && !IsLeaf));
}
}
private object _tag;
public object Tag
{
get { return _tag; }
}
private Collection<TreeNodeAdv> _nodes;
internal Collection<TreeNodeAdv> Nodes
{
get { return _nodes; }
}
private ReadOnlyCollection<TreeNodeAdv> _children;
public ReadOnlyCollection<TreeNodeAdv> Children
{
get
{
return _children;
}
}
private int? _rightBounds;
internal int? RightBounds
{
get { return _rightBounds; }
set { _rightBounds = value; }
}
private int? _height;
internal int? Height
{
get { return _height; }
set { _height = value; }
}
private bool _isExpandingNow;
internal bool IsExpandingNow
{
get { return _isExpandingNow; }
set { _isExpandingNow = value; }
}
private bool _autoExpandOnStructureChanged = false;
public bool AutoExpandOnStructureChanged
{
get { return _autoExpandOnStructureChanged; }
set { _autoExpandOnStructureChanged = value; }
}
#endregion
public TreeNodeAdv(object tag)
: this(null, tag)
{
}
internal TreeNodeAdv(TreeViewAdv tree, object tag)
{
_row = -1;
_tree = tree;
_nodes = new NodeCollection(this);
_children = new ReadOnlyCollection<TreeNodeAdv>(_nodes);
_tag = tag;
}
public override string ToString()
{
if (Tag != null)
return Tag.ToString();
else
return base.ToString();
}
public void Collapse()
{
if (_isExpanded)
Collapse(true);
}
public void CollapseAll()
{
Collapse(false);
}
public void Collapse(bool ignoreChildren)
{
SetIsExpanded(false, ignoreChildren);
}
public void Expand()
{
if (!_isExpanded)
Expand(true);
}
public void ExpandAll()
{
Expand(false);
}
public void Expand(bool ignoreChildren)
{
SetIsExpanded(true, ignoreChildren);
}
private void SetIsExpanded(bool value, bool ignoreChildren)
{
if (Tree == null)
_isExpanded = value;
else
Tree.SetIsExpanded(this, value, ignoreChildren);
}
#region ISerializable Members
private TreeNodeAdv(SerializationInfo info, StreamingContext context)
: this(null, null)
{
int nodesCount = 0;
nodesCount = info.GetInt32("NodesCount");
_isExpanded = info.GetBoolean("IsExpanded");
_tag = info.GetValue("Tag", typeof(object));
for (int i = 0; i < nodesCount; i++)
{
TreeNodeAdv child = (TreeNodeAdv)info.GetValue("Child" + i, typeof(TreeNodeAdv));
Nodes.Add(child);
}
}
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("IsExpanded", IsExpanded);
info.AddValue("NodesCount", Nodes.Count);
if ((Tag != null) && Tag.GetType().IsSerializable)
info.AddValue("Tag", Tag, Tag.GetType());
for (int i = 0; i < Nodes.Count; i++)
info.AddValue("Child" + i, Nodes[i], typeof(TreeNodeAdv));
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Legacy.Support;
using Xunit;
using Microsoft.DotNet.XUnitExtensions;
namespace System.IO.Ports.Tests
{
public class WriteLine_Generic : PortsTest
{
//Set bounds for random timeout values.
//If the min is to low write will not timeout accurately and the testcase will fail
private const int minRandomTimeout = 250;
//If the max is to large then the testcase will take forever to run
private const int maxRandomTimeout = 2000;
//If the percentage difference between the expected timeout and the actual timeout
//found through Stopwatch is greater then 10% then the timeout value was not correctly
//to the write method and the testcase fails.
private const double maxPercentageDifference = .15;
//The string used when we expect the ReadCall to throw an exception for something other
//then the contents of the string itself
private const string DEFAULT_STRING = "DEFAULT_STRING";
//The string size used when veryifying BytesToWrite
private static readonly int s_STRING_SIZE_BYTES_TO_WRITE = TCSupport.MinimumBlockingByteCount;
//The string size used when veryifying Handshake
private static readonly int s_STRING_SIZE_HANDSHAKE = TCSupport.MinimumBlockingByteCount;
private const int NUM_TRYS = 5;
#region Test Cases
[Fact]
public void WriteWithoutOpen()
{
using (SerialPort com = new SerialPort())
{
Debug.WriteLine("Case WriteWithoutOpen : Verifying write method throws System.InvalidOperationException without a call to Open()");
VerifyWriteException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteAfterFailedOpen()
{
using (SerialPort com = new SerialPort("BAD_PORT_NAME"))
{
Debug.WriteLine("Case WriteAfterFailedOpen : Verifying write method throws exception with a failed call to Open()");
//Since the PortName is set to a bad port name Open will thrown an exception
//however we don't care what it is since we are verifying a write method
Assert.ThrowsAny<Exception>(() => com.Open());
VerifyWriteException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteAfterClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Case WriteAfterClose : Verifying write method throws exception after a call to Close()");
com.Open();
com.Close();
VerifyWriteException(com, typeof(InvalidOperationException));
}
}
[KnownFailure]
[ConditionalFact(nameof(HasNullModem))]
public void SimpleTimeout()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] XOffBuffer = new byte[1];
XOffBuffer[0] = 19;
com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Handshake = Handshake.XOnXOff;
Debug.WriteLine("Case SimpleTimeout : Verifying WriteTimeout={0}", com1.WriteTimeout);
com1.Open();
com2.Open();
com2.Write(XOffBuffer, 0, 1);
Thread.Sleep(250);
com2.Close();
VerifyTimeout(com1);
}
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive
[ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))]
public void SuccessiveReadTimeout()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
com.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com.Handshake = Handshake.RequestToSendXOnXOff;
com.Encoding = Encoding.Unicode;
Debug.WriteLine("Case SuccessiveReadTimeout : Verifying WriteTimeout={0} with successive call to write method", com.WriteTimeout);
com.Open();
try
{
com.WriteLine(DEFAULT_STRING);
}
catch (TimeoutException)
{
}
VerifyTimeout(com);
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void SuccessiveReadTimeoutWithWriteSucceeding()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
AsyncEnableRts asyncEnableRts = new AsyncEnableRts();
var t = new Task(asyncEnableRts.EnableRTS);
com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Handshake = Handshake.RequestToSend;
com1.Encoding = new UTF8Encoding();
Debug.WriteLine("Case SuccessiveReadTimeoutWithWriteSucceeding : Verifying WriteTimeout={0} with successive call to write method with the write succeeding sometime before its timeout", com1.WriteTimeout);
com1.Open();
//Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed
//before the timeout is reached
t.Start();
TCSupport.WaitForTaskToStart(t);
try
{
com1.WriteLine(DEFAULT_STRING);
}
catch (TimeoutException)
{
}
asyncEnableRts.Stop();
TCSupport.WaitForTaskCompletion(t);
VerifyTimeout(com1);
}
}
[ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))]
public void BytesToWrite()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, s_STRING_SIZE_BYTES_TO_WRITE);
var t = new Task(asyncWriteRndStr.WriteRndStr);
int numNewLineBytes;
Debug.WriteLine("Case BytesToWrite : Verifying BytesToWrite with one call to Write");
com.Handshake = Handshake.RequestToSend;
com.Open();
com.WriteTimeout = 500;
numNewLineBytes = com.Encoding.GetByteCount(com.NewLine.ToCharArray());
//Write a random string asynchronously so we can verify some things while the write call is blocking
t.Start();
TCSupport.WaitForTaskToStart(t);
TCSupport.WaitForWriteBufferToLoad(com, s_STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes);
TCSupport.WaitForTaskCompletion(t);
}
}
[ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))]
public void BytesToWriteSuccessive()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, s_STRING_SIZE_BYTES_TO_WRITE);
var t1 = new Task(asyncWriteRndStr.WriteRndStr);
var t2 = new Task(asyncWriteRndStr.WriteRndStr);
int numNewLineBytes;
Debug.WriteLine("Case BytesToWriteSuccessive : Verifying BytesToWrite with successive calls to Write");
com.Handshake = Handshake.RequestToSend;
com.Open();
com.WriteTimeout = 1000;
numNewLineBytes = com.Encoding.GetByteCount(com.NewLine.ToCharArray());
//Write a random string asynchronously so we can verify some things while the write call is blocking
t1.Start();
TCSupport.WaitForTaskToStart(t1);
TCSupport.WaitForWriteBufferToLoad(com, s_STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes);
//Write a random string asynchronously so we can verify some things while the write call is blocking
t2.Start();
TCSupport.WaitForTaskToStart(t2);
TCSupport.WaitForWriteBufferToLoad(com, (s_STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes) * 2);
//Wait for both write methods to timeout
TCSupport.WaitForTaskCompletion(t1);
var aggregatedException = Assert.Throws<AggregateException>(() => TCSupport.WaitForTaskCompletion(t2));
Assert.IsType<IOException>(aggregatedException.InnerException);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_None()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, s_STRING_SIZE_HANDSHAKE);
var t = new Task(asyncWriteRndStr.WriteRndStr);
//Write a random string asynchronously so we can verify some things while the write call is blocking
Debug.WriteLine("Case Handshake_None : Verifying Handshake=None");
com.Open();
t.Start();
TCSupport.WaitForTaskCompletion(t);
Assert.Equal(0, com.BytesToWrite);
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void Handshake_RequestToSend()
{
Debug.WriteLine("Case Handshake_RequestToSend : Verifying Handshake=RequestToSend");
Verify_Handshake(Handshake.RequestToSend);
}
[KnownFailure]
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_XOnXOff()
{
Debug.WriteLine("Case Handshake_XOnXOff : Verifying Handshake=XOnXOff");
Verify_Handshake(Handshake.XOnXOff);
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void Handshake_RequestToSendXOnXOff()
{
Debug.WriteLine("Case Handshake_RequestToSendXOnXOff : Verifying Handshake=RequestToSendXOnXOff");
Verify_Handshake(Handshake.RequestToSendXOnXOff);
}
private class AsyncEnableRts
{
private bool _stop;
public void EnableRTS()
{
lock (this)
{
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2);
//Sleep some random period with of a maximum duration of half the largest possible timeout value for a write method on COM1
Thread.Sleep(sleepPeriod);
com2.Open();
com2.RtsEnable = true;
while (!_stop)
Monitor.Wait(this);
com2.RtsEnable = false;
}
}
}
public void Stop()
{
lock (this)
{
_stop = true;
Monitor.Pulse(this);
}
}
}
private class AsyncWriteRndStr
{
private readonly SerialPort _com;
private readonly int _strSize;
public AsyncWriteRndStr(SerialPort com, int strSize)
{
_com = com;
_strSize = strSize;
}
public void WriteRndStr()
{
string stringToWrite = TCSupport.GetRandomString(_strSize, TCSupport.CharacterOptions.Surrogates);
try
{
_com.WriteLine(stringToWrite);
}
catch (TimeoutException)
{
}
}
}
#endregion
#region Verification for Test Cases
private static void VerifyWriteException(SerialPort com, Type expectedException)
{
Assert.Throws(expectedException, () => com.WriteLine(DEFAULT_STRING));
}
private void VerifyTimeout(SerialPort com)
{
Stopwatch timer = new Stopwatch();
int expectedTime = com.WriteTimeout;
int actualTime = 0;
double percentageDifference;
try
{
com.WriteLine(DEFAULT_STRING); //Warm up write method
}
catch (TimeoutException) { }
Thread.CurrentThread.Priority = ThreadPriority.Highest;
for (int i = 0; i < NUM_TRYS; i++)
{
timer.Start();
try
{
com.WriteLine(DEFAULT_STRING);
}
catch (TimeoutException) { }
timer.Stop();
actualTime += (int)timer.ElapsedMilliseconds;
timer.Reset();
}
Thread.CurrentThread.Priority = ThreadPriority.Normal;
actualTime /= NUM_TRYS;
percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime);
//Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference
if (maxPercentageDifference < percentageDifference)
{
Fail("ERROR!!!: The write method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference);
}
}
private void Verify_Handshake(Handshake handshake)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
byte[] XOffBuffer = new byte[1];
byte[] XOnBuffer = new byte[1];
XOffBuffer[0] = 19;
XOnBuffer[0] = 17;
int numNewLineBytes;
Debug.WriteLine("Verifying Handshake={0}", handshake);
com1.WriteTimeout = 3000;
com1.Handshake = handshake;
com1.Open();
com2.Open();
numNewLineBytes = com1.Encoding.GetByteCount(com1.NewLine.ToCharArray());
//Setup to ensure write will block with type of handshake method being used
if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.RtsEnable = false;
}
if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.Write(XOffBuffer, 0, 1);
Thread.Sleep(250);
}
//Write a random string asynchronously so we can verify some things while the write call is blocking
string randomLine = TCSupport.GetRandomString(s_STRING_SIZE_HANDSHAKE, TCSupport.CharacterOptions.Surrogates);
byte[] randomLineBytes = com1.Encoding.GetBytes(randomLine);
Task task = Task.Run(() => com1.WriteLine(randomLine));
TCSupport.WaitForTaskToStart(task);
TCSupport.WaitForWriteBufferToLoad(com1, randomLineBytes.Length + numNewLineBytes);
//Verify that CtsHolding is false if the RequestToSend or RequestToSendXOnXOff handshake method is used
if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && com1.CtsHolding)
{
Fail("ERROR!!! Expcted CtsHolding={0} actual {1}", false, com1.CtsHolding);
}
//Setup to ensure write will succeed
if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.RtsEnable = true;
}
if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.Write(XOnBuffer, 0, 1);
}
//Wait till write finishes
TCSupport.WaitForTaskCompletion(task);
Assert.Equal(0, com1.BytesToWrite);
//Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used
if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) &&
!com1.CtsHolding)
{
Fail("ERROR!!! Expected CtsHolding={0} actual {1}", true, com1.CtsHolding);
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Internal;
using Orleans.Runtime.Scheduler;
using Orleans.Statistics;
namespace Orleans.Runtime
{
/// <summary>
/// This class collects runtime statistics for all silos in the current deployment for use by placement.
/// </summary>
internal class DeploymentLoadPublisher : SystemTarget, IDeploymentLoadPublisher, ISiloStatusListener
{
private readonly ILocalSiloDetails siloDetails;
private readonly ISiloStatusOracle siloStatusOracle;
private readonly IInternalGrainFactory grainFactory;
private readonly OrleansTaskScheduler scheduler;
private readonly IMessageCenter messageCenter;
private readonly ActivationDirectory activationDirectory;
private readonly ActivationCollector activationCollector;
private readonly IAppEnvironmentStatistics appEnvironmentStatistics;
private readonly IHostEnvironmentStatistics hostEnvironmentStatistics;
private readonly IOptions<LoadSheddingOptions> loadSheddingOptions;
private readonly ConcurrentDictionary<SiloAddress, SiloRuntimeStatistics> periodicStats;
private readonly TimeSpan statisticsRefreshTime;
private readonly IList<ISiloStatisticsChangeListener> siloStatisticsChangeListeners;
private readonly ILogger logger;
private IDisposable publishTimer;
public ConcurrentDictionary<SiloAddress, SiloRuntimeStatistics> PeriodicStatistics { get { return periodicStats; } }
public DeploymentLoadPublisher(
ILocalSiloDetails siloDetails,
ISiloStatusOracle siloStatusOracle,
IOptions<DeploymentLoadPublisherOptions> options,
IInternalGrainFactory grainFactory,
OrleansTaskScheduler scheduler,
ILoggerFactory loggerFactory,
IMessageCenter messageCenter,
ActivationDirectory activationDirectory,
ActivationCollector activationCollector,
IAppEnvironmentStatistics appEnvironmentStatistics,
IHostEnvironmentStatistics hostEnvironmentStatistics,
IOptions<LoadSheddingOptions> loadSheddingOptions)
: base(Constants.DeploymentLoadPublisherSystemTargetType, siloDetails.SiloAddress, loggerFactory)
{
this.logger = loggerFactory.CreateLogger<DeploymentLoadPublisher>();
this.siloDetails = siloDetails;
this.siloStatusOracle = siloStatusOracle;
this.grainFactory = grainFactory;
this.scheduler = scheduler;
this.messageCenter = messageCenter;
this.activationDirectory = activationDirectory;
this.activationCollector = activationCollector;
this.appEnvironmentStatistics = appEnvironmentStatistics;
this.hostEnvironmentStatistics = hostEnvironmentStatistics;
this.loadSheddingOptions = loadSheddingOptions;
statisticsRefreshTime = options.Value.DeploymentLoadPublisherRefreshTime;
periodicStats = new ConcurrentDictionary<SiloAddress, SiloRuntimeStatistics>();
siloStatisticsChangeListeners = new List<ISiloStatisticsChangeListener>();
}
public async Task Start()
{
logger.Info("Starting DeploymentLoadPublisher.");
if (statisticsRefreshTime > TimeSpan.Zero)
{
// Randomize PublishStatistics timer,
// but also upon start publish my stats to everyone and take everyone's stats for me to start with something.
var randomTimerOffset = ThreadSafeRandom.NextTimeSpan(statisticsRefreshTime);
this.publishTimer = this.RegisterTimer(PublishStatistics, null, randomTimerOffset, statisticsRefreshTime, "DeploymentLoadPublisher.PublishStatisticsTimer");
}
await RefreshStatistics();
await PublishStatistics(null);
logger.Info("Started DeploymentLoadPublisher.");
}
private async Task PublishStatistics(object _)
{
try
{
if(logger.IsEnabled(LogLevel.Debug)) logger.Debug("PublishStatistics.");
var members = this.siloStatusOracle.GetApproximateSiloStatuses(true).Keys;
var tasks = new List<Task>();
var activationCount = this.activationDirectory.Count;
var recentlyUsedActivationCount = this.activationCollector.GetNumRecentlyUsed(TimeSpan.FromMinutes(10));
var myStats = new SiloRuntimeStatistics(
this.messageCenter,
activationCount,
recentlyUsedActivationCount,
this.appEnvironmentStatistics,
this.hostEnvironmentStatistics,
this.loadSheddingOptions,
DateTime.UtcNow);
foreach (var siloAddress in members)
{
try
{
tasks.Add(this.grainFactory.GetSystemTarget<IDeploymentLoadPublisher>(
Constants.DeploymentLoadPublisherSystemTargetType, siloAddress)
.UpdateRuntimeStatistics(this.siloDetails.SiloAddress, myStats));
}
catch (Exception)
{
logger.Warn(ErrorCode.Placement_RuntimeStatisticsUpdateFailure_1,
String.Format("An unexpected exception was thrown by PublishStatistics.UpdateRuntimeStatistics(). Ignored."));
}
}
await Task.WhenAll(tasks);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Placement_RuntimeStatisticsUpdateFailure_2,
String.Format("An exception was thrown by PublishStatistics.UpdateRuntimeStatistics(). Ignoring."), exc);
}
}
public Task UpdateRuntimeStatistics(SiloAddress siloAddress, SiloRuntimeStatistics siloStats)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("UpdateRuntimeStatistics from {0}", siloAddress);
if (this.siloStatusOracle.GetApproximateSiloStatus(siloAddress) != SiloStatus.Active)
return Task.CompletedTask;
SiloRuntimeStatistics old;
// Take only if newer.
if (periodicStats.TryGetValue(siloAddress, out old) && old.DateTime > siloStats.DateTime)
return Task.CompletedTask;
periodicStats[siloAddress] = siloStats;
NotifyAllStatisticsChangeEventsSubscribers(siloAddress, siloStats);
return Task.CompletedTask;
}
internal async Task<ConcurrentDictionary<SiloAddress, SiloRuntimeStatistics>> RefreshStatistics()
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("RefreshStatistics.");
await this.scheduler.RunOrQueueTask(() =>
{
var tasks = new List<Task>();
var members = this.siloStatusOracle.GetApproximateSiloStatuses(true).Keys;
foreach (var siloAddress in members)
{
var capture = siloAddress;
Task task = this.grainFactory.GetSystemTarget<ISiloControl>(Constants.SiloControlType, capture)
.GetRuntimeStatistics()
.ContinueWith((Task<SiloRuntimeStatistics> statsTask) =>
{
if (statsTask.Status == TaskStatus.RanToCompletion)
{
UpdateRuntimeStatistics(capture, statsTask.Result);
}
else
{
logger.Warn(ErrorCode.Placement_RuntimeStatisticsUpdateFailure_3,
String.Format("An unexpected exception was thrown from RefreshStatistics by ISiloControl.GetRuntimeStatistics({0}). Will keep using stale statistics.", capture),
statsTask.Exception);
}
});
tasks.Add(task);
task.Ignore();
}
return Task.WhenAll(tasks);
}, this);
return periodicStats;
}
public bool SubscribeToStatisticsChangeEvents(ISiloStatisticsChangeListener observer)
{
lock (siloStatisticsChangeListeners)
{
if (siloStatisticsChangeListeners.Contains(observer)) return false;
siloStatisticsChangeListeners.Add(observer);
return true;
}
}
public bool UnsubscribeStatisticsChangeEvents(ISiloStatisticsChangeListener observer)
{
lock (siloStatisticsChangeListeners)
{
return siloStatisticsChangeListeners.Contains(observer) &&
siloStatisticsChangeListeners.Remove(observer);
}
}
private void NotifyAllStatisticsChangeEventsSubscribers(SiloAddress silo, SiloRuntimeStatistics stats)
{
lock (siloStatisticsChangeListeners)
{
foreach (var subscriber in siloStatisticsChangeListeners)
{
if (stats==null)
{
subscriber.RemoveSilo(silo);
}
else
{
subscriber.SiloStatisticsChangeNotification(silo, stats);
}
}
}
}
public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status)
{
this.ScheduleTask(() => { Utils.SafeExecute(() => this.OnSiloStatusChange(updatedSilo, status), this.logger); }).Ignore();
}
private void OnSiloStatusChange(SiloAddress updatedSilo, SiloStatus status)
{
if (!status.IsTerminating()) return;
if (Equals(updatedSilo, this.Silo))
this.publishTimer.Dispose();
periodicStats.TryRemove(updatedSilo, out _);
NotifyAllStatisticsChangeEventsSubscribers(updatedSilo, null);
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
namespace YAF.Lucene.Net.Store
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Base implementation class for buffered <see cref="IndexInput"/>. </summary>
public abstract class BufferedIndexInput : IndexInput
{
/// <summary>
/// Default buffer size set to <see cref="BUFFER_SIZE"/>. </summary>
public const int BUFFER_SIZE = 1024;
// The normal read buffer size defaults to 1024, but
// increasing this during merging seems to yield
// performance gains. However we don't want to increase
// it too much because there are quite a few
// BufferedIndexInputs created during merging. See
// LUCENE-888 for details.
/// <summary>
/// A buffer size for merges set to <see cref="MERGE_BUFFER_SIZE"/>.
/// </summary>
public const int MERGE_BUFFER_SIZE = 4096;
private int bufferSize = BUFFER_SIZE;
protected byte[] m_buffer;
private long bufferStart = 0; // position in file of buffer
private int bufferLength = 0; // end of valid bytes
private int bufferPosition = 0; // next byte to read
public override sealed byte ReadByte()
{
if (bufferPosition >= bufferLength)
{
Refill();
}
return m_buffer[bufferPosition++];
}
public BufferedIndexInput(string resourceDesc)
: this(resourceDesc, BUFFER_SIZE)
{
}
public BufferedIndexInput(string resourceDesc, IOContext context)
: this(resourceDesc, GetBufferSize(context))
{
}
/// <summary>
/// Inits <see cref="BufferedIndexInput"/> with a specific <paramref name="bufferSize"/> </summary>
public BufferedIndexInput(string resourceDesc, int bufferSize)
: base(resourceDesc)
{
CheckBufferSize(bufferSize);
this.bufferSize = bufferSize;
}
/// <summary>
/// Change the buffer size used by this <see cref="IndexInput"/> </summary>
public void SetBufferSize(int newSize)
{
Debug.Assert(m_buffer == null || bufferSize == m_buffer.Length, "buffer=" + m_buffer + " bufferSize=" + bufferSize + " buffer.length=" + (m_buffer != null ? m_buffer.Length : 0));
if (newSize != bufferSize)
{
CheckBufferSize(newSize);
bufferSize = newSize;
if (m_buffer != null)
{
// Resize the existing buffer and carefully save as
// many bytes as possible starting from the current
// bufferPosition
byte[] newBuffer = new byte[newSize];
int leftInBuffer = bufferLength - bufferPosition;
int numToCopy;
if (leftInBuffer > newSize)
{
numToCopy = newSize;
}
else
{
numToCopy = leftInBuffer;
}
Array.Copy(m_buffer, bufferPosition, newBuffer, 0, numToCopy);
bufferStart += bufferPosition;
bufferPosition = 0;
bufferLength = numToCopy;
NewBuffer(newBuffer);
}
}
}
protected virtual void NewBuffer(byte[] newBuffer)
{
// Subclasses can do something here
m_buffer = newBuffer;
}
/// <summary>
/// Returns buffer size.
/// </summary>
/// <seealso cref="SetBufferSize(int)"/>
public int BufferSize
{
get
{
return bufferSize;
}
}
private void CheckBufferSize(int bufferSize)
{
if (bufferSize <= 0)
{
throw new ArgumentException("bufferSize must be greater than 0 (got " + bufferSize + ")");
}
}
public override sealed void ReadBytes(byte[] b, int offset, int len)
{
ReadBytes(b, offset, len, true);
}
public override sealed void ReadBytes(byte[] b, int offset, int len, bool useBuffer)
{
int available = bufferLength - bufferPosition;
if (len <= available)
{
// the buffer contains enough data to satisfy this request
if (len > 0) // to allow b to be null if len is 0...
{
Buffer.BlockCopy(m_buffer, bufferPosition, b, offset, len);
}
bufferPosition += len;
}
else
{
// the buffer does not have enough data. First serve all we've got.
if (available > 0)
{
Buffer.BlockCopy(m_buffer, bufferPosition, b, offset, available);
offset += available;
len -= available;
bufferPosition += available;
}
// and now, read the remaining 'len' bytes:
if (useBuffer && len < bufferSize)
{
// If the amount left to read is small enough, and
// we are allowed to use our buffer, do it in the usual
// buffered way: fill the buffer and copy from it:
Refill();
if (bufferLength < len)
{
// Throw an exception when refill() could not read len bytes:
Buffer.BlockCopy(m_buffer, 0, b, offset, bufferLength);
throw new EndOfStreamException("read past EOF: " + this);
}
else
{
Buffer.BlockCopy(m_buffer, 0, b, offset, len);
bufferPosition = len;
}
}
else
{
// The amount left to read is larger than the buffer
// or we've been asked to not use our buffer -
// there's no performance reason not to read it all
// at once. Note that unlike the previous code of
// this function, there is no need to do a seek
// here, because there's no need to reread what we
// had in the buffer.
long after = bufferStart + bufferPosition + len;
if (after > Length)
{
throw new EndOfStreamException("read past EOF: " + this);
}
ReadInternal(b, offset, len);
bufferStart = after;
bufferPosition = 0;
bufferLength = 0; // trigger refill() on read
}
}
}
/// <summary>
/// NOTE: this was readShort() in Lucene
/// </summary>
public override sealed short ReadInt16()
{
if (2 <= (bufferLength - bufferPosition))
{
return (short)(((m_buffer[bufferPosition++] & 0xFF) << 8) | (m_buffer[bufferPosition++] & 0xFF));
}
else
{
return base.ReadInt16();
}
}
/// <summary>
/// NOTE: this was readInt() in Lucene
/// </summary>
public override sealed int ReadInt32()
{
if (4 <= (bufferLength - bufferPosition))
{
return ((m_buffer[bufferPosition++] & 0xFF) << 24) | ((m_buffer[bufferPosition++] & 0xFF) << 16)
| ((m_buffer[bufferPosition++] & 0xFF) << 8) | (m_buffer[bufferPosition++] & 0xFF);
}
else
{
return base.ReadInt32();
}
}
/// <summary>
/// NOTE: this was readLong() in Lucene
/// </summary>
public override sealed long ReadInt64()
{
if (8 <= (bufferLength - bufferPosition))
{
int i1 = ((m_buffer[bufferPosition++] & 0xff) << 24) | ((m_buffer[bufferPosition++] & 0xff) << 16)
| ((m_buffer[bufferPosition++] & 0xff) << 8) | (m_buffer[bufferPosition++] & 0xff);
int i2 = ((m_buffer[bufferPosition++] & 0xff) << 24) | ((m_buffer[bufferPosition++] & 0xff) << 16)
| ((m_buffer[bufferPosition++] & 0xff) << 8) | (m_buffer[bufferPosition++] & 0xff);
return (((long)i1) << 32) | (i2 & 0xFFFFFFFFL);
}
else
{
return base.ReadInt64();
}
}
/// <summary>
/// NOTE: this was readVInt() in Lucene
/// </summary>
public override sealed int ReadVInt32()
{
if (5 <= (bufferLength - bufferPosition))
{
byte b = m_buffer[bufferPosition++];
if ((sbyte)b >= 0)
{
return b;
}
int i = b & 0x7F;
b = m_buffer[bufferPosition++];
i |= (b & 0x7F) << 7;
if ((sbyte)b >= 0)
{
return i;
}
b = m_buffer[bufferPosition++];
i |= (b & 0x7F) << 14;
if ((sbyte)b >= 0)
{
return i;
}
b = m_buffer[bufferPosition++];
i |= (b & 0x7F) << 21;
if ((sbyte)b >= 0)
{
return i;
}
b = m_buffer[bufferPosition++];
// Warning: the next ands use 0x0F / 0xF0 - beware copy/paste errors:
i |= (b & 0x0F) << 28;
if ((b & 0xF0) == 0)
{
return i;
}
throw new IOException("Invalid VInt32 detected (too many bits)");
}
else
{
return base.ReadVInt32();
}
}
/// <summary>
/// NOTE: this was readVLong() in Lucene
/// </summary>
public override sealed long ReadVInt64()
{
if (9 <= bufferLength - bufferPosition)
{
byte b = m_buffer[bufferPosition++];
if ((sbyte)b >= 0)
{
return b;
}
long i = b & 0x7FL;
b = m_buffer[bufferPosition++];
i |= (b & 0x7FL) << 7;
if ((sbyte)b >= 0)
{
return i;
}
b = m_buffer[bufferPosition++];
i |= (b & 0x7FL) << 14;
if ((sbyte)b >= 0)
{
return i;
}
b = m_buffer[bufferPosition++];
i |= (b & 0x7FL) << 21;
if ((sbyte)b >= 0)
{
return i;
}
b = m_buffer[bufferPosition++];
i |= (b & 0x7FL) << 28;
if ((sbyte)b >= 0)
{
return i;
}
b = m_buffer[bufferPosition++];
i |= (b & 0x7FL) << 35;
if ((sbyte)b >= 0)
{
return i;
}
b = m_buffer[bufferPosition++];
i |= (b & 0x7FL) << 42;
if ((sbyte)b >= 0)
{
return i;
}
b = m_buffer[bufferPosition++];
i |= (b & 0x7FL) << 49;
if ((sbyte)b >= 0)
{
return i;
}
b = m_buffer[bufferPosition++];
i |= (b & 0x7FL) << 56;
if ((sbyte)b >= 0)
{
return i;
}
throw new IOException("Invalid VInt64 detected (negative values disallowed)");
}
else
{
return base.ReadVInt64();
}
}
private void Refill()
{
long start = bufferStart + bufferPosition;
long end = start + bufferSize;
if (end > Length) // don't read past EOF
{
end = Length;
}
int newLength = (int)(end - start);
if (newLength <= 0)
{
throw new EndOfStreamException("read past EOF: " + this);
}
if (m_buffer == null)
{
NewBuffer(new byte[bufferSize]); // allocate buffer lazily
SeekInternal(bufferStart);
}
ReadInternal(m_buffer, 0, newLength);
bufferLength = newLength;
bufferStart = start;
bufferPosition = 0;
}
/// <summary>
/// Expert: implements buffer refill. Reads bytes from the current position
/// in the input. </summary>
/// <param name="b"> the array to read bytes into </param>
/// <param name="offset"> the offset in the array to start storing bytes </param>
/// <param name="length"> the number of bytes to read </param>
protected abstract void ReadInternal(byte[] b, int offset, int length);
public override sealed long GetFilePointer()
{
return bufferStart + bufferPosition;
}
public override sealed void Seek(long pos)
{
if (pos >= bufferStart && pos < (bufferStart + bufferLength))
{
bufferPosition = (int)(pos - bufferStart); // seek within buffer
}
else
{
bufferStart = pos;
bufferPosition = 0;
bufferLength = 0; // trigger refill() on read()
SeekInternal(pos);
}
}
/// <summary>
/// Expert: implements seek. Sets current position in this file, where the
/// next <see cref="ReadInternal(byte[], int, int)"/> will occur. </summary>
/// <seealso cref="ReadInternal(byte[], int, int)"/>
protected abstract void SeekInternal(long pos);
public override object Clone()
{
BufferedIndexInput clone = (BufferedIndexInput)base.Clone();
clone.m_buffer = null;
clone.bufferLength = 0;
clone.bufferPosition = 0;
clone.bufferStart = GetFilePointer();
return clone;
}
/// <summary>
/// Flushes the in-memory buffer to the given output, copying at most
/// <paramref name="numBytes"/>.
/// <para/>
/// <b>NOTE:</b> this method does not refill the buffer, however it does
/// advance the buffer position.
/// </summary>
/// <returns> the number of bytes actually flushed from the in-memory buffer. </returns>
protected int FlushBuffer(IndexOutput @out, long numBytes)
{
int toCopy = bufferLength - bufferPosition;
if (toCopy > numBytes)
{
toCopy = (int)numBytes;
}
if (toCopy > 0)
{
@out.WriteBytes(m_buffer, bufferPosition, toCopy);
bufferPosition += toCopy;
}
return toCopy;
}
/// <summary>
/// Returns default buffer sizes for the given <see cref="IOContext"/>
/// </summary>
public static int GetBufferSize(IOContext context) // LUCENENET NOTE: Renamed from BufferSize to prevent naming conflict
{
switch (context.Context)
{
case IOContext.UsageContext.MERGE:
return MERGE_BUFFER_SIZE;
default:
return BUFFER_SIZE;
}
}
}
}
| |
// QuickGraph Library
//
// Copyright (c) 2004 Jonathan de Halleux
//
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from
// the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment in the product
// documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must
// not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
// QuickGraph Library HomePage: http://www.mbunit.com
// Author: Jonathan de Halleux
using System;
using System.Collections;
namespace QuickGraph.Algorithms.Travelling
{
using QuickGraph.Concepts;
using QuickGraph.Concepts.Traversals;
using QuickGraph.Concepts.MutableTraversals;
using QuickGraph.Concepts.Modifications;
using QuickGraph.Concepts.Algorithms;
using QuickGraph.Concepts.Predicates;
using QuickGraph.Concepts.Collections;
using QuickGraph.Collections.Filtered;
using QuickGraph.Algorithms.Search;
using QuickGraph.Algorithms.Visitors;
using QuickGraph.Predicates;
using QuickGraph.Collections;
/// <summary>
/// Under construction
/// </summary>
public class EulerianTrailAlgorithm :
IAlgorithm
{
private IVertexAndEdgeListGraph visitedGraph;
private EdgeCollection circuit;
private EdgeCollection temporaryCircuit;
private IVertex currentVertex;
private EdgeCollection temporaryEdges;
/// <summary>
/// Construct an eulerian trail builder
/// </summary>
/// <param name="g"></param>
public EulerianTrailAlgorithm(IVertexAndEdgeListGraph g)
{
if (g==null)
throw new ArgumentNullException("g");
visitedGraph = g;
circuit = new EdgeCollection();
temporaryCircuit = new EdgeCollection();
currentVertex = null;
temporaryEdges = new EdgeCollection();
}
/// <summary>
/// Visited Graph
/// </summary>
public IVertexAndEdgeListGraph VisitedGraph
{
get
{
return visitedGraph;
}
}
/// <summary>
///
/// </summary>
Object IAlgorithm.VisitedGraph
{
get
{
return this.VisitedGraph;
}
}
/// <summary>
/// Eulerian circuit on modified graph
/// </summary>
public EdgeCollection Circuit
{
get
{
return circuit;
}
}
/// <summary>
/// Used internally
/// </summary>
internal EdgeCollection TemporaryCircuit
{
get
{
return temporaryCircuit;
}
}
internal IVertex CurrentVertex
{
get
{
return currentVertex;
}
set
{
currentVertex = value;
}
}
internal EdgeCollection TemporaryEdges
{
get
{
return temporaryEdges;
}
}
private IEdgeEnumerable SelectOutEdgesNotInCircuit(IVertex v)
{
return new FilteredEdgeEnumerable(
VisitedGraph.OutEdges(v),
new NotInCircuitEdgePredicate(Circuit,TemporaryCircuit)
);
}
private IEdge SelectSingleOutEdgeNotInCircuit(IVertex v)
{
IEdgeEnumerable en = this.SelectOutEdgesNotInCircuit(v);
IEdgeEnumerator eor = en.GetEnumerator();
if (!eor.MoveNext())
return null;
else
return eor.Current;
}
/// <summary>
///
/// </summary>
public event EdgeEventHandler TreeEdge;
/// <summary>
///
/// </summary>
/// <param name="e"></param>
protected virtual void OnTreeEdge(IEdge e)
{
if (TreeEdge!=null)
TreeEdge(this, new EdgeEventArgs(e));
}
/// <summary>
///
/// </summary>
public event EdgeEventHandler CircuitEdge;
/// <summary>
///
/// </summary>
/// <param name="e"></param>
protected virtual void OnCircuitEdge(IEdge e)
{
if (CircuitEdge!=null)
CircuitEdge(this, new EdgeEventArgs(e));
}
/// <summary>
///
/// </summary>
public event EdgeEventHandler VisitEdge;
/// <summary>
///
/// </summary>
/// <param name="e"></param>
protected virtual void OnVisitEdge(IEdge e)
{
if (VisitEdge!=null)
VisitEdge(this, new EdgeEventArgs(e));
}
/// <summary>
/// Search a new path to add to the current circuit
/// </summary>
/// <param name="u">start vertex</param>
/// <returns>true if successfull, false otherwize</returns>
protected bool Search(IVertex u)
{
foreach(IEdge e in SelectOutEdgesNotInCircuit(u))
{
OnTreeEdge(e);
IVertex v = e.Target;
// add edge to temporary path
TemporaryCircuit.Add(e);
// e.Target should be equal to CurrentVertex.
if (e.Target == CurrentVertex)
return true;
// continue search
if (Search(v))
return true;
else
// remove edge
TemporaryCircuit.Remove(e);
}
// it's a dead end.
return false;
}
/// <summary>
/// Looks for a new path to add to the current vertex.
/// </summary>
/// <returns>true if found a new path, false otherwize</returns>
protected bool Visit()
{
// find a vertex that needs to be visited
foreach(IEdge e in Circuit)
{
IEdge fe = SelectSingleOutEdgeNotInCircuit(e.Source);
if (fe!=null)
{
OnVisitEdge(fe);
CurrentVertex = e.Source;
if(Search(CurrentVertex))
return true;
}
}
// Could not augment circuit
return false;
}
/// <summary>
/// Computes the number of eulerian trail in the graph. If negative,
/// there is an eulerian circuit.
/// </summary>
/// <param name="g"></param>
/// <returns>number of eulerian trails</returns>
public static int ComputeEulerianPathCount(IVertexAndEdgeListGraph g)
{
if (g==null)
throw new ArgumentNullException("g");
int odd = AlgoUtility.OddVertices(g).Count;
if (odd==0)
return -1;
if (odd%2!=0)
return 0;
else if (odd==0)
return 1;
else
return odd/2;
}
/// <summary>
/// Merges the temporary circuit with the current circuit
/// </summary>
/// <returns>true if all the graph edges are in the circuit</returns>
protected bool CircuitAugmentation()
{
EdgeCollection newC=new EdgeCollection();
int i,j;
// follow C until w is found
for(i=0;i<Circuit.Count;++i)
{
IEdge e = Circuit[i];
if (e.Source==CurrentVertex)
break;
newC.Add(e);
}
// follow D until w is found again
for(j=0;j<TemporaryCircuit.Count;++j)
{
IEdge e = TemporaryCircuit[j];
newC.Add(e);
OnCircuitEdge(e);
if (e.Target==CurrentVertex)
break;
}
TemporaryCircuit.Clear();
// continue C
for(;i<Circuit.Count;++i)
{
IEdge e = Circuit[i];
newC.Add(e);
}
// set as new circuit
circuit = newC;
// check if contains all edges
if (Circuit.Count == VisitedGraph.EdgesCount)
return true;
return false;
}
/// <summary>
/// Computes the eulerian trails
/// </summary>
public void Compute()
{
CurrentVertex = Traversal.FirstVertex(VisitedGraph);
// start search
Search(CurrentVertex);
if (CircuitAugmentation())
return; // circuit is found
do
{
if (!Visit())
break; // visit edges and build path
if (CircuitAugmentation())
break; // circuit is found
} while(true);
}
/// <summary>
/// Adds temporary edges to the graph to make all vertex even.
/// </summary>
/// <param name="g"></param>
/// <returns></returns>
public EdgeCollection AddTemporaryEdges(IMutableVertexAndEdgeListGraph g)
{
if (g==null)
throw new ArgumentNullException("g");
// first gather odd edges.
VertexCollection oddVertices = AlgoUtility.OddVertices(g);
// check that there are an even number of them
if (oddVertices.Count%2!=0)
throw new Exception("number of odd vertices in not even!");
// add temporary edges to create even edges:
EdgeCollection ec = new EdgeCollection();
bool found,foundbe,foundadjacent;
while (oddVertices.Count > 0)
{
IVertex u = oddVertices[0];
// find adjacent odd vertex.
found = false;
foundadjacent = false;
foreach(IEdge e in g.OutEdges(u))
{
IVertex v = e.Target;
if (v!=u && oddVertices.Contains(v))
{
foundadjacent=true;
// check that v does not have an out-edge towards u
foundbe = false;
foreach(IEdge be in g.OutEdges(v))
{
if (be.Target==u)
{
foundbe = true;
break;
}
}
if (foundbe)
continue;
// add temporary edge
IEdge tempEdge = g.AddEdge(v,u);
// add to collection
ec.Add(tempEdge);
// remove u,v from oddVertices
oddVertices.Remove(u);
oddVertices.Remove(v);
// set u to null
found = true;
break;
}
}
if (!foundadjacent)
{
// pick another vertex
if (oddVertices.Count<2)
throw new Exception("Eulerian trail failure");
IVertex v = oddVertices[1];
IEdge tempEdge = g.AddEdge(u,v);
// add to collection
ec.Add(tempEdge);
// remove u,v from oddVertices
oddVertices.Remove(u);
oddVertices.Remove(v);
// set u to null
found = true;
}
if (!found)
{
oddVertices.Remove(u);
oddVertices.Add(u);
}
}
temporaryEdges = ec;
return ec;
}
/// <summary>
/// Removes temporary edges
/// </summary>
/// <param name="g"></param>
public void RemoveTemporaryEdges(IEdgeMutableGraph g)
{
// remove from graph
foreach(IEdge e in TemporaryEdges)
g.RemoveEdge(e);
}
/// <summary>
/// Computes the set of eulerian trails that traverse the edge set.
/// </summary>
/// <remarks>
/// This method returns a set of disjoint eulerian trails. This set
/// of trails spans the entire set of edges.
/// </remarks>
/// <returns>Eulerian trail set</returns>
public EdgeCollectionCollection Trails()
{
EdgeCollectionCollection trails = new EdgeCollectionCollection();
EdgeCollection trail = new EdgeCollection();
foreach(IEdge e in this.Circuit)
{
if (TemporaryEdges.Contains(e))
{
// store previous trail and start new one.
if(trail.Count != 0)
trails.Add(trail);
// start new trail
trail = new EdgeCollection();
}
else
trail.Add(e);
}
if(trail.Count != 0)
trails.Add(trail);
return trails;
}
/// <summary>
/// Computes a set of eulerian trail, starting at <paramref name="s"/>
/// that spans the entire graph.
/// </summary>
/// <remarks>
/// <para>
/// This method computes a set of eulerian trail starting at <paramref name="s"/>
/// that spans the entire graph.The algorithm outline is as follows:
/// </para>
/// <para>
/// The algorithms iterates throught the Eulerian circuit of the augmented
/// graph (the augmented graph is the graph with additional edges to make
/// the number of odd vertices even).
/// </para>
/// <para>
/// If the current edge is not temporary, it is added to the current trail.
/// </para>
/// <para>
/// If the current edge is temporary, the current trail is finished and
/// added to the trail collection. The shortest path between the
/// start vertex <paramref name="s"/> and the target vertex of the
/// temporary edge is then used to start the new trail. This shortest
/// path is computed using the <see cref="BreadthFirstSearchAlgorithm"/>.
/// </para>
/// </remarks>
/// <param name="s">start vertex</param>
/// <returns>eulerian trail set, all starting at s</returns>
/// <exception cref="ArgumentNullException">s is a null reference.</exception>
/// <exception cref="Exception">Eulerian trail not computed yet.</exception>
public EdgeCollectionCollection Trails(IVertex s)
{
if (s==null)
throw new ArgumentNullException("s");
if (this.Circuit.Count==0)
throw new Exception("Circuit is empty");
// find the first edge in the circuit.
int i=0;
for(i=0;i<this.Circuit.Count;++i)
{
IEdge e = this.Circuit[i];
if (TemporaryEdges.Contains(e))
continue;
if (e.Source == s)
break;
}
if (i==this.Circuit.Count)
throw new Exception("Did not find vertex in eulerian trail?");
// create collections
EdgeCollectionCollection trails = new EdgeCollectionCollection();
EdgeCollection trail = new EdgeCollection();
BreadthFirstSearchAlgorithm bfs =
new BreadthFirstSearchAlgorithm(VisitedGraph);
PredecessorRecorderVisitor vis = new PredecessorRecorderVisitor();
bfs.RegisterPredecessorRecorderHandlers(vis);
bfs.Compute(s);
// go throught the edges and build the predecessor table.
int start = i;
for (;i<this.Circuit.Count;++i)
{
IEdge e = this.Circuit[i];
if (TemporaryEdges.Contains(e))
{
// store previous trail and start new one.
if(trail.Count != 0)
trails.Add(trail);
// start new trail
// take the shortest path from the start vertex to
// the target vertex
trail = vis.Path(e.Target);
}
else
trail.Add(e);
}
// starting again on the circuit
for (i=0;i<start;++i)
{
IEdge e = this.Circuit[i];
if (TemporaryEdges.Contains(e))
{
// store previous trail and start new one.
if(trail.Count != 0)
trails.Add(trail);
// start new trail
// take the shortest path from the start vertex to
// the target vertex
trail = vis.Path(e.Target);
}
else
trail.Add(e);
}
// adding the last element
if (trail.Count!=0)
trails.Add(trail);
return trails;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="WebBrowserContainer.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Diagnostics;
using System;
using System.Reflection;
using System.Globalization;
using System.Security.Permissions;
using System.Collections;
using System.Drawing;
using System.Windows.Forms.Design;
using System.ComponentModel.Design;
using System.Security;
namespace System.Windows.Forms {
internal class WebBrowserContainer : UnsafeNativeMethods.IOleContainer, UnsafeNativeMethods.IOleInPlaceFrame {
//
// Private fields:
//
private WebBrowserBase parent;
private IContainer assocContainer; // associated IContainer...
// the assocContainer may be null, in which case all this container does is
// forward [de]activation messages to the requisite container...
private WebBrowserBase siteUIActive;
private WebBrowserBase siteActive;
private Hashtable containerCache = new Hashtable(); // name -> Control
private Hashtable components = null; // Control -> any
private WebBrowserBase ctlInEditMode = null;
internal WebBrowserContainer(WebBrowserBase parent) {
this.parent = parent;
}
//
// IOleContainer methods:
//
int UnsafeNativeMethods.IOleContainer.ParseDisplayName(Object pbc, string pszDisplayName, int[] pchEaten, Object[] ppmkOut) {
if (ppmkOut != null)
ppmkOut[0] = null;
return NativeMethods.E_NOTIMPL;
}
int UnsafeNativeMethods.IOleContainer.EnumObjects(int grfFlags, out UnsafeNativeMethods.IEnumUnknown ppenum) {
ppenum = null;
if ((grfFlags & 1) != 0) { // 1 == OLECONTF_EMBEDDINGS
Debug.Assert(parent != null, "gotta have it...");
ArrayList list = new ArrayList();
ListAXControls(list, true);
if (list.Count > 0) {
Object[] temp = new Object[list.Count];
list.CopyTo(temp, 0);
ppenum = new AxHost.EnumUnknown(temp);
return NativeMethods.S_OK;
}
}
ppenum = new AxHost.EnumUnknown(null);
return NativeMethods.S_OK;
}
int UnsafeNativeMethods.IOleContainer.LockContainer(bool fLock) {
return NativeMethods.E_NOTIMPL;
}
//
// IOleInPlaceFrame methods:
//
IntPtr UnsafeNativeMethods.IOleInPlaceFrame.GetWindow() {
return parent.Handle;
}
int UnsafeNativeMethods.IOleInPlaceFrame.ContextSensitiveHelp(int fEnterMode) {
return NativeMethods.S_OK;
}
int UnsafeNativeMethods.IOleInPlaceFrame.GetBorder(NativeMethods.COMRECT lprectBorder) {
return NativeMethods.E_NOTIMPL;
}
int UnsafeNativeMethods.IOleInPlaceFrame.RequestBorderSpace(NativeMethods.COMRECT pborderwidths) {
return NativeMethods.E_NOTIMPL;
}
int UnsafeNativeMethods.IOleInPlaceFrame.SetBorderSpace(NativeMethods.COMRECT pborderwidths) {
return NativeMethods.E_NOTIMPL;
}
int UnsafeNativeMethods.IOleInPlaceFrame.SetActiveObject(UnsafeNativeMethods.IOleInPlaceActiveObject pActiveObject, string pszObjName) {
if (pActiveObject == null) {
if (ctlInEditMode != null) {
ctlInEditMode.SetEditMode(WebBrowserHelper.AXEditMode.None);
ctlInEditMode = null;
}
return NativeMethods.S_OK;
}
WebBrowserBase ctl = null;
UnsafeNativeMethods.IOleObject oleObject = pActiveObject as UnsafeNativeMethods.IOleObject;
if (oleObject != null) {
UnsafeNativeMethods.IOleClientSite clientSite = null;
try {
clientSite = oleObject.GetClientSite();
WebBrowserSiteBase webBrowserSiteBase = clientSite as WebBrowserSiteBase;
if (webBrowserSiteBase != null)
{
ctl = webBrowserSiteBase.GetAXHost();
}
}
catch (COMException t) {
Debug.Fail(t.ToString());
}
if (ctlInEditMode != null) {
Debug.Fail("control " + ctlInEditMode.ToString() + " did not reset its edit mode to null");
ctlInEditMode.SetSelectionStyle(WebBrowserHelper.SelectionStyle.Selected);
ctlInEditMode.SetEditMode(WebBrowserHelper.AXEditMode.None);
}
if (ctl == null) {
ctlInEditMode = null;
}
else {
if (!ctl.IsUserMode) {
ctlInEditMode = ctl;
ctl.SetEditMode(WebBrowserHelper.AXEditMode.Object);
ctl.AddSelectionHandler();
ctl.SetSelectionStyle(WebBrowserHelper.SelectionStyle.Active);
}
}
}
return NativeMethods.S_OK;
}
int UnsafeNativeMethods.IOleInPlaceFrame.InsertMenus(IntPtr hmenuShared, NativeMethods.tagOleMenuGroupWidths lpMenuWidths) {
return NativeMethods.S_OK;
}
int UnsafeNativeMethods.IOleInPlaceFrame.SetMenu(IntPtr hmenuShared, IntPtr holemenu, IntPtr hwndActiveObject) {
return NativeMethods.E_NOTIMPL;
}
int UnsafeNativeMethods.IOleInPlaceFrame.RemoveMenus(IntPtr hmenuShared) {
return NativeMethods.E_NOTIMPL;
}
int UnsafeNativeMethods.IOleInPlaceFrame.SetStatusText(string pszStatusText) {
return NativeMethods.E_NOTIMPL;
}
int UnsafeNativeMethods.IOleInPlaceFrame.EnableModeless(bool fEnable) {
return NativeMethods.E_NOTIMPL;
}
int UnsafeNativeMethods.IOleInPlaceFrame.TranslateAccelerator(ref NativeMethods.MSG lpmsg, short wID) {
return NativeMethods.S_FALSE;
}
//
// Private helper methods:
//
private void ListAXControls(ArrayList list, bool fuseOcx) {
Hashtable components = GetComponents();
if (components == null)
{
return;
}
Control[] ctls = new Control[components.Keys.Count];
components.Keys.CopyTo(ctls, 0);
if (ctls != null) {
for (int i = 0; i < ctls.Length; i++) {
Control ctl = ctls[i];
WebBrowserBase webBrowserBase = ctl as WebBrowserBase;
if (webBrowserBase != null) {
if (fuseOcx) {
object ax = webBrowserBase.activeXInstance;
if (ax != null) {
list.Add(ax);
}
}
else {
list.Add(ctl);
}
}
}
}
}
private Hashtable GetComponents() {
return GetComponents(GetParentsContainer());
}
private IContainer GetParentsContainer() {
//
IContainer rval = GetParentIContainer();
Debug.Assert(rval == null || assocContainer == null || rval == assocContainer,
"mismatch between getIPD & aContainer");
return rval == null ? assocContainer : rval;
}
private IContainer GetParentIContainer() {
ISite site = parent.Site;
if (site != null && site.DesignMode) return site.Container;
return null;
}
private Hashtable GetComponents(IContainer cont) {
FillComponentsTable(cont);
return components;
}
private void FillComponentsTable(IContainer container) {
if (container != null) {
ComponentCollection comps = container.Components;
if (comps != null) {
components = new Hashtable();
foreach (IComponent comp in comps) {
if (comp is Control && comp != parent && comp.Site != null) {
components.Add(comp, comp);
}
}
return;
}
}
Debug.Assert(parent.Site == null, "Parent is sited but we could not find IContainer!!!");
bool checkHashTable = true;
Control[] ctls = new Control[containerCache.Values.Count];
containerCache.Values.CopyTo(ctls, 0);
if (ctls != null) {
if (ctls.Length > 0 && components == null) {
components = new Hashtable();
checkHashTable = false;
}
for (int i = 0; i < ctls.Length; i ++) {
if (checkHashTable && !components.Contains(ctls[i])) {
components.Add(ctls[i], ctls[i]);
}
}
}
GetAllChildren(this.parent);
}
private void GetAllChildren(Control ctl) {
if (ctl == null)
return;
if (components == null) {
components = new Hashtable();
}
if (ctl != this.parent && !components.Contains(ctl))
components.Add(ctl, ctl);
foreach(Control c in ctl.Controls) {
GetAllChildren(c);
}
}
private bool RegisterControl(WebBrowserBase ctl) {
ISite site = ctl.Site;
if (site != null) {
IContainer cont = site.Container;
if (cont != null) {
if (assocContainer != null) {
return cont == assocContainer;
}
else {
assocContainer = cont;
IComponentChangeService ccs = (IComponentChangeService)site.GetService(typeof(IComponentChangeService));
if (ccs != null) {
ccs.ComponentRemoved += new ComponentEventHandler(this.OnComponentRemoved);
}
return true;
}
}
}
return false;
}
private void OnComponentRemoved(object sender, ComponentEventArgs e) {
Control c = e.Component as Control;
if (sender == assocContainer && c != null) {
RemoveControl(c);
}
}
//
// Internal helper methods:
//
internal void AddControl(Control ctl) {
if (containerCache.Contains(ctl))
throw new ArgumentException(SR.GetString(SR.AXDuplicateControl, GetNameForControl(ctl)), "ctl");
containerCache.Add(ctl, ctl);
if (assocContainer == null) {
ISite site = ctl.Site;
if (site != null) {
assocContainer = site.Container;
IComponentChangeService ccs = (IComponentChangeService)site.GetService(typeof(IComponentChangeService));
if (ccs != null) {
ccs.ComponentRemoved += new ComponentEventHandler(this.OnComponentRemoved);
}
}
}
}
internal void RemoveControl(Control ctl) {
//ctl may not be in containerCache: Remove is a no-op if it's not there.
containerCache.Remove(ctl);
}
internal static WebBrowserContainer FindContainerForControl(WebBrowserBase ctl) {
if (ctl != null) {
if (ctl.container != null)
{
return ctl.container;
}
ScrollableControl f = ctl.ContainingControl;
if (f != null) {
WebBrowserContainer container = ctl.CreateWebBrowserContainer();
if (container.RegisterControl(ctl)) {
container.AddControl(ctl);
return container;
}
}
}
return null;
}
internal string GetNameForControl(Control ctl) {
string name = (ctl.Site != null) ? ctl.Site.Name : ctl.Name;
return name ?? "";
}
internal void OnUIActivate(WebBrowserBase site) {
// The ShDocVw control repeatedly calls OnUIActivate() with the same
// site. This causes the assert below to fire.
//
if (siteUIActive == site)
return;
if (siteUIActive != null && siteUIActive != site) {
WebBrowserBase tempSite = siteUIActive;
tempSite.AXInPlaceObject.UIDeactivate();
}
site.AddSelectionHandler();
Debug.Assert(siteUIActive == null, "Object did not call OnUIDeactivate");
siteUIActive = site;
ContainerControl f = site.ContainingControl;
if (f != null && f.Contains(site)) {
f.SetActiveControlInternal(site);
}
}
internal void OnUIDeactivate(WebBrowserBase site) {
#if DEBUG
if (siteUIActive != null) {
Debug.Assert(siteUIActive == site, "deactivating when not active...");
}
#endif // DEBUG
siteUIActive = null;
site.RemoveSelectionHandler();
site.SetSelectionStyle(WebBrowserHelper.SelectionStyle.Selected);
site.SetEditMode(WebBrowserHelper.AXEditMode.None);
}
internal void OnInPlaceDeactivate(WebBrowserBase site) {
if (siteActive == site) {
siteActive = null;
ContainerControl parentContainer = parent.FindContainerControlInternal();
if (parentContainer != null) {
parentContainer.SetActiveControlInternal(null);
}
}
}
internal void OnExitEditMode(WebBrowserBase ctl) {
Debug.Assert(ctlInEditMode == null || ctlInEditMode == ctl, "who is exiting edit mode?");
if (ctlInEditMode == ctl) {
ctlInEditMode = 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;
using System.Globalization;
using System.Xml;
using System.Text;
using System.IO;
using OLEDB.Test.ModuleCore;
using XmlCoreTest.Common;
namespace XmlWriterAPI.Test
{
//[TestCase(Name = "XmlWriterSettings: NamespaceHandling")]
public partial class TCNamespaceHandling : XmlFactoryWriterTestCaseBase
{
public override int Init(object o)
{
if (!(WriterType == WriterType.CustomWriter || WriterType == WriterType.UTF8WriterIndent || WriterType == WriterType.UnicodeWriterIndent /*|| WriterType == WriterType.DOMWriter || WriterType == WriterType.XmlTextWriter*/))
{
int i = base.Init(0);
return i;
}
return TEST_SKIPPED;
}
private static NamespaceHandling[] s_nlHandlingMembers = { NamespaceHandling.Default, NamespaceHandling.OmitDuplicates };
private StringWriter _strWriter = null;
private XmlWriter CreateMemWriter(XmlWriterSettings settings)
{
XmlWriterSettings wSettings = settings.Clone();
wSettings.CloseOutput = false;
wSettings.OmitXmlDeclaration = true;
wSettings.CheckCharacters = false;
XmlWriter w = null;
switch (WriterType)
{
case WriterType.UTF8Writer:
wSettings.Encoding = Encoding.UTF8;
if (_strWriter != null) _strWriter.Dispose();
_strWriter = new StringWriter();
w = WriterHelper.Create(_strWriter, wSettings);
break;
case WriterType.UnicodeWriter:
wSettings.Encoding = Encoding.Unicode;
if (_strWriter != null) _strWriter.Dispose();
_strWriter = new StringWriter();
w = WriterHelper.Create(_strWriter, wSettings);
break;
case WriterType.WrappedWriter:
if (_strWriter != null) _strWriter.Dispose();
_strWriter = new StringWriter();
XmlWriter ww = WriterHelper.Create(_strWriter, wSettings);
w = WriterHelper.Create(ww, wSettings);
break;
case WriterType.CharCheckingWriter:
if (_strWriter != null) _strWriter.Dispose();
_strWriter = new StringWriter();
XmlWriter cw = WriterHelper.Create(_strWriter, wSettings);
XmlWriterSettings cws = settings.Clone();
cws.CheckCharacters = true;
w = WriterHelper.Create(cw, cws);
break;
default:
throw new Exception("Unknown writer type");
}
return w;
}
private void VerifyOutput(string expected)
{
string actual = _strWriter.ToString();
if (actual != expected)
{
CError.WriteLineIgnore("Expected: " + expected);
CError.WriteLineIgnore("Actual: " + actual);
CError.Compare(false, "Expected and actual output differ!");
}
}
//[Variation(Desc = "NamespaceHandling Default value - NamespaceHandling.Default")]
public int NS_Handling_1()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
CError.Compare(wSettings.NamespaceHandling, NamespaceHandling.Default, "Incorect default value for XmlWriterSettings.NamespaceHandling");
using (XmlWriter w = CreateMemWriter(wSettings))
{
CError.Compare(w.Settings.NamespaceHandling, NamespaceHandling.Default, "Incorect default value for XmlWriter.Settings.NamespaceHandling");
}
return TEST_PASS;
}
//[Variation(Desc = "XmlWriter creation with NamespaceHandling.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "XmlWriter creation with NamespaceHandling.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_2()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
using (XmlWriter w = CreateMemWriter(wSettings))
{
CError.Compare(w != null, "XmlWriter creation failed");
CError.Compare(w.Settings.NamespaceHandling, (NamespaceHandling)this.CurVariation.Param, "Invalid NamespaceHandling assignment");
}
return TEST_PASS;
}
//[Variation(Desc = "NamespaceHandling = NamespaceHandling.Default | NamespaceHandling.OmitDuplicates")]
public int NS_Handling_2a()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = NamespaceHandling.Default | NamespaceHandling.OmitDuplicates;
using (XmlWriter w = CreateMemWriter(wSettings))
{
CError.Compare(w.Settings.NamespaceHandling, NamespaceHandling.OmitDuplicates, "Invalid NamespaceHandling assignment");
}
return TEST_PASS;
}
//[Variation(Desc = "NamespaceHandling override with Default.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "NamespaceHandling override with Default.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_3()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = NamespaceHandling.OmitDuplicates;
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
using (XmlWriter w = CreateMemWriter(wSettings))
{
wSettings.NamespaceHandling = NamespaceHandling.Default;
CError.Compare(w != null, "XmlWriter creation failed");
CError.Compare(w.Settings.NamespaceHandling, (NamespaceHandling)this.CurVariation.Param, "Invalid NamespaceHandling assignment");
}
return TEST_PASS;
}
//[Variation(Desc = "NamespaceHandling override with negativeVal.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "NamespaceHandling override with negativeVal.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_3a()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
try
{
wSettings.NamespaceHandling = (NamespaceHandling)(-1);
CError.Compare(false, "Failed");
}
catch (ArgumentOutOfRangeException)
{
try
{
wSettings.NamespaceHandling = (NamespaceHandling)(999);
CError.Compare(false, "Failed2");
}
catch (ArgumentOutOfRangeException) { }
}
using (XmlWriter w = CreateMemWriter(wSettings))
{
CError.Compare(w != null, "XmlWriter creation failed");
CError.Compare(w.Settings.NamespaceHandling, (NamespaceHandling)this.CurVariation.Param, "Invalid NamespaceHandling assignment");
}
return TEST_PASS;
}
//[Variation(Desc = "1.NamespaceHandling.Default", Params = new object[] { NamespaceHandling.Default, "<root><p:foo xmlns:p=\"uri\"><a xmlns:p=\"uri\" /></p:foo></root>",null })]
//[Variation(Desc = "1.NamespaceHandling.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, "<root><p:foo xmlns:p=\"uri\"><a xmlns:p=\"uri\" /></p:foo></root>","<root><p:foo xmlns:p=\"uri\"><a /></p:foo></root>" })]
//[Variation(Desc = "2.NamespaceHandling.Default", Params = new object[] { NamespaceHandling.Default, "<root><foo xmlns=\"uri\"><a xmlns=\"uri\" /></foo></root>", null })]
//[Variation(Desc = "2.NamespaceHandling.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, "<root><foo xmlns=\"uri\"><a xmlns=\"uri\" /></foo></root>","<root><foo xmlns=\"uri\"><a /></foo></root>" })]
//[Variation(Desc = "3.NamespaceHandling.Default", Params = new object[] { NamespaceHandling.Default, "<root><p:foo xmlns:p=\"uri\"><a xmlns:p=\"uriOther\" /></p:foo></root>",null })]
//[Variation(Desc = "3.NamespaceHandling.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, "<root><p:foo xmlns:p=\"uri\"><a xmlns:p=\"uriOther\" /></p:foo></root>",null })]
//[Variation(Desc = "4.NamespaceHandling.Default", Params = new object[] { NamespaceHandling.Default, "<root><p:foo xmlns:p=\"uri\"><a xmlns:pOther=\"uri\" /></p:foo></root>",null })]
//[Variation(Desc = "4.NamespaceHandling.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, "<root><p:foo xmlns:p=\"uri\"><a xmlns:pOther=\"uri\" /></p:foo></root>",null })]
//[Variation(Desc = "5.NamespaceHandling.Default", Params = new object[] { NamespaceHandling.Default, "<root xmlns:p=\"uri\"><p:foo><p:a xmlns:p=\"uri\" /></p:foo></root>", null })]
//[Variation(Desc = "5.NamespaceHandling.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, "<root xmlns:p=\"uri\"><p:foo><p:a xmlns:p=\"uri\" /></p:foo></root>", "<root xmlns:p=\"uri\"><p:foo><p:a /></p:foo></root>" })]
//[Variation(Desc = "6.NamespaceHandling.Default", Params = new object[] { NamespaceHandling.Default, "<root xmlns:p=\"uri\"><p:foo><a xmlns:p=\"uri\" /></p:foo></root>", null })]
//[Variation(Desc = "6.NamespaceHandling.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, "<root xmlns:p=\"uri\"><p:foo><a xmlns:p=\"uri\" /></p:foo></root>","<root xmlns:p=\"uri\"><p:foo><a /></p:foo></root>" })]
//[Variation(Desc = "7.NamespaceHandling.Default", Params = new object[] { NamespaceHandling.Default, "<root><p xmlns:xml=\"http://www.w3.org/XML/1998/namespace\" /></root>", null })]
//[Variation(Desc = "7.NamespaceHandling.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, "<root><p xmlns:xml=\"http://www.w3.org/XML/1998/namespace\" /></root>","<root><p /></root>" })]
//[Variation(Desc = "8.NamespaceHandling.Default NS Redefinition.Default", Params = new object[] { NamespaceHandling.Default, "<a xmlns=\"p1\"><b xmlns=\"p2\"><c xmlns=\"p1\" /></b><d xmlns=\"\"><e xmlns=\"p1\"><f xmlns=\"\" /></e></d></a>", null })]
//[Variation(Desc = "8.NamespaceHandling.Default NS Redefinition.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, "<a xmlns=\"p1\"><b xmlns=\"p2\"><c xmlns=\"p1\" /></b><d xmlns=\"\"><e xmlns=\"p1\"><f xmlns=\"\" /></e></d></a>", null })]
//[Variation(Desc = "9.Unused namespace declarations.Default", Params = new object[] { NamespaceHandling.Default, "<root> <elem1 xmlns=\"urn:namespace\" att1=\"foo\" /></root>", null })]
//[Variation(Desc = "9.Unused namespace declarations.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, "<root> <elem1 xmlns=\"urn:namespace\" att1=\"foo\" /></root>", null })]
//[Variation(Desc = "10.NamespaceHandling.Same NS.Diff prefix.Default", Params = new object[] { NamespaceHandling.Default, "<a xmlns:p=\"p1\"><b xmlns:a=\"p1\"><c xmlns:b=\"p1\" /></b></a>", null })]
//[Variation(Desc = "10.NamespaceHandling.Same NS.Diff prefix.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, "<a xmlns:p=\"p1\"><b xmlns:a=\"p1\"><c xmlns:b=\"p1\" /></b></a>", null })]
//[Variation(Desc = "11.NamespaceHandling.Diff NS.Same prefix.Default", Params = new object[] { NamespaceHandling.Default, "<a xmlns:p=\"p1\"><b xmlns:p=\"p2\"><c xmlns:p=\"p3\" /></b></a>", null })]
//[Variation(Desc = "11.NamespaceHandling.Diff NS.Same prefix.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, "<a xmlns:p=\"p1\"><b xmlns:p=\"p2\"><c xmlns:p=\"p3\" /></b></a>", null })]
//[Variation(Desc = "12.NamespaceHandling.NS Redefinition.Unused NS.Default", Params = new object[] { NamespaceHandling.Default, "<a xmlns:p=\"p1\"><b xmlns:p=\"p2\"><c xmlns:p=\"p1\" /></b></a>", null })]
//[Variation(Desc = "12.NamespaceHandling.NS Redefinition.Unused NS.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, "<a xmlns:p=\"p1\"><b xmlns:p=\"p2\"><c xmlns:p=\"p1\" /></b></a>", null })]
public int NS_Handling_3b()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Params[0];
string xml = (string)this.CurVariation.Params[1];
string exp = (string)this.CurVariation.Params[2];
using (XmlReader r = ReaderHelper.Create(new StringReader(xml)))
{
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteNode(r, false);
w.Dispose();
VerifyOutput(exp == null ? xml : exp);
}
}
return TEST_PASS;
}
//[Variation(Desc = "NamespaceHandling wrap with Default.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "NamespaceHandling wrap with Default.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_4a()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
using (XmlWriter ww = CreateMemWriter(wSettings))
{
XmlWriterSettings ws = wSettings.Clone();
ws.NamespaceHandling = NamespaceHandling.Default;
ws.CheckCharacters = true;
using (XmlWriter w = WriterHelper.Create(ww, ws))
{
CError.Compare(w != null, "XmlWriter creation failed");
CError.Compare(w.Settings.NamespaceHandling, (NamespaceHandling)this.CurVariation.Param, "Invalid NamespaceHandling assignment");
}
}
return TEST_PASS;
}
//[Variation(Desc = "NamespaceHandling wrap with OmitDuplicates.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "NamespaceHandling wrap with OmitDuplicates.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_4b()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
using (XmlWriter ww = CreateMemWriter(wSettings))
{
XmlWriterSettings ws = wSettings.Clone();
ws.NamespaceHandling = NamespaceHandling.OmitDuplicates;
ws.CheckCharacters = true;
using (XmlWriter w = WriterHelper.Create(ww, ws))
{
CError.Compare(w != null, "XmlWriter creation failed");
CError.Compare(w.Settings.NamespaceHandling, (NamespaceHandling)this.CurVariation.Param, "Invalid NamespaceHandling assignment");
}
}
return TEST_PASS;
}
//[Variation(Desc = "XmlWriter.WriteStartElement() should inspect attributes before emitting the element tag.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "XmlWriter.WriteStartElement() should inspect attributes before emitting the element tag.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_5()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteStartElement("root", "uri");
w.WriteStartAttribute("xmlns", "p", "http://www.w3.org/2000/xmlns/");
w.WriteString("uri");
w.WriteEndElement();
}
VerifyOutput("<root xmlns:p=\"uri\" xmlns=\"uri\" />");
return TEST_PASS;
}
//[Variation(Desc = "WriteStartElement,AttrString with null prefix.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "WriteStartElement,AttrString with null prefix.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_6()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteStartElement(null, "e", "ns");
w.WriteAttributeString(null, "attr", "ns", "val");
w.WriteElementString(null, "el", "ns", "val");
}
VerifyOutput("<e p1:attr=\"val\" xmlns:p1=\"ns\" xmlns=\"ns\"><p1:el>val</p1:el></e>");
return TEST_PASS;
}
//[Variation(Desc = "WriteStartElement,AttrString with empty prefix.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "WriteStartElement,AttrString with empty prefix.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_7()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteStartElement(String.Empty, "e", "ns");
w.WriteAttributeString(String.Empty, "attr", "ns", "val");
w.WriteElementString(String.Empty, "el", "ns", "val");
}
VerifyOutput("<e p1:attr=\"val\" xmlns:p1=\"ns\" xmlns=\"ns\"><el>val</el></e>");
return TEST_PASS;
}
//[Variation(Desc = "WriteStartElement,AttrString with not null prefix and namespace.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "WriteStartElement,AttrString with not null prefix and namespace.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_8()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteStartElement("a", "e", "ns");
w.WriteAttributeString("a", "attr", "ns", "val");
w.WriteElementString("a", "el", "ns", "val");
}
VerifyOutput("<a:e a:attr=\"val\" xmlns:a=\"ns\"><a:el>val</a:el></a:e>");
return TEST_PASS;
}
//[Variation(Desc = "WriteStartElement,AttrString without prefix.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "WriteStartElement,AttrString without prefix.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_9()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteStartElement("e", "ns");
w.WriteAttributeString("attr", "ns", "val");
w.WriteElementString("el", "ns", "val");
}
VerifyOutput("<e p1:attr=\"val\" xmlns:p1=\"ns\" xmlns=\"ns\"><p1:el>val</p1:el></e>");
return TEST_PASS;
}
//[Variation(Desc = "WriteStartElement,AttrString with null namespace,prefix.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "WriteStartElement,AttrString with null namespace,prefix.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_10()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteStartElement(null, "e", null);
w.WriteAttributeString(null, "attr", null, "val");
w.WriteElementString(null, "el", null, "val");
}
VerifyOutput("<e attr=\"val\"><el>val</el></e>");
return TEST_PASS;
}
//[Variation(Desc = "WriteStartElement,AttrString with empty namespace,prefix.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "WriteStartElement,AttrString with empty namespace,prefix.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_11()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteStartElement(String.Empty, "e", String.Empty);
w.WriteAttributeString(String.Empty, "attr", String.Empty, "val");
w.WriteElementString(String.Empty, "el", String.Empty, "val");
}
VerifyOutput("<e attr=\"val\"><el>val</el></e>");
return TEST_PASS;
}
//[Variation(Desc = "WriteStartElement,AttrString without namespace,prefix.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "WriteStartElement,AttrString without namespace,prefix.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_12()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteStartElement("e");
w.WriteAttributeString("attr", "val");
w.WriteElementString("el", "val");
}
VerifyOutput("<e attr=\"val\"><el>val</el></e>");
return TEST_PASS;
}
//[Variation(Desc = "LookupPrefix.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "LookupPrefix.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_16()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteStartElement("a", "foo", "b");
CError.Compare(w.LookupPrefix("foo"), null, "FailedEl");
w.WriteAttributeString("a", "foo", "b");
CError.Compare(w.LookupPrefix("foo"), "p1", "FailedAttr");
w.WriteElementString("e", "foo", "b");
CError.Compare(w.LookupPrefix("foo"), "p1", "FailedEl");
}
VerifyOutput("<a:foo p1:a=\"b\" xmlns:p1=\"foo\" xmlns:a=\"b\"><p1:e>b</p1:e></a:foo>");
return TEST_PASS;
}
//[Variation(Desc = "WriteAttributeString with dup.namespace,w/o prefix.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "WriteAttributeString with dup.namespace,w/o prefix.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_17()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteDocType("a", null, null, "<!ATTLIST Root a CDATA #IMPLIED>");
w.WriteStartElement("Root");
for (int i = 0; i < 1000; i++)
{
w.WriteAttributeString("a", "n" + i, "val");
}
try
{
w.WriteAttributeString("a", "n" + 999, "val");
CError.Compare(false, "Failed");
}
catch (XmlException e) { CError.WriteLine(e); return TEST_PASS; }
}
return TEST_FAIL;
}
//[Variation(Desc = "WriteAttributeString with prefix bind to the same ns.Default", Params = new object[] { NamespaceHandling.Default, true })]
//[Variation(Desc = "WriteAttributeString with prefix bind to the same ns.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, true })]
//[Variation(Desc = "WriteElementString with prefix bind to the same ns.Default", Params = new object[] { NamespaceHandling.Default, false })]
//[Variation(Desc = "WriteElementString with prefix bind to the same ns.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, false })]
public int NS_Handling_17a()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Params[0];
bool isAttr = (bool)this.CurVariation.Params[1];
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteDocType("a", null, null, "<!ATTLIST Root a CDATA #IMPLIED>");
w.WriteStartElement("Root");
for (int i = 0; i < 10; i++)
{
if (isAttr)
w.WriteAttributeString("p", "a" + i, "n", "val");
else
w.WriteElementString("p", "a" + i, "n", "val");
}
}
string exp = isAttr ?
"<!DOCTYPE a [<!ATTLIST Root a CDATA #IMPLIED>]><Root p:a0=\"val\" p:a1=\"val\" p:a2=\"val\" p:a3=\"val\" p:a4=\"val\" p:a5=\"val\" p:a6=\"val\" p:a7=\"val\" p:a8=\"val\" p:a9=\"val\" xmlns:p=\"n\" />" :
"<!DOCTYPE a [<!ATTLIST Root a CDATA #IMPLIED>]><Root><p:a0 xmlns:p=\"n\">val</p:a0><p:a1 xmlns:p=\"n\">val</p:a1><p:a2 xmlns:p=\"n\">val</p:a2><p:a3 xmlns:p=\"n\">val</p:a3><p:a4 xmlns:p=\"n\">val</p:a4><p:a5 xmlns:p=\"n\">val</p:a5><p:a6 xmlns:p=\"n\">val</p:a6><p:a7 xmlns:p=\"n\">val</p:a7><p:a8 xmlns:p=\"n\">val</p:a8><p:a9 xmlns:p=\"n\">val</p:a9></Root>";
VerifyOutput(exp);
return TEST_PASS;
}
//[Variation(Desc = "WriteAttributeString with prefix bind to default ns.Default", Params = new object[] { NamespaceHandling.Default, true })]
//[Variation(Desc = "WriteAttributeString with prefix bind to default ns.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, true })]
//[Variation(Desc = "WriteElementString with prefix bind to default ns.Default", Params = new object[] { NamespaceHandling.Default, false })]
//[Variation(Desc = "WriteElementString with prefix bind to default ns.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, false })]
public int NS_Handling_17b()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Params[0];
bool isAttr = (bool)this.CurVariation.Params[1];
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteStartElement("Root");
for (int i = 0; i < 5; i++)
{
if (isAttr)
w.WriteAttributeString("p", "a" + i, "xmlns", "val");
else
w.WriteElementString("p", "a" + i, "xmlns", "val");
}
}
string exp = isAttr ?
"<Root p:a0=\"val\" p:a1=\"val\" p:a2=\"val\" p:a3=\"val\" p:a4=\"val\" xmlns:p=\"xmlns\" />" :
"<Root><p:a0 xmlns:p=\"xmlns\">val</p:a0><p:a1 xmlns:p=\"xmlns\">val</p:a1><p:a2 xmlns:p=\"xmlns\">val</p:a2><p:a3 xmlns:p=\"xmlns\">val</p:a3><p:a4 xmlns:p=\"xmlns\">val</p:a4></Root>";
VerifyOutput(exp);
return TEST_PASS;
}
//[Variation(Desc = "WriteAttributeString with prefix bind to non-default ns.dup.namespace.Default", Params = new object[] { NamespaceHandling.Default, true })]
//[Variation(Desc = "WriteAttributeString with prefix bind to non-default ns.dup.namespace.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, true })]
//[Variation(Desc = "WriteElementString with prefix bind to non-default ns.dup.namespace.Default", Params = new object[] { NamespaceHandling.Default, false })]
//[Variation(Desc = "WriteElementString with prefix bind to non-default ns.dup.namespace.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, false })]
public int NS_Handling_17c()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Params[0];
bool isAttr = (bool)this.CurVariation.Params[1];
XmlWriter w = CreateMemWriter(wSettings);
w.WriteStartElement("Root");
for (int i = 0; i < 5; i++)
{
if (isAttr)
w.WriteAttributeString("p" + i, "a", "n" + i, "val" + i);
else
w.WriteElementString("p" + i, "a", "n" + i, "val" + i);
}
try
{
if (isAttr)
{
w.WriteAttributeString("p", "a", "n" + 4, "val");
CError.Compare(false, "Failed");
}
else
w.WriteElementString("p", "a", "n" + 4, "val");
}
catch (XmlException) { }
finally
{
w.Dispose();
string exp = isAttr ?
"<Root p0:a=\"val0\" p1:a=\"val1\" p2:a=\"val2\" p3:a=\"val3\" p4:a=\"val4\"" :
"<Root><p0:a xmlns:p0=\"n0\">val0</p0:a><p1:a xmlns:p1=\"n1\">val1</p1:a><p2:a xmlns:p2=\"n2\">val2</p2:a><p3:a xmlns:p3=\"n3\">val3</p3:a><p4:a xmlns:p4=\"n4\">val4</p4:a><p:a xmlns:p=\"n4\">val</p:a></Root>";
VerifyOutput(exp);
}
return TEST_PASS;
}
//[Variation(Desc = "WriteAttributeString with prefix bind to ns uri.Default", Params = new object[] { NamespaceHandling.Default, true })]
//[Variation(Desc = "WriteAttributeString with prefix bind to ns uri.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, true })]
//[Variation(Desc = "WriteElementString with prefix bind to ns uri.Default", Params = new object[] { NamespaceHandling.Default, false })]
//[Variation(Desc = "WriteElementString with prefix bind to ns uri.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, false })]
public int NS_Handling_17d()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Params[0];
bool isAttr = (bool)this.CurVariation.Params[1];
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteStartElement("Root");
for (int i = 0; i < 5; i++)
{
if (isAttr)
{
w.WriteAttributeString("xml", "a" + i, "http://www.w3.org/XML/1998/namespace", "val");
w.WriteAttributeString("xmlns", "a" + i, "http://www.w3.org/2000/xmlns/", "val");
}
else
{
w.WriteElementString("xml", "a" + i, "http://www.w3.org/XML/1998/namespace", "val");
}
}
}
string exp = isAttr ?
"<Root xml:a0=\"val\" xmlns:a0=\"val\" xml:a1=\"val\" xmlns:a1=\"val\" xml:a2=\"val\" xmlns:a2=\"val\" xml:a3=\"val\" xmlns:a3=\"val\" xml:a4=\"val\" xmlns:a4=\"val\" />" :
"<Root><xml:a0>val</xml:a0><xml:a1>val</xml:a1><xml:a2>val</xml:a2><xml:a3>val</xml:a3><xml:a4>val</xml:a4></Root>";
VerifyOutput(exp); return TEST_PASS;
}
//[Variation(Desc = "WriteAttributeString with ns uri.Default", Params = new object[] { NamespaceHandling.Default, true })]
//[Variation(Desc = "WriteAttributeString with ns uri.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, true })]
//[Variation(Desc = "WriteElementString with ns uri.Default", Params = new object[] { NamespaceHandling.Default, false })]
//[Variation(Desc = "WriteElementString with ns uri.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, false })]
public int NS_Handling_17e()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Params[0];
bool isAttr = (bool)this.CurVariation.Params[1];
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteStartElement("Root");
for (int i = 0; i < 5; i++)
{
if (isAttr)
w.WriteAttributeString("a" + i, "http://www.w3.org/XML/1998/namespace", "val");
else
w.WriteElementString("a" + i, "http://www.w3.org/XML/1998/namespace", "val");
}
}
string exp = isAttr ?
"<Root xml:a0=\"val\" xml:a1=\"val\" xml:a2=\"val\" xml:a3=\"val\" xml:a4=\"val\" />" :
"<Root><xml:a0>val</xml:a0><xml:a1>val</xml:a1><xml:a2>val</xml:a2><xml:a3>val</xml:a3><xml:a4>val</xml:a4></Root>";
VerifyOutput(exp); return TEST_PASS;
}
//[Variation(Desc = "WriteAttribute/ElemString with prefixes.namespace.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "WriteAttribute/ElemString with prefixes.namespace.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_18()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteStartElement("test");
w.WriteAttributeString("p", "a1", "ns1", "v");
w.WriteStartElement("base");
w.WriteAttributeString("a2", "ns1", "v");
w.WriteAttributeString("p", "a3", "ns2", "v");
w.WriteElementString("p", "e", "ns2", "v");
w.WriteEndElement();
w.WriteEndElement();
}
string exp = "<test p:a1=\"v\" xmlns:p=\"ns1\"><base p:a2=\"v\" p4:a3=\"v\" xmlns:p4=\"ns2\"><p:e xmlns:p=\"ns2\">v</p:e></base></test>";
VerifyOutput(exp); return TEST_PASS;
}
//[Variation(Desc = "WriteAttribute/ElemString with xmlns:xml,space,lang.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "WriteAttribute/ElemString with xmlns:xml,space,lang.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_19()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteStartElement("Root");
w.WriteAttributeString("xmlns", "xml", null, "http://www.w3.org/XML/1998/namespace");
w.WriteAttributeString("xmlns", "space", null, "preserve");
w.WriteAttributeString("xmlns", "lang", null, "chs");
w.WriteElementString("xml", "lang", null, "jpn");
w.WriteElementString("xml", "space", null, "default");
w.WriteElementString("xml", "xml", null, "http://www.w3.org/XML/1998/namespace");
w.WriteEndElement();
}
string exp = ((NamespaceHandling)this.CurVariation.Param == NamespaceHandling.OmitDuplicates) ?
"<Root xmlns:space=\"preserve\" xmlns:lang=\"chs\"><xml:lang>jpn</xml:lang><xml:space>default</xml:space><xml:xml>http://www.w3.org/XML/1998/namespace</xml:xml></Root>" :
"<Root xmlns:xml=\"http://www.w3.org/XML/1998/namespace\" xmlns:space=\"preserve\" xmlns:lang=\"chs\"><xml:lang>jpn</xml:lang><xml:space>default</xml:space><xml:xml>http://www.w3.org/XML/1998/namespace</xml:xml></Root>";
VerifyOutput(exp); return TEST_PASS;
}
//[Variation(Desc = "WriteAttributeString with null val,ns.attr=xmlns:xml.Default", Params = new object[] { NamespaceHandling.Default, "xmlns", "xml", true })]
//[Variation(Desc = "WriteAttributeString with null val,ns.attr=xmlns:xml.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, "xmlns", "xml", true })]
//[Variation(Desc = "WriteAttributeString with null val,ns.elem=xmlns:xml.Default", Params = new object[] { NamespaceHandling.Default, "xmlns", "xml", false })]
//[Variation(Desc = "WriteAttributeString with null val,ns.elem=xmlns:xml.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, "xmlns", "xml", false })]
//[Variation(Desc = "WriteAttributeString with null val,ns.attr=xml:space.Default", Params = new object[] { NamespaceHandling.Default, "xml", "space", true })]
//[Variation(Desc = "WriteAttributeString with null val,ns.attr=xml:space.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, "xml", "space", true })]
//[Variation(Desc = "WriteAttributeString with null val,ns.elem=xmlns:space.Default", Params = new object[] { NamespaceHandling.Default, "xmlns", "space", false })]
//[Variation(Desc = "WriteAttributeString with null val,ns.elem=xmlns:space.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, "xmlns", "space", false })]
//[Variation(Desc = "WriteAttributeString with null val,ns.attr=xmlns:lang.Default", Params = new object[] { NamespaceHandling.Default, "xmlns", "lang", true })]
//[Variation(Desc = "WriteAttributeString with null val,ns.attr=xmlns:lang.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, "xmlns", "lang", true })]
//[Variation(Desc = "WriteAttributeString with null val,ns.elem=xmlns:lang.Default", Params = new object[] { NamespaceHandling.Default, "xmlns", "lang", false })]
//[Variation(Desc = "WriteAttributeString with null val,ns.elem=xmlns:lang.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, "xmlns", "lang", false })]
public int NS_Handling_19a()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Params[0];
string prefix = (string)this.CurVariation.Params[1];
string name = (string)this.CurVariation.Params[2];
bool isAttr = (bool)this.CurVariation.Params[3];
XmlWriter w = CreateMemWriter(wSettings);
w.WriteStartElement("Root");
try
{
if (isAttr)
w.WriteAttributeString(prefix, name, null, null);
else
w.WriteElementString(prefix, name, null, null);
CError.Compare(false, "error");
}
catch (ArgumentException e) { CError.WriteLine(e); CError.Compare(w.WriteState, WriteState.Error, "state"); }
finally
{
w.Dispose();
CError.Compare(w.WriteState, WriteState.Closed, "state");
}
return TEST_PASS;
}
//[Variation(Desc = "WriteAttributeString in error state.Default", Params = new object[] { NamespaceHandling.Default, true })]
//[Variation(Desc = "WriteAttributeString in error state.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, true })]
//[Variation(Desc = "WriteElementString in error state.Default", Params = new object[] { NamespaceHandling.Default, false })]
//[Variation(Desc = "WriteElementString in error state.OmitDuplicates", Params = new object[] { NamespaceHandling.OmitDuplicates, false })]
public int NS_Handling_19b()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Params[0];
bool isAttr = (bool)this.CurVariation.Params[1];
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteStartElement("Root");
try
{
if (isAttr)
w.WriteAttributeString("xmlns", "xml", null, null);
else
w.WriteElementString("xmlns", "xml", null, null);
}
catch (ArgumentException e) { CError.WriteLine(e.Message); }
}
string exp = isAttr ? "<Root" : "<Root><xmlns:xml";
VerifyOutput(exp); return TEST_PASS;
}
//[Variation(Desc = "WriteAttributeString,StartElement with hello:world.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "WriteAttributeString,StartElement with hello:worldl.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_20()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteStartElement("d", "Data", "http://example.org/data");
w.WriteStartElement("g", "GoodStuff", "http://example.org/data/good");
w.WriteAttributeString("hello", "world");
w.WriteEndElement();
w.WriteStartElement("BadStuff", "http://example.org/data/bad");
w.WriteAttributeString("hello", "world");
w.WriteEndElement();
w.WriteEndElement();
}
VerifyOutput("<d:Data xmlns:d=\"http://example.org/data\"><g:GoodStuff hello=\"world\" xmlns:g=\"http://example.org/data/good\" /><BadStuff hello=\"world\" xmlns=\"http://example.org/data/bad\" /></d:Data>");
return TEST_PASS;
}
//[Variation(Desc = "WriteStartAttribute(xml:lang),WriteRaw(0,0).Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "WriteStartAttribute(xml:lang),WriteRaw(0,0).OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_21()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
string strraw = "abc";
char[] buffer = strraw.ToCharArray();
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteStartElement("root");
w.WriteStartAttribute("xml", "lang", null);
w.WriteRaw(buffer, 0, 0);
w.WriteRaw(buffer, 1, 1);
w.WriteRaw(buffer, 0, 2);
w.WriteEndElement();
}
VerifyOutput("<root xml:lang=\"bab\" />"); return TEST_PASS;
}
//[Variation(Desc = "WriteStartAttribute(xml:lang),WriteBinHex(0,0).Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "WriteStartAttribute(xml:lang),WriteBinHex(0,0).OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_22()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
byte[] buffer = new byte[] { (byte)'a', (byte)'b', (byte)'c' };
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteStartElement("root");
w.WriteStartAttribute("xml", "lang", null);
w.WriteBinHex(buffer, 0, 0);
w.WriteBinHex(buffer, 1, 1);
w.WriteBinHex(buffer, 0, 2);
w.WriteEndElement();
}
VerifyOutput("<root xml:lang=\"626162\" />"); return TEST_PASS;
}
//[Variation(Desc = "WriteStartAttribute(xml:lang),WriteBase64(0,0).Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "WriteStartAttribute(xml:lang),WriteBase64(0,0).OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_23()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
byte[] buffer = new byte[] { (byte)'a', (byte)'b', (byte)'c' };
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteStartElement("root");
w.WriteStartAttribute("a", "b", null);
w.WriteBase64(buffer, 0, 0);
w.WriteBase64(buffer, 1, 1);
w.WriteBase64(buffer, 0, 2);
w.WriteEndElement();
}
VerifyOutput("<root b=\"YmFi\" />"); return TEST_PASS;
}
//[Variation(Desc = "Duplicate attribute conflict when the namespace decl. is being omitted.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "Duplicate attribute conflict when the namespace decl. is being omitted.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_24()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
XmlWriter w = CreateMemWriter(wSettings);
byte[] buffer = new byte[] { (byte)'a', (byte)'b', (byte)'c' };
w.WriteStartElement("A");
w.WriteAttributeString("xmlns", "p", null, "ns1");
w.WriteStartElement("B");
w.WriteAttributeString("xmlns", "p", null, "ns1"); // will be omitted
try
{
w.WriteAttributeString("xmlns", "p", null, "ns1");
CError.Compare(false, "error");
}
catch (XmlException e) { CError.WriteLine(e); }
finally
{
w.Dispose();
VerifyOutput((NamespaceHandling)this.CurVariation.Param == NamespaceHandling.OmitDuplicates ? "<A xmlns:p=\"ns1\"><B" : "<A xmlns:p=\"ns1\"><B xmlns:p=\"ns1\"");
}
return TEST_PASS;
}
//[Variation(Desc = "1.Namespace redefinition.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "1.Namespace redefinition.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_25()
{
string xml = "<employees xmlns:email=\"http://www.w3c.org/some-spec-3.2\">" +
"<employee><name>Bob Worker</name><address xmlns=\"http://postal.ie/spec-1.0\"><street>Nassau Street</street>" +
"<city>Dublin 3</city><country>Ireland</country></address><email:address>bob.worker@hisjob.ie</email:address>" +
"</employee></employees>";
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Params[0];
using (XmlReader r = ReaderHelper.Create(new StringReader(xml)))
{
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteNode(r, false);
}
}
VerifyOutput(xml); return TEST_PASS;
}
//[Variation(Desc = "2.Default Namespace redefinition.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "2.Default Namespace redefinition.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_25a()
{
string xml = "<root><elem1 xmlns=\"urn:URN1\" xmlns:ns1=\"urn:URN2\"><ns1:childElem1><grandChild1 /></ns1:childElem1><childElem2><grandChild2 /></childElem2></elem1></root>";
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Params[0];
using (XmlReader r = ReaderHelper.Create(new StringReader(xml)))
{
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteNode(r, false);
}
}
VerifyOutput(xml); return TEST_PASS;
}
//[Variation(Desc = "Namespaces with the same prefix different NS value.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "Namespaces with the same prefix different NS value.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_26()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteStartElement("p", "e", "uri1");
w.WriteAttributeString("p", "e", "uri1", "val");
w.WriteAttributeString("p", "e", "uri2", "val");
w.WriteElementString("p", "e", "uri1", "val");
w.WriteElementString("p", "e", "uri2", "val");
}
VerifyOutput("<p:e p:e=\"val\" p1:e=\"val\" xmlns:p1=\"uri2\" xmlns:p=\"uri1\"><p:e>val</p:e><p:e xmlns:p=\"uri2\">val</p:e></p:e>");
return TEST_PASS;
}
//[Variation(Desc = "Namespaces with the same NS value but different prefixes.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "Namespaces with the same NS value but different prefixes.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_27()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteStartElement("p1", "e", "uri");
w.WriteAttributeString("p1", "e", "uri", "val");
w.WriteAttributeString("p2", "e2", "uri", "val");
w.WriteElementString("p1", "e", "uri", "val");
w.WriteElementString("p2", "e", "uri", "val");
}
VerifyOutput("<p1:e p1:e=\"val\" p2:e2=\"val\" xmlns:p2=\"uri\" xmlns:p1=\"uri\"><p1:e>val</p1:e><p2:e>val</p2:e></p1:e>");
return TEST_PASS;
}
//[Variation(Desc = "Reader got the namespaces as a fixed value from DTD.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "Reader got the namespaces as a fixed value from DTD.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_29()
{
string xml = "<!DOCTYPE root [ <!ELEMENT root ANY > <!ELEMENT ns1:elem1 ANY >" +
"<!ATTLIST ns1:elem1 xmlns CDATA #FIXED \"urn:URN2\"> <!ATTLIST ns1:elem1 xmlns:ns1 CDATA #FIXED \"urn:URN1\">" +
"<!ELEMENT childElem1 ANY > <!ATTLIST childElem1 childElem1Att1 CDATA #FIXED \"attributeValue\">]>" +
"<root> <ns1:elem1 xmlns:ns1=\"urn:URN1\" xmlns=\"urn:URN2\"> text node in elem1 <![CDATA[<doc> content </doc>]]>" +
"<childElem1 childElem1Att1=\"attributeValue\"> <?PI in childElem1 ?> </childElem1> <!-- Comment in elem1 --> & </ns1:elem1></root>";
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Params[0];
XmlReaderSettings rs = new XmlReaderSettings();
using (XmlReader r = ReaderHelper.Create(new StringReader(xml), rs))
{
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteNode(r, false);
}
}
VerifyOutput(xml); return TEST_PASS;
}
//[Variation(Desc = "Reader got the namespaces as default attribute from DTD.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "Reader got the namespaces as default attribute from DTD.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_30()
{
string xml = "<!DOCTYPE doc " +
"[<!ELEMENT doc ANY>" +
"<!ELEMENT test1 (#PCDATA)>" +
"<!ELEMENT test2 ANY>" +
"<!ELEMENT test3 (#PCDATA)>" +
"<!ENTITY e1 \"&e2;\">" +
"<!ENTITY e2 \"xmlns:p='x'\">" +
"<!ATTLIST test3 a1 CDATA #IMPLIED>" +
"<!ATTLIST test3 a2 CDATA #IMPLIED>" +
"]>" +
"<doc xmlns:p='&e2;'>" +
" &e2;" +
" <test1 xmlns:p='&e2;'>AA&e2;AA</test1>" +
" <test2 xmlns:p='&e1;'>BB&e1;BB</test2>" +
" <test3 a1=\"&e2;\" a2=\"&e1;\">World</test3>" +
"</doc>";
string exp = ((NamespaceHandling)this.CurVariation.Param == NamespaceHandling.OmitDuplicates) ?
"<!DOCTYPE doc [<!ELEMENT doc ANY><!ELEMENT test1 (#PCDATA)><!ELEMENT test2 ANY><!ELEMENT test3 (#PCDATA)><!ENTITY e1 \"&e2;\"><!ENTITY e2 \"xmlns:p='x'\"><!ATTLIST test3 a1 CDATA #IMPLIED><!ATTLIST test3 a2 CDATA #IMPLIED>]><doc xmlns:p=\"xmlns:p='x'\"> xmlns:p='x' <test1>AAxmlns:p='x'AA</test1> <test2>BBxmlns:p='x'BB</test2> <test3 a1=\"xmlns:p='x'\" a2=\"xmlns:p='x'\">World</test3></doc>" :
"<!DOCTYPE doc [<!ELEMENT doc ANY><!ELEMENT test1 (#PCDATA)><!ELEMENT test2 ANY><!ELEMENT test3 (#PCDATA)><!ENTITY e1 \"&e2;\"><!ENTITY e2 \"xmlns:p='x'\"><!ATTLIST test3 a1 CDATA #IMPLIED><!ATTLIST test3 a2 CDATA #IMPLIED>]><doc xmlns:p=\"xmlns:p='x'\"> xmlns:p='x' <test1 xmlns:p=\"xmlns:p='x'\">AAxmlns:p='x'AA</test1> <test2 xmlns:p=\"xmlns:p='x'\">BBxmlns:p='x'BB</test2> <test3 a1=\"xmlns:p='x'\" a2=\"xmlns:p='x'\">World</test3></doc>";
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Params[0];
XmlReaderSettings rs = new XmlReaderSettings();
using (XmlReader r = ReaderHelper.Create(new StringReader(xml), rs))
{
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteNode(r, false);
}
}
VerifyOutput(exp); return TEST_PASS;
}
//[Variation(Desc = "Reader got the default namespaces as default attribute from DTD.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "Reader got the default namespaces as default attribute from DTD.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_30a()
{
string xml = "<!DOCTYPE doc " +
"[<!ELEMENT doc ANY>" +
"<!ELEMENT test1 (#PCDATA)>" +
"<!ELEMENT test2 ANY>" +
"<!ELEMENT test3 (#PCDATA)>" +
"<!ENTITY e1 \"&e2;\">" +
"<!ENTITY e2 \"xmlns='x'\">" +
"<!ATTLIST test3 a1 CDATA #IMPLIED>" +
"<!ATTLIST test3 a2 CDATA #IMPLIED>" +
"]>" +
"<doc xmlns:p='&e2;'>" +
" &e2;" +
" <test1 xmlns:p='&e2;'>AA&e2;AA</test1>" +
" <test2 xmlns:p='&e1;'>BB&e1;BB</test2>" +
" <test3 a1=\"&e2;\" a2=\"&e1;\">World</test3>" +
"</doc>";
string exp = ((NamespaceHandling)this.CurVariation.Param == NamespaceHandling.OmitDuplicates) ?
"<!DOCTYPE doc [<!ELEMENT doc ANY><!ELEMENT test1 (#PCDATA)><!ELEMENT test2 ANY><!ELEMENT test3 (#PCDATA)><!ENTITY e1 \"&e2;\"><!ENTITY e2 \"xmlns='x'\"><!ATTLIST test3 a1 CDATA #IMPLIED><!ATTLIST test3 a2 CDATA #IMPLIED>]><doc xmlns:p=\"xmlns='x'\"> xmlns='x' <test1>AAxmlns='x'AA</test1> <test2>BBxmlns='x'BB</test2> <test3 a1=\"xmlns='x'\" a2=\"xmlns='x'\">World</test3></doc>" :
"<!DOCTYPE doc [<!ELEMENT doc ANY><!ELEMENT test1 (#PCDATA)><!ELEMENT test2 ANY><!ELEMENT test3 (#PCDATA)><!ENTITY e1 \"&e2;\"><!ENTITY e2 \"xmlns='x'\"><!ATTLIST test3 a1 CDATA #IMPLIED><!ATTLIST test3 a2 CDATA #IMPLIED>]><doc xmlns:p=\"xmlns='x'\"> xmlns='x' <test1 xmlns:p=\"xmlns='x'\">AAxmlns='x'AA</test1> <test2 xmlns:p=\"xmlns='x'\">BBxmlns='x'BB</test2> <test3 a1=\"xmlns='x'\" a2=\"xmlns='x'\">World</test3></doc>";
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Params[0];
XmlReaderSettings rs = new XmlReaderSettings();
using (XmlReader r = ReaderHelper.Create(new StringReader(xml), rs))
{
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteNode(r, false);
}
}
VerifyOutput(exp); return TEST_PASS;
}
//[Variation(Desc = "XmlTextWriter : Wrong prefix management if the same prefix is used at inner level.Default", Param = NamespaceHandling.Default)]
//[Variation(Desc = "XmlTextWriter : Wrong prefix management if the same prefix is used at inner level.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)]
public int NS_Handling_31()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Param;
using (XmlWriter w = CreateMemWriter(wSettings))
{
w.WriteStartElement("test");
w.WriteAttributeString("p", "a1", "ns1", "v");
w.WriteStartElement("base");
w.WriteAttributeString("a2", "ns1", "v");
w.WriteAttributeString("p", "a3", "ns2", "v");
w.WriteEndElement();
w.WriteEndElement();
}
VerifyOutput("<test p:a1=\"v\" xmlns:p=\"ns1\"><base p:a2=\"v\" p4:a3=\"v\" xmlns:p4=\"ns2\" /></test>");
return TEST_PASS;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Imported.PeanutButter.Utils;
using NExpect.Exceptions;
using NExpect.Implementations;
using NExpect.Interfaces;
using static NExpect.Implementations.MessageHelpers;
// ReSharper disable UsePatternMatching
// ReSharper disable PossibleMultipleEnumeration
namespace NExpect.MatcherLogic
{
/// <summary>
/// Provides extension methods to add matchers to continuations which support it
/// </summary>
public static class AddMatcherExtensions
{
/// <summary>
/// Simplifies adding matchers which also include a context switch
/// </summary>
/// <param name="continuation"></param>
/// <param name="matcher"></param>
/// <typeparam name="TCurrent"></typeparam>
/// <typeparam name="TNext"></typeparam>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public static IMore<TNext> AddMatcher<TCurrent, TNext>(
this ICanAddMatcher<TCurrent> continuation,
Func<TCurrent, IMatcherResultWithNext<TNext>> matcher
)
{
var result = AddMatcherPrivate(continuation, matcher)
as IMatcherResultWithNext<TNext>;
if (result is null)
{
throw new InvalidOperationException(
"Expected to get a matcher result with NextFetcher, but got null"
);
}
return new Next<TNext>(
result.NextFetcher,
continuation as IExpectationContext
);
}
/// <summary>
/// Most general matcher add - onto ICanAddMatcher<T>
/// </summary>
/// <param name="continuation">Continuation to add matcher to</param>
/// <param name="matcher">Matcher to run</param>
/// <typeparam name="T">Type of the object under test</typeparam>
public static IMore<T> AddMatcher<T>(
this ICanAddMatcher<T> continuation,
Func<T, IMatcherResult> matcher)
{
AddMatcherPrivate(continuation, matcher);
return continuation.More();
}
/// <summary>
/// Add a matcher onto an Exception property continuation
/// </summary>
/// <param name="continuation">Continuation to add matcher to</param>
/// <param name="matcher">Matcher to run</param>
/// <typeparam name="T">Type of the object under test</typeparam>
public static void AddMatcher<T>(
this IExceptionPropertyContinuation<T> continuation,
Func<string, IMatcherResult> matcher
)
{
AddMatcherPrivate(continuation, matcher);
}
/// <summary>
/// Add a matcher onto a Collection continuation
/// </summary>
/// <param name="continuation">Continuation to add matcher to</param>
/// <param name="matcher">Matcher to run</param>
/// <typeparam name="T">Type of the object under test</typeparam>
public static IMore<IEnumerable<T>> AddMatcher<T>(
this ICanAddMatcher<IEnumerable<T>> continuation,
Func<IEnumerable<T>, IMatcherResult> matcher
)
{
AddMatcherPrivate(continuation, matcher);
var more = continuation.More();
continuation.CopyPropertiesTo(more);
return more;
}
/// <summary>
/// Use to compose expectations into one matcher
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expectationsRunner">Runs your composed expectations</param>
/// <param name="callingMethod"></param>
/// <typeparam name="T"></typeparam>
public static IMore<T> Compose<T>(
this ICanAddMatcher<T> continuation,
Action<T> expectationsRunner,
[CallerMemberName] string callingMethod = null
)
{
return continuation.Compose(expectationsRunner,
(a, b) => $"Expectation \"{callingMethod}\" should {(!b).AsNot()}have failed.");
}
/// <summary>
/// Use to compose expectations into one matcher
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expectationsRunner">Runs your composed expectations</param>
/// <param name="messageGenerator">Generates the final message, passing in the actual instance being tested as well as a boolean for passed/failed</param>
/// <typeparam name="T"></typeparam>
public static IMore<T> Compose<T>(
this ICanAddMatcher<T> continuation,
Action<T> expectationsRunner,
Func<T, bool, string> messageGenerator
)
{
continuation.AddMatcher(actual =>
{
try
{
// if we're using custom assertions, we won't get an UnmetExpectationException
// on a failure
// worse, if those custom assertions are from NUnit, we can't stop the failure
// -> it's part of the design of NUnit
using var _ = Assertions.TemporarilyUseDefaultAssertionsFactoryForThisThread();
expectationsRunner(actual);
return new MatcherResult(true, () => messageGenerator(actual, true));
}
catch (UnmetExpectationException e)
{
return new MatcherResult(false,
() => FinalMessageFor(
new[] { "Specifically:", e.Message },
messageGenerator?.Invoke(actual, false)
)
);
}
});
return continuation.More();
}
/// <summary>
/// Use to compose expectations into one matcher
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expectationsRunner">Runs your composed expectations</param>
/// <param name="callingMethod"></param>
/// <typeparam name="T"></typeparam>
public static IMore<IEnumerable<T>> Compose<T>(
this ICanAddMatcher<IEnumerable<T>> continuation,
Action<IEnumerable<T>> expectationsRunner,
[CallerMemberName] string callingMethod = null
)
{
return continuation.Compose(expectationsRunner,
(a, b) => $"{callingMethod} should {b.AsNot()}have passed.");
}
/// <summary>
/// Use to compose expectations into one matcher
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expectationsRunner">Runs your composed expectations</param>
/// <param name="messageGenerator">Generates the final message, passing in the actual instance being tested as well as a boolean for passed/failed</param>
/// <typeparam name="T"></typeparam>
public static IMore<IEnumerable<T>> Compose<T>(
this ICanAddMatcher<IEnumerable<T>> continuation,
Action<IEnumerable<T>> expectationsRunner,
Func<IEnumerable<T>, bool, string> messageGenerator
)
{
continuation.AddMatcher(actual =>
{
try
{
expectationsRunner(actual);
return new MatcherResult(true, () => messageGenerator(actual, true));
}
catch (UnmetExpectationException e)
{
return new MatcherResult(false,
() => FinalMessageFor(
new[] { "Specifically:", e.Message },
messageGenerator?.Invoke(actual, false)
)
);
}
});
return continuation.More();
}
private static IMatcherResult AddMatcherPrivate<T>(
object continuation,
Func<T, IMatcherResult> matcher)
{
System.Diagnostics.Debug.WriteLine($"Adding matcher for type {typeof(T)}");
var asContext = continuation as IExpectationContext<T>;
if (asContext == null)
{
throw new InvalidOperationException($"{continuation} does not implement IExpectationContext<T>");
}
return asContext.RunMatcher(matcher) ?? throw new InvalidOperationException(
"Unable to run matcher - null result returned"
);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
namespace IronPythonTest {
public enum DeTestEnum {
Value_0,
Value_1,
Value_2,
Value_3,
Value_4
}
public enum DeTestEnumLong : long {
Value_1 = 12345678901234L,
Value_2 = 43210987654321L
}
public struct DeTestStruct {
public int intVal;
//public string stringVal;
//public float floatVal;
//public double doubleVal;
//public DeTestEnum eshort;
//public DeTestEnumLong elong;
#pragma warning disable 169
void Init() {
intVal = 0;
//stringVal = "Hello";
//floatVal = 0;
//doubleVal = 0;
//eshort = DeTestEnum.Value_3;
//elong = DeTestEnumLong.Value_2;
}
#pragma warning restore 169
}
public class DeTest {
public delegate DeTestStruct TestStruct(DeTestStruct dts);
public delegate string TestTrivial(string s1);
public delegate string TestStringDelegate(string s1, string s2, string s3, string s4, string s5, string s6);
public delegate int TestEnumDelegate(DeTestEnum e);
public delegate long TestEnumDelegateLong(DeTestEnumLong e);
public delegate string TestComplexDelegate(string s, int i, float f, double d, DeTestEnum e, string s2, DeTestEnum e2, DeTestEnumLong e3);
public event TestStruct e_struct;
public event TestTrivial e_tt;
public event TestTrivial e_tt2;
public event TestStringDelegate e_tsd;
public event TestEnumDelegate e_ted;
public event TestComplexDelegate e_tcd;
public event TestEnumDelegateLong e_tedl;
public TestStruct d_struct;
public TestTrivial d_tt;
public TestTrivial d_tt2;
public TestStringDelegate d_tsd;
public TestEnumDelegate d_ted;
public TestComplexDelegate d_tcd;
public TestEnumDelegateLong d_tedl;
public string stringVal;
public string stringVal2;
public int intVal;
public float floatVal;
public double doubleVal;
public DeTestEnum enumVal;
public DeTestEnumLong longEnumVal;
public DeTest() {
}
public void Init() {
e_struct = ActualTestStruct;
e_tt = VoidTestTrivial;
e_tsd = VoidTestString;
e_ted = VoidTestEnum;
e_tedl = VoidTestEnumLong;
e_tcd = VoidTestComplex;
e_struct = ActualTestStruct;
d_tt = VoidTestTrivial;
d_tsd = VoidTestString;
d_ted = VoidTestEnum;
d_tedl = VoidTestEnumLong;
d_tcd = VoidTestComplex;
}
public void RunTest() {
if (e_struct != null) {
DeTestStruct dts;
dts.intVal = intVal;
//dts.stringVal = stringVal;
//dts.floatVal = floatVal;
//dts.doubleVal = doubleVal;
//dts.elong = longEnumVal;
//dts.eshort = enumVal;
e_struct(dts);
}
e_tt?.Invoke(stringVal);
e_tt2?.Invoke(stringVal2);
d_tt?.Invoke(stringVal);
e_tsd?.Invoke(stringVal, stringVal2, stringVal, stringVal2, stringVal, stringVal2);
d_tsd?.Invoke(stringVal, stringVal2, stringVal, stringVal2, stringVal, stringVal2);
e_ted?.Invoke(enumVal);
d_ted?.Invoke(enumVal);
e_tedl?.Invoke(longEnumVal);
d_tedl?.Invoke(longEnumVal);
e_tcd?.Invoke(stringVal, intVal, floatVal, doubleVal, enumVal, stringVal2, enumVal, longEnumVal);
d_tcd?.Invoke(stringVal, intVal, floatVal, doubleVal, enumVal, stringVal2, enumVal, longEnumVal);
}
public DeTestStruct ActualTestStruct(DeTestStruct dts) {
object x = dts;
return (DeTestStruct)x;
}
public string ActualTestTrivial(string s1) {
return s1;
}
public string VoidTestTrivial(string s1) {
return String.Empty;
}
public string ActualTestString(string s1, string s2, string s3, string s4, string s5, string s6) {
return s1 + " " + s2 + " " + s3 + " " + s4 + " " + s5 + " " + s6;
}
public string VoidTestString(string s1, string s2, string s3, string s4, string s5, string s6) {
return String.Empty;
}
public int ActualTestEnum(DeTestEnum e) {
return (int)e + 1000;
}
public int VoidTestEnum(DeTestEnum e) {
return 0;
}
public long ActualTestEnumLong(DeTestEnumLong e) {
return (long)e + 1000000000;
}
public long VoidTestEnumLong(DeTestEnumLong e) {
return 0;
}
public string ActualTestComplex(string s, int i, float f, double d, DeTestEnum e, string s2, DeTestEnum e2, DeTestEnumLong e3) {
return s + " " + i.ToString() + " " + f.ToString() + " " + d.ToString() + " " + s2 + " " + e2.ToString() + " " + e3.ToString();
}
public string VoidTestComplex(string s, int i, float f, double d, DeTestEnum e, string s2, DeTestEnum e2, DeTestEnumLong e3) {
return String.Empty;
}
public void SetupE() {
e_tt = ActualTestTrivial;
e_tt2 = ActualTestTrivial;
e_tsd = ActualTestString;
e_ted = ActualTestEnum;
e_tedl = ActualTestEnumLong;
e_tcd = ActualTestComplex;
}
public void SetupS() {
e_struct += ActualTestStruct;
e_struct += ActualTestStruct;
}
public void SetupD() {
d_tt = ActualTestTrivial;
d_tt2 = ActualTestTrivial;
d_tsd = ActualTestString;
d_ted = ActualTestEnum;
d_tedl = ActualTestEnumLong;
d_tcd = ActualTestComplex;
}
public void Setup() {
SetupE();
SetupD();
}
public static DeTestStruct staticDeTestStruct(object o, DeTestStruct dts) {
object oo = dts;
return (DeTestStruct)oo;
}
public static void Test() {
DeTest dt = new DeTest();
dt.SetupS();
dt.RunTest();
}
}
public delegate float FloatDelegate(float f);
public class ReturnTypes {
public event FloatDelegate floatEvent;
public float RunFloat(float f) {
return floatEvent(f);
}
}
public delegate void VoidDelegate();
public class SimpleType {
public event VoidDelegate SimpleEvent;
public void RaiseEvent() {
if (SimpleEvent != null)
SimpleEvent();
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* 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.Runtime.Serialization;
using ASC.CRM.Core;
using ASC.CRM.Core.Entities;
using ASC.Web.Core.Utility.Skins;
using ASC.Web.CRM.Configuration;
namespace ASC.Api.CRM.Wrappers
{
#region History Category
[DataContract(Name = "historyCategoryBase", Namespace = "")]
public class HistoryCategoryBaseWrapper : ListItemWrapper
{
public HistoryCategoryBaseWrapper() : base(0)
{
}
public HistoryCategoryBaseWrapper(ListItem listItem)
: base(listItem)
{
if (!String.IsNullOrEmpty(listItem.AdditionalParams))
ImagePath = WebImageSupplier.GetAbsoluteWebPath(listItem.AdditionalParams, ProductEntryPoint.ID);
}
[DataMember]
public String ImagePath { get; set; }
public static HistoryCategoryBaseWrapper GetSample()
{
return new HistoryCategoryBaseWrapper
{
ID = 30,
Title = "Lunch",
SortOrder = 10,
Color = String.Empty,
Description = "",
ImagePath = "path to image"
};
}
}
[DataContract(Name = "historyCategory", Namespace = "")]
public class HistoryCategoryWrapper : HistoryCategoryBaseWrapper
{
public HistoryCategoryWrapper()
{
}
public HistoryCategoryWrapper(ListItem listItem)
: base(listItem)
{
}
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public int RelativeItemsCount { get; set; }
public new static HistoryCategoryWrapper GetSample()
{
return new HistoryCategoryWrapper
{
ID = 30,
Title = "Lunch",
SortOrder = 10,
Color = String.Empty,
Description = "",
ImagePath = "path to image",
RelativeItemsCount = 1
};
}
}
#endregion
#region Deal Milestone
[DataContract(Name = "opportunityStagesBase", Namespace = "")]
public class DealMilestoneBaseWrapper : ListItemWrapper
{
public DealMilestoneBaseWrapper()
: base(0)
{
}
public DealMilestoneBaseWrapper(DealMilestone dealMilestone)
: base(dealMilestone.ID)
{
SuccessProbability = dealMilestone.Probability;
StageType = dealMilestone.Status;
Color = dealMilestone.Color;
Description = dealMilestone.Description;
Title = dealMilestone.Title;
}
[DataMember]
public int SuccessProbability { get; set; }
[DataMember]
public DealMilestoneStatus StageType { get; set; }
public static DealMilestoneBaseWrapper GetSample()
{
return new DealMilestoneBaseWrapper
{
ID = 30,
Title = "Discussion",
SortOrder = 2,
Color = "#B9AFD3",
Description = "The potential buyer showed his/her interest and sees how your offering meets his/her goal",
StageType = DealMilestoneStatus.Open,
SuccessProbability = 20
};
}
}
[DataContract(Name = "opportunityStages", Namespace = "")]
public class DealMilestoneWrapper : DealMilestoneBaseWrapper
{
public DealMilestoneWrapper()
{
}
public DealMilestoneWrapper(DealMilestone dealMilestone)
: base(dealMilestone)
{
}
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public int RelativeItemsCount { get; set; }
public new static DealMilestoneWrapper GetSample()
{
return new DealMilestoneWrapper
{
ID = 30,
Title = "Discussion",
SortOrder = 2,
Color = "#B9AFD3",
Description = "The potential buyer showed his/her interest and sees how your offering meets his/her goal",
StageType = DealMilestoneStatus.Open,
SuccessProbability = 20,
RelativeItemsCount = 1
};
}
}
#endregion
#region Task Category
[DataContract(Name = "taskCategoryBase", Namespace = "")]
public class TaskCategoryBaseWrapper : ListItemWrapper
{
public TaskCategoryBaseWrapper()
: base(0)
{
}
public TaskCategoryBaseWrapper(ListItem listItem)
: base(listItem)
{
ImagePath = WebImageSupplier.GetAbsoluteWebPath(listItem.AdditionalParams, ProductEntryPoint.ID);
}
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public String ImagePath { get; set; }
public static TaskCategoryBaseWrapper GetSample()
{
return new TaskCategoryBaseWrapper
{
ID = 30,
Title = "Appointment",
SortOrder = 2,
Description = "",
ImagePath = "path to image"
};
}
}
[DataContract(Name = "taskCategory", Namespace = "")]
public class TaskCategoryWrapper : TaskCategoryBaseWrapper
{
public TaskCategoryWrapper()
{
}
public TaskCategoryWrapper(ListItem listItem)
: base(listItem)
{
}
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public int RelativeItemsCount { get; set; }
public new static TaskCategoryWrapper GetSample()
{
return new TaskCategoryWrapper
{
ID = 30,
Title = "Appointment",
SortOrder = 2,
Description = "",
ImagePath = "path to image",
RelativeItemsCount = 1
};
}
}
#endregion
#region Contact Status
[DataContract(Name = "contactStatusBase", Namespace = "")]
public class ContactStatusBaseWrapper : ListItemWrapper
{
public ContactStatusBaseWrapper() :
base(0)
{
}
public ContactStatusBaseWrapper(ListItem listItem)
: base(listItem)
{
}
public static ContactStatusBaseWrapper GetSample()
{
return new ContactStatusBaseWrapper
{
ID = 30,
Title = "Cold",
SortOrder = 2,
Description = ""
};
}
}
[DataContract(Name = "contactStatus", Namespace = "")]
public class ContactStatusWrapper : ContactStatusBaseWrapper
{
public ContactStatusWrapper()
{
}
public ContactStatusWrapper(ListItem listItem)
: base(listItem)
{
}
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public int RelativeItemsCount { get; set; }
public new static ContactStatusWrapper GetSample()
{
return new ContactStatusWrapper
{
ID = 30,
Title = "Cold",
SortOrder = 2,
Description = "",
RelativeItemsCount = 1
};
}
}
#endregion
#region Contact Type
[DataContract(Name = "contactTypeBase", Namespace = "")]
public class ContactTypeBaseWrapper : ListItemWrapper
{
public ContactTypeBaseWrapper() :
base(0)
{
}
public ContactTypeBaseWrapper(ListItem listItem)
: base(listItem)
{
}
public static ContactTypeBaseWrapper GetSample()
{
return new ContactTypeBaseWrapper
{
ID = 30,
Title = "Client",
SortOrder = 2,
Description = ""
};
}
}
[DataContract(Name = "contactType", Namespace = "")]
public class ContactTypeWrapper : ContactTypeBaseWrapper
{
public ContactTypeWrapper()
{
}
public ContactTypeWrapper(ListItem listItem)
: base(listItem)
{
}
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public int RelativeItemsCount { get; set; }
public new static ContactTypeWrapper GetSample()
{
return new ContactTypeWrapper
{
ID = 30,
Title = "Client",
SortOrder = 2,
Description = "",
RelativeItemsCount = 1
};
}
}
#endregion
#region Tags
[DataContract(Name = "tagWrapper", Namespace = "")]
public class TagWrapper
{
public TagWrapper()
{
Title = String.Empty;
RelativeItemsCount = 0;
}
public TagWrapper(String tag, int relativeItemsCount = 0)
{
Title = tag;
RelativeItemsCount = relativeItemsCount;
}
[DataMember(IsRequired = true, EmitDefaultValue = false)]
public String Title { get; set; }
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public int RelativeItemsCount { get; set; }
public static TagWrapper GetSample()
{
return new TagWrapper
{
Title = "Tag",
RelativeItemsCount = 1
};
}
}
#endregion
[DataContract(Name = "listItem", Namespace = "")]
public abstract class ListItemWrapper : ObjectWrapperBase
{
protected ListItemWrapper(int id)
: base(id)
{
}
protected ListItemWrapper(ListItem listItem)
: base(listItem.ID)
{
Title = listItem.Title;
Description = listItem.Description;
Color = listItem.Color;
SortOrder = listItem.SortOrder;
}
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public String Title { get; set; }
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public String Description { get; set; }
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public String Color { get; set; }
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public int SortOrder { get; set; }
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Text;
using System.Runtime.InteropServices;
namespace programmer_sound
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button exit_button;
private System.Windows.Forms.StatusBar statusBar;
private System.Windows.Forms.Label label;
private System.Windows.Forms.Button startEvent;
private System.Windows.Forms.Timer timer1;
private System.ComponentModel.IContainer components;
private bool initialised = false;
private bool eventstart = false;
private bool exit = false;
private static FMOD.EVENT_CALLBACK eventcallback = new FMOD.EVENT_CALLBACK(FMOD_EVENT_CALLBACK);
private static FMOD.RESULT FMOD_EVENT_CALLBACK(IntPtr eventraw, FMOD.EVENT_CALLBACKTYPE type, IntPtr param1, IntPtr param2, IntPtr userdata)
{
unsafe
{
switch (type)
{
case FMOD.EVENT_CALLBACKTYPE.SOUNDDEF_CREATE :
{
int entryindex = *(int*)param2.ToPointer() ; // [in] (int) index of sound definition entry
uint *realpointer = (uint *)param2.ToPointer(); // [out] (FMOD::Sound *) a valid lower level API FMOD Sound handle
FMOD.Sound s = null;
fsb.getSubSound(entryindex, ref s);
*realpointer = (uint)s.getRaw().ToPointer();
break;
}
case FMOD.EVENT_CALLBACKTYPE.SOUNDDEF_RELEASE :
{
break;
}
}
}
return FMOD.RESULT.OK;
}
/*
ALL FMOD CALLS MUST HAPPEN WITHIN THE SAME THREAD.
WE WILL DO EVERYTHING IN THE TIMER THREAD
*/
static FMOD.Sound fsb = null;
FMOD.System sys = null;
FMOD.EventSystem eventsystem = null;
FMOD.EventGroup eventgroup = null;
FMOD.Event _event = null;
private void timer1_Tick(object sender, System.EventArgs e)
{
FMOD.RESULT result;
if (!initialised)
{
ERRCHECK(result = FMOD.Event_Factory.EventSystem_Create(ref eventsystem));
ERRCHECK(result = eventsystem.init(64, FMOD.INITFLAGS.NORMAL, (IntPtr)null, FMOD.EVENT_INITFLAGS.NORMAL));
ERRCHECK(result = eventsystem.setMediaPath("../../../../examples/media/"));
ERRCHECK(result = eventsystem.load("examples.fev"));
ERRCHECK(result = eventsystem.getGroup("examples/FeatureDemonstration/SequencingAndStitching", false, ref eventgroup));
ERRCHECK(result = eventsystem.getSystemObject(ref sys));
ERRCHECK(result = sys.createStream("../../../../examples/media/tutorial_bank.fsb", (FMOD.MODE._2D | FMOD.MODE.SOFTWARE), ref fsb));
initialised = true;
}
/*
"Main Loop"
*/
ERRCHECK(result = eventsystem.update());
if (eventstart)
{
ERRCHECK(result = eventgroup.getEvent("ProgrammerSounds", FMOD.EVENT_MODE.DEFAULT, ref _event));
ERRCHECK(result = _event.setCallback(eventcallback, (IntPtr)null));
ERRCHECK(result = _event.start());
eventstart = false;
}
/*
Cleanup and exit
*/
if (exit)
{
ERRCHECK(result = eventsystem.unload());
ERRCHECK(result = fsb.release());
ERRCHECK(result = eventsystem.release());
Application.Exit();
}
}
public Form1()
{
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (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.components = new System.ComponentModel.Container();
this.exit_button = new System.Windows.Forms.Button();
this.statusBar = new System.Windows.Forms.StatusBar();
this.label = new System.Windows.Forms.Label();
this.startEvent = new System.Windows.Forms.Button();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.SuspendLayout();
//
// exit_button
//
this.exit_button.Location = new System.Drawing.Point(168, 48);
this.exit_button.Name = "exit_button";
this.exit_button.Size = new System.Drawing.Size(72, 24);
this.exit_button.TabIndex = 19;
this.exit_button.Text = "Exit";
this.exit_button.Click += new System.EventHandler(this.exit_button_Click);
//
// statusBar
//
this.statusBar.Location = new System.Drawing.Point(0, 86);
this.statusBar.Name = "statusBar";
this.statusBar.Size = new System.Drawing.Size(292, 24);
this.statusBar.TabIndex = 20;
//
// label
//
this.label.Location = new System.Drawing.Point(16, 8);
this.label.Name = "label";
this.label.Size = new System.Drawing.Size(264, 32);
this.label.TabIndex = 21;
this.label.Text = "Copyright (c) Firelight Technologies 2004-2011";
this.label.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// startEvent
//
this.startEvent.Location = new System.Drawing.Point(48, 48);
this.startEvent.Name = "startEvent";
this.startEvent.Size = new System.Drawing.Size(72, 24);
this.startEvent.TabIndex = 22;
this.startEvent.Text = "Start Event";
this.startEvent.Click += new System.EventHandler(this.startEvent_Click);
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Interval = 10;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 110);
this.Controls.Add(this.startEvent);
this.Controls.Add(this.label);
this.Controls.Add(this.statusBar);
this.Controls.Add(this.exit_button);
this.Name = "Form1";
this.Text = "Programmer Sound Example";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void Form1_Load(object sender, System.EventArgs e)
{
}
private void ERRCHECK(FMOD.RESULT result)
{
if (result != FMOD.RESULT.OK)
{
timer1.Stop();
MessageBox.Show("FMOD error! " + result + " - " + FMOD.Error.String(result));
Environment.Exit(-1);
}
}
private void startEvent_Click(object sender, System.EventArgs e)
{
eventstart = true;
}
private void exit_button_Click(object sender, System.EventArgs e)
{
exit = true;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
namespace Microsoft.Azure.Management.Automation
{
public static partial class RunbookOperationsExtensions
{
/// <summary>
/// Retrieve the content of runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='runbookName'>
/// Required. The runbook name.
/// </param>
/// <returns>
/// The response model for the runbook content operation.
/// </returns>
public static RunbookContentResponse Content(this IRunbookOperations operations, string resourceGroupName, string automationAccount, string runbookName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRunbookOperations)s).ContentAsync(resourceGroupName, automationAccount, runbookName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve the content of runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='runbookName'>
/// Required. The runbook name.
/// </param>
/// <returns>
/// The response model for the runbook content operation.
/// </returns>
public static Task<RunbookContentResponse> ContentAsync(this IRunbookOperations operations, string resourceGroupName, string automationAccount, string runbookName)
{
return operations.ContentAsync(resourceGroupName, automationAccount, runbookName, CancellationToken.None);
}
/// <summary>
/// Create the runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The create or update parameters for runbook.
/// </param>
/// <returns>
/// The response model for the runbook create response.
/// </returns>
public static RunbookCreateOrUpdateResponse CreateOrUpdate(this IRunbookOperations operations, string resourceGroupName, string automationAccount, RunbookCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRunbookOperations)s).CreateOrUpdateAsync(resourceGroupName, automationAccount, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create the runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The create or update parameters for runbook.
/// </param>
/// <returns>
/// The response model for the runbook create response.
/// </returns>
public static Task<RunbookCreateOrUpdateResponse> CreateOrUpdateAsync(this IRunbookOperations operations, string resourceGroupName, string automationAccount, RunbookCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None);
}
/// <summary>
/// Create the runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The create or update parameters for runbook.
/// </param>
/// <returns>
/// The response model for the runbook create response.
/// </returns>
public static RunbookCreateOrUpdateResponse CreateOrUpdateWithDraft(this IRunbookOperations operations, string resourceGroupName, string automationAccount, RunbookCreateOrUpdateDraftParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRunbookOperations)s).CreateOrUpdateWithDraftAsync(resourceGroupName, automationAccount, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create the runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The create or update parameters for runbook.
/// </param>
/// <returns>
/// The response model for the runbook create response.
/// </returns>
public static Task<RunbookCreateOrUpdateResponse> CreateOrUpdateWithDraftAsync(this IRunbookOperations operations, string resourceGroupName, string automationAccount, RunbookCreateOrUpdateDraftParameters parameters)
{
return operations.CreateOrUpdateWithDraftAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None);
}
/// <summary>
/// Delete the runbook by name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='runbookName'>
/// Required. The runbook name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IRunbookOperations operations, string resourceGroupName, string automationAccount, string runbookName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRunbookOperations)s).DeleteAsync(resourceGroupName, automationAccount, runbookName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete the runbook by name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='runbookName'>
/// Required. The runbook name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IRunbookOperations operations, string resourceGroupName, string automationAccount, string runbookName)
{
return operations.DeleteAsync(resourceGroupName, automationAccount, runbookName, CancellationToken.None);
}
/// <summary>
/// Retrieve the runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='runbookName'>
/// Required. The runbook name.
/// </param>
/// <returns>
/// The response model for the get runbook operation.
/// </returns>
public static RunbookGetResponse Get(this IRunbookOperations operations, string resourceGroupName, string automationAccount, string runbookName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRunbookOperations)s).GetAsync(resourceGroupName, automationAccount, runbookName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve the runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='runbookName'>
/// Required. The runbook name.
/// </param>
/// <returns>
/// The response model for the get runbook operation.
/// </returns>
public static Task<RunbookGetResponse> GetAsync(this IRunbookOperations operations, string resourceGroupName, string automationAccount, string runbookName)
{
return operations.GetAsync(resourceGroupName, automationAccount, runbookName, CancellationToken.None);
}
/// <summary>
/// Retrieve a list of runbooks. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <returns>
/// The response model for the list runbook operation.
/// </returns>
public static RunbookListResponse List(this IRunbookOperations operations, string resourceGroupName, string automationAccount)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRunbookOperations)s).ListAsync(resourceGroupName, automationAccount);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve a list of runbooks. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <returns>
/// The response model for the list runbook operation.
/// </returns>
public static Task<RunbookListResponse> ListAsync(this IRunbookOperations operations, string resourceGroupName, string automationAccount)
{
return operations.ListAsync(resourceGroupName, automationAccount, CancellationToken.None);
}
/// <summary>
/// Retrieve next list of runbooks. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <returns>
/// The response model for the list runbook operation.
/// </returns>
public static RunbookListResponse ListNext(this IRunbookOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRunbookOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve next list of runbooks. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <returns>
/// The response model for the list runbook operation.
/// </returns>
public static Task<RunbookListResponse> ListNextAsync(this IRunbookOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
/// <summary>
/// Update the runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The patch parameters for runbook.
/// </param>
/// <returns>
/// The response model for the get runbook operation.
/// </returns>
public static RunbookGetResponse Patch(this IRunbookOperations operations, string resourceGroupName, string automationAccount, RunbookPatchParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRunbookOperations)s).PatchAsync(resourceGroupName, automationAccount, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Update the runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The patch parameters for runbook.
/// </param>
/// <returns>
/// The response model for the get runbook operation.
/// </returns>
public static Task<RunbookGetResponse> PatchAsync(this IRunbookOperations operations, string resourceGroupName, string automationAccount, RunbookPatchParameters parameters)
{
return operations.PatchAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace System
{
public partial class Uri
{
//
// All public ctors go through here
//
private void CreateThis(string uri, bool dontEscape, UriKind uriKind)
{
// if (!Enum.IsDefined(typeof(UriKind), uriKind)) -- We currently believe that Enum.IsDefined() is too slow
// to be used here.
if ((int)uriKind < (int)UriKind.RelativeOrAbsolute || (int)uriKind > (int)UriKind.Relative)
{
throw new ArgumentException(SR.Format(SR.net_uri_InvalidUriKind, uriKind));
}
_string = uri == null ? string.Empty : uri;
if (dontEscape)
_flags |= Flags.UserEscaped;
ParsingError err = ParseScheme(_string, ref _flags, ref _syntax);
UriFormatException e;
InitializeUri(err, uriKind, out e);
if (e != null)
throw e;
}
private void InitializeUri(ParsingError err, UriKind uriKind, out UriFormatException e)
{
if (err == ParsingError.None)
{
if (IsImplicitFile)
{
// V1 compat
// A relative Uri wins over implicit UNC path unless the UNC path is of the form "\\something" and
// uriKind != Absolute
if (NotAny(Flags.DosPath) &&
uriKind != UriKind.Absolute &&
(uriKind == UriKind.Relative || (_string.Length >= 2 && (_string[0] != '\\' || _string[1] != '\\'))))
{
_syntax = null; //make it be relative Uri
_flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri
e = null;
return;
// Otherwise an absolute file Uri wins when it's of the form "\\something"
}
//
// V1 compat issue
// We should support relative Uris of the form c:\bla or c:/bla
//
else if (uriKind == UriKind.Relative && InFact(Flags.DosPath))
{
_syntax = null; //make it be relative Uri
_flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri
e = null;
return;
// Otherwise an absolute file Uri wins when it's of the form "c:\something"
}
}
}
else if (err > ParsingError.LastRelativeUriOkErrIndex)
{
//This is a fatal error based solely on scheme name parsing
_string = null; // make it be invalid Uri
e = GetException(err);
return;
}
bool hasUnicode = false;
_iriParsing = (s_IriParsing && ((_syntax == null) || _syntax.InFact(UriSyntaxFlags.AllowIriParsing)));
if (_iriParsing &&
(CheckForUnicode(_string) || CheckForEscapedUnreserved(_string)))
{
_flags |= Flags.HasUnicode;
hasUnicode = true;
// switch internal strings
_originalUnicodeString = _string; // original string location changed
}
if (_syntax != null)
{
if (_syntax.IsSimple)
{
if ((err = PrivateParseMinimal()) != ParsingError.None)
{
if (uriKind != UriKind.Absolute && err <= ParsingError.LastRelativeUriOkErrIndex)
{
// RFC 3986 Section 5.4.2 - http:(relativeUri) may be considered a valid relative Uri.
_syntax = null; // convert to relative uri
e = null;
_flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri
return;
}
else
e = GetException(err);
}
else if (uriKind == UriKind.Relative)
{
// Here we know that we can create an absolute Uri, but the user has requested only a relative one
e = GetException(ParsingError.CannotCreateRelative);
}
else
e = null;
// will return from here
if (_iriParsing && hasUnicode)
{
// In this scenario we need to parse the whole string
EnsureParseRemaining();
}
}
else
{
// offer custom parser to create a parsing context
_syntax = _syntax.InternalOnNewUri();
// in case they won't call us
_flags |= Flags.UserDrivenParsing;
// Ask a registered type to validate this uri
_syntax.InternalValidate(this, out e);
if (e != null)
{
// Can we still take it as a relative Uri?
if (uriKind != UriKind.Absolute && err != ParsingError.None
&& err <= ParsingError.LastRelativeUriOkErrIndex)
{
_syntax = null; // convert it to relative
e = null;
_flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri
}
}
else // e == null
{
if (err != ParsingError.None || InFact(Flags.ErrorOrParsingRecursion))
{
// User parser took over on an invalid Uri
SetUserDrivenParsing();
}
else if (uriKind == UriKind.Relative)
{
// Here we know that custom parser can create an absolute Uri, but the user has requested only a
// relative one
e = GetException(ParsingError.CannotCreateRelative);
}
if (_iriParsing && hasUnicode)
{
// In this scenario we need to parse the whole string
EnsureParseRemaining();
}
}
// will return from here
}
}
// If we encountered any parsing errors that indicate this may be a relative Uri,
// and we'll allow relative Uri's, then create one.
else if (err != ParsingError.None && uriKind != UriKind.Absolute
&& err <= ParsingError.LastRelativeUriOkErrIndex)
{
e = null;
_flags &= (Flags.UserEscaped | Flags.HasUnicode); // the only flags that makes sense for a relative uri
if (_iriParsing && hasUnicode)
{
// Iri'ze and then normalize relative uris
_string = EscapeUnescapeIri(_originalUnicodeString, 0, _originalUnicodeString.Length,
(UriComponents)0);
}
}
else
{
_string = null; // make it be invalid Uri
e = GetException(err);
}
}
//
// Unescapes entire string and checks if it has unicode chars
//
private bool CheckForUnicode(string data)
{
bool hasUnicode = false;
char[] chars = new char[data.Length];
int count = 0;
chars = UriHelper.UnescapeString(data, 0, data.Length, chars, ref count, c_DummyChar, c_DummyChar,
c_DummyChar, UnescapeMode.Unescape | UnescapeMode.UnescapeAll, null, false);
for (int i = 0; i < count; ++i)
{
if (chars[i] > '\x7f')
{
// Unicode
hasUnicode = true;
break;
}
}
return hasUnicode;
}
// Does this string have any %6A sequences that are 3986 Unreserved characters? These should be un-escaped.
private unsafe bool CheckForEscapedUnreserved(string data)
{
fixed (char* tempPtr = data)
{
for (int i = 0; i < data.Length - 2; ++i)
{
if (tempPtr[i] == '%' && UriHelper.IsHexDigit(tempPtr[i + 1]) && UriHelper.IsHexDigit(tempPtr[i + 2])
&& tempPtr[i + 1] >= '0' && tempPtr[i + 1] <= '7') // max 0x7F
{
char ch = UriHelper.EscapedAscii(tempPtr[i + 1], tempPtr[i + 2]);
if (ch != c_DummyChar && UriHelper.Is3986Unreserved(ch))
{
return true;
}
}
}
}
return false;
}
//
// Returns true if the string represents a valid argument to the Uri ctor
// If uriKind != AbsoluteUri then certain parsing errors are ignored but Uri usage is limited
//
public static bool TryCreate(string uriString, UriKind uriKind, out Uri result)
{
if ((object)uriString == null)
{
result = null;
return false;
}
UriFormatException e = null;
result = CreateHelper(uriString, false, uriKind, ref e);
return (object)e == null && result != null;
}
public static bool TryCreate(Uri baseUri, string relativeUri, out Uri result)
{
Uri relativeLink;
if (TryCreate(relativeUri, UriKind.RelativeOrAbsolute, out relativeLink))
{
if (!relativeLink.IsAbsoluteUri)
return TryCreate(baseUri, relativeLink, out result);
result = relativeLink;
return true;
}
result = null;
return false;
}
public static bool TryCreate(Uri baseUri, Uri relativeUri, out Uri result)
{
result = null;
if ((object)baseUri == null || (object)relativeUri == null)
return false;
if (baseUri.IsNotAbsoluteUri)
return false;
UriFormatException e;
string newUriString = null;
bool dontEscape;
if (baseUri.Syntax.IsSimple)
{
dontEscape = relativeUri.UserEscaped;
result = ResolveHelper(baseUri, relativeUri, ref newUriString, ref dontEscape, out e);
}
else
{
dontEscape = false;
newUriString = baseUri.Syntax.InternalResolve(baseUri, relativeUri, out e);
}
if (e != null)
return false;
if ((object)result == null)
result = CreateHelper(newUriString, dontEscape, UriKind.Absolute, ref e);
return (object)e == null && result != null && result.IsAbsoluteUri;
}
public string GetComponents(UriComponents components, UriFormat format)
{
if (((components & UriComponents.SerializationInfoString) != 0) && components != UriComponents.SerializationInfoString)
throw new ArgumentOutOfRangeException(nameof(components), components, SR.net_uri_NotJustSerialization);
if ((format & ~UriFormat.SafeUnescaped) != 0)
throw new ArgumentOutOfRangeException(nameof(format));
if (IsNotAbsoluteUri)
{
if (components == UriComponents.SerializationInfoString)
return GetRelativeSerializationString(format);
else
throw new InvalidOperationException(SR.net_uri_NotAbsolute);
}
if (Syntax.IsSimple)
return GetComponentsHelper(components, format);
return Syntax.InternalGetComponents(this, components, format);
}
//
// This is for languages that do not support == != operators overloading
//
// Note that Uri.Equals will get an optimized path but is limited to true/false result only
//
public static int Compare(Uri uri1, Uri uri2, UriComponents partsToCompare, UriFormat compareFormat,
StringComparison comparisonType)
{
if ((object)uri1 == null)
{
if (uri2 == null)
return 0; // Equal
return -1; // null < non-null
}
if ((object)uri2 == null)
return 1; // non-null > null
// a relative uri is always less than an absolute one
if (!uri1.IsAbsoluteUri || !uri2.IsAbsoluteUri)
return uri1.IsAbsoluteUri ? 1 : uri2.IsAbsoluteUri ? -1 : string.Compare(uri1.OriginalString,
uri2.OriginalString, comparisonType);
return string.Compare(
uri1.GetParts(partsToCompare, compareFormat),
uri2.GetParts(partsToCompare, compareFormat),
comparisonType
);
}
public bool IsWellFormedOriginalString()
{
if (IsNotAbsoluteUri || Syntax.IsSimple)
return InternalIsWellFormedOriginalString();
return Syntax.InternalIsWellFormedOriginalString(this);
}
public static bool IsWellFormedUriString(string uriString, UriKind uriKind)
{
Uri result;
if (!Uri.TryCreate(uriString, uriKind, out result))
return false;
return result.IsWellFormedOriginalString();
}
//
// Internal stuff
//
// Returns false if OriginalString value
// (1) is not correctly escaped as per URI spec excluding intl UNC name case
// (2) or is an absolute Uri that represents implicit file Uri "c:\dir\file"
// (3) or is an absolute Uri that misses a slash before path "file://c:/dir/file"
// (4) or contains unescaped backslashes even if they will be treated
// as forward slashes like http:\\host/path\file or file:\\\c:\path
//
internal unsafe bool InternalIsWellFormedOriginalString()
{
if (UserDrivenParsing)
throw new InvalidOperationException(SR.Format(SR.net_uri_UserDrivenParsing, this.GetType().ToString()));
fixed (char* str = _string)
{
ushort idx = 0;
//
// For a relative Uri we only care about escaping and backslashes
//
if (!IsAbsoluteUri)
{
// my:scheme/path?query is not well formed because the colon is ambiguous
if (CheckForColonInFirstPathSegment(_string))
{
return false;
}
return (CheckCanonical(str, ref idx, (ushort)_string.Length, c_EOL)
& (Check.BackslashInPath | Check.EscapedCanonical)) == Check.EscapedCanonical;
}
//
// (2) or is an absolute Uri that represents implicit file Uri "c:\dir\file"
//
if (IsImplicitFile)
return false;
//This will get all the offsets, a Host name will be checked separately below
EnsureParseRemaining();
Flags nonCanonical = (_flags & (Flags.E_CannotDisplayCanonical | Flags.IriCanonical));
// User, Path, Query or Fragment may have some non escaped characters
if (((nonCanonical & Flags.E_CannotDisplayCanonical & (Flags.E_UserNotCanonical | Flags.E_PathNotCanonical |
Flags.E_QueryNotCanonical | Flags.E_FragmentNotCanonical)) != Flags.Zero) &&
(!_iriParsing || (_iriParsing &&
(((nonCanonical & Flags.E_UserNotCanonical) == 0) || ((nonCanonical & Flags.UserIriCanonical) == 0)) &&
(((nonCanonical & Flags.E_PathNotCanonical) == 0) || ((nonCanonical & Flags.PathIriCanonical) == 0)) &&
(((nonCanonical & Flags.E_QueryNotCanonical) == 0) || ((nonCanonical & Flags.QueryIriCanonical) == 0)) &&
(((nonCanonical & Flags.E_FragmentNotCanonical) == 0) || ((nonCanonical & Flags.FragmentIriCanonical) == 0)))))
{
return false;
}
// checking on scheme:\\ or file:////
if (InFact(Flags.AuthorityFound))
{
idx = (ushort)(_info.Offset.Scheme + _syntax.SchemeName.Length + 2);
if (idx >= _info.Offset.User || _string[idx - 1] == '\\' || _string[idx] == '\\')
return false;
if (InFact(Flags.UncPath | Flags.DosPath))
{
while (++idx < _info.Offset.User && (_string[idx] == '/' || _string[idx] == '\\'))
return false;
}
}
// (3) or is an absolute Uri that misses a slash before path "file://c:/dir/file"
// Note that for this check to be more general we assert that if Path is non empty and if it requires a first slash
// (which looks absent) then the method has to fail.
// Today it's only possible for a Dos like path, i.e. file://c:/bla would fail below check.
if (InFact(Flags.FirstSlashAbsent) && _info.Offset.Query > _info.Offset.Path)
return false;
// (4) or contains unescaped backslashes even if they will be treated
// as forward slashes like http:\\host/path\file or file:\\\c:\path
// Note we do not check for Flags.ShouldBeCompressed i.e. allow // /./ and alike as valid
if (InFact(Flags.BackslashInPath))
return false;
// Capturing a rare case like file:///c|/dir
if (IsDosPath && _string[_info.Offset.Path + SecuredPathIndex - 1] == '|')
return false;
//
// May need some real CPU processing to answer the request
//
//
// Check escaping for authority
//
// IPv6 hosts cannot be properly validated by CheckCannonical
if ((_flags & Flags.CanonicalDnsHost) == 0 && HostType != Flags.IPv6HostType)
{
idx = _info.Offset.User;
Check result = CheckCanonical(str, ref idx, (ushort)_info.Offset.Path, '/');
if (((result & (Check.ReservedFound | Check.BackslashInPath | Check.EscapedCanonical))
!= Check.EscapedCanonical)
&& (!_iriParsing || (_iriParsing
&& ((result & (Check.DisplayCanonical | Check.FoundNonAscii | Check.NotIriCanonical))
!= (Check.DisplayCanonical | Check.FoundNonAscii)))))
{
return false;
}
}
// Want to ensure there are slashes after the scheme
if ((_flags & (Flags.SchemeNotCanonical | Flags.AuthorityFound))
== (Flags.SchemeNotCanonical | Flags.AuthorityFound))
{
idx = (ushort)_syntax.SchemeName.Length;
while (str[idx++] != ':') ;
if (idx + 1 >= _string.Length || str[idx] != '/' || str[idx + 1] != '/')
return false;
}
}
//
// May be scheme, host, port or path need some canonicalization but still the uri string is found to be a
// "well formed" one
//
return true;
}
public static string UnescapeDataString(string stringToUnescape)
{
if ((object)stringToUnescape == null)
throw new ArgumentNullException(nameof(stringToUnescape));
if (stringToUnescape.Length == 0)
return string.Empty;
unsafe
{
fixed (char* pStr = stringToUnescape)
{
int position;
for (position = 0; position < stringToUnescape.Length; ++position)
if (pStr[position] == '%')
break;
if (position == stringToUnescape.Length)
return stringToUnescape;
UnescapeMode unescapeMode = UnescapeMode.Unescape | UnescapeMode.UnescapeAll;
position = 0;
char[] dest = new char[stringToUnescape.Length];
dest = UriHelper.UnescapeString(stringToUnescape, 0, stringToUnescape.Length, dest, ref position,
c_DummyChar, c_DummyChar, c_DummyChar, unescapeMode, null, false);
return new string(dest, 0, position);
}
}
}
//
// Where stringToEscape is intended to be a completely unescaped URI string.
// This method will escape any character that is not a reserved or unreserved character, including percent signs.
// Note that EscapeUriString will also do not escape a '#' sign.
//
public static string EscapeUriString(string stringToEscape)
{
if ((object)stringToEscape == null)
throw new ArgumentNullException(nameof(stringToEscape));
if (stringToEscape.Length == 0)
return string.Empty;
int position = 0;
char[] dest = UriHelper.EscapeString(stringToEscape, 0, stringToEscape.Length, null, ref position, true,
c_DummyChar, c_DummyChar, c_DummyChar);
if ((object)dest == null)
return stringToEscape;
return new string(dest, 0, position);
}
//
// Where stringToEscape is intended to be URI data, but not an entire URI.
// This method will escape any character that is not an unreserved character, including percent signs.
//
public static string EscapeDataString(string stringToEscape)
{
if ((object)stringToEscape == null)
throw new ArgumentNullException(nameof(stringToEscape));
if (stringToEscape.Length == 0)
return string.Empty;
int position = 0;
char[] dest = UriHelper.EscapeString(stringToEscape, 0, stringToEscape.Length, null, ref position, false,
c_DummyChar, c_DummyChar, c_DummyChar);
if (dest == null)
return stringToEscape;
return new string(dest, 0, position);
}
//
// Cleans up the specified component according to Iri rules
// a) Chars allowed by iri in a component are unescaped if found escaped
// b) Bidi chars are stripped
//
// should be called only if IRI parsing is switched on
internal unsafe string EscapeUnescapeIri(string input, int start, int end, UriComponents component)
{
fixed (char* pInput = input)
{
return IriHelper.EscapeUnescapeIri(pInput, start, end, component);
}
}
// Should never be used except by the below method
private Uri(Flags flags, UriParser uriParser, string uri)
{
_flags = flags;
_syntax = uriParser;
_string = uri;
}
//
// a Uri.TryCreate() method goes through here.
//
internal static Uri CreateHelper(string uriString, bool dontEscape, UriKind uriKind, ref UriFormatException e)
{
// if (!Enum.IsDefined(typeof(UriKind), uriKind)) -- We currently believe that Enum.IsDefined() is too slow
// to be used here.
if ((int)uriKind < (int)UriKind.RelativeOrAbsolute || (int)uriKind > (int)UriKind.Relative)
{
throw new ArgumentException(SR.Format(SR.net_uri_InvalidUriKind, uriKind));
}
UriParser syntax = null;
Flags flags = Flags.Zero;
ParsingError err = ParseScheme(uriString, ref flags, ref syntax);
if (dontEscape)
flags |= Flags.UserEscaped;
// We won't use User factory for these errors
if (err != ParsingError.None)
{
// If it looks as a relative Uri, custom factory is ignored
if (uriKind != UriKind.Absolute && err <= ParsingError.LastRelativeUriOkErrIndex)
return new Uri((flags & Flags.UserEscaped), null, uriString);
return null;
}
// Cannot be relative Uri if came here
Uri result = new Uri(flags, syntax, uriString);
// Validate instance using ether built in or a user Parser
try
{
result.InitializeUri(err, uriKind, out e);
if (e == null)
return result;
return null;
}
catch (UriFormatException ee)
{
Debug.Assert(!syntax.IsSimple, "A UriPraser threw on InitializeAndValidate.");
e = ee;
// A precaution since custom Parser should never throw in this case.
return null;
}
}
//
// Resolves into either baseUri or relativeUri according to conditions OR if not possible it uses newUriString
// to return combined URI strings from both Uris
// otherwise if e != null on output the operation has failed
//
internal static Uri ResolveHelper(Uri baseUri, Uri relativeUri, ref string newUriString, ref bool userEscaped,
out UriFormatException e)
{
Debug.Assert(!baseUri.IsNotAbsoluteUri && !baseUri.UserDrivenParsing, "Uri::ResolveHelper()|baseUri is not Absolute or is controlled by User Parser.");
e = null;
string relativeStr = string.Empty;
if ((object)relativeUri != null)
{
if (relativeUri.IsAbsoluteUri)
return relativeUri;
relativeStr = relativeUri.OriginalString;
userEscaped = relativeUri.UserEscaped;
}
else
relativeStr = string.Empty;
// Here we can assert that passed "relativeUri" is indeed a relative one
if (relativeStr.Length > 0 && (UriHelper.IsLWS(relativeStr[0]) || UriHelper.IsLWS(relativeStr[relativeStr.Length - 1])))
relativeStr = relativeStr.Trim(UriHelper.s_WSchars);
if (relativeStr.Length == 0)
{
newUriString = baseUri.GetParts(UriComponents.AbsoluteUri,
baseUri.UserEscaped ? UriFormat.UriEscaped : UriFormat.SafeUnescaped);
return null;
}
// Check for a simple fragment in relative part
if (relativeStr[0] == '#' && !baseUri.IsImplicitFile && baseUri.Syntax.InFact(UriSyntaxFlags.MayHaveFragment))
{
newUriString = baseUri.GetParts(UriComponents.AbsoluteUri & ~UriComponents.Fragment,
UriFormat.UriEscaped) + relativeStr;
return null;
}
// Check for a simple query in relative part
if (relativeStr[0] == '?' && !baseUri.IsImplicitFile && baseUri.Syntax.InFact(UriSyntaxFlags.MayHaveQuery))
{
newUriString = baseUri.GetParts(UriComponents.AbsoluteUri & ~UriComponents.Query & ~UriComponents.Fragment,
UriFormat.UriEscaped) + relativeStr;
return null;
}
// Check on the DOS path in the relative Uri (a special case)
if (relativeStr.Length >= 3
&& (relativeStr[1] == ':' || relativeStr[1] == '|')
&& UriHelper.IsAsciiLetter(relativeStr[0])
&& (relativeStr[2] == '\\' || relativeStr[2] == '/'))
{
if (baseUri.IsImplicitFile)
{
// It could have file:/// prepended to the result but we want to keep it as *Implicit* File Uri
newUriString = relativeStr;
return null;
}
else if (baseUri.Syntax.InFact(UriSyntaxFlags.AllowDOSPath))
{
// The scheme is not changed just the path gets replaced
string prefix;
if (baseUri.InFact(Flags.AuthorityFound))
prefix = baseUri.Syntax.InFact(UriSyntaxFlags.PathIsRooted) ? ":///" : "://";
else
prefix = baseUri.Syntax.InFact(UriSyntaxFlags.PathIsRooted) ? ":/" : ":";
newUriString = baseUri.Scheme + prefix + relativeStr;
return null;
}
// If we are here then input like "http://host/path/" + "C:\x" will produce the result http://host/path/c:/x
}
ParsingError err = GetCombinedString(baseUri, relativeStr, userEscaped, ref newUriString);
if (err != ParsingError.None)
{
e = GetException(err);
return null;
}
if ((object)newUriString == (object)baseUri._string)
return baseUri;
return null;
}
private unsafe string GetRelativeSerializationString(UriFormat format)
{
if (format == UriFormat.UriEscaped)
{
if (_string.Length == 0)
return string.Empty;
int position = 0;
char[] dest = UriHelper.EscapeString(_string, 0, _string.Length, null, ref position, true,
c_DummyChar, c_DummyChar, '%');
if ((object)dest == null)
return _string;
return new string(dest, 0, position);
}
else if (format == UriFormat.Unescaped)
return UnescapeDataString(_string);
else if (format == UriFormat.SafeUnescaped)
{
if (_string.Length == 0)
return string.Empty;
char[] dest = new char[_string.Length];
int position = 0;
dest = UriHelper.UnescapeString(_string, 0, _string.Length, dest, ref position, c_DummyChar,
c_DummyChar, c_DummyChar, UnescapeMode.EscapeUnescape, null, false);
return new string(dest, 0, position);
}
else
throw new ArgumentOutOfRangeException(nameof(format));
}
//
// UriParser helpers methods
//
internal string GetComponentsHelper(UriComponents uriComponents, UriFormat uriFormat)
{
if (uriComponents == UriComponents.Scheme)
return _syntax.SchemeName;
// A serialization info is "almost" the same as AbsoluteUri except for IPv6 + ScopeID hostname case
if ((uriComponents & UriComponents.SerializationInfoString) != 0)
uriComponents |= UriComponents.AbsoluteUri;
//This will get all the offsets, HostString will be created below if needed
EnsureParseRemaining();
if ((uriComponents & UriComponents.NormalizedHost) != 0)
{
// Down the path we rely on Host to be ON for NormalizedHost
uriComponents |= UriComponents.Host;
}
//Check to see if we need the host/authority string
if ((uriComponents & UriComponents.Host) != 0)
EnsureHostString(true);
//This, single Port request is always processed here
if (uriComponents == UriComponents.Port || uriComponents == UriComponents.StrongPort)
{
if (((_flags & Flags.NotDefaultPort) != 0) || (uriComponents == UriComponents.StrongPort
&& _syntax.DefaultPort != UriParser.NoDefaultPort))
{
// recreate string from the port value
return _info.Offset.PortValue.ToString(CultureInfo.InvariantCulture);
}
return string.Empty;
}
if ((uriComponents & UriComponents.StrongPort) != 0)
{
// Down the path we rely on Port to be ON for StrongPort
uriComponents |= UriComponents.Port;
}
//This request sometime is faster to process here
if (uriComponents == UriComponents.Host && (uriFormat == UriFormat.UriEscaped
|| ((_flags & (Flags.HostNotCanonical | Flags.E_HostNotCanonical)) == 0)))
{
EnsureHostString(false);
return _info.Host;
}
switch (uriFormat)
{
case UriFormat.UriEscaped:
return GetEscapedParts(uriComponents);
case V1ToStringUnescape:
case UriFormat.SafeUnescaped:
case UriFormat.Unescaped:
return GetUnescapedParts(uriComponents, uriFormat);
default:
throw new ArgumentOutOfRangeException(nameof(uriFormat));
}
}
public bool IsBaseOf(Uri uri)
{
if ((object)uri == null)
throw new ArgumentNullException(nameof(uri));
if (!IsAbsoluteUri)
return false;
if (Syntax.IsSimple)
return IsBaseOfHelper(uri);
return Syntax.InternalIsBaseOf(this, uri);
}
internal bool IsBaseOfHelper(Uri uriLink)
{
if (!IsAbsoluteUri || UserDrivenParsing)
return false;
if (!uriLink.IsAbsoluteUri)
{
//a relative uri could have quite tricky form, it's better to fix it now.
string newUriString = null;
UriFormatException e;
bool dontEscape = false;
uriLink = ResolveHelper(this, uriLink, ref newUriString, ref dontEscape, out e);
if (e != null)
return false;
if ((object)uriLink == null)
uriLink = CreateHelper(newUriString, dontEscape, UriKind.Absolute, ref e);
if (e != null)
return false;
}
if (Syntax.SchemeName != uriLink.Syntax.SchemeName)
return false;
// Canonicalize and test for substring match up to the last path slash
string self = GetParts(UriComponents.AbsoluteUri & ~UriComponents.Fragment, UriFormat.SafeUnescaped);
string other = uriLink.GetParts(UriComponents.AbsoluteUri & ~UriComponents.Fragment, UriFormat.SafeUnescaped);
unsafe
{
fixed (char* selfPtr = self)
{
fixed (char* otherPtr = other)
{
return UriHelper.TestForSubPath(selfPtr, (ushort)self.Length, otherPtr, (ushort)other.Length,
IsUncOrDosPath || uriLink.IsUncOrDosPath);
}
}
}
}
//
// Only a ctor time call
//
private void CreateThisFromUri(Uri otherUri)
{
// Clone the other guy but develop own UriInfo member
_info = null;
_flags = otherUri._flags;
if (InFact(Flags.MinimalUriInfoSet))
{
_flags &= ~(Flags.MinimalUriInfoSet | Flags.AllUriInfoSet | Flags.IndexMask);
// Port / Path offset
int portIndex = otherUri._info.Offset.Path;
if (InFact(Flags.NotDefaultPort))
{
// Find the start of the port. Account for non-canonical ports like :00123
while (otherUri._string[portIndex] != ':' && portIndex > otherUri._info.Offset.Host)
{
portIndex--;
}
if (otherUri._string[portIndex] != ':')
{
// Something wrong with the NotDefaultPort flag. Reset to path index
Debug.Assert(false, "Uri failed to locate custom port at index: " + portIndex);
portIndex = otherUri._info.Offset.Path;
}
}
_flags |= (Flags)portIndex; // Port or path
}
_syntax = otherUri._syntax;
_string = otherUri._string;
_iriParsing = otherUri._iriParsing;
if (otherUri.OriginalStringSwitched)
{
_originalUnicodeString = otherUri._originalUnicodeString;
}
if (otherUri.AllowIdn && (otherUri.InFact(Flags.IdnHost) || otherUri.InFact(Flags.UnicodeHost)))
{
_dnsSafeHost = otherUri._dnsSafeHost;
}
}
}
}
| |
//! \file ArcFile.cs
//! \date Tue Jul 08 12:53:45 2014
//! \brief Game Archive file class.
//
// Copyright (C) 2014-2015 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
namespace GameRes
{
public class ArcFile : IDisposable
{
private ArcView m_arc;
private ArchiveFormat m_interface;
private ICollection<Entry> m_dir;
/// <summary>Tag that identifies this archive format.</summary>
public string Tag { get { return m_interface.Tag; } }
/// <summary>Short archive format description.</summary>
public string Description { get { return m_interface.Description; } }
/// <summary>Memory-mapped view of the archive.</summary>
public ArcView File { get { return m_arc; } }
/// <summary>Archive contents.</summary>
public ICollection<Entry> Dir { get { return m_dir; } }
public ArcFile (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir)
{
m_arc = arc;
m_interface = impl;
m_dir = dir;
}
/// <summary>
/// Try to open <paramref name="filename"/> as archive.
/// </summary>
/// <returns>
/// ArcFile object if file is opened successfully, null otherwise.
/// </returns>
public static ArcFile TryOpen (string filename)
{
var entry = VFS.FindFile (filename);
if (entry.Size < 4)
return null;
var ext = new Lazy<string> (() => Path.GetExtension (filename).TrimStart ('.').ToLowerInvariant());
var file = VFS.OpenView (entry);
try
{
uint signature = file.View.ReadUInt32 (0);
for (;;)
{
var range = FormatCatalog.Instance.LookupSignature<ArchiveFormat> (signature);
// check formats that match filename extension first
if (range.Skip(1).Any()) // if range.Count() > 1
range = range.OrderByDescending (f => f.Extensions.Any (e => e == ext.Value));
foreach (var impl in range)
{
try
{
var arc = impl.TryOpen (file);
if (null != arc)
{
file = null; // file ownership passed to ArcFile
return arc;
}
}
catch (OperationCanceledException X)
{
FormatCatalog.Instance.LastError = X;
return null;
}
catch (Exception X)
{
// ignore failed open attmepts
Trace.WriteLine (string.Format ("[{0}] {1}: {2}", impl.Tag, filename, X.Message));
FormatCatalog.Instance.LastError = X;
}
}
if (0 == signature)
break;
signature = 0;
}
}
finally
{
if (null != file)
file.Dispose();
}
return null;
}
/// <summary>
/// Extract all entries from the archive into current directory.
/// <paramref name="callback"/> could be used to observe/control extraction process.
/// </summary>
public void ExtractFiles (EntryCallback callback)
{
int i = 0;
foreach (var entry in Dir.OrderBy (e => e.Offset))
{
var action = callback (i, entry, null);
if (ArchiveOperation.Abort == action)
break;
if (ArchiveOperation.Skip != action)
Extract (entry);
++i;
}
}
/// <summary>
/// Extract specified <paramref name="entry"/> into current directory.
/// </summary>
public void Extract (Entry entry)
{
if (-1 != entry.Offset)
m_interface.Extract (this, entry);
}
/// <summary>
/// Open specified <paramref name="entry"/> as Stream.
/// </summary>
public Stream OpenEntry (Entry entry)
{
return m_interface.OpenEntry (this, entry);
}
/// <summary>
/// Open specified <paramref name="entry"/> as memory-mapped view.
/// </summary>
public ArcView OpenView (Entry entry)
{
using (var stream = OpenEntry (entry))
{
uint size;
var packed_entry = entry as PackedEntry;
if (stream.CanSeek)
size = (uint)stream.Length;
else if (null != packed_entry && packed_entry.IsPacked)
size = packed_entry.UnpackedSize;
else
size = entry.Size;
return new ArcView (stream, entry.Name, size);
}
}
/// <summary>
/// Open specified <paramref name="entry"/> as a seekable Stream.
/// </summary>
public Stream OpenSeekableEntry (Entry entry)
{
var input = OpenEntry (entry);
if (input.CanSeek)
return input;
using (input)
{
int capacity = (int)entry.Size;
var packed_entry = entry as PackedEntry;
if (packed_entry != null && packed_entry.UnpackedSize != 0)
capacity = (int)packed_entry.UnpackedSize;
var copy = new MemoryStream (capacity);
input.CopyTo (copy);
copy.Position = 0;
return copy;
}
}
public ArchiveFileSystem CreateFileSystem ()
{
if (m_interface.IsHierarchic)
return new TreeArchiveFileSystem (this);
else
return new FlatArchiveFileSystem (this);
}
#region IDisposable Members
bool disposed = false;
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (!disposed)
{
if (disposing)
m_arc.Dispose();
disposed = true;
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace My1st5minApp.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
namespace SpiffCode
{
/// <summary>
/// Summary description for PreviewControl.
/// </summary>
public class PreviewControl : System.Windows.Forms.UserControl
{
private bool m_fFrameRecentering = false;
private bool m_fSpaceDown = false;
private bool m_fAllFrames;
private bool m_fRepositionBitmaps = false;
private BitmapPlacer m_plcSelected = null;
private Point m_ptPreSetSpecialPoint;
private bool m_fSetSpecialPoint = false;
private PreviewControlMode m_mode = PreviewControlMode.RepositionBitmap;
#if false
private bool m_fOnionSkin = true;
#endif
private bool m_fDragging = false;
private Point m_ptDragStart;
private Point[] m_aptPreDragBitmap;
private Point m_ptOffset;
private Point m_ptInitialOffset;
private System.Windows.Forms.Label label1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public PreviewControl()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// My initialization
ResizeRedraw = true;
Globals.ActiveDocumentChanged += new EventHandler(OnActiveDocumentChanged);
Globals.ActiveFrameChanged += new EventHandler(OnInvalidatingChange);
Globals.GridChanged += new EventHandler(OnInvalidatingChange);
Globals.SideColorMappingOnChanged += new EventHandler(OnInvalidatingChange);
Globals.ShowOriginPointChanged += new EventHandler(OnInvalidatingChange);
Globals.ShowSpecialPointChanged += new EventHandler(OnInvalidatingChange);
Globals.FrameContentChanged += new EventHandler(OnInvalidatingChange);
Globals.KeyDown += new KeyEventHandler(OnGlobalKeyDown);
Globals.KeyUp += new KeyEventHandler(OnGlobalKeyUp);
m_ptOffset = new Point(0, 0);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(56, 16);
this.label1.TabIndex = 1;
this.label1.Text = "Preview";
//
// PreviewControl
//
this.AllowDrop = true;
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.label1});
this.Name = "PreviewControl";
this.DragEnter += new System.Windows.Forms.DragEventHandler(this.PreviewControl_DragEnter);
this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.PreviewControl_MouseUp);
this.DragDrop += new System.Windows.Forms.DragEventHandler(this.PreviewControl_DragDrop);
this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.PreviewControl_MouseMove);
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PreviewControl_MouseDown);
this.ResumeLayout(false);
}
#endregion
public event FrameOffsetEventHandler FrameOffsetChanged;
public PreviewControlMode Mode {
set {
m_mode = value;
}
get {
return m_mode;
}
}
private void OnGlobalKeyDown(object obSender, KeyEventArgs e) {
if (e.KeyCode == Keys.Space) {
Cursor = m_fFrameRecentering ? Globals.GrabCursor : Globals.HandCursor;
m_fSpaceDown = true;
}
}
private void OnGlobalKeyUp(object obSender, KeyEventArgs e) {
if (e.KeyCode == Keys.Space) {
if (!m_fFrameRecentering)
Cursor = Cursors.Default;
m_fSpaceDown = false;
}
}
private void OnActiveDocumentChanged(object obSender, EventArgs e) {
Invalidate();
}
public void OnFrameOffsetChanged(object obSender, FrameOffsetEventArgs e) {
m_ptOffset.X = e.X;
m_ptOffset.Y = e.Y;
Invalidate();
}
private void OnInvalidatingChange(object obSender, EventArgs e) {
Invalidate();
}
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) {
Frame.DrawArgs drwa = new Frame.DrawArgs();
drwa.clrBackground = BackColor;
drwa.fDrawBackground = true;
drwa.fMapSideColors = Globals.SideColorMappingOn;
drwa.fShowGrid = Globals.GridOn;
drwa.cxGrid = Globals.GridWidth;
drwa.cyGrid = Globals.GridHeight;
drwa.fShowOrigin = Globals.ShowOriginPoint;
drwa.fShowSpecialPoint = Globals.ShowSpecialPoint || (m_mode == PreviewControlMode.SetSpecialPoint);
drwa.nScale = Globals.PreviewScale;
if (Globals.ActiveStrip != null && Globals.ActiveStrip.Count != 0) {
Frame fr;
Rectangle rc = new Rectangle(0, 0, ClientRectangle.Width, ClientRectangle.Height);
#if false
if (m_fOnionSkin && Globals.ActiveFrame > 0) {
drwa.fShowGrid = false;
drwa.fShowOrigin = false;
drwa.fShowSpecialPoint = false;
drwa.nAlpha = 128;
fr = Globals.ActiveStrip[Globals.ActiveFrame - 1];
fr.Draw(e.Graphics, rc, drwa, m_ptOffset);
}
#endif
fr = Globals.ActiveStrip[Globals.ActiveFrame];
fr.Draw(e.Graphics, rc, drwa, m_ptOffset);
#if false
if (m_fOnionSkin && Globals.ActiveFrame < Globals.ActiveStrip.Count - 1) {
fr = Globals.ActiveStrip[Globals.ActiveFrame + 1];
fr.Draw(e.Graphics, rc, drwa, m_ptOffset);
}
#endif
#if false
// Draw selection rectangle
if (m_plcSelected != null) {
Point ptUpperLeft = WxyFromFxy(FxyFromBxy(m_plcSelected, new Point(0, 0)));
Point ptLowerRight = WxyFromFxy(FxyFromBxy(m_plcSelected,
new Point(m_plcSelected.XBitmap.Width, m_plcSelected.XBitmap.Height)));
e.Graphics.DrawRectangle(new Pen(Color.Black),
ptUpperLeft.X, ptUpperLeft.Y, ptLowerRight.X - ptUpperLeft.X, ptLowerRight.Y - ptUpperLeft.Y);
}
#endif
} else {
e.Graphics.FillRectangle(new SolidBrush(BackColor), e.ClipRectangle);
}
}
protected override void OnPaintBackground(System.Windows.Forms.PaintEventArgs e) {
if (Globals.ActiveStrip == null)
base.OnPaintBackground(e);
}
private Point WxyFromFxy(Point ptFrame) {
return new Point(((ptFrame.X + m_ptOffset.X) * Globals.PreviewScale) + (ClientRectangle.Width / 2),
((ptFrame.Y + m_ptOffset.Y) * Globals.PreviewScale) + (ClientRectangle.Height / 2));
}
private Point FxyFromBxy(BitmapPlacer plc, Point ptBitmap) {
return new Point(ptBitmap.X - plc.X, ptBitmap.Y - plc.Y);
}
private Point FxyFromWxy(Point ptWindow) {
Rectangle rcClient = ClientRectangle;
int xCenter = rcClient.Width / 2;
int yCenter = rcClient.Height / 2;
int dx = ptWindow.X - xCenter;
if (dx < 0)
dx -= Globals.PreviewScale;
int dy = ptWindow.Y - yCenter;
if (dy < 0)
dy -= Globals.PreviewScale;
return new Point((dx / Globals.PreviewScale) - m_ptOffset.X, (dy / Globals.PreviewScale) - m_ptOffset.Y);
}
private Point BxyFromFxy(BitmapPlacer plc, Point ptFrame) {
return new Point(ptFrame.X + plc.X, ptFrame.Y + plc.Y);
}
private BitmapPlacer HitTest(int wx, int wy) {
Color clrTransparent = Color.FromArgb(0xff, 0, 0xff);
Point fpt = FxyFromWxy(new Point(wx, wy));
foreach (BitmapPlacer plc in Globals.ActiveStrip[Globals.ActiveFrame].BitmapPlacers) {
Point bpt = BxyFromFxy(plc, fpt);
if (bpt.X < 0 || bpt.Y < 0 || bpt.X >= plc.XBitmap.Width || bpt.Y >= plc.XBitmap.Height)
continue;
if (plc.XBitmap.Bitmap.GetPixel(bpt.X, bpt.Y) != clrTransparent)
return plc;
}
return null;
}
private void PreviewControl_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) {
Strip stp = Globals.ActiveStrip;
if (stp == null)
return;
if (m_fSpaceDown) {
m_fFrameRecentering = true;
m_fDragging = true;
m_ptDragStart = FxyFromWxy(new Point(e.X, e.Y));
m_ptInitialOffset = m_ptOffset;
Cursor = Globals.GrabCursor;
return;
}
switch (m_mode) {
case PreviewControlMode.SetSpecialPoint:
{
m_fDragging = true;
m_fSetSpecialPoint = true;
Point ptT = FxyFromWxy(new Point(e.X, e.Y));
Frame fr = stp[Globals.ActiveFrame];
m_ptPreSetSpecialPoint = fr.SpecialPoint;
fr.SpecialPoint = ptT;
Globals.ActiveDocument.Dirty = true;
Globals.OnFrameContentChanged(this, new EventArgs());
}
break;
case PreviewControlMode.RepositionBitmap:
{
BitmapPlacer plc = HitTest(e.X, e.Y);
if (plc == null)
break;
m_plcSelected = plc;
m_fDragging = true;
m_fAllFrames = (ModifierKeys & Keys.Shift) != 0;
// UNDONE: across frame operations don't really make sense until we have Tracks
m_aptPreDragBitmap = new Point[stp.Count];
for (int ifr = 0; ifr < stp.Count; ifr++) {
Frame fr = stp[ifr];
if (fr.BitmapPlacers.Count > 0) {
m_aptPreDragBitmap[ifr].X = fr.BitmapPlacers[0].X;
m_aptPreDragBitmap[ifr].Y = fr.BitmapPlacers[0].Y;
}
}
// Special handling for active frame
m_aptPreDragBitmap[stp.ActiveFrame].X = m_plcSelected.X;
m_aptPreDragBitmap[stp.ActiveFrame].Y = m_plcSelected.Y;
m_ptDragStart = FxyFromWxy(new Point(e.X, e.Y));
}
break;
}
}
private void PreviewControl_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) {
if (!m_fDragging)
return;
Strip stp = Globals.ActiveStrip;
if (stp == null)
return;
if (m_fFrameRecentering) {
m_ptOffset = m_ptInitialOffset;
Point ptNew = FxyFromWxy(new Point(e.X, e.Y));
m_ptOffset.X = m_ptInitialOffset.X + (ptNew.X - m_ptDragStart.X);
m_ptOffset.Y = m_ptInitialOffset.Y + (ptNew.Y - m_ptDragStart.Y);
Invalidate();
Update();
// Notify anyone who cares that we've changed the Frame offset
if (FrameOffsetChanged != null)
FrameOffsetChanged(this, new FrameOffsetEventArgs(m_ptOffset.X, m_ptOffset.Y));
return;
}
switch (m_mode) {
case PreviewControlMode.SetSpecialPoint:
{
Point ptT = FxyFromWxy(new Point(e.X, e.Y));
Frame fr = stp[Globals.ActiveFrame];
fr.SpecialPoint = ptT;
Globals.ActiveDocument.Dirty = true;
Globals.OnFrameContentChanged(this, new EventArgs());
}
break;
case PreviewControlMode.RepositionBitmap:
{
Point ptT = FxyFromWxy(new Point(e.X, e.Y));
int ipl = stp[Globals.ActiveFrame].BitmapPlacers.
Index(m_plcSelected);
int ifr;
int cfr;
if (m_fAllFrames) {
ifr = 0;
cfr = stp.Count;
} else {
ifr = Globals.ActiveFrame;
cfr = Globals.ActiveFrameCount;
}
for (int ifrT = ifr; ifrT < ifr + cfr; ifrT++) {
int iplT = ipl;
if (iplT >= stp[ifrT].BitmapPlacers.Count) {
iplT = 0;
}
BitmapPlacer plc = stp[ifrT].BitmapPlacers[iplT];
plc.X = m_aptPreDragBitmap[ifrT].X + m_ptDragStart.X -
ptT.X;
plc.Y = m_aptPreDragBitmap[ifrT].Y + m_ptDragStart.Y -
ptT.Y;
}
m_fRepositionBitmaps = true;
Globals.ActiveDocument.Dirty = true;
Globals.OnFrameContentChanged(this, new EventArgs());
}
break;
}
}
private void PreviewControl_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) {
m_fDragging = false;
if (m_fFrameRecentering) {
Cursor = Cursors.Default;
m_fFrameRecentering = false;
}
if (m_fRepositionBitmaps) {
m_fRepositionBitmaps = false;
Strip stp = Globals.ActiveStrip;
UndoManager.BeginGroup();
for (int ifr = 0; ifr < stp.Count; ifr++) {
if (ifr != stp.ActiveFrame) {
if (stp[ifr].BitmapPlacers.Count > 0) {
UndoManager.AddUndo(new UndoDelegate(UndoSetBitmapPosition),
new Object[] { stp[ifr].BitmapPlacers[0], m_aptPreDragBitmap[ifr].X, m_aptPreDragBitmap[ifr].Y });
}
}
}
UndoManager.AddUndo(new UndoDelegate(UndoSetBitmapPosition),
new Object[] { m_plcSelected, m_aptPreDragBitmap[stp.ActiveFrame].X, m_aptPreDragBitmap[stp.ActiveFrame].Y });
UndoManager.EndGroup();
}
if (m_fSetSpecialPoint) {
m_fSetSpecialPoint = false;
UndoManager.AddUndo(new UndoDelegate(UndoSetSpecialPoint),
new Object[] { Globals.ActiveStrip[Globals.ActiveFrame], m_ptPreSetSpecialPoint.X, m_ptPreSetSpecialPoint.Y });
}
}
private void UndoSetBitmapPosition(object[] aobArgs) {
BitmapPlacer plc = (BitmapPlacer)aobArgs[0];
plc.X = (int)aobArgs[1];
plc.Y = (int)aobArgs[2];
Globals.ActiveDocument.Dirty = true;
Globals.OnFrameContentChanged(this, new EventArgs());
}
private void UndoSetSpecialPoint(object[] aobArgs) {
Frame fr = (Frame)aobArgs[0];
fr.SpecialPoint = new Point((int)aobArgs[1], (int)aobArgs[2]);
Globals.ActiveDocument.Dirty = true;
Globals.OnFrameContentChanged(this, new EventArgs());
}
private void PreviewControl_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) {
XBitmap[] axbm = (XBitmap[])e.Data.GetData(typeof(XBitmap[]));
if (axbm == null)
e.Effect = DragDropEffects.None;
else
e.Effect = DragDropEffects.Copy;
}
private void PreviewControl_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) {
XBitmap[] axbm = (XBitmap[])e.Data.GetData(typeof(XBitmap[]));
if (axbm == null)
return;
BitmapPlacerList plcl = Globals.ActiveStrip[Globals.ActiveFrame].BitmapPlacers;
foreach (XBitmap xbm in axbm) {
BitmapPlacer plc = new BitmapPlacer();
plc.X = 0;
plc.Y = 0;
plc.XBitmap = xbm;
plcl.Insert(0, plc);
}
Globals.ActiveDocument.Dirty = true;
Globals.OnFrameContentChanged(this, new EventArgs());
}
}
public enum PreviewControlMode {
SetSpecialPoint,
RepositionBitmap,
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.